Files
muSRFlow/MSR_GUI_SYNC.md
T
salman 398e282cfc Document multi-group asymmetry fits, parameter NaN guards, and binaries preference
Extend the user manual (preferences, runs-fitting, t0/background), the
MSR-to-GUI synchronization notes, and the changelog with:
- slash-separated forward/backward groups generating one RUN block per group;
- multi-group t0/background and data-range read-back with fail-closed checks;
- the non-finite parameter guard (NaN value keeps the last good value, NaN
  step becomes 1% of the value, NaN/inf bounds are dropped);
- the musrfit binaries directory preference for non-standard tool locations.
2026-09-22 15:35:41 +02:00

12 KiB

MSR-to-GUI synchronization

This document describes how muSRFlow reconstructs GUI state from an existing musrfit MSR file. The synchronization is semantic: the objective is to recover the same fit model and constraints, not to reproduce the original parameter numbers, whitespace, comments, or legacy parameter names.

Design principles

  1. The MSR remains authoritative after synchronization. Importing values into the GUI does not silently transfer ownership to the GUI. The editor stays locked as the source of truth until the user explicitly unlocks it or asks to regenerate it from the GUI.
  2. Recognized sections are synchronized independently. A custom THEORY block that cannot be represented by the GUI does not prevent safe fields such as the run number, fit range, or Fourier settings from being imported.
  3. Ambiguous structures fail closed. The importer does not select the "closest" GUI model or guess how an unsupported expression should behave.
  4. Regeneration preserves meaning, not numbering. Parameters and functions may receive new numeric indices, but every THEORY, FUNCTION, RUN, and map reference is rebuilt from parameter names so that the relationships remain consistent.

Synchronization sequence

Opening an MSR file and selecting Sync to GUI use the same order:

flowchart TD
    A["Read MSR text"] --> B["Runs and settings"]
    B --> C["THEORY and FUNCTIONS"]
    C --> D["Parameter values"]
    D --> E["t0 and background"]
    E --> F["Keep editor authoritative"]

The order matters. Run type and histogram layout must exist before THEORY is applied; THEORY must exist before the parameter table is rebuilt; and the final RUN layout must exist before t0/background overrides are assigned.

The corresponding implementation entry points in muSRFitlib.js are:

  • parseMSRGUISettings() / applyMSRGUISettings()
  • parseMSRTheoryModel() / applyMSRTheoryModel()
  • parseMSRParameters() / applyMSRParametersToGUI()
  • parseMSRT0BgRunBlocks() / syncT0BgFromMSR()
  • syncCurrentEditorToGUI() and loadMSRIntoEditor() orchestrate the sequence

1. Runs and directly represented settings

parseMSRGUISettings() scans the MSR by section and imports fields that have a direct GUI control.

MSR information GUI state
RUN filename Run number, year, instrument
ADDRUN + members of one logical data set
Repeated RUN blocks Histogram groups without duplicating the physical run
GLOBAL fittype 0 Single Hist
GLOBAL fittype 2 Asymmetry
GLOBAL fit Fit start and end
GLOBAL packing Fit packing
forward / backward Histogram grouping
COMMANDS Minimizer, errors, objective, strategy, Save
PLOT Plot time and Y ranges, view packing, log axes, lifetime correction, RRF
FOURIER Units, power, apodization, display type, phase and ranges

Instrument and year are inferred only from recognized PSI filename patterns. Conflicting years, instruments, beamlines, GLOBAL/PLOT fit types, or incompatible histogram layouts generate a warning and leave the affected GUI field unchanged.

For example, two RUN blocks using 2026/lem26_his_2321 with forward 21 25 and forward 23 27 become:

Run:         2321
Year:        2026
Instrument:  LEM
Histograms:  21 25,23 27

2. Reconstructing the fit model

The GUI model catalogue is funcDictionary. Each entry contains the THEORY lines emitted by one GUI component, for example:

GaussianCos:
    asymmetry Asy
    simpleGss Sgm
    TFieldCos Phi Frq

The importer splits the MSR THEORY block at + separators. Each component is matched against the catalogue using the ordered sequence of theory-function names and argument counts. Numeric parameter references are deliberately ignored during this signature comparison because their indices are file-specific.

A component is accepted only when exactly one catalogue entry matches. This prevents an arbitrary userFcn or a modified theory expression from being silently converted to a different GUI model.

THEORY references

After identifying the component, every catalogue placeholder is paired with its MSR reference:

MSR reference Interpretation
3 FITPARAMETER 3 supplies this model parameter
fun1 FUNCTION 1 calculates this model parameter
map1 RUN map slot 1 supplies detector-dependent parameters

For multiple GUI components, the normal GUI suffixing is applied (Asy1, Asy2, Phi1, Phi2, and so on).

Detector phase maps in THEORY

For a Single Hist model containing a direct phase map such as:

TFieldCos map1 fun1

the RUN blocks determine the concrete phase parameter for each detector group. The GUI represents these as Phi, PhiH2, PhiH3, etc. Regeneration assigns a map slot and writes the newly calculated parameter number into every RUN block.

Only detector-dependent phase maps are currently reconstructed this way. Other Single Hist THEORY maps are rejected because the GUI has no general control for their detector-dependent meaning.

3. Reconstructing FUNCTIONS and custom parameters

The target of each funN is inferred from where it is used:

  • a THEORY argument identifies a physical model parameter such as Frq or Phi;
  • RUN norm funN identifies a detector normalization such as No3;
  • a RUN-level alpha reference identifies Alpha.

Within the right-hand side, parN is replaced with the semantic GUI parameter name associated with FITPARAMETER N. A file containing:

TFieldCos map1 fun1
fun1 = gamma_mu * par3

