Add more logic for syncing complicated functions and maps.

This commit is contained in:
salman committed 2026-08-26 15:36:01 +02:00
1 parent 8898b26c9b
commit 0b0b685df2
3 files changed
+805 -54

No files matched your search

+493 -54
View File
@@ -1066,9 +1066,10 @@ function syncCurrentEditorToGUI() {
let text = getCurrentEditorText();
let source = window.MSREditor.activeSource;
let settingsSync = syncSettingsFromMSR(text);
let theorySync = syncTheoryFromMSR(text);
let parameterSync = syncParametersFromMSR(text);
let t0BgSync = syncT0BgFromMSR(text);
if (settingsSync || parameterSync || t0BgSync) {
if (settingsSync || theorySync || parameterSync || t0BgSync) {
// Sync remains intentionally conservative. It updates fields represented by
// the GUI but does not surrender editor ownership of either document.
acceptMSRTextAsKnown(text, source);
@@ -1222,9 +1223,9 @@ function uniqueMSRValues(values) {
}
function parseMSRGUISettings(msrText) {
// This first settings importer intentionally covers only values already
// represented directly by Runs-tab controls. THEORY and FUNCTIONS need a
// separate model reconstruction pass and remain editor-owned for now.
// Keep direct Runs-tab settings separate from THEORY/FUNCTIONS reconstruction
// so each importer can reject unsupported expert syntax without partially
// applying the other one's state.
let parsed = {
ok: true,
values: {},
@@ -1600,6 +1601,386 @@ function parseMSRParameters(msrText) {
return params;
}
function indexedTheoryParameterName(parameterName, componentIndex, componentCount) {
return componentCount > 1 ? parameterName + componentIndex : parameterName;
}
function theorySignature(theoryLines) {
return theoryLines.map(function(line) {
let parts = line.trim().split(/\s+/);
return parts[0].toLowerCase() + ":" + Math.max(0, parts.length - 1);
}).join("|");
}
function assignImportedParameterTarget(parsed, parameterNo, targetName) {
if (!/^\d+$/.test(String(parameterNo || "")) || !targetName) return false;
let existing = parsed.parameterTargets[parameterNo];
if (existing && existing != targetName) {
parsed.error = "Fit parameter " + parameterNo + " maps to both "
+ existing + " and " + targetName + ".";
return false;
}
parsed.parameterTargets[parameterNo] = targetName;
return true;
}
function parseMSRTheoryModel(msrText) {
// Reconstruct only models emitted by funcDictionary. Expert/custom THEORY
// remains editor-owned: guessing a merely similar model could silently change
// the fitted function when the GUI is regenerated.
let parsed = {
ok: false,
components: [],
constraints: [],
customParameters: [],
functionMaps: Object.create(null),
parameterTargets: Object.create(null),
error: "",
warnings: []
};
if (!msrText || typeof msrText !== "string") return parsed;
let fitParameters = parseMSRParameters(msrText);
let parameterByNo = Object.create(null);
for (let parameter of fitParameters) parameterByNo[parameter.order] = parameter;
let section = "";
let theoryComponents = [[]];
let functions = Object.create(null);
let runBlocks = [];
let currentRun = null;
let fitType = null;
for (let rawLine of msrText.split(/\r?\n/)) {
let line = rawLine.split("#", 1)[0].replace(/\s+\([^()]*\)\s*$/, "").trim();
if (line === "") continue;
let blockMatch = line.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b\s*(.*)$/i);
if (blockMatch) {
section = blockMatch[1].toUpperCase();
currentRun = null;
if (section == "RUN") {
currentRun = {
fileToken: (blockMatch[2].trim().split(/\s+/)[0] || ""),
map: [],
norm: "",
backgroundFit: "",
alpha: ""
};
runBlocks.push(currentRun);
}
continue;
}
if (section == "THEORY") {
if (/^\+$/.test(line)) {
if (theoryComponents[theoryComponents.length - 1].length === 0) {
parsed.error = "Empty THEORY component.";
return parsed;
}
theoryComponents.push([]);
} else {
theoryComponents[theoryComponents.length - 1].push(line);
}
} else if (section == "FUNCTIONS") {
let functionMatch = line.match(/^fun(\d+)\s*=\s*(.+)$/i);
if (!functionMatch || functions[functionMatch[1]]) {
parsed.error = "FUNCTIONS contains an unsupported or duplicate definition.";
return parsed;
}
functions[functionMatch[1]] = functionMatch[2].trim();
} else if (section == "GLOBAL") {
let fitTypeMatch = line.match(/^fittype\s+([02])\b/i);
if (fitTypeMatch) fitType = parseInt(fitTypeMatch[1], 10);
} else if (section == "RUN" && currentRun) {
let directiveMatch = line.match(/^(map|norm|backgr\.fit|alpha)\b\s*(.*)$/i);
if (!directiveMatch) continue;
let directive = directiveMatch[1].toLowerCase();
let values = directiveMatch[2].trim().split(/\s+/).filter(Boolean);
if (directive == "map") currentRun.map = values;
else if (directive == "norm") currentRun.norm = values[0] || "";
else if (directive == "backgr.fit") currentRun.backgroundFit = values[0] || "";
else if (directive == "alpha") currentRun.alpha = values[0] || "";
}
}
if (theoryComponents.length === 0
|| theoryComponents.some(function(component) { return component.length === 0; })) {
parsed.error = "THEORY is empty.";
return parsed;
}
let catalogue = Object.keys(funcDictionary).map(function(name) {
return {
name: name,
lines: funcDictionary[name].theoryBlk.split("\n"),
signature: theorySignature(funcDictionary[name].theoryBlk.split("\n"))
};
});
let functionTargets = Object.create(null);
let mapTargets = Object.create(null);
let resolvedMaps = Object.create(null);
for (let componentIndex = 0; componentIndex < theoryComponents.length; componentIndex++) {
let sourceLines = theoryComponents[componentIndex];
let matches = catalogue.filter(function(entry) {
return entry.signature == theorySignature(sourceLines);
});
if (matches.length != 1) {
parsed.error = "THEORY component " + (componentIndex + 1)
+ " is not represented uniquely by the GUI model catalogue.";
return parsed;
}
let match = matches[0];
parsed.components.push(match.name);
for (let lineIndex = 0; lineIndex < sourceLines.length; lineIndex++) {
let sourceParts = sourceLines[lineIndex].trim().split(/\s+/);
let templateParts = match.lines[lineIndex].trim().split(/\s+/);
for (let argumentIndex = 1; argumentIndex < sourceParts.length; argumentIndex++) {
let targetName = indexedTheoryParameterName(
templateParts[argumentIndex], componentIndex + 1, theoryComponents.length
);
let reference = sourceParts[argumentIndex];
let referenceMatch = reference.match(/^(\d+|map(\d+)|fun(\d+))$/i);
if (!referenceMatch) {
parsed.error = "Unsupported THEORY reference " + reference + ".";
return parsed;
}
if (/^\d+$/.test(reference)) {
if (!assignImportedParameterTarget(parsed, reference, targetName)) return parsed;
} else if (referenceMatch[2]) {
let mapNo = referenceMatch[2];
if (mapTargets[mapNo] && mapTargets[mapNo] != targetName) {
parsed.error = "map" + mapNo + " has more than one GUI meaning.";
return parsed;
}
mapTargets[mapNo] = targetName;
} else {
let functionNo = referenceMatch[3];
if (functionTargets[functionNo] && functionTargets[functionNo] != targetName) {
parsed.error = "fun" + functionNo + " has more than one GUI target.";
return parsed;
}
functionTargets[functionNo] = targetName;
}
}
}
}
// RUN maps provide the concrete fit-parameter number behind each THEORY map.
// In SingleHist files successive blocks for the same physical run correspond
// to detector groups, so phase maps become Phi, PhiH2, PhiH3, ... in the GUI.
let distinctRunFiles = uniqueMSRValues(runBlocks.map(function(runBlock) {
return runBlock.fileToken;
}));
if (distinctRunFiles.length > 1) {
parsed.error = "Multi-run THEORY sharing cannot yet be reconstructed safely.";
return parsed;
}
let histogramCounts = Object.create(null);
for (let runBlock of runBlocks) {
let runKey = runBlock.fileToken || "run";
histogramCounts[runKey] = (histogramCounts[runKey] || 0) + 1;
let histogramIndex = histogramCounts[runKey];
for (let mapNo in mapTargets) {
let parameterNo = runBlock.map[parseInt(mapNo, 10) - 1];
if (!parameterNo || parameterNo == "0") continue;
resolvedMaps[mapNo] = true;
let targetName = mapTargets[mapNo];
if (fitType === 0 && histogramIndex > 1) {
if (!/^Phi(?:\d+)?$/.test(targetName)) {
parsed.error = "Only detector-dependent phase maps are represented in SingleHist mode.";
return parsed;
}
targetName += "H" + histogramIndex;
}
if (!assignImportedParameterTarget(parsed, parameterNo, targetName)) return parsed;
}
if (fitType === 0) {
let detectorSuffix = String(histogramIndex);
for (let directive of [
{ reference: runBlock.norm, target: "No" + detectorSuffix },
{ reference: runBlock.backgroundFit, target: "NBg" + detectorSuffix }
]) {
if (!directive.reference) continue;
let functionMatch = directive.reference.match(/^fun(\d+)$/i);
if (functionMatch) {
let functionNo = functionMatch[1];
if (functionTargets[functionNo] && functionTargets[functionNo] != directive.target) {
parsed.error = "fun" + functionNo + " has more than one GUI target.";
return parsed;
}
functionTargets[functionNo] = directive.target;
} else if (!assignImportedParameterTarget(parsed, directive.reference, directive.target)) {
return parsed;
}
}
} 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;
}
}
for (let mapNo in mapTargets) {
if (!resolvedMaps[mapNo]) {
parsed.error = "map" + mapNo + " is not resolved by the RUN blocks.";
return parsed;
}
}
// Any fit parameter not consumed by the model/RUN semantics is a GUI custom
// parameter. Preserve its MSR name so function expressions stay meaningful.
for (let parameterNo in parsed.parameterTargets) {
if (!parameterByNo[parameterNo]) {
parsed.error = "THEORY or RUN references missing fit parameter " + parameterNo + ".";
return parsed;
}
}
for (let parameter of fitParameters) {
if (parsed.parameterTargets[parameter.order]) continue;
let customName = parameter.name.replace(/_\d+$/, "");
if (!/^[A-Za-z]\w*$/.test(customName)) {
parsed.error = "Fit parameter " + parameter.name + " is not a valid GUI parameter name.";
return parsed;
}
parsed.parameterTargets[parameter.order] = customName;
if (!parsed.customParameters.includes(customName)) parsed.customParameters.push(customName);
}
let functionNumbers = Object.keys(functions).sort(function(a, b) {
return parseInt(a, 10) - parseInt(b, 10);
});
for (let functionNo of functionNumbers) {
let target = functionTargets[functionNo];
if (!target) {
parsed.error = "fun" + functionNo + " is not connected to a GUI model or RUN field.";
return parsed;
}
let invalidParameterReference = false;
let expression = functions[functionNo].replace(/\bpar(\d+)\b/gi, function(full, parameterNo) {
let replacement = parsed.parameterTargets[parameterNo];
if (!replacement) invalidParameterReference = true;
return replacement || full;
});
if (invalidParameterReference || /\bparR?\s*\(/i.test(expression) || /\bfun\d+\b/i.test(expression)) {
parsed.error = "fun" + functionNo + " uses a reference not represented by GUI constraints.";
return parsed;
}
// A function may combine a common parameter with a detector-specific map,
// e.g. `fun1 = par3 + map1` for common plus relative phase. Preserve the
// concrete parameter behind that map in each RUN block so regeneration can
// rebuild the same function and RUN map instead of flattening the phases.
let expressionMapNumbers = uniqueMSRValues(
Array.from(expression.matchAll(/\bmap(\d+)\b/gi), function(match) {
return match[1];
})
);
if (expressionMapNumbers.length > 0 && fitType !== 0) {
parsed.error = "FUNCTIONS maps are currently represented only for SingleHist fits.";
return parsed;
}
for (let mapNo of expressionMapNumbers) {
let mappedParameters = [];
for (let runBlock of runBlocks) {
let parameterNo = runBlock.map[parseInt(mapNo, 10) - 1];
let parameterName = parsed.parameterTargets[parameterNo];
if (!parameterNo || parameterNo == "0" || !parameterName) {
parsed.error = "map" + mapNo + " in fun" + functionNo
+ " is not resolved by every RUN block.";
return parsed;
}
mappedParameters.push(parameterName);
}
let existingMap = parsed.functionMaps[mapNo];
if (existingMap && (existingMap.target != target
|| JSON.stringify(existingMap.parameters) != JSON.stringify(mappedParameters))) {
parsed.error = "map" + mapNo + " has conflicting FUNCTION meanings.";
return parsed;
}
parsed.functionMaps[mapNo] = {
target: target,
parameters: mappedParameters
};
}
parsed.constraints.push({ target: target, expression: expression });
}
for (let functionNo in functionTargets) {
if (!functions[functionNo]) {
parsed.error = "fun" + functionNo + " is referenced but not defined.";
return parsed;
}
}
parsed.ok = true;
return parsed;
}
function appendCustomParameterOptions() {
let funSel = document.getElementById("funSel");
if (!funSel) return;
let existing = new Set();
for (let option of funSel.options) existing.add(option.value);
for (let parameterName of customParams) {
if (existing.has(parameterName)) continue;
let option = document.createElement("option");
option.textContent = parameterName;
option.value = parameterName;
option.id = "fn" + parameterName;
funSel.appendChild(option);
}
}
function applyMSRTheoryModel(parsed, all = All) {
if (!parsed || !parsed.ok || parsed.components.length === 0 || !all) return(0);
all.numComps = String(parsed.components.length);
for (let key in all) {
if (/^fitFunc\d+$/.test(key)) delete all[key];
}
for (let index = 0; index < parsed.components.length; index++) {
all["fitFunc" + (index + 1)] = parsed.components[index];
}
if (parsed.functionMaps && Object.keys(parsed.functionMaps).length > 0) {
all.msrFunctionMaps = JSON.parse(JSON.stringify(parsed.functionMaps));
} else {
delete all.msrFunctionMaps;
}
if (typeof document === "undefined") return(1);
let countInput = document.getElementById("numComps");
let componentRows = document.getElementById("compRows");
let funBlock = document.getElementById("funBlock");
let funSel = document.getElementById("funSel");
let funInput = document.getElementById("funLine");
if (!countInput || !componentRows || !funBlock || !funSel || !funInput) return(0);
countInput.value = String(parsed.components.length);
renderFitComponents(parsed.components);
customParams = parsed.customParameters.slice();
funBlock.innerHTML = "";
updateTheoryBlock();
appendCustomParameterOptions();
for (let constraint of parsed.constraints) {
let targetOption = document.getElementById("fn" + constraint.target);
if (!targetOption || targetOption.disabled) return(0);
funSel.value = constraint.target;
funInput.value = constraint.expression;
addFunLine();
}
funInput.value = "";
updateCustomParamList();
let paramsTab = document.getElementById("Params");
if (paramsTab) paramsTab.innerHTML = "";
return(1);
}
function syncTheoryFromMSR(msrText, all = All) {
return applyMSRTheoryModel(parseMSRTheoryModel(msrText), all);
}
function parseMSRT0BgRunBlocks(msrText) {
// Keep the parser limited to directives represented by the t0/Bg tab. Other
// RUN settings remain editor-only and are deliberately ignored here.
@@ -1824,50 +2205,49 @@ function syncT0BgFromMSR(msrText, all = All) {
return(1);
}
function applyMSRParametersToGUI(params) {
function importedGUIParameterName(param, parameterTargets, all = All) {
let target = parameterTargets && parameterTargets[param.order]
? parameterTargets[param.order] : param.name;
let candidates = [target, param.name];
let runs = all && all.runNumbers ? arrayRunNumbers(all.runNumbers) : [];
if (runs.length == 1 && target.indexOf("_") < 0) {
let suffix = runSuffixFromFile(
runs[0], all.instrName || "", all.selYear || "", all.dataRoot || defaultDataRoot
);
candidates.unshift(target + "_" + suffix);
}
let rawBase = param.name.replace(/_\d+$/, "");
if (!candidates.includes(rawBase)) candidates.push(rawBase);
if (typeof document !== "undefined") {
for (let candidate of candidates) {
if (document.getElementById("val" + candidate)) return candidate;
}
}
return target;
}
function applyMSRParametersToGUI(params, parameterTargets) {
if (!params || params.length === 0) return(0);
// Rebuild the parameter table. cfgParams() calls prepCFG() which reads the
// DOM and may contain stale values, but we correct All and the fresh DOM
// inputs afterwards.
cfgParams();
for (let param of params) {
All["val" + param.name] = param.value;
All["err" + param.name] = param.error;
All["min" + param.name] = param.min;
All["max" + param.name] = param.max;
let el = document.getElementById("val" + param.name);
if (!el) {
// Per-run parameter name (e.g. "Alpha_0414") not found in shared table.
// Strip the run-number suffix and try the base name.
let baseName = param.name.replace(/_\d+$/, "");
if (baseName !== param.name) {
el = document.getElementById("val" + baseName);
}
}
// THEORY/RUN reconstruction supplies semantic aliases for legacy names.
// For example N0L and PhiR become No1 and PhiH2 in the current GUI model.
let guiName = importedGUIParameterName(param, parameterTargets, All);
All["val" + guiName] = param.value;
All["err" + guiName] = param.error;
All["min" + guiName] = param.min;
All["max" + guiName] = param.max;
let el = document.getElementById("val" + guiName);
if (el) el.value = param.value;
el = document.getElementById("err" + param.name);
if (!el) {
let baseName = param.name.replace(/_\d+$/, "");
if (baseName !== param.name) {
el = document.getElementById("err" + baseName);
}
}
el = document.getElementById("err" + guiName);
if (el) el.value = param.error;
el = document.getElementById("min" + param.name);
if (!el) {
let baseName = param.name.replace(/_\d+$/, "");
if (baseName !== param.name) {
el = document.getElementById("min" + baseName);
}
}
el = document.getElementById("min" + guiName);
if (el) el.value = param.min;
el = document.getElementById("max" + param.name);
if (!el) {
let baseName = param.name.replace(/_\d+$/, "");
if (baseName !== param.name) {
el = document.getElementById("max" + baseName);
}
}
el = document.getElementById("max" + guiName);
if (el) el.value = param.max;
}
setFitStatus("Updated parameter table from fitted MSR (" + params.length + " parameters).", true);
@@ -1876,7 +2256,10 @@ function applyMSRParametersToGUI(params) {
function syncParametersFromMSR(msrText) {
let params = parseMSRParameters(msrText);
let applied = applyMSRParametersToGUI(params);
let theory = parseMSRTheoryModel(msrText);
let applied = applyMSRParametersToGUI(
params, theory.ok ? theory.parameterTargets : null
);
if (applied) {
updateJobStatus({
parameterSync: "Updated from MSR (" + params.length + " parameters)"
@@ -2479,6 +2862,7 @@ function loadMSRIntoEditor(content, filePath = "", markClean = true, options = {
updateMSREditorSourceState();
if (options.syncGUI !== false) {
syncSettingsFromMSR(text);
syncTheoryFromMSR(text);
syncParametersFromMSR(text);
syncT0BgFromMSR(text);
}
@@ -2687,6 +3071,11 @@ function clearTabs(reinitializeInitialGuesses)
initialParameterGuessState.generation++;
}
// Detector maps embedded in imported FUNCTIONS describe the imported model.
// A user-initiated theory/histogram rebuild invalidates that hidden mapping;
// a fresh MSR synchronization installs a new one before rebuilding controls.
delete All.msrFunctionMaps;
// Clean up functions and sharing
document.getElementById("funBlock").innerHTML = "";
let shareTab = document.getElementById("Share");
@@ -3871,6 +4260,8 @@ function legalFunLine(funLine,params) {
for (let eqPart of funEqParts) {
// Allow parN format (e.g., par5) for direct parameter-number references
if (/^par\d+$/i.test(eqPart)) continue;
let mapMatch = eqPart.match(/^map(\d+)$/i);
if (mapMatch && All.msrFunctionMaps && All.msrFunctionMaps[mapMatch[1]]) continue;
if (isNaN(eqPart) && allComparisons.indexOf(eqPart) < 0) {
// Not a known term
noErr = false;
@@ -4041,7 +4432,12 @@ function cfgConstraints() {
pars.push("No"+iHist);
}
}
if (pars.includes("Phi")) {
let indexedPhaseName = All.numComps > 1 ? "Phi" + i : "Phi";
let functionMappedPhase = All.msrFunctionMaps
&& Object.keys(All.msrFunctionMaps).some(function(mapNo) {
return All.msrFunctionMaps[mapNo].target == indexedPhaseName;
});
if (pars.includes("Phi") && !functionMappedPhase) {
for (let iHist = 2; iHist <= hists.length; iHist++) {
pars.push("PhiH"+iHist);
}
@@ -5030,6 +5426,19 @@ function buildModelBlocks(config, fitType) {
// Holder for No and NBg maps, funs etc.
let n0Maps = new Object();
function rememberRunParameterReference(parName, reference) {
// Alpha, detector normalization, and fitted background are written in RUN
// directives rather than THEORY. They can point either to a fit-parameter
// number or to a funN constraint, so retain the resolved reference in both
// cases. Match the structural names exactly: a custom parameter such as
// AlphaLR must not accidentally become the RUN alpha reference.
if (parName == "Alpha") {
alphaLine += reference;
} else if (/^(?:No|NBg)\d+$/.test(parName)) {
n0Maps[parName] = reference;
}
}
// SingleHist detector groups can have different phases even though the rest
// of the physical model is shared. Keep a parameter-number lookup plus the
// ordered phase map slots so each RUN block can point mapN at its own Phi.
@@ -5037,6 +5446,13 @@ function buildModelBlocks(config, fitType) {
// msr2data is responsible for expanding the template to the selected runs.
let parameterNumbers = Object.create(null);
let singleHistPhaseMaps = [];
let importedFunctionMaps = all.msrFunctionMaps && typeof all.msrFunctionMaps === "object"
? all.msrFunctionMaps : {};
let occupiedMapNumbers = new Set(Object.keys(importedFunctionMaps).map(function(mapNo) {
return parseInt(mapNo, 10);
}).filter(function(mapNo) {
return Number.isInteger(mapNo) && mapNo > 0;
}));
// Parameter counter
let i = 1;
@@ -5055,8 +5471,10 @@ function buildModelBlocks(config, fitType) {
if (opt.disabled) {
// There is a function here, use it
ifun++;
funBlock = replaceAllWords(funBlock, parName, "fun"+ifun);
theoryBlk = replaceAllWords(theoryBlk, parName, "fun"+ifun);
let functionReference = "fun" + ifun;
funBlock = replaceAllWords(funBlock, parName, functionReference);
theoryBlk = replaceAllWords(theoryBlk, parName, functionReference);
rememberRunParameterReference(parName, functionReference);
} else {
let cparName = defaultParameterKey(parName);
// Replacement string in theoryBlck
@@ -5074,7 +5492,9 @@ function buildModelBlocks(config, fitType) {
if (singleHistPhase) {
// THEORY/FUNCTIONS must not point directly at the first detector's phase.
// A map slot lets each histogram RUN select its own phase parameter.
let mapNo = singleHistPhaseMaps.length + 1;
let mapNo = 1;
while (occupiedMapNumbers.has(mapNo)) mapNo++;
occupiedMapNumbers.add(mapNo);
rplcTh = "map" + mapNo;
rplcFn = "map" + mapNo;
singleHistPhaseMaps.push({ baseName: parName, mapNo: mapNo });
@@ -5101,14 +5521,8 @@ function buildModelBlocks(config, fitType) {
// mapN; RUN blocks need the actual fit-parameter number in their map line.
parameterNumbers[parName] = i;
// Prepare alpha line and for No and NBg lines
if (/Alpha/.test(parName)) {
alphaLine += rplcTh;
} else if (/No/.test(parName)) {
n0Maps[parName] = i;
} else if (/NBg/.test(parName)) {
n0Maps[parName] = i;
}
// Prepare RUN references for alpha, normalization, and fitted background.
rememberRunParameterReference(parName, rplcTh);
theoryBlk = replaceWord(theoryBlk, parName, rplcTh);
funBlock = replaceWord(funBlock, parName, rplcFn);
parLine = formatFitParameterLine(i, msrParName, value, step, min, max);
@@ -5134,15 +5548,40 @@ function buildModelBlocks(config, fitType) {
let t0BgLines = buildT0BgRunLines(all, fitType, iHist - 1, n0Maps["NBg"+iHist]);
let runLines = [runLine, n0Line, forwLine];
let mapValues = [];
if (singleHistPhaseMaps.length > 0) {
let mapValues = [];
for (let phaseMap of singleHistPhaseMaps) {
let phaseName = singleHistPhaseParameterForHistogram(phaseMap.baseName, iHist);
// Older/incomplete GUI state may not yet contain the extra detector
// phase. Reusing the first phase keeps the generated MSR valid; a normal
// constraints refresh creates the explicit PhiH<N> parameter.
let parameterNo = parameterNumbers[phaseName] || parameterNumbers[phaseMap.baseName];
mapValues.push(parameterNo);
mapValues[phaseMap.mapNo - 1] = parameterNo;
}
}
// Imported FUNCTIONS may refer to detector maps directly, for example a
// common phase plus a fixed detector-relative phase. Resolve each stored
// parameter name after numbering so the regenerated map follows the new
// FITPARAMETER order rather than copying obsolete numeric indices.
for (let mapNoText of Object.keys(importedFunctionMaps)) {
let mapNo = parseInt(mapNoText, 10);
let mapSpec = importedFunctionMaps[mapNoText];
let parameterName = mapSpec && mapSpec.parameters
? mapSpec.parameters[iHist - 1] : "";
let parameterNo = parameterNumbers[parameterName];
if (!Number.isInteger(mapNo) || mapNo < 1 || !parameterName || !parameterNo) {
throw new Error("Incomplete imported map" + mapNoText
+ " definition for histogram " + iHist + ".");
}
if (mapValues[mapNo - 1] && mapValues[mapNo - 1] != parameterNo) {
throw new Error("Conflicting map" + mapNo + " definition.");
}
mapValues[mapNo - 1] = parameterNo;
}
if (mapValues.length > 0) {
for (let mapIndex = 0; mapIndex < mapValues.length; mapIndex++) {
if (!mapValues[mapIndex]) mapValues[mapIndex] = 0;
}
runLines.push("map " + mapValues.join(" "));
}
+50
View File
@@ -0,0 +1,50 @@
FITPARAMETER
1 Asy 0.08185 -0.00086 0.00086
2 Lambda 0.2091 -0.0067 0.0067
3 Ph 13.51 -0.57 0.57
4 Field 75.922 -0.071 0.072
5 RelPh_L 0 0 none
6 N0_L 661.24 -0.47 0.47
7 N_bkg_L 2.470 -0.063 0.063
8 RelPh_T -90 0 none
9 N0_T 637.15 -0.46 0.46
10 N_bkg_T 2.402 -0.062 0.062
11 RelPh_R 180 0 none
12 alpha_LR 1.0464 -0.0011 0.0011
13 N_bkg_R 3.185 -0.066 0.066
14 RelPh_B 90 0 none
15 alpha_TB 1.0487 -0.0011 0.0011
16 N_bkg_B 2.882 -0.064 0.064
THEORY
asymmetry 1
simplExpo 2
TFieldCos fun1 fun2
FUNCTIONS
fun1 = par3 + map1
fun2 = gamma_mu * par4
fun3 = par6 * par12
fun4 = par9 * par15
GLOBAL
fittype 0
RUN 2026/lem26_his_2249 MUE4 PSI MUSR-ROOT
map 5 0 0 0 0 0 0 0 0 0
forward 21 25
norm 6
backgr.fit 7
RUN 2026/lem26_his_2249 MUE4 PSI MUSR-ROOT
map 8 0 0 0 0 0 0 0 0 0
forward 22 26
norm 9
backgr.fit 10
RUN 2026/lem26_his_2249 MUE4 PSI MUSR-ROOT
map 11 0 0 0 0 0 0 0 0 0
forward 23 27
norm fun3
backgr.fit 13
RUN 2026/lem26_his_2249 MUE4 PSI MUSR-ROOT
map 14 0 0 0 0 0 0 0 0 0
forward 24 28
norm fun4
backgr.fit 16
COMMANDS
MINIMIZE
+262
View File
@@ -501,6 +501,266 @@ function testParseAndApplyMSRGUISettings(lib) {
assert.strictEqual(all.rrfEnabled, "");
}
function testParseMSRTheoryAndFunctions(lib) {
const msr = [
"FITPARAMETER",
"1 Asy 0.0232 -0.0017 0.0019 0 0.3",
"2 Sgm 0.85 -0.11 0.14 0 10",
"3 Field 304.4 -1.2 1.3 0 500",
"4 N0L 595.31 -0.43 0.44",
"5 NBgL 3.569 -0.049 0.049",
"6 PhiL -6.4 -4.8 4.8 -360 360",
"7 AlphaLR 1.0160 -0.0010 0.0011",
"8 NBgR 4.763 -0.051 0.051",
"9 PhiR 157.2 -4.9 4.8 -360 360",
"THEORY",
"asymmetry 1",
"simpleGss 2 (rate)",
"TFieldCos map1 fun1 (phase frequency)",
"FUNCTIONS",
"fun1 = gamma_mu * par3",
"fun2 = par4 * par7",
"GLOBAL",
"fittype 0",
"RUN 2026/lem26_his_2321 MUE4 PSI MUSR-ROOT",
"norm 4",
"backgr.fit 5",
"forward 21 25",
"map 6 0 0 0 0 0 0 0 0 0",
"RUN 2026/lem26_his_2321 MUE4 PSI MUSR-ROOT",
"norm fun2",
"backgr.fit 8",
"forward 23 27",
"map 9 0 0 0 0 0 0 0 0 0",
"COMMANDS",
"MIGRAD"
].join("\n");
const parsed = JSON.parse(JSON.stringify(lib.parseMSRTheoryModel(msr)));
assert.strictEqual(parsed.ok, true);
assert.deepStrictEqual(parsed.components, ["GaussianCos"]);
assert.deepStrictEqual(parsed.constraints, [
{ target: "Frq", expression: "gamma_mu * Field" },
{ target: "No2", expression: "No1 * AlphaLR" }
]);
assert.deepStrictEqual(parsed.customParameters, ["Field", "AlphaLR"]);
assert.deepStrictEqual(parsed.parameterTargets, {
1: "Asy",
2: "Sgm",
3: "Field",
4: "No1",
5: "NBg1",
6: "Phi",
7: "AlphaLR",
8: "NBg2",
9: "PhiH2"
});
const all = {};
const previousDocument = lib.document;
lib.document = undefined;
assert.strictEqual(lib.applyMSRTheoryModel(parsed, all), 1);
lib.document = previousDocument;
assert.strictEqual(all.numComps, "1");
assert.strictEqual(all.fitFunc1, "GaussianCos");
// Rebuilding from the reconstructed GUI state may renumber parameters, but
// it must preserve the model, detector phase map, and both constraints.
const modelAll = {
fitAsyType: "SingleHist",
numComps: "1",
fitFunc1: "GaussianCos",
theoFunBlock: "asymmetry Asy\nsimpleGss Sgm\nTFieldCos Phi Frq",
runNumbers: "2321",
selYear: "2026",
instrName: "LEM",
dataRoot: "/psi.ch/data",
LRBF: "21 25,23 27"
};
const valuesByNumber = {
1: ["0.0232", "-0.0017", "0", "0.3"],
2: ["0.85", "-0.11", "0", "10"],
3: ["304.4", "-1.2", "0", "500"],
4: ["595.31", "-0.43", "", ""],
5: ["3.569", "-0.049", "", ""],
6: ["-6.4", "-4.8", "-360", "360"],
7: ["1.0160", "-0.0010", "", ""],
8: ["4.763", "-0.051", "", ""],
9: ["157.2", "-4.9", "-360", "360"]
};
Object.keys(valuesByNumber).forEach(function(number) {
const target = parsed.parameterTargets[number] + "_2321";
const values = valuesByNumber[number];
modelAll["val" + target] = values[0];
modelAll["err" + target] = values[1];
modelAll["min" + target] = values[2];
modelAll["max" + target] = values[3];
});
const regenerated = lib.buildModelBlocks({
all: modelAll,
funOptions: [
{ value: "Asy", disabled: false },
{ value: "Sgm", disabled: false },
{ value: "Phi", disabled: false },
{ value: "Frq", disabled: true },
{ value: "NBg1", disabled: false },
{ value: "No1", disabled: false },
{ value: "NBg2", disabled: false },
{ value: "No2", disabled: true },
{ value: "PhiH2", disabled: false },
{ value: "Field", disabled: false },
{ value: "AlphaLR", disabled: false }
],
funLines: [
"Frq = gamma_mu * Field",
"No2 = No1 * AlphaLR"
],
sharedFlags: {}
}, 0);
assert.match(regenerated.theoryBlock, /^asymmetry\s+1$/m);
assert.match(regenerated.theoryBlock, /^simpleGss\s+2$/m);
assert.match(regenerated.theoryBlock, /^TFieldCos\s+map1\s+fun1$/m);
assert.match(regenerated.functionsBlock, /^fun1 = gamma_mu \* par\d+$/m);
assert.match(regenerated.functionsBlock, /^fun2 = par\d+ \* par\d+$/m);
assert.strictEqual((regenerated.runBlock.match(/^RUN\b/gm) || []).length, 2);
assert.match(regenerated.runBlock, /^norm\s+5$/m);
assert.match(regenerated.runBlock, /^norm\s+fun2$/m);
assert.match(regenerated.runBlock, /^map\s+3$/m);
assert.match(regenerated.runBlock, /^map\s+7$/m);
assert.doesNotMatch(regenerated.runBlock, /undefined/);
assert.match(regenerated.parameterBlock, /\bField_2321\s+304\.4\s+-1\.2\s+0\s+500/);
assert.match(regenerated.parameterBlock, /\bPhiH2_2321\s+157\.2\s+-4\.9\s+-360\s+360/);
const unsupported = lib.parseMSRTheoryModel([
"FITPARAMETER",
"1 Asy 0.2 0.01",
"THEORY",
"userFcn 1 7",
"GLOBAL",
"fittype 2"
].join("\n"));
assert.strictEqual(unsupported.ok, false);
assert.match(unsupported.error, /not represented uniquely/);
}
function testParseFunctionMappedDetectorPhases(lib) {
const msr = fs.readFileSync(
path.join(__dirname, "fixtures", "function-map-singlehist.msr"), "utf8"
);
const parsed = JSON.parse(JSON.stringify(lib.parseMSRTheoryModel(msr)));
assert.strictEqual(parsed.ok, true);
assert.deepStrictEqual(parsed.components, ["ExponentialCos"]);
assert.deepStrictEqual(parsed.constraints, [
{ target: "Phi", expression: "Ph + map1" },
{ target: "Frq", expression: "gamma_mu * Field" },
{ target: "No3", expression: "No1 * alpha_LR" },
{ target: "No4", expression: "No2 * alpha_TB" }
]);
assert.deepStrictEqual(parsed.functionMaps, {
1: {
target: "Phi",
parameters: ["RelPh_L", "RelPh_T", "RelPh_R", "RelPh_B"]
}
});
assert.deepStrictEqual(parsed.customParameters, [
"Ph", "Field", "RelPh_L", "RelPh_T", "RelPh_R",
"alpha_LR", "RelPh_B", "alpha_TB"
]);
const previousFunctionMaps = lib.All.msrFunctionMaps;
lib.All.msrFunctionMaps = parsed.functionMaps;
assert.strictEqual(lib.legalFunLine("Ph + map1", ["Ph"]), true);
if (previousFunctionMaps === undefined) delete lib.All.msrFunctionMaps;
else lib.All.msrFunctionMaps = previousFunctionMaps;
const all = {};
const previousDocument = lib.document;
lib.document = undefined;
assert.strictEqual(lib.applyMSRTheoryModel(parsed, all), 1);
lib.document = previousDocument;
assert.deepStrictEqual(JSON.parse(JSON.stringify(all.msrFunctionMaps)), parsed.functionMaps);
const modelAll = {
fitAsyType: "SingleHist",
numComps: "1",
fitFunc1: "ExponentialCos",
theoFunBlock: "asymmetry Asy\nsimplExpo Lam\nTFieldCos Phi Frq",
runNumbers: "2249",
selYear: "2026",
instrName: "LEM",
dataRoot: "/psi.ch/data",
LRBF: "21 25,22 26,23 27,24 28",
msrFunctionMaps: parsed.functionMaps
};
for (const parameter of lib.parseMSRParameters(msr)) {
const target = parsed.parameterTargets[parameter.order] + "_2249";
modelAll["val" + target] = parameter.value;
modelAll["err" + target] = parameter.error;
modelAll["min" + target] = parameter.min;
modelAll["max" + target] = parameter.max;
}
const regenerated = lib.buildModelBlocks({
all: modelAll,
funOptions: [
{ value: "Asy", disabled: false },
{ value: "Lam", disabled: false },
{ value: "Phi", disabled: true },
{ value: "Frq", disabled: true },
{ value: "NBg1", disabled: false },
{ value: "No1", disabled: false },
{ value: "NBg2", disabled: false },
{ value: "No2", disabled: false },
{ value: "NBg3", disabled: false },
{ value: "No3", disabled: true },
{ value: "NBg4", disabled: false },
{ value: "No4", disabled: true },
{ value: "Ph", disabled: false },
{ value: "Field", disabled: false },
{ value: "RelPh_L", disabled: false },
{ value: "RelPh_T", disabled: false },
{ value: "RelPh_R", disabled: false },
{ value: "alpha_LR", disabled: false },
{ value: "RelPh_B", disabled: false },
{ value: "alpha_TB", disabled: false }
],
funLines: [
"Phi = Ph + map1",
"Frq = gamma_mu * Field",
"No3 = No1 * alpha_LR",
"No4 = No2 * alpha_TB"
],
sharedFlags: {}
}, 0);
function parameterNumber(name) {
const match = regenerated.parameterBlock.match(
new RegExp("^\\s*(\\d+)\\s+" + name + "_2249\\b", "m")
);
assert.ok(match, "missing regenerated parameter " + name);
return match[1];
}
assert.match(regenerated.theoryBlock, /^TFieldCos\s+fun1\s+fun2$/m);
assert.match(regenerated.functionsBlock, /^fun1 = par\d+ \+ map1$/m);
assert.match(regenerated.functionsBlock, /^fun2 = gamma_mu \* par\d+$/m);
assert.match(regenerated.functionsBlock, /^fun3 = par\d+ \* par\d+$/m);
assert.match(regenerated.functionsBlock, /^fun4 = par\d+ \* par\d+$/m);
assert.deepStrictEqual(
Array.from(regenerated.runBlock.matchAll(/^map\s+(\d+)$/gm), function(match) {
return match[1];
}),
[
parameterNumber("RelPh_L"),
parameterNumber("RelPh_T"),
parameterNumber("RelPh_R"),
parameterNumber("RelPh_B")
]
);
assert.strictEqual((regenerated.runBlock.match(/^norm\s+fun3$/gm) || []).length, 1);
assert.strictEqual((regenerated.runBlock.match(/^norm\s+fun4$/gm) || []).length, 1);
assert.doesNotMatch(regenerated.runBlock, /undefined/);
}
function testParseMSRRunSelectionWithAddRun(lib) {
const msr = [
"GLOBAL",
@@ -2050,6 +2310,8 @@ testCompactJobStatusVisibility(lib);
testParameterPlotSelection(lib);
testParseMSRParameters(lib);
testParseAndApplyMSRGUISettings(lib);
testParseMSRTheoryAndFunctions(lib);
testParseFunctionMappedDetectorPhases(lib);
testParseMSRRunSelectionWithAddRun(lib);
testParseMSRT0BgRunBlocks(lib);
testSyncCommonAsymmetryT0BgFromMSR(lib);