diff --git a/muSRFitlib.js b/muSRFitlib.js index 0f2a721..4b418ef 100644 --- a/muSRFitlib.js +++ b/muSRFitlib.js @@ -879,6 +879,11 @@ for (let key in funcDictionary) { const defVals = { Asy : { value : 0.22}, + // Fixed unit ratio for the first group of a multi-group asymmetry fit; + // the step is pinned to zero so the parameter never floats. + One : { + value : 1.0, + err : 0}, Alpha : { value : 1.0}, No : { @@ -4065,7 +4070,24 @@ function parseMSRGUISettings(msrText) { if (runBlock.forward === null || runBlock.backward === null) return ""; return runBlock.forward + "," + runBlock.backward; })); - if (layouts.length == 1) remember("LRBF", layouts[0]); + if (layouts.length == 1) { + remember("LRBF", layouts[0]); + } else { + // Several RUN blocks that share one physical file and each carry a + // forward and backward pair are the per-group RUN blocks of a + // multi-group asymmetry fit, so rebuild the "1,2/3,4" histogram list. + let files = uniqueMSRValues(runBlocks.map(function(runBlock) { + return runBlock.fileToken; + })); + if (files.length == 1 && runBlocks.length > 1 + && runBlocks.every(function(runBlock) { + return runBlock.forward !== null && runBlock.backward !== null; + })) { + remember("LRBF", runBlocks.map(function(runBlock) { + return runBlock.forward + "," + runBlock.backward; + }).join("/")); + } + } } } @@ -4526,6 +4548,12 @@ function parseMSRTheoryModel(msrText) { parsed.error = "Multi-run THEORY sharing cannot yet be reconstructed safely."; return parsed; } + // Several RUN blocks sharing one physical file that carry a phase map and an + // alpha describe a multi-group asymmetry fit: one forward,backward pair per + // group run on a single run (LRBF "1,2/3,4"). THEORY-mapped values then get + // per-group GUI suffixes like Phi1, Phi2, and every block's alpha its AlphaG. + let multiGroup = fitType === 2 && distinctRunFiles.length === 1 + && runBlocks.length > 1; let histogramCounts = Object.create(null); for (let runBlock of runBlocks) { let runKey = runBlock.fileToken || "run"; @@ -4542,6 +4570,8 @@ function parseMSRTheoryModel(msrText) { return parsed; } targetName += "H" + histogramIndex; + } else if (multiGroup) { + targetName += histogramIndex; } if (!assignImportedParameterTarget(parsed, parameterNo, targetName)) return parsed; } @@ -4567,8 +4597,9 @@ function parseMSRTheoryModel(msrText) { } } else if (fitType === 2 && runBlock.alpha) { let alphaFunction = runBlock.alpha.match(/^fun(\d+)$/i); - if (alphaFunction) functionTargets[alphaFunction[1]] = "Alpha"; - else if (!assignImportedParameterTarget(parsed, runBlock.alpha, "Alpha")) return parsed; + let alphaTarget = multiGroup ? "Alpha" + histogramIndex : "Alpha"; + if (alphaFunction) functionTargets[alphaFunction[1]] = alphaTarget; + else if (!assignImportedParameterTarget(parsed, runBlock.alpha, alphaTarget)) return parsed; } } @@ -4627,10 +4658,16 @@ function parseMSRTheoryModel(msrText) { return match[1]; }) ); - if (expressionMapNumbers.length > 0 && fitType !== 0) { - parsed.error = "FUNCTIONS maps are currently represented only for SingleHist fits."; + if (expressionMapNumbers.length > 0 && fitType !== 0 && !multiGroup) { + parsed.error = "FUNCTIONS maps are currently represented only for SingleHist or multi-group asymmetry fits."; return parsed; } + // The amplitude function generated for a multi-group asymmetry fit scales + // the free amplitude Asy1 with the ratio selected by each RUN block + // (funN = Asy1 * map1). Validate it structurally but keep it out of the + // GUI constraints: the generator rebuilds it automatically, and the + // dropdown offers Asy1 as a parameter rather than Asy as a function. + let isAmplitudeFunction = multiGroup && target == "Asy"; for (let mapNo of expressionMapNumbers) { let mappedParameters = []; for (let runBlock of runBlocks) { @@ -4649,11 +4686,13 @@ function parseMSRTheoryModel(msrText) { parsed.error = "map" + mapNo + " has conflicting FUNCTION meanings."; return parsed; } + if (isAmplitudeFunction) continue; parsed.functionMaps[mapNo] = { target: target, parameters: mappedParameters }; } + if (isAmplitudeFunction) continue; parsed.constraints.push({ target: target, expression: expression }); } for (let functionNo in functionTargets) { @@ -8071,7 +8110,38 @@ function cfgConstraints() { if (fitFunc && fitFunc != "") { let pars = funcDictionary[fitFunc].pars.slice(); if ((All.fitAsyType == "Asymmetry" || All.fitAsyType == "AsymmetryGLB") && i == 1 ) { - pars.unshift("Alpha"); + let multiAsyGroups = multiAsymmetryGroupCount(All); + if (multiAsyGroups > 0) { + // A multi-group asymmetry fit has one forward,backward pair per group + // for the same physical run (LRBF "1,2/3,4"). Physical parameters are + // shared and stay on top, then every group gets an alpha, ratios + // scale the free amplitude Asy1 (r_g * Asy1, group 1 always the fixed + // factor One), and finally one phase per group when the model has one. + let multiPars = []; + let phaseSeen = false; + for (let modelPar of pars) { + if (modelPar == "Phi") { + phaseSeen = true; + continue; + } + multiPars.push(modelPar == "Asy" ? "Asy1" : modelPar); + } + for (let groupNo = 1; groupNo <= multiAsyGroups; groupNo++) { + multiPars.push("Alpha" + groupNo); + } + multiPars.push("One"); + for (let groupNo = 2; groupNo <= multiAsyGroups; groupNo++) { + multiPars.push("r" + groupNo); + } + if (phaseSeen) { + for (let groupNo = 1; groupNo <= multiAsyGroups; groupNo++) { + multiPars.push("Phi" + groupNo); + } + } + pars = multiPars; + } else { + pars.unshift("Alpha"); + } } else if (All.fitAsyType == "SingleHist") { // A single-histogram fit has one RUN block per histogram group. N0 and // background belong to the detector histogram, while physical model @@ -8130,6 +8200,12 @@ function updateTheoryBlock() { for (let par of funcDictionary[fitFunc].pars.slice()) { theoryBlk1 = theoryBlk1.replace(par,par+i); } + } else if (isMultiAsymmetryFit(All)) { + // Multi-group asymmetry fits name the free amplitude Asy1 so the + // parameter list can distinctively suffix per-group copies; the + // fit-time THEORY block replaces it with the generated amplitude + // function. + theoryBlk1 = theoryBlk1.replace("Asy", "Asy1"); } theoryBlock += theoryBlk1; } @@ -9261,8 +9337,10 @@ let tdParNum = trPar.insertCell(-1); } } else { let defVal = defVals[cparName] ? defVals[cparName].value : 1.0; + let defErr = defVals[cparName] && defVals[cparName].err !== undefined + ? defVals[cparName].err : defVal * 0.01; All["val" + parName] = defVal; - All["err" + parName] = defVal * 0.01; + All["err" + parName] = defErr; All["min" + parName] = ""; All["max" + parName] = ""; } @@ -9612,12 +9690,64 @@ function replaceWord(str, word, replacement) { return str.replace(regex, replacement); } +function parseAsymmetryGroups(lrbf) { + // Slash-separated forward,backward pairs describe several asymmetry groups + // fitted to the same physical run, e.g. "1,2/3,4". The ordinary grouped + // layout "21 25,23 27" has no slash and does not match. + if (typeof lrbf !== "string" || lrbf.indexOf("/") < 0) { + return null; + } + let groups = lrbf.split("/").map(function(group) { + let pair = group.split(","); + if (pair.length !== 2) return null; + let forward = pair[0].trim(); + let backward = pair[1].trim(); + if (forward === "" || backward === "") return null; + return { forward: forward, backward: backward }; + }); + if (groups.some(function(group) { return group === null; })) { + return null; + } + return groups; +} + +function multiAsymmetryGroupCount(all) { + // Number of asymmetry groups fitted to one run ("1,2/3,4"), or 0 when the + // current configuration is not a multi-group asymmetry fit. Multi-component + // models are out of scope for now, as are the per-run forward/backward pairs + // of a global (multi-run) asymmetry fit. + all = all || {}; + let fitTypeText = all.fitAsyType; + if (fitTypeText !== "Asymmetry" && fitTypeText !== "AsymmetryGLB") { + return 0; + } + if (all.numComps !== undefined && all.numComps !== null + && String(all.numComps) !== "1") { + return 0; + } + let groups = parseAsymmetryGroups(all.LRBF); + if (!groups || groups.length < 2) { + return 0; + } + return groups.length; +} + +function isMultiAsymmetryFit(all) { + return multiAsymmetryGroupCount(all) > 0; +} + function buildModelBlocks(config, fitType) { let all = config.all || {}; let funOptions = config.funOptions || []; let funLines = config.funLines || []; let sharedFlags = config.sharedFlags || {}; + // Multi-group asymmetry fits ("1,2/3,4") generate one RUN block per group + // for the same physical run through a dedicated builder. + if (isMultiAsymmetryFit(all)) { + return buildMultiAsymmetryModelBlocks(config, fitType); + } + // THEORY block let theoryBlk = all.theoFunBlock; @@ -9839,6 +9969,245 @@ function buildModelBlocks(config, fitType) { }; } +function multiGroupT0BgGroupValue(all, fieldName, rowIndex, groupIndex, commonAllowed) { + // Multi-group asymmetry fits share one physical run across several + // forward,backward pairs. Row-level t0/background/data-range values may be + // entered space-separated per group ("0.1 0.12"); a single value applies to + // every group. Common (shared) fields mirror the same fallback behavior as + // the ordinary fitType-2 path. + let raw = readT0BgField(all, fieldName, rowIndex); + if (raw === "" && commonAllowed) { + raw = readT0BgCommonField(all, fieldName); + } + let tokens = String(raw || "").trim().split(/\s+/).filter(Boolean); + if (tokens.length === 0) return ""; + if (groupIndex < tokens.length) return tokens[groupIndex]; + return tokens[0]; +} + +function buildMultiGroupT0BgRunLines(all, fitType, groupIndex) { + if (fitType !== 2) { + return buildT0BgRunLines(all, fitType, groupIndex); + } + let lines = []; + let t0Forward = multiGroupT0BgGroupValue(all, "T0F", 0, groupIndex, true); + let t0Backward = multiGroupT0BgGroupValue(all, "T0B", 0, groupIndex, true); + if (t0Forward !== "" && t0Backward !== "") { + lines.push("t0 " + t0Forward + " " + t0Backward); + } + + let rowMode = readT0BgField(all, "BgMode", 0); + let commonMode = readT0BgCommonField(all, "BgMode"); + if (commonMode === "") commonMode = defaultT0BgMode(fitType); + let bgMode = t0BgModeForRow(all, fitType, 0); + let rowCanOverrideBg = rowMode !== "" && rowMode != "common"; + if (bgMode == "range") { + let fStart = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgFStart", 0, groupIndex, false) : ""; + let fEnd = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgFEnd", 0, groupIndex, false) : ""; + let bStart = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgBStart", 0, groupIndex, false) : ""; + let bEnd = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgBEnd", 0, groupIndex, false) : ""; + if (fStart === "" && commonMode == bgMode) fStart = multiGroupT0BgGroupValue(all, "BgFStart", 0, groupIndex, true); + if (fEnd === "" && commonMode == bgMode) fEnd = multiGroupT0BgGroupValue(all, "BgFEnd", 0, groupIndex, true); + if (bStart === "" && commonMode == bgMode) bStart = multiGroupT0BgGroupValue(all, "BgBStart", 0, groupIndex, true); + if (bEnd === "" && commonMode == bgMode) bEnd = multiGroupT0BgGroupValue(all, "BgBEnd", 0, groupIndex, true); + if (fStart !== "" && fEnd !== "" && bStart !== "" && bEnd !== "") { + lines.push("background " + fStart + " " + fEnd + " " + bStart + " " + bEnd); + } + } else if (bgMode == "fixed") { + let fixedForward = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgFixF", 0, groupIndex, false) : ""; + let fixedBackward = rowCanOverrideBg ? multiGroupT0BgGroupValue(all, "BgFixB", 0, groupIndex, false) : ""; + if (fixedForward === "" && commonMode == bgMode) fixedForward = multiGroupT0BgGroupValue(all, "BgFixF", 0, groupIndex, true); + if (fixedBackward === "" && commonMode == bgMode) fixedBackward = multiGroupT0BgGroupValue(all, "BgFixB", 0, groupIndex, true); + if (fixedForward !== "" && fixedBackward !== "") { + lines.push("backgr.fix " + fixedForward + " " + fixedBackward); + } + } + + let dataFStart = multiGroupT0BgGroupValue(all, "DataFStart", 0, groupIndex, true); + let dataFEnd = multiGroupT0BgGroupValue(all, "DataFEnd", 0, groupIndex, true); + let dataBStart = multiGroupT0BgGroupValue(all, "DataBStart", 0, groupIndex, true); + let dataBEnd = multiGroupT0BgGroupValue(all, "DataBEnd", 0, groupIndex, true); + if (dataFStart !== "" && dataFEnd !== "" && dataBStart !== "" && dataBEnd !== "") { + lines.push("data " + dataFStart + " " + dataFEnd + " " + dataBStart + " " + dataBEnd); + } + return lines; +} + +function buildMultiAsymmetryModelBlocks(config, fitType) { + let all = config.all || {}; + let funOptions = config.funOptions || []; + let funLines = config.funLines || []; + let sharedFlags = config.sharedFlags || {}; + let groups = parseAsymmetryGroups(all.LRBF) || []; + let numGroups = groups.length; + + // THEORY block. The model declares the free amplitude as Asy1; normalize any + // legacy plain "Asy" placeholder so files import/regenerate the same shape. + let theoryBlk = replaceWord(all.theoFunBlock, "Asy", "Asy1"); + + let runs = arrayRunNumbers(all.runNumbers); + let runLine = runFileNameAuto(runs[0], all.selYear, all.instrName, all.dataRoot); + + // Comments and order captured from an imported MSR's FITPARAMETER block are + // replayed during regeneration so the round-trip keeps the file's structure: + // each emitted parameter re-attaches the leading comments of its imported + // counterpart, and any block-level trailing comments land after the last line. + let importedComments = null; + if (Array.isArray(importedMSRFitParameterOrder) + && Array.isArray(importedMSRFitParameterComments)) { + importedComments = Object.create(null); + for (let index = 0; index < importedMSRFitParameterOrder.length; index++) { + if (importedMSRFitParameterOrder[index] in importedComments) continue; + importedComments[importedMSRFitParameterOrder[index]] = importedMSRFitParameterComments[index].before; + } + } + let importedTrailingComments = []; + if (Array.isArray(importedMSRFitParameterOrder) + && Array.isArray(importedMSRFitParameterComments) + && importedMSRFitParameterOrder.length + && importedMSRFitParameterComments[importedMSRFitParameterComments.length - 1]) { + let last = importedMSRFitParameterComments[importedMSRFitParameterComments.length - 1]; + if (Array.isArray(last.after)) importedTrailingComments = last.after; + } + + let parameterNumbers = Object.create(null); + let amplitudeNumber = null; + let alphaNumbers = []; + let ratioNumbers = []; + let phaseNumbers = []; + let phaseMapNo = null; + + let i = 1; + let paramBlk = ""; + let ifun = 0; + let funBlock = ""; + for (let funLine of funLines) { + funBlock += funLine + "\n"; + } + + for (let opt of funOptions) { + let parName = opt.value; + if (opt.disabled) { + // A user function replaces this parameter everywhere. + ifun++; + let functionReference = "fun" + ifun; + funBlock = replaceAllWords(funBlock, parName, functionReference); + theoryBlk = replaceAllWords(theoryBlk, parName, functionReference); + let alphaMatch = parName.match(/^Alpha(\d+)$/); + if (alphaMatch) { + alphaNumbers[parseInt(alphaMatch[1], 10) - 1] = functionReference; + } + continue; + } + + let cparName = defaultParameterKey(parName); + let isAmplitude = /^Asy\d+$/.test(parName) && amplitudeNumber === null; + let parLine = " " + i + " " + parName; + let shPar = runs.length > 1 && !!sharedFlags[parName]; + if (!shPar) { + let suf = runSuffixFromFile(runs[0], all.instrName, all.selYear, all.dataRoot); + parLine += "_" + suf; + } + let msrParName = parLine.trim().split(/\s+/)[1]; + let defVal = cparName == "One" + ? 1.0 : (defVals[cparName] ? defVals[cparName].value : 1.0); + let value = all["val" + msrParName] ?? all["val" + parName] ?? defVal; + let step = all["err" + msrParName] ?? all["err" + parName] ?? (defVal * 0.01); + let min = all["min" + msrParName] ?? all["min" + parName] ?? ""; + let max = all["max" + msrParName] ?? all["max" + parName] ?? ""; + + parameterNumbers[parName] = i; + + if (isAmplitude) { + // The amplitude is a normal fit parameter, but THEORY/FUNCTIONS point + // the asymmetry line at a generated function funN = parN * map1, where + // each group's RUN block selects its ratio through map1. + amplitudeNumber = i; + funBlock = replaceWord(funBlock, parName, "par" + i); + } else { + theoryBlk = replaceWord(theoryBlk, parName, i); + funBlock = replaceWord(funBlock, parName, "par" + i); + } + + if (cparName == "One") { + // Group 1's ratio is the fixed identity. Keep the parameter present so + // group-1 RUN blocks can reference it through map1. + ratioNumbers[0] = i; + value = 1.0; + step = 0; + min = ""; + max = ""; + } else if (/^r\d+$/.test(parName)) { + ratioNumbers[parseInt(parName.slice(1), 10) - 1] = i; + } else if (/^Alpha\d+$/.test(parName)) { + alphaNumbers[parseInt(parName.slice(5), 10) - 1] = i; + } else if (/^Phi\d+$/.test(parName)) { + // The phase goes through map2 for every group; slot 1 holds the ratio + // map. Reserve the phase slot only when the model really uses Phi. + let groupIndex = parseInt(parName.slice(3), 10) - 1; + phaseNumbers[groupIndex] = i; + if (phaseMapNo === null) { + let withPhase = replaceWord(theoryBlk, "Phi", "map2"); + if (withPhase !== theoryBlk) { + theoryBlk = withPhase; + phaseMapNo = 2; + } + } + } + + parLine = formatFitParameterLine(i, msrParName, value, step, min, max); + if (importedComments && importedComments[parName]) { + for (let text of importedComments[parName]) paramBlk += text + "\n"; + } + paramBlk += parLine; + i++; + } + for (let text of importedTrailingComments) paramBlk += text + "\n"; + + if (amplitudeNumber === null) { + throw new Error("A multi-group asymmetry fit requires an amplitude parameter (e.g. Asy1)."); + } + + // The asymmetry amplitude function is generated after any user functions. + let amplitudeFunctionNo = ifun + 1; + theoryBlk = replaceAllWords(theoryBlk, "Asy1", "fun" + amplitudeFunctionNo); + funBlock += "fun" + amplitudeFunctionNo + " = par" + amplitudeNumber + " * map1\n"; + + let runBlk = ""; + for (let groupIndex = 0; groupIndex < numGroups; groupIndex++) { + let group = groups[groupIndex]; + let runLines = [runLine]; + let alphaReference = alphaNumbers[groupIndex]; + if (alphaReference) runLines.push("alpha " + alphaReference); + runLines.push("forward " + group.forward); + runLines.push("backward " + group.backward); + + // map1 selects the group's amplitude ratio (One for the first group), + // map2 selects the group's phase when the model contains one. + let mapValues = []; + if (ratioNumbers[groupIndex] !== undefined) mapValues[0] = ratioNumbers[groupIndex]; + if (phaseMapNo !== null && phaseNumbers[groupIndex] !== undefined) { + mapValues[phaseMapNo - 1] = phaseNumbers[groupIndex]; + } + if (mapValues.length > 0) { + for (let mapIndex = 0; mapIndex < mapValues.length; mapIndex++) { + if (!mapValues[mapIndex]) mapValues[mapIndex] = 0; + } + runLines.push("map " + mapValues.join(" ")); + } + runLines = runLines.concat(buildMultiGroupT0BgRunLines(all, fitType, groupIndex)); + runBlk += runLines.join("\n"); + runBlk += "\n"; + } + + return { + parameterBlock: paramBlk, + theoryBlock: theoryBlk, + functionsBlock: funBlock, + runBlock: runBlk + }; +} + function renderMSRTemplate(blocks) { let msrFile = msrTemplate; let replacements = { diff --git a/tests/fixtures/reference/multiasym.generated.msr b/tests/fixtures/reference/multiasym.generated.msr new file mode 100644 index 0000000..36cfb99 --- /dev/null +++ b/tests/fixtures/reference/multiasym.generated.msr @@ -0,0 +1,66 @@ + +# Run Numbers: 2452 +############################################################### +FITPARAMETER +############################################################### +# No Name Value Step PosErr Min Max + 1 Asy1_2452 0.09 0.01 + 2 Lam_2452 0.5 0.01 none 0.0 5.0 + 3 Frq_2452 1.3 0.01 + 4 Alpha1_2452 0.9 0.01 + 5 Alpha2_2452 0.95 0.01 + 6 One_2452 1 0 + 7 r2_2452 0.4 0.01 + 8 Phi1_2452 16.9 0.8 + 9 Phi2_2452 5.7 0.8 + +############################################################### +THEORY +asymmetry fun1 +simplExpo 2 +TFieldCos map2 3 +############################################################### +FUNCTIONS +fun1 = par1 * map1 +############################################################### + +GLOBAL +fittype 2 +fit 0.07 9 +packing 50 + +############################################################### +RUN /mnt/fake/lem/his/2026/lem26_his_2452 MUE4 PSI MUSR-ROOT +alpha 4 +forward 1 +backward 2 +map 6 8 +RUN /mnt/fake/lem/his/2026/lem26_his_2452 MUE4 PSI MUSR-ROOT +alpha 5 +forward 3 +backward 4 +map 7 9 + +############################################################### +COMMANDS +MAX_LIKELIHOOD +MINIMIZE +HESSE +SAVE +############################################################### +PLOT 2 +runs 1 +range 0 11 -0.3 0.3 +view_packing 500 + +############################################################### +FOURIER +units Gauss +fourier_power 12 +dc-corrected FALSE +apodization STRONG +plot power +range 0 11 + +############################################################### +# Created by muSRFlow (Zaher Salman; GNU GPL version 3 or later; https://musruser.psi.ch/muSRFlow/) diff --git a/tests/integration-musrfit.test.js b/tests/integration-musrfit.test.js index 41c3e28..e70078b 100644 --- a/tests/integration-musrfit.test.js +++ b/tests/integration-musrfit.test.js @@ -31,7 +31,10 @@ const FAKE_DATA_ROOT = "/mnt/fake/lem/his/2026"; const singleRunWorkflows = { asymmetry: { expected: "39.776426" }, bounds: { expected: "60.869627" }, - t0background: { expected: "5.602355" } + t0background: { expected: "5.602355" }, + // Multi-group asymmetry fit: two forward,backward pairs from run 2452 are + // fitted as separate datasets through their own RUN blocks (LRBF "1,2/3,4"). + multiasym: { expected: "1.025906" } }; // Global fit: runs 2452-2460, template expanded by msr2data, then musrfit. diff --git a/tests/msr-generation.test.js b/tests/msr-generation.test.js index 9163977..4325440 100644 --- a/tests/msr-generation.test.js +++ b/tests/msr-generation.test.js @@ -3378,6 +3378,108 @@ function testApplyT0BgOverridesToMSRReplacesDataLines(lib) { assert.doesNotMatch(updated, /^data\s+100\s+200\s+300\s+400$/m); } +function testMultiAsymmetryRoundTrip(lib) { + const msr = fs.readFileSync( + path.join(__dirname, "fixtures", "reference", "multiasym.generated.msr"), "utf8" + ); + + // The two forward,backward groups of run 2452 reconstruct to the catalogue + // ExponentialCos model. The generated amplitude function fun1 = Asy1 * map1 + // is validated structurally but intentionally not exposed as an editable GUI + // constraint (the dropdown holds Asy1, not Asy), and its map is not stored + // as a user function map either: regeneration rebuilds it from the ratio list. + const theory = JSON.parse(JSON.stringify(lib.parseMSRTheoryModel(msr))); + assert.strictEqual(theory.ok, true); + assert.deepStrictEqual(theory.components, ["ExponentialCos"]); + assert.deepStrictEqual(theory.constraints, []); + assert.deepStrictEqual(theory.functionMaps, {}); + assert.deepStrictEqual(theory.customParameters, ["Asy1", "One", "r2"]); + assert.strictEqual(theory.parameterTargets["1"], "Asy1"); + assert.strictEqual(theory.parameterTargets["4"], "Alpha1"); + assert.strictEqual(theory.parameterTargets["5"], "Alpha2"); + assert.strictEqual(theory.parameterTargets["6"], "One"); + assert.strictEqual(theory.parameterTargets["7"], "r2"); + assert.strictEqual(theory.parameterTargets["8"], "Phi1"); + assert.strictEqual(theory.parameterTargets["9"], "Phi2"); + + // The GUI recovers the slash-separated forward,backward pair list. + const gui = JSON.parse(JSON.stringify(lib.parseMSRGUISettings(msr))); + assert.strictEqual(gui.values.fitAsyType, "AsymmetryGLB"); + assert.strictEqual(gui.values.LRBF, "1,2/3,4"); + assert.strictEqual(gui.values.runNumbers, "2452"); + assert.strictEqual(gui.values.selYear, "2026"); + assert.strictEqual(gui.values.instrName, "LEM"); + + // The fit-edit-fit loop regenerates an identical file. The GUI keeps its own + // data root (the MSR stores only instrument/year/run), so restore it here. + const all = {}; + all.theoFunBlock = "asymmetry Asy1\nsimplExpo Lam\nTFieldCos Phi Frq"; + const previousDocument = lib.document; + lib.document = undefined; + assert.strictEqual(lib.applyMSRGUISettings(gui, all), 1); + assert.strictEqual(lib.applyMSRTheoryModel(theory, all), 1); + lib.document = previousDocument; + all.dataRoot = "/mnt/fake"; + + const modelAll = JSON.parse(JSON.stringify(all)); + for (const parameter of lib.parseMSRParameters(msr)) { + const target = theory.parameterTargets[parameter.order] + "_2452"; + modelAll["val" + target] = parameter.value; + modelAll["err" + target] = parameter.error; + modelAll["min" + target] = parameter.min; + modelAll["max" + target] = parameter.max; + } + const regenerated = lib.buildMSR({ + all: modelAll, + funOptions: [ + { value: "Asy1", disabled: false }, + { value: "Lam", disabled: false }, + { value: "Frq", disabled: false }, + { value: "Alpha1", disabled: false }, + { value: "Alpha2", disabled: false }, + { value: "One", disabled: false }, + { value: "r2", disabled: false }, + { value: "Phi1", disabled: false }, + { value: "Phi2", disabled: false } + ], + funLines: [], + sharedFlags: {} + }); + assert.strictEqual(regenerated, msr); + + // The builder also normalizes a legacy plain "Asy" THEORY placeholder the + // way the catalogue plus updateTheoryBlock would produce it. + const blocks = lib.buildModelBlocks({ + all: { + fitAsyType: "AsymmetryGLB", + numComps: "1", + LRBF: "1,2/3,4", + theoFunBlock: "asymmetry Asy\nsimplExpo Lam\nTFieldCos Phi Frq", + runNumbers: "2452", + selYear: "2026", + instrName: "LEM", + dataRoot: "/mnt/fake" + }, + funOptions: [ + { value: "Asy1", disabled: false }, + { value: "Lam", disabled: false }, + { value: "Frq", disabled: false }, + { value: "Alpha1", disabled: false }, + { value: "Alpha2", disabled: false }, + { value: "One", disabled: false }, + { value: "r2", disabled: false }, + { value: "Phi1", disabled: false }, + { value: "Phi2", disabled: false } + ], + funLines: [], + sharedFlags: {} + }, 2); + assert.match(blocks.theoryBlock, /^asymmetry fun1$/m); + assert.match(blocks.theoryBlock, /^TFieldCos map2 3$/m); + assert.strictEqual(blocks.functionsBlock.trim(), "fun1 = par1 * map1"); + assert.doesNotMatch(blocks.runBlock, /undefined/); +} + const lib = loadLibrary(); testElectronPreferencesAndSuffixControls(lib); testInitialFrequencyGuess(lib); @@ -3404,6 +3506,7 @@ testSyncSingleHistogramDataRangeFromMSR(lib); testT0BgDataRangeValidation(lib); testApplyT0BgOverridesToMSRReplacesDataLines(lib); testParseMSRTheoryAndFunctions(lib); +testMultiAsymmetryRoundTrip(lib); testParseFunctionMappedDetectorPhases(lib); testFunctionExpressionValidation(lib); testParseMSRRunSelectionWithAddRun(lib); diff --git a/tests/reference-fixtures.test.js b/tests/reference-fixtures.test.js index 03637b4..78f8d9d 100644 --- a/tests/reference-fixtures.test.js +++ b/tests/reference-fixtures.test.js @@ -154,6 +154,56 @@ const fixtures = { ], sharedFlags: { Phi: true } }), + // Multi-group asymmetry workflow: two forward,backward pairs from run 2452 + // (LRBF "1,2/3,4"). The generator emits one RUN block per group with its own + // alpha and a map selecting ratio (map1) and phase (map2); the asymmetry + // line points at the generated amplitude function fun1 = Asy1 * map1. + "multiasym": withConfig({ + fitAsyType: "AsymmetryGLB", + Tis: "0.07", + Tfs: "9", + BINS: "50", + minType: "MINIMIZE", + fitObjective: "MAX_LIKELIHOOD", + fftUnits: "Gauss", + fftType: "power", + fftPhase: "", + fftPhaseCorrection: "off", + fftxi: "0", + fftxf: "11", + Tpis: "0", + Tpfs: "11", + Ypis: "-0.3", + Ypfs: "0.3", + VIEWBINS: "500", + theoFunBlock: "asymmetry Asy1\nsimplExpo Lam\nTFieldCos Phi Frq", + runNumbers: "2452", + selYear: "2026", + instrName: "LEM", + dataRoot: "/mnt/fake", + LRBF: "1,2/3,4", + valAsy1_2452: "0.09", errAsy1_2452: "0.01", + valLam_2452: "0.5", errLam_2452: "0.01", + valFrq_2452: "1.3", errFrq_2452: "0.01", + valAlpha1_2452: "0.9", errAlpha1_2452: "0.01", + valAlpha2_2452: "0.95", errAlpha2_2452: "0.01", + valOne_2452: "1", errOne_2452: "0", + valr2_2452: "0.4", errr2_2452: "0.01", + valPhi1_2452: "16.9", errPhi1_2452: "0.8", + valPhi2_2452: "5.7", errPhi2_2452: "0.8" + }, { + funOptions: [ + { value: "Asy1", disabled: false }, + { value: "Lam", disabled: false }, + { value: "Frq", disabled: false }, + { value: "Alpha1", disabled: false }, + { value: "Alpha2", disabled: false }, + { value: "One", disabled: false }, + { value: "r2", disabled: false }, + { value: "Phi1", disabled: false }, + { value: "Phi2", disabled: false } + ] + }), // SingleHist detector-normalization workflow: four histogram groups each // with its own No/NBg normalization and a detector-resolved phase, so the // RUN blocks carry norm + map rather than a single asymmetry forward count.