Skip to content

Replace print-based diagnostics with the logging module#76

Open
kripnerl wants to merge 34 commits into
developfrom
claude/equilibrium-init-refactor-4biwkn
Open

Replace print-based diagnostics with the logging module#76
kripnerl wants to merge 34 commits into
developfrom
claude/equilibrium-init-refactor-4biwkn

Conversation

@kripnerl

Copy link
Copy Markdown
Owner

All modules now log through named loggers under the 'pleque' hierarchy.
The package root installs a NullHandler (library best practice) and gains
a pleque.set_log_level() convenience helper that attaches a single stream
handler for interactive use.

https://claude.ai/code/session_01T8Bv18R1iJkgxQ7e4rTAKc

kripnerl and others added 30 commits June 5, 2026 13:31
Master-develop merge

Closes #68 and #76

See merge request kripner/pleque!138
Merge phd-thesis work to the master

See merge request kripner/pleque!141
Bump version to 0.0.10 and update release documentation

See merge request kripner/pleque!142
- Remove four redundant in-method `mu_0` imports; module-level import covers them
- Remove commented-out old __init__ signature left over from a prior refactor
- Remove commented-out matplotlib debug code from arg_longest_monotonic_subsequence
- Wire critical-point search grid (700×1200) to pleque.config.settings so
  users can override nr_grid/nz_grid via environment variables
- Extract triplicated psi_xysq_func closure in equi_tools.py to a single
  _make_psi_grad_sq factory, eliminating the duplication across find_extremes,
  recognize_mg_axis, and recognize_x_points

https://claude.ai/code/session_01FS9C1xD1y9tceTjGBvcyhn
- Remove three deprecated mis-named methods from Coordinates: incidence_angle_cos,
  impact_angle_cos, pol_projection_impact_angle_cos. All were wrappers around the
  correctly-named sin variants and had no callers anywhere in the codebase.
- Delete pleque/io/_test_gfile_loader.py: dead code with no callers, superseded by
  the proper geqdsk.read() path, and contained Equilibrium monkey-patching.
- Populate pleque/io/__init__.py with top-level re-exports (read_geqdsk, write_geqdsk,
  read_efithdf5, read_fiesta_equilibrium) so users can import directly from pleque.io.

https://claude.ai/code/session_01FS9C1xD1y9tceTjGBvcyhn
…oup 5)

__init__ is now a ~30-line orchestration that delegates to five private methods:
- _load_spatial_data: loads psi grid, first wall, and spatial metadata from dataset
- _load_profiles: loads 1D profile arrays (F, FFprime, pressure, pprime)
- _setup_psi_spline: builds the 2D RectBivariateSpline for psi(R, Z)
- _find_critical_points: finds x-points/o-points and recognizes plasma type
- _setup_plasma_boundary: finds LCFS contour and strike points
- _setup_1d_profiles: builds all UnivariateSpline profile interpolants

No behavior change; all tests pass. Also included in this commit:
- Remove three deprecated cos-misnamed methods from Coordinates that had no callers
  (incidence_angle_cos, impact_angle_cos, pol_projection_impact_angle_cos)

https://claude.ai/code/session_01FS9C1xD1y9tceTjGBvcyhn
…2203

Refactor: clean up code structure (Groups 1 & 2)
- Replace flake8 and pylint with ruff + ty in pyproject.toml
- Configure ruff with rules E,W,F,I,B,UP,RUF at 120-char line limit
- Ignore N802/N803/N806: physics variable naming (R, Z, X, Y) is
  intentional and forms part of the public API
- Add GitLab CI lint:ruff job after test:pytest
- Add GitHub Actions CI with separate test, lint, and typecheck jobs
  (ty runs with continue-on-error until annotations are more complete)
- Fix auto-fixable issues: unused imports, invalid escape sequences,
  import ordering, f-string modernisation, UP04x pyupgrade fixes
- Fix bare except → except Exception in omas.py and plotting.py
- Fix E741 ambiguous variable l → lis_len/arc_length in tools/fluxsurface
- Fix B008 mutable default args: np.array/np.eye moved into function bodies
- Fix B007 unused loop variable i → _i in tools.py arglis
- Fix affine.py bug: np.zeros_like(transform) → np.zeros_like(self.transformation)
- Change star import in fluxsurface.py to explicit import of deprecated
- Use explicit re-export (X as X) in pleque/core/__init__.py
- Add E402 noqa suppression in test_cdb.py (importorskip must come first)

Memo – issues not fixed (would break public API or need larger refactor):
- N802/N803/N806: physics coordinate names (R, Z, X, Y, B_tor, …)
- C901/PLR0913/PLR0915: physics algorithms are inherently complex
- E501 (18 remaining at 120 chars): all in long docstring prose
- F841/RUF059: some unpacked variables are intentional
- ANN*: type annotations largely absent; tracked separately