can therefore become:

Frq = gamma_mu * Field

Any FITPARAMETER not consumed directly by the selected model or a RUN directive is retained as a custom GUI parameter. This preserves auxiliary quantities such as Field, AlphaLR, Ph, or fixed detector offsets.

Maps used inside FUNCTIONS

Some MSRs calculate a model parameter from a common value plus a detector map:

TFieldCos fun1 fun2
fun1 = par3 + map1

For Single Hist fits, the importer stores both parts of this relationship:

  • the GUI constraint, for example Phi = Ph + map1;
  • the ordered parameters that populate map1 in the RUN blocks.

For 2249_tf_histo.msr, the preserved mapping is:

RUN/histogram map1 parameter
21 25 RelPh_L
22 26 RelPh_T
23 27 RelPh_R
24 28 RelPh_B

This mapping is stored with the imported model. When the MSR is regenerated, buildModelBlocks() resolves these names against the new FITPARAMETER order and writes the correct new indices. It never copies obsolete numeric indices from the original file.

The imported map state is cleared when the user changes the theory or histogram layout, because the original detector-to-parameter association may no longer be valid.

4. Mapping parameter values into the GUI

parseMSRParameters() accepts both input and fitted FITPARAMETER layouts. For a fitted file it retains the value, step/error, and optional bounds; the additional positive-error column written by musrfit is not mistaken for a lower bound.

Non-finite tokens are never carried into the GUI or a generated MSR. A fitted NaN value keeps the GUI's last good value (the parsed value is dropped), a NaN step becomes 1% of the value, and NaN/inf bounds are removed. The same guard applies at generation time, so a stale NaN in the parameter table can never leak into a regenerated file.

Parameter values are assigned by semantic role rather than by the original name. This is important for older MSRs whose naming conventions differ from the current GUI.

Examples from 2321_singleHist(1).msr include:

Original parameter GUI parameter
N0L No1
NBgL NBg1
PhiL Phi
NBgR NBg2
PhiR PhiH2
Field Custom parameter Field
AlphaLR Custom parameter AlphaLR

For a single physical run, the GUI's normal filename-derived run suffix is added when locating the parameter-table row, for example PhiH2_2321. This lets a legacy unsuffixed fitted file populate the current run-qualified table.

5. t0 and background synchronization

The RUN blocks are parsed separately for:

  • t0
  • background
  • backgr.fix
  • backgr.fit

The importer first validates the complete set of RUN blocks and only then mutates GUI state. It checks the expected number of RUN rows, the value count required by Single Hist or Asymmetry mode, and that mutually exclusive background directives are not combined.

Equal values across all RUN blocks are stored in the GUI's common fields. Different values are stored as per-row overrides. This preserves the compact GUI representation without losing genuine run-to-run differences.

A multi-group asymmetry fit (one physical run, several forward/backward groups in the Histograms field, e.g. 1,2/3,4) shares the single GUI row of that run, so fields carry one space-separated token per group in group order. Agreeing values collapse into the tab's common fields. The read-back validates before it mutates: t0 presence must be uniform, the background mode must be identical across groups, and good-bin data ranges must be present for every group; any inconsistency leaves the previously stored GUI values untouched (failing closed, per the design principles), because a missing token would silently shift every later group's value.

6. Regeneration rules

After synchronization, generating an MSR uses the ordinary GUI builders. The important invariants are:

  • every non-function model parameter receives a current FITPARAMETER number;
  • constrained parameters receive funN references;
  • norm, fitted-background, and alpha RUN directives may reference either a numeric parameter or funN;
  • direct detector phases and maps inside FUNCTIONS are rebuilt using current parameter numbers;
  • no RUN line may contain undefined;
  • function and parameter numbering may differ from the source MSR while the mathematical relationships remain equivalent.

For the two current synchronization examples this gives:

2321_singleHist(1).msr

  • model: GaussianCos;
  • Frq = gamma_mu * Field;
  • No2 = No1 * AlphaLR;
  • two detector phase parameters selected through a RUN map;
  • the second normalization regenerates as norm fun2.

2249_tf_histo.msr

  • model: ExponentialCos;
  • Phi = Ph + map1;
  • Frq = gamma_mu * Field;
  • No3 = No1 * alpha_LR;
  • No4 = No2 * alpha_TB;
  • four fixed relative phases remain coupled to the common fitted phase.

Unsupported or deliberately conservative cases

Case Current behavior
THEORY component absent from funcDictionary Leave THEORY editor-owned
Ambiguous catalogue match Reject theory synchronization
Multi-run/global THEORY sharing Reject rather than guess shared flags/maps
Function par(...) or parR(...) references Reject theory synchronization
Function-to-function references Reject theory synchronization
Function maps in Asymmetry mode Reject; currently supported only for Single Hist
Conflicting or incomplete RUN maps Reject theory synchronization
Conflicting instrument/year/fit-type metadata Leave affected direct fields unchanged and warn

Even when THEORY synchronization is rejected, independently recognized settings can still be imported. The editor remains authoritative, so the unsupported MSR text is not overwritten by a partial GUI reconstruction.

Regression coverage

The JavaScript tests cover:

  • direct settings and RUN/ADDRUN parsing;
  • model-catalogue reconstruction;
  • legacy-to-semantic parameter mapping;
  • direct detector phase maps;
  • maps embedded in FUNCTIONS;
  • function-based detector normalization (norm funN);
  • semantic regeneration with renumbered parameters;
  • rejection of unsupported THEORY and incomplete mappings;
  • absence of undefined in regenerated RUN blocks.

The synchronization tests are part of tests/msr-generation.test.js; reusable MSR fragments live under tests/fixtures/.