Repository navigation
Add Fortran input.param reader - #286
Merged
Merged
Conversation
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.
…m-reader # Conflicts: # docs/changelog.md
…m-reader # Conflicts: # docs/changelog.md
This was referenced Aug 23, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.pyaddsread_fortran_param_file(path) -> dict, a translator (not a second parameter-handling implementation) that parses the literal Fortraninput.paramtext format into a dict keyed by pamica's actual constructor/fit()parameter names.AMICA.from_params_fileauto-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_filestashes 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 anyAMICATorchNGconstructor keyword passed through**kwargs. An argument explicitly passed tofit()always wins over the file's value. A file setting that matches neither surface (data-location metadata likefiles/outdir/data_dim, or a Fortran setting with no pamica equivalent) is named in a singlelogger.warningrather than applied or dropped silently. This applies identically whether the instance was built from a.paramor a.jsonfile.Key-mapping table
The mapping was built by reading every
case('...')arm ofamica15.f90's parameter parser (get_cmd_args, ~amica15.f90:3100-3700) againstAMICATorchNG's constructor andvalidate_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_compsandnum_mixfor 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:
input.param)min_grad_normmin_ndAMICATorchNG.min_ndmax_decsmaxdecsAMICATorchNG.maxdecsnumrejmaxrejAMICATorchNG.maxrejnum_mix_comps/num_mixboth collapse to the pamica keynum_mix, read directly byfrom_params_fileto size the instance (AMICA(n_mix=...)) before the rest of the dict reachesfit().share_iteris not renamed -- it already matchesAMICATorchNG.share_iterexactly, unlikesample_params.json's own schema, which spells the same settingshare_int(a pre-existing mismatch in that JSON file, out of scope here, thatfit()'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:
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_gmupdate_A,update_c,update_mu,update_beta,update_alpha,update_gm,do_rhoblk_min,blk_max,blk_step,do_opt_blockprint_debug,write_nd,write_LLt,writestep,do_history,histstepdble_data,byte_sizefilter_length,dft_lengthmax_threads,decwindow,fix_initA keyword absent from both the mapped and unsupported tables is not a Fortran keyword this module recognizes at all (typo, or a different
amica15.f90revision) and is also warned about, separately. The bundledsample_data/input.paramtemplate itself carries three such stale entries --field_blocksize,doPCA,load_W-- none of which is an actualcase('...')arm inamica15.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) raisesValueErrorrather than being dropped or defaulted silently, a deliberate divergence from the Fortran parser itself, whichcycles/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'sd/Ddouble-precision exponent marker (e.g."1.5d-3"), normalized toebeforefloat().Tests
pamica/tests/test_fortran_params.py(33 tests): parses the real bundledsample_data/input.paramand asserts the known mappings (block_size512,pdftype0,kurt_start3, the three corrected renames, boolean-flag semantics matching Fortran's ownk == 1check), asserts unknown/unsupported-key warnings fire, a mapping-table partition consistency check against the liveamica15.f90source, malformed-line and zero-recognized-file hard-error cases, inline-comment andd/D-exponent parsing, content-sniffing overriding a misleading.paramextension (including the exact compact-JSON-named-.paramregression case), a round-trip test comparingread_fortran_param_file(input.param)againstjson.load(sample_params.json)on every overlapping key, and real-data evidence (TestFitAppliesFileDefaults) thatfrom_params_file's settings actually reach the fittedAMICATorchNGbackend (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 passeduv run pytest -m "not slow" -n auto: 445 passed, 25 skipped, 1 xfailed, 0 failedruff check/ruff format --check/ty check: zero new diagnostics (repo-wide, all pass)Closes #132.