https://claude.ai/code/session_01NoBcY348U4MKRmAgQHCx1w
Equilibrium must be imported last since equilibrium.py depends on
Coordinates, FluxFunctions, Surface and SurfaceFunctions already
being registered on the pleque.core module object.

https://claude.ai/code/session_01NoBcY348U4MKRmAgQHCx1w
…-dependent

Equilibrium must be imported last to avoid circular imports; isort
cannot reorder these freely.

https://claude.ai/code/session_01NoBcY348U4MKRmAgQHCx1w
Resolve conflicts with the develop refactor (PR #69 split of
Equilibrium.__init__ into helpers and dead-code removal):

- equilibrium.py: take develop's _setup_plasma_boundary() extraction;
  the inline boundary block my branch only lint-touched now lives in
  the dedicated helper. Re-applied the UP032 f-string fix there.
- equi_tools.py: take develop's _make_psi_grad_sq() helper that
  replaces the duplicated nested psi_xysq_func.
- _test_gfile_loader.py: accept develop's deletion (dead code, no
  references); my branch had only lint-touched it.
- io/__init__.py: develop added public-API re-exports; sorted imports
  and added the module to ruff F401 per-file-ignores.

ruff passes; full test suite green (775 passed, 37 skipped).

https://claude.ai/code/session_01NoBcY348U4MKRmAgQHCx1w
Add ruff and ty linting; replace flake8/pylint; add CI workflows
- GitLab CI: run pytest with --junitxml and expose report.xml via
  artifacts.reports.junit so results appear in the GitLab test report UI
- GitHub Actions: new workflow that installs Poetry, runs pytest with
  --junitxml, uploads report.xml via actions/upload-artifact, and
  publishes a check-run summary via dorny/test-reporter

https://claude.ai/code/session_01SCWaAYTAKQdf4DpfiuczAM
Add pytest-cov to dev dependencies and run pytest with --cov=pleque
--cov-report=xml:coverage.xml in both pipelines.

- GitLab CI: exposes coverage.xml via artifacts.reports.coverage_report
  (Cobertura format) so GitLab renders line-level coverage diffs in MRs
- GitHub Actions: uploads coverage.xml as artifact, publishes a coverage
  summary badge+table via irongut/CodeCoverageSummary, and posts a
  sticky comment on PRs with the coverage breakdown

https://claude.ai/code/session_01SCWaAYTAKQdf4DpfiuczAM
…-ayr3rk

ci: store pytest results as artifacts in GitLab and GitHub CI
…docs

Coordinates.__init__ parsed the rich input syntax on every construction
(~7 us even for a single point), which dominated single-point evaluations
such as eq.B_R(R, Z) (~half of the 25 us call) and the field-line tracer
RHS, which builds three Coordinates objects per ODE evaluation.

Performance:
- Add Coordinates.from_coords() classmethod as the canonical rich-syntax
  factory; Coordinates.__init__ now takes a fast path for the common case
  of 1-3 positional scalars/1-D arrays in the default coordinate type and
  emits a DeprecationWarning for direct rich-syntax construction
  (named coordinates, (N, dim) arrays, non-default coord_type).
- Cache cocos_coefs() with lru_cache and return a read-only mapping
  (it is a pure function of the COCOS index and was rebuilt per init).
- Move the _valid_coordinates* sets to class attributes.
- Clean up the slow parser (module-level Iterable import, single
  np.atleast_1d conversions, set comparison instead of permutation scans;
  3D named input is now also converted with np.atleast_1d).
- Migrate internal call sites (Equilibrium.coordinates, Surface/
  FluxSurface, metis.py, examples, tests) to the warning-free paths.

Measured: Coordinates(eq, 0.7, 0.1) 7 -> 2.1 us; kwargs construction
7 -> 3.0 us; eq.B_R(0.7, 0.1) 25 -> 20.7 us. Bulk array calls are
spline-bound and unchanged.

Documentation:
- The coordinate input syntax was fully documented only in
  Coordinates.__init__ and duplicated in docs/source/coordinates.rst,
  while the ~44 coordinate-accepting Equilibrium methods documented it
  not at all (empty :param: stubs). The syntax now lives once in
  COORDINATES_DOC/COORD_PARAMS_DOC and a new append_to_doc decorator
  injects the full text into Coordinates.from_coords and
  Equilibrium.coordinates, and a short cross-referencing note into all
  coordinate-accepting Equilibrium methods; the empty :param: stubs are
  removed and coordinates.rst embeds the canonical docstring via
  automethod instead of a copy.

Tests: add fast/slow path parity tests and deprecation tests; full suite
777 passed. Sphinx build warning count drops from 10 to 8 (remaining
ones pre-date this change).

https://claude.ai/code/session_01KvV66UPfmyCtKH71MthmWo
…loading

Extract magic numbers (grid resolutions, solver tolerances, search
heuristics, spline parameters, plotting and IO writer defaults) from
equilibrium.py, equi_tools.py, surfaces.py, field_line_tracers.py,
plotting.py, geqdsk.py and omas.py into pleque.config.Settings,
organized into per-topic sections (grid, splines, critical_points,
lcfs, field_line_tracing, flux_surfaces, plotting, io). Function
arguments still override settings per call; settings are now read at
use time instead of being captured at import time.

