Skip to content

Add Fortran input.param reader - #286

Merged
neuromechanist merged 13 commits into
devfrom
feature/issue-132-param-reader
Aug 23, 2026
Merged

neuromechanist merged 13 commits into
devfrom
feature/issue-132-param-reader

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Summary

JOSS reviewer feedback (Arnaud Delorme) asked whether pyAMICA and the reference Fortran binary can be driven from the same configuration file.

pamica/fortran_params.py adds read_fortran_param_file(path) -> dict, a translator (not a second parameter-handling implementation) that parses the literal Fortran input.param text format into a dict keyed by pamica's actual constructor/fit() parameter names.

AMICA.from_params_file auto-detects the format by sniffing content (not trusting the file extension) and routes through the translator. This was the least-API-invasive integration: no new public method, the existing call just accepts either file now.

Design decision (added after review, stated here for the record): from_params_file stashes the full translated dict on the returned instance (self._file_params); fit() applies it as per-call defaults for its five named parameters (max_iter, lrate, do_mean, do_sphere, do_newton) and for any AMICATorchNG constructor keyword passed through **kwargs. An argument explicitly passed to fit() always wins over the file's value. A file setting that matches neither surface (data-location metadata like files/outdir/data_dim, or a Fortran setting with no pamica equivalent) is named in a single logger.warning rather than applied or dropped silently. This applies identically whether the instance was built from a .param or a .json file.

Key-mapping table

The mapping was built by reading every case('...') arm of amica15.f90's parameter parser (get_cmd_args, ~amica15.f90:3100-3700) against AMICATorchNG's constructor and validate_implementations.py's _NG_PARAMS/_HANDLED_KEYS.

89 Fortran keywords are recognized in total.

53 of them (52 distinct pamica-side names, since Fortran accepts both num_mix_comps and num_mix for the same setting) are translated into pamica's own parameter names.

Only three are renamed, because Fortran spells them differently from the pamica-side (constructor) name:

Fortran keyword (input.param) pamica key Note
min_grad_norm min_nd matches AMICATorchNG.min_nd
max_decs maxdecs matches AMICATorchNG.maxdecs
numrej maxrej matches AMICATorchNG.maxrej

num_mix_comps/num_mix both collapse to the pamica key num_mix, read directly by from_params_file to size the instance (AMICA(n_mix=...)) before the rest of the dict reaches fit(). share_iter is not renamed -- it already matches AMICATorchNG.share_iter exactly, unlike sample_params.json's own schema, which spells the same setting share_int (a pre-existing mismatch in that JSON file, out of scope here, that fit()'s per-call-default merge now surfaces as a "not applied" warning rather than silently ignoring it).

Every other translated keyword keeps its Fortran spelling: files, outdir, indir, data_dim, field_dim, num_samples, num_comps, num_models, max_iter, do_mean, do_sphere, do_approx_sphere, pcakeep, pcadb, mineig, lrate, minlrate, lratefact, use_min_dll, min_dll, use_grad_norm, block_size, do_newton, newt_start, newt_ramp, newtrate, do_reject, rejsig, rejstart, rejint, rho0, minrho, maxrho, rholrate, rholratefact, pdftype, kurt_start, num_kurt, kurt_int, share_comps, comp_thresh, share_start, share_iter, doscaling, scalestep, invsigmax, invsigmin, seed.

Deliberately-unmapped keys

36 known Fortran keywords have no pamica equivalent and are warned about by name (never silently dropped), grouped by why:

  • checkpoint warm-start: load_rho, load_rej, load_A, load_c, load_comp_list, load_all_param, load_sphere, load_mean, load_mu, load_beta, load_alpha, load_gm
  • per-family EM freeze toggles: update_A, update_c, update_mu, update_beta, update_alpha, update_gm, do_rho
  • optimal block-size search: blk_min, blk_max, blk_step, do_opt_block
  • Fortran-side console/output-file reporting: print_debug, write_nd, write_LLt, writestep, do_history, histstep
  • raw-data I/O format: dble_data, byte_size
  • pre-filtering pipeline: filter_length, dft_length
  • misc: max_threads, decwindow, fix_init

A keyword absent from both the mapped and unsupported tables is not a Fortran keyword this module recognizes at all (typo, or a different amica15.f90 revision) and is also warned about, separately. The bundled sample_data/input.param template itself carries three such stale entries -- field_blocksize, doPCA, load_W -- none of which is an actual case('...') arm in amica15.f90, so the reference binary already silently ignores them too; this reader now flags them instead.

A malformed line (a keyword with no value, or a non-empty file where not one keyword is recognized by the reference parser at all -- e.g. JSON mistakenly handed to read_fortran_param_file) raises ValueError rather than being dropped or defaulted silently, a deliberate divergence from the Fortran parser itself, which cycles/silently-defaults past these.

Additional permissiveness (fail-safe direction)

An inline trailing " #..." comment is stripped from a value before type coercion (Fortran itself only treats a line-leading # as a comment), and float values accept Fortran's d/D double-precision exponent marker (e.g. "1.5d-3"), normalized to e before float().

Tests

pamica/tests/test_fortran_params.py (33 tests): parses the real bundled sample_data/input.param and asserts the known mappings (block_size 512, pdftype 0, kurt_start 3, the three corrected renames, boolean-flag semantics matching Fortran's own k == 1 check), asserts unknown/unsupported-key warnings fire, a mapping-table partition consistency check against the live amica15.f90 source, malformed-line and zero-recognized-file hard-error cases, inline-comment and d/D-exponent parsing, content-sniffing overriding a misleading .param extension (including the exact compact-JSON-named-.param regression case), a round-trip test comparing read_fortran_param_file(input.param) against json.load(sample_params.json) on every overlapping key, and real-data evidence (TestFitAppliesFileDefaults) that from_params_file's settings actually reach the fitted AMICATorchNG backend (do_newton, block_size, lrate, newt_start), with an explicit-kwarg-wins test and a plain-AMICA(...)-is-unaffected test.

Gates

  • uv run pytest pamica/tests/test_fortran_params.py pamica/tests/test_fortran_param_forwarding.py -q --no-cov: 47 passed
  • uv run pytest -m "not slow" -n auto: 445 passed, 25 skipped, 1 xfailed, 0 failed
  • ruff check / ruff format --check / ty check: zero new diagnostics (repo-wide, all pass)

Closes #132.

neuromechanist and others added 13 commits August 23, 2026 11:38
Parses amica15.f90's whitespace key-value text format into pamica's
JSON parameter schema: translates the three mismatched keywords
(num_mix_comps/numrej/share_iter), warns loudly on any of the 36
known-but-unsupported keywords or unrecognized ones, and hard-errors
only on malformed lines. Tested against the real bundled
sample_data/input.param, no synthetic fixtures beyond tiny
malformed-line cases.

Closes #132.
Auto-detects the Fortran text format alongside the existing JSON
schema (by extension, falling back to content sniffing), routing
through read_fortran_param_file. No new public API: the same
from_params_file call now accepts either file.

Part of #132.
Mapping table and usage example in docs/guides/validation.md, plus a
changelog bullet.

Part of #132.
Review findings (PR #286):
- share_iter was mis-renamed to share_int; the AMICATorchNG
  constructor spells it share_iter, so any forwarded value would
  TypeError. Now identity, matching the constructor.
- min_grad_norm and max_decs stayed at their Fortran spelling, which
  matches neither AMICATorchNG (min_nd, maxdecs) nor fit(). Now
  renamed to the constructor's spelling.
- Strip a trailing inline " #comment" before type coercion, and
  accept Fortran's d/D double-precision exponent marker in floats.
- Raise when a non-empty file has content lines but not one keyword
  is recognized by the reference parser at all (e.g. JSON handed to
  this reader by mistake), instead of silently returning {}.

Updated the module docstring's rename table and rationale to match.
Review findings (PR #286):
- from_params_file forwarded only num_models/num_mix; the other ~50
  translated settings (e.g. do_newton, block_size) were silently
  discarded, so a file that set do_newton=1 produced a model that
  actually ran with do_newton=False.
- .param detection was skipped for a .param-named file that actually
  held JSON content, so it was parsed as garbled Fortran text and
  silently fell back to a default model.

from_params_file now stashes the full translated dict on the
instance (self._file_params) and always sniffs content over
extension. fit() applies the dict as per-call defaults for its five
named parameters and for AMICATorchNG **kwargs: an explicitly passed
argument always wins over the file. A setting that matches neither
surface (data-location metadata, or one with no pamica equivalent)
is named in a single logger.warning rather than applied or dropped
silently. Applies identically to the JSON route.
Covers PR #286's four review findings: the corrected share_iter/
min_nd/maxdecs mapping, real-data evidence that from_params_file's
settings actually reach the fitted AMICATorchNG backend (do_newton,
block_size, lrate, newt_start) with explicit kwargs winning, content
sniffing overriding a misleading .param extension (including the
compact-JSON-named-.param regression case), and inline comments plus
Fortran d/D exponent literals.
Corrected rename table (min_grad_norm/max_decs/numrej, not
num_mix_comps/share_iter/numrej), the content-sniffing-over-extension
behavior, and fit()'s per-call-default/warning semantics.
@neuromechanist
neuromechanist merged commit 9bc882a into dev Aug 23, 2026
8 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-132-param-reader branch August 23, 2026 22:55
This was referenced Aug 23, 2026
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.

Add a native Fortran .param file reader

1 participant