Settings load from the first existing of: $PLEQUE_CONFIG_FILE,
./pleque.toml, the per-user config dir (%APPDATA%\pleque on Windows,
$XDG_CONFIG_HOME/pleque elsewhere), or a [tool.pleque] table in the
nearest pyproject.toml, with PLEQUE_-prefixed environment variables
taking precedence over files. The winning file is recorded on the
settings object (config_source, config_files_consulted) and
reload_settings() re-reads the configuration at runtime.

The old flat fields moved into sections: npsi_grid -> flux_surfaces.n_psi,
psin0 -> flux_surfaces.psi_n_min, nr_grid/nz_grid -> lcfs.search_grid_nr/nz
(the None sentinel is gone; defaults are 700/1200 directly).

Also fix lcfs_field_line ignoring its vect_no and xp_shift arguments
(they were hardcoded in the track_plasma_boundary call).

Add tests for defaults, precedence, source tracking, env vars and
reload; document the feature in docs/source/configuration.rst (kept in
sync by a test) and README. pydantic-settings gains the toml extra for
Python 3.10 support.

https://claude.ai/code/session_01HRFoBXP3uhqR5cZuURzdhS
…magic-numbers-7rq85x

Centralize algorithm parameters in grouped Settings with config-file loading
- coordinates.py: remove unused itertools import, fix import sort order,
  remove redundant `object` base class, annotate mutable class-level sets/dict
  with ClassVar to satisfy RUF012
- equilibrium.py: remove unused `import pleque`, collapse duplicate import
  blocks (F811 redefinitions introduced by the previous commit), fix import
  sort order

https://claude.ai/code/session_012QryKbWtWjQQrWmHdhe1pR
…tion-f2rrvs

Optimize Coordinates construction and de-duplicate coordinate syntax docs
All modules now log through named loggers under the 'pleque' hierarchy.
The package root installs a NullHandler (library best practice) and gains
a pleque.set_log_level() convenience helper that attaches a single stream
handler for interactive use.

https://claude.ai/code/session_01T8Bv18R1iJkgxQ7e4rTAKc
claude added 4 commits June 12, 2026 12:51
- Initialisation hints (mg_axis, psi_lcfs, x_points, strike_points) can now
  also be provided as basedata variables; explicit arguments take precedence
  with a logged warning (idea from MR !63 / feature/fast_forward_init).
- init_method is now functional: 'full' ignores all hints, 'hints' (default)
  uses them to assist the recognition, and 'fast_forward' takes the axis and
  X-point hints as final and skips the critical-point search (with fallback
  to 'hints' when the required hints are missing). Unknown values raise
  ValueError; read_geqdsk and EquilibriaTimeSlices.get_time_slice pass the
  option through.
- The bare except around the initialisation now catches Exception, logs the
  traceback, and draws the (blocking) debug plot only when the new
  debug_plots setting is enabled (PLEQUE_DEBUG_PLOTS=1); the same gating
  applies to the diagnostic plot in find_extremes. Initialisation failures
  no longer open matplotlib windows in headless/CI environments.
- First-wall resolution extracted into _resolve_first_wall with the
  synthetic rectangular wall construction moved to
  equi_tools.synthesize_rectangular_wall; the chosen wall source is logged.
- find_extremes warns when no O-point candidate is found; F'=FF'/F is
  guarded against division by zero.
- Class and constructor docstrings now describe the actual initialisation
  sequence, including where it deliberately differs from the thesis-chapter
  description (1D profile splines built after the critical-point search;
  LCFS found by marching squares + downhill refinement, not by field-line
  tracing).

https://claude.ai/code/session_01T8Bv18R1iJkgxQ7e4rTAKc
- New tests/test_equilibrium_init.py: synthetic-wall generation, vacuum
  equilibria, profile-derivative vs direct-profile equivalence, hint
  arguments and basedata hints (incl. duplicity warning), init_method
  full/hints/fast_forward consistency on bundled cases, double-null
  X-points, spline-order override, logging assertions, and the failure
  path (logged exception, no debug plot by default, debug plot with
  PLEQUE_DEBUG_PLOTS=1).
- The synthetic analytic equilibrium builder moved from
  tests/test_invert_equilibrium.py to pleque.tests.utils
  (synthetic_dataset/synthetic_test_wall) for reuse.
- tests/test_equilibria.py::test_critical placeholder replaced with real
  assertions for limiter and X-point configurations.

https://claude.ai/code/session_01T8Bv18R1iJkgxQ7e4rTAKc
Resolve conflict in pleque/core/coordinates.py: keep the Coordinates
refactor from develop (PR #75) and re-apply the named logger, converting
the warning print added by the refactor to logger.warning as well.

https://claude.ai/code/session_01T8Bv18R1iJkgxQ7e4rTAKc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants