13461 lines
528 KiB
JavaScript
13461 lines
528 KiB
JavaScript
// Copyright (C) 2026 Zaher Salman
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
// Shared GUI/editor/job state. Values from visible controls are copied into All
|
|
// immediately before MSR generation.
|
|
var All = new Object();
|
|
var editingFunId = null;
|
|
var customParams = [];
|
|
// Parameter names selected in the Parameters tab for comparison plots.
|
|
var selectedParameterPlotNames = [];
|
|
var parameterPlotSelectionAnchor = "";
|
|
var defaultDataRoot = "/psi.ch/group/lmu/public/data";
|
|
var defaultWorkPath = ".";
|
|
var defaultAsymmetrySuffix = "_asy";
|
|
var defaultSingleHistSuffix = "_singleHist";
|
|
var dataRootStorageKey = "musrflow.dataRoot";
|
|
var workPathStorageKey = "musrflow.workPath";
|
|
var asymmetrySuffixStorageKey = "musrflow.asymmetrySuffix";
|
|
var singleHistSuffixStorageKey = "musrflow.singleHistSuffix";
|
|
var guessInitialParametersStorageKey = "musrflow.guessInitialParameters";
|
|
var startupXmlStorageKey = "musrflow.startupXml";
|
|
// Directory holding the local musrfit/musrview/msr2data/dump_header tools.
|
|
// Empty means auto-detect from the usual installation locations. Web runs never
|
|
// resolve local commands, so this stays a renderer-only Electron preference.
|
|
var binDirStorageKey = "musrflow.binDir";
|
|
// Number of OpenMP threads handed to a local musrfit run via `-u`. Empty means
|
|
// "auto": omit the flag and let musrfit use all cores. Web runs fit server-side,
|
|
// so this stays a renderer-only Electron preference.
|
|
var musrfitThreadsStorageKey = "musrflow.musrfitThreads";
|
|
// Whether a local fit first forces t0 to the prompt peak for instruments whose
|
|
// data-file header t0 needs estimating. Never applies to LEM or HAL/HIFI. Enabled by default;
|
|
// web runs fit server-side and never apply it.
|
|
var estimateT0FromPromptPeakStorageKey = "musrflow.estimateT0FromPromptPeak";
|
|
// The first model follows the first-run field until the user, an imported MSR,
|
|
// or a shared configuration explicitly chooses a model.
|
|
var automaticInitialFitModel = true;
|
|
var zeroFieldThresholdGauss = 1.0;
|
|
|
|
// Portable RUN naming through musrfit_startup.xml.
|
|
//
|
|
// When enabled and a matching, resolvable run-name template exists, generated
|
|
// RUN/ADDRUN lines carry a sub-path relative to a <data_path> instead of an
|
|
// absolute machine-specific path. This state is opt-in: the default generation
|
|
// path (runFileNameAuto) stays absolute until portable naming is configured and
|
|
// validated. The data-path resolver is platform-specific (Electron stats the
|
|
// file; the web uses server-owned startup configuration) and is injected by
|
|
// each adapter so this library remains transport-neutral.
|
|
var portableRunNamingEnabled = false;
|
|
var portableRunNamingStartup = null; // { dataPaths: [], templates: {} } from parseMusrfitStartupXML
|
|
var resolveMusrfitRunFile = null; // (subPath, dataPath) => boolean (is the file resolvable)
|
|
|
|
function setPortableRunNaming(enabled, startup, resolver) {
|
|
portableRunNamingEnabled = !!enabled;
|
|
portableRunNamingStartup = startup || null;
|
|
resolveMusrfitRunFile = typeof resolver === "function" ? resolver : null;
|
|
return portableRunNamingEnabled;
|
|
}
|
|
|
|
// Shared configuration-link model. Platform files only encode/copy the resulting
|
|
// object; deciding which GUI state belongs in a share link is common to both.
|
|
var MUSRFLOW_SHARE_CONFIG_VERSION = 1;
|
|
|
|
// The FITPARAMETER block of the most recently imported MSR keeps its own
|
|
// structure: the parameter order the author chose and any comment lines. When
|
|
// the GUI regenerates an MSR from its model (single fit or series), the block
|
|
// is normally rebuilt in catalogue order. If a file was imported first, these
|
|
// fields replay its order and comments so the round-trip stays faithful to the
|
|
// file the user started from.
|
|
// order: base parameter names in the file's FITPARAMETER sequence
|
|
// comments: array parallel to `order`, one comment object per parameter:
|
|
// { before: [lines, ...], after: [lines, ...] }
|
|
var importedMSRFitParameterOrder = null;
|
|
var importedMSRFitParameterComments = null;
|
|
|
|
function readSharedControlValue(element) {
|
|
if (!element) return null;
|
|
if (element.type === "checkbox") return Boolean(element.checked);
|
|
return element.value !== undefined ? String(element.value) : "";
|
|
}
|
|
|
|
function collectSharedParameterControls() {
|
|
let values = {};
|
|
let table = document.getElementById("Params");
|
|
if (!table || !table.querySelectorAll) return values;
|
|
for (let element of table.querySelectorAll("input[id]")) {
|
|
if (!/^(?:sh|val|err|min|max)/.test(element.id)) continue;
|
|
values[element.id] = readSharedControlValue(element);
|
|
}
|
|
return values;
|
|
}
|
|
|
|
// The parameter-plot configuration for the currently resolved data source is
|
|
// embedded as a plain JSON stanza so a shared link carries the style registry,
|
|
// panel arrangement, and overlay files along. On the receiving machine the plot
|
|
// window restores the state directly when the same source identity exists (a
|
|
// matching on-disk path or an identical inline table); different paths simply
|
|
// ignore the stanza. The helpers live in muSRFitParameterPlot.js, which shares
|
|
// the main page on both platforms, so they are guarded for standalone use.
|
|
function currentParameterPlotSnapshot() {
|
|
if (typeof parameterDataSetKey !== "function"
|
|
|| typeof readRememberedParameterPlotState !== "function"
|
|
|| typeof parameterPlotStateStorage !== "function") {
|
|
return null;
|
|
}
|
|
let resolved = resolveCurrentParameterPlotSource();
|
|
if (!resolved) return null;
|
|
let source = resolved.source;
|
|
if (typeof normalizeParameterSource === "function") {
|
|
source = normalizeParameterSource(source);
|
|
}
|
|
let snapshot = readRememberedParameterPlotState(
|
|
parameterPlotStateStorage(),
|
|
parameterDataSetKey(source)
|
|
);
|
|
if (!snapshot || typeof snapshot !== "object") return null;
|
|
// Fresh copy: a recipient or later call must not mutate the stored map.
|
|
return JSON.parse(JSON.stringify(snapshot));
|
|
}
|
|
|
|
function buildSharedConfiguration() {
|
|
// Share analysis state, never machine-specific paths or transient windows/logs.
|
|
// prepCFG() makes edits in the visible parameter table authoritative first.
|
|
if (typeof prepCFG === "function") prepCFG();
|
|
|
|
let constraints = [];
|
|
if (document.querySelectorAll) {
|
|
for (let line of document.querySelectorAll("#funBlock .funLine")) {
|
|
constraints.push(String(line.innerText || line.textContent || "").trim());
|
|
}
|
|
}
|
|
|
|
return {
|
|
v: MUSRFLOW_SHARE_CONFIG_VERSION,
|
|
controls: (function(root) {
|
|
let values = {};
|
|
if (!root || !root.querySelectorAll) return values;
|
|
for (let element of root.querySelectorAll("input[id], select[id]")) {
|
|
// Components are stored separately as an ordered theory-model list.
|
|
if (/^fitFunc\d+$/.test(element.id) || element.id === "numComps") continue;
|
|
values[element.id] = readSharedControlValue(element);
|
|
}
|
|
return values;
|
|
})(document.getElementById("Runs")),
|
|
components: typeof getFitComponentValues === "function" ? getFitComponentValues() : [],
|
|
parameters: collectSharedParameterControls(),
|
|
customParameters: typeof customParams !== "undefined" ? customParams.slice() : [],
|
|
constraints: constraints,
|
|
// Imported SingleHist FUNCTIONS can use mapN to select a different fit
|
|
// parameter in each histogram RUN block. The visible expression alone
|
|
// cannot reconstruct that ordered detector mapping on another machine.
|
|
functionMaps: All.msrFunctionMaps && typeof All.msrFunctionMaps === "object"
|
|
? JSON.parse(JSON.stringify(All.msrFunctionMaps)) : {},
|
|
// JSON.stringify drops the undefined value, so a link without an open
|
|
// parameter plot simply omits the stanza instead of carrying parameterPlot
|
|
// with a null value (which earlier share links emitted).
|
|
parameterPlot: currentParameterPlotSnapshot() || undefined
|
|
};
|
|
}
|
|
|
|
function validateSharedConfiguration(config) {
|
|
// Links from any version are restorable: an older application restores only
|
|
// the fields it knows and ignores anything a newer version added, while a
|
|
// newer application still accepts every field an older link carries. Only a
|
|
// link with a missing/unknown numeric version or an unusable controls map is
|
|
// rejected outright.
|
|
if (!config || typeof config.v !== "number" || !(config.v >= 1)
|
|
|| typeof config.controls !== "object" || config.controls === null) {
|
|
throw new Error("unsupported configuration format");
|
|
}
|
|
|
|
let functionMaps = config.functionMaps;
|
|
if (functionMaps !== undefined
|
|
&& (typeof functionMaps !== "object" || functionMaps === null
|
|
|| Array.isArray(functionMaps))) {
|
|
throw new Error("invalid detector-map definitions");
|
|
}
|
|
for (let mapNo of Object.keys(functionMaps || {})) {
|
|
let map = functionMaps[mapNo];
|
|
if (!/^[1-9]\d*$/.test(mapNo) || !map || !/^[A-Za-z]\w*$/.test(map.target || "")
|
|
|| !Array.isArray(map.parameters) || map.parameters.length === 0
|
|
|| map.parameters.some(function(name) { return !/^[A-Za-z]\w*$/.test(name); })) {
|
|
throw new Error("invalid map" + mapNo + " definition");
|
|
}
|
|
}
|
|
|
|
// Version-1 links created before detector maps were included cannot safely
|
|
// restore a map-based function. Reject them before mutating any GUI state.
|
|
let requiredMaps = new Set();
|
|
for (let line of Array.isArray(config.constraints) ? config.constraints : []) {
|
|
for (let match of String(line || "").matchAll(/\bmap([1-9]\d*)\b/gi)) {
|
|
requiredMaps.add(match[1]);
|
|
}
|
|
}
|
|
for (let mapNo of requiredMaps) {
|
|
if (!functionMaps || !functionMaps[mapNo]) {
|
|
throw new Error("configuration is missing the detector definition for map" + mapNo
|
|
+ "; create a new share link from the source application");
|
|
}
|
|
}
|
|
|
|
// The parameter-plot stanza is optional and carries a plain JSON snapshot of
|
|
// the sender's plot window. Structural checks reject crafted payloads; the
|
|
// plot-side validator (muSRFitParameterPlot.js) performs the full check when
|
|
// it is loaded, and the restore step never trusts an unvalidated stanza.
|
|
// A null stanza (written by earlier share links when no plot was open) means
|
|
// the same as an absent stanza and is accepted.
|
|
let parameterPlot = config.parameterPlot;
|
|
if (parameterPlot !== undefined && parameterPlot !== null
|
|
&& (typeof parameterPlot !== "object" || Array.isArray(parameterPlot))) {
|
|
throw new Error("invalid parameter-plot configuration");
|
|
}
|
|
if (parameterPlot && typeof validateParameterPlotState === "function"
|
|
&& !validateParameterPlotState(parameterPlot)) {
|
|
// A stanza written by an older or newer application version cannot be
|
|
// restored here. Drop it instead of failing the whole link, because
|
|
// everything else in the configuration remains restorable.
|
|
if (typeof MUSRFIT_PARAMETER_PLOT_STATE_VERSION === "number"
|
|
&& typeof parameterPlot.v === "number"
|
|
&& parameterPlot.v !== MUSRFIT_PARAMETER_PLOT_STATE_VERSION) {
|
|
config.parameterPlot = null;
|
|
} else {
|
|
throw new Error("invalid parameter-plot configuration");
|
|
}
|
|
}
|
|
return config;
|
|
}
|
|
|
|
// Shared-configuration link protocol. A #c= fragment carries gzipped base64url
|
|
// JSON; #cfg= is kept as the legacy uncompressed form. The platform adapters
|
|
// inject only a gzip/gunzip text primitive (Node zlib through the preload bridge
|
|
// in Electron, CompressionStream/DecompressionStream in the browser), so the
|
|
// protocol itself is identical in both runtimes.
|
|
|
|
// Desktop protocol links. Browsers keep http(s) navigation to themselves, so a
|
|
// web visitor who installed the desktop build cannot be handed off from an
|
|
// https page. The web Share flow therefore also emits a musrflow:// link that
|
|
// the installed app is registered to receive; the fragment is byte-identical to
|
|
// the web form, only the base URL differs.
|
|
var MUSRFLOW_DESKTOP_LINK_PREFIX = "musrflow://open/";
|
|
|
|
// Prefix an already-encoded #c=/#cfg= fragment with the desktop protocol base.
|
|
function desktopConfigurationLink(encoded) {
|
|
return MUSRFLOW_DESKTOP_LINK_PREFIX
|
|
+ String(encoded && encoded.prefix || "")
|
|
+ String(encoded && encoded.payload || "");
|
|
}
|
|
|
|
function parseSharedConfigurationFragment(value) {
|
|
let input = String(value || "").trim();
|
|
let hash = "";
|
|
try {
|
|
// Only the fragment carries shared state. Parsing the URL does not
|
|
// navigate to it or make a network request.
|
|
hash = input.startsWith("#") ? input : new URL(input).hash;
|
|
} catch (error) {
|
|
return { ok: false, error: "Enter a complete muSRFlow configuration link." };
|
|
}
|
|
if (hash.startsWith("#c=")) {
|
|
return { ok: true, compressed: true, payload: hash.substring(3) };
|
|
}
|
|
if (hash.startsWith("#cfg=")) {
|
|
return { ok: true, compressed: false, payload: hash.substring(5) };
|
|
}
|
|
return { ok: false, error: "The link does not contain a muSRFlow configuration." };
|
|
}
|
|
|
|
async function encodeSharedConfigurationLink(config, gzipText) {
|
|
let json = JSON.stringify(config);
|
|
try {
|
|
let payload = gzipText(json);
|
|
if (payload && typeof payload.then === "function") {
|
|
payload = await payload;
|
|
}
|
|
return { prefix: "#c=", payload: payload, compressed: true };
|
|
} catch (error) {
|
|
// A platform without gzip support (older browser, restricted renderer)
|
|
// still produces a compatible, uncompressed link.
|
|
return { prefix: "#cfg=", payload: encodeURIComponent(json), compressed: false };
|
|
}
|
|
}
|
|
|
|
async function decodeSharedConfigurationFragment(value, gunzipText) {
|
|
let parsed = parseSharedConfigurationFragment(value);
|
|
if (!parsed.ok) {
|
|
return { config: null, error: parsed.error, consumed: false };
|
|
}
|
|
let result = { config: null, error: "", consumed: true };
|
|
try {
|
|
let json = "";
|
|
if (parsed.compressed) {
|
|
json = gunzipText(parsed.payload);
|
|
if (json && typeof json.then === "function") {
|
|
json = await json;
|
|
}
|
|
} else {
|
|
json = decodeURIComponent(parsed.payload);
|
|
}
|
|
result.config = validateSharedConfiguration(JSON.parse(json));
|
|
} catch (error) {
|
|
result.error = "Could not read shared configuration: "
|
|
+ (error && error.message ? error.message : String(error));
|
|
}
|
|
return result;
|
|
}
|
|
|
|
// Build the encoded #c=/#cfg= fragment for the current GUI state. Session
|
|
// persistence and the Share button both record the same canonical state, so
|
|
// they share one encode path. The parameter-plot stanza is hydrated the same
|
|
// way in both callers.
|
|
async function buildEncodedSharedConfigurationLink(gzipText) {
|
|
let config = buildSharedConfiguration();
|
|
// When the plot module and platform are available, replace a path-based
|
|
// parameter-plot snapshot with a self-contained copy that carries the sender's
|
|
// actual msr2data table (scan variable, fitted values, errors) as inline
|
|
// text. The receiver can then render the identical plot without reproducing
|
|
// the sender's "*_par.dat" on its own file system.
|
|
if (config.parameterPlot && typeof hydratedParameterPlotSnapshot === "function") {
|
|
try {
|
|
let hydrated = await hydratedParameterPlotSnapshot(config.parameterPlot);
|
|
if (hydrated) config.parameterPlot = hydrated;
|
|
} catch (error) {
|
|
// The source is no longer readable; keep the remembered state without
|
|
// data, which still restores the layout, palette, and overlay choices.
|
|
}
|
|
}
|
|
return encodeSharedConfigurationLink(config, gzipText);
|
|
}
|
|
|
|
async function shareConfigurationLink(platform) {
|
|
// platform: { baseURL(), writeClipboard(url), gzipText(json) }. The clipboard
|
|
// write and URL base live in each adapter; the rest of the copy flow is shared.
|
|
let encoded;
|
|
try {
|
|
encoded = await buildEncodedSharedConfigurationLink(platform.gzipText);
|
|
} catch (error) {
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Could not encode configuration link.", { level: "error" });
|
|
}
|
|
return false;
|
|
}
|
|
let url = platform.baseURL() + encoded.prefix + encoded.payload;
|
|
|
|
try {
|
|
await platform.writeClipboard(url);
|
|
} catch (error) {
|
|
// Browser clipboard access can be blocked by policy. A prompt still gives
|
|
// the user the exact link without storing it anywhere in the application.
|
|
if (typeof window !== "undefined" && typeof window.prompt === "function") {
|
|
try {
|
|
window.prompt("Copy configuration link:", url);
|
|
return true;
|
|
} catch (promptError) {
|
|
// Electron defines prompt() but throws "prompt() is not supported.";
|
|
// fall through to the transient warning and status error path.
|
|
}
|
|
}
|
|
if (typeof showTransientWarning === "function") {
|
|
showTransientWarning(
|
|
"Could not copy configuration link.",
|
|
document.getElementById("shareConfigButton"),
|
|
3500
|
|
);
|
|
}
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Could not copy configuration link.", { level: "error" });
|
|
}
|
|
return false;
|
|
}
|
|
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Configuration link copied.", { level: "success" });
|
|
}
|
|
if (typeof showTransientWarning === "function") {
|
|
showTransientWarning(
|
|
"Configuration link copied.",
|
|
document.getElementById("shareConfigButton"),
|
|
3500
|
|
);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function installSharedCustomParameters(names) {
|
|
if (typeof customParams === "undefined") return;
|
|
customParams.length = 0;
|
|
let funSel = document.getElementById("funSel");
|
|
for (let name of Array.isArray(names) ? names : []) {
|
|
name = String(name || "").trim();
|
|
if (!/^[A-Za-z]\w*$/.test(name) || customParams.includes(name)) continue;
|
|
customParams.push(name);
|
|
if (funSel && !document.getElementById("fn" + name)) {
|
|
let option = document.createElement("option");
|
|
option.textContent = name;
|
|
option.value = name;
|
|
option.id = "fn" + name;
|
|
funSel.appendChild(option);
|
|
}
|
|
}
|
|
if (typeof updateCustomParamList === "function") updateCustomParamList();
|
|
}
|
|
|
|
function restoreSharedConstraintLines(lines) {
|
|
let funSel = document.getElementById("funSel");
|
|
let funInput = document.getElementById("funLine");
|
|
if (!funSel || !funInput || typeof addFunLine !== "function") return;
|
|
|
|
for (let line of Array.isArray(lines) ? lines : []) {
|
|
line = String(line || "");
|
|
let split = line.indexOf("=");
|
|
if (split <= 0) continue;
|
|
let name = line.substring(0, split).trim();
|
|
let expression = line.substring(split + 1).trim();
|
|
let option = document.getElementById("fn" + name);
|
|
if (!option || !expression) continue;
|
|
funSel.value = name;
|
|
funInput.value = expression;
|
|
addFunLine();
|
|
}
|
|
funInput.value = "";
|
|
}
|
|
|
|
async function restoreSharedConfiguration(config) {
|
|
// Encoding differs between a browser and Node.js, but applying a decoded
|
|
// configuration must remain identical in the web and Electron applications.
|
|
config = validateSharedConfiguration(config);
|
|
|
|
// A shared configuration restores a complete, known GUI state instead of a
|
|
// user editing it. Suppress edit capture so the restore is not mistaken for
|
|
// a series-parameter/structure change.
|
|
suppressSeriesGUIEditCapture = true;
|
|
try {
|
|
|
|
// Install detector maps before updateTheoryBlock()/cfgConstraints() rebuilds
|
|
// histogram-specific phase options and before addFunLine() validates mapN.
|
|
if (config.functionMaps && Object.keys(config.functionMaps).length > 0) {
|
|
All.msrFunctionMaps = JSON.parse(JSON.stringify(config.functionMaps));
|
|
} else {
|
|
delete All.msrFunctionMaps;
|
|
}
|
|
|
|
// Restore stable Runs-tab controls first, then rebuild model-dependent
|
|
// controls exactly as a user changing the theory would do.
|
|
let controls = config.controls || {};
|
|
let runsRoot = document.getElementById("Runs");
|
|
for (let id of Object.keys(controls)) {
|
|
let element = document.getElementById(id);
|
|
// Do not allow a crafted link to address Preferences or other controls
|
|
// merely by knowing their DOM ids.
|
|
if (runsRoot && element && runsRoot.contains(element)) {
|
|
if (element.type === "checkbox") {
|
|
element.checked = Boolean(controls[id]);
|
|
} else {
|
|
element.value = controls[id] === undefined || controls[id] === null
|
|
? "" : String(controls[id]);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (Array.isArray(config.components) && config.components.length > 0
|
|
&& typeof renderFitComponents === "function") {
|
|
if (typeof markFitModelExplicit === "function") markFitModelExplicit();
|
|
renderFitComponents(config.components);
|
|
let count = document.getElementById("numComps");
|
|
if (count) count.value = String(config.components.length);
|
|
}
|
|
|
|
// Parameter values are copied into All before cfgParams(), because shared
|
|
// flags affect which run-qualified rows cfgParams() creates. They are copied
|
|
// to the live controls again after header guessing so the shared state wins.
|
|
let parameterValues = {};
|
|
for (let id of Object.keys(config.parameters || {})) {
|
|
if (/^(?:sh|val|err|min|max)/.test(id)) {
|
|
parameterValues[id] = config.parameters[id];
|
|
}
|
|
}
|
|
if (typeof All === "object" && All) {
|
|
for (let id of Object.keys(parameterValues)) {
|
|
let value = parameterValues[id];
|
|
All[id] = id.startsWith("sh") ? (value ? "1" : "") : String(value ?? "");
|
|
}
|
|
}
|
|
|
|
if (typeof customParams !== "undefined") customParams.length = 0;
|
|
let funBlock = document.getElementById("funBlock");
|
|
let paramsTab = document.getElementById("Params");
|
|
let t0BgTab = document.getElementById("t0Bg");
|
|
if (funBlock) funBlock.innerHTML = "";
|
|
if (paramsTab) paramsTab.innerHTML = "";
|
|
if (t0BgTab) t0BgTab.innerHTML = "";
|
|
if (typeof clearStoredT0BgValues === "function") clearStoredT0BgValues();
|
|
if (typeof adjustComps === "function") adjustComps();
|
|
if (typeof updateTheoryBlock === "function") updateTheoryBlock();
|
|
|
|
installSharedCustomParameters(config.customParameters);
|
|
restoreSharedConstraintLines(config.constraints);
|
|
|
|
let guess = typeof cfgParams === "function" ? cfgParams() : null;
|
|
if (guess && typeof guess.then === "function") await guess;
|
|
|
|
for (let id of Object.keys(parameterValues)) {
|
|
let element = document.getElementById(id);
|
|
if (paramsTab && element && paramsTab.contains(element)) {
|
|
if (element.type === "checkbox") {
|
|
element.checked = Boolean(parameterValues[id]);
|
|
} else {
|
|
element.value = parameterValues[id] === undefined || parameterValues[id] === null
|
|
? "" : String(parameterValues[id]);
|
|
}
|
|
}
|
|
}
|
|
if (typeof prepCFG === "function") prepCFG();
|
|
if (typeof updatePlotOptionVisibility === "function") updatePlotOptionVisibility();
|
|
if (typeof cfgFFTRRF === "function") cfgFFTRRF();
|
|
if (typeof updateResolvedDataPathPreview === "function") updateResolvedDataPathPreview();
|
|
if (typeof updateSeriesActionVisibility === "function") updateSeriesActionVisibility();
|
|
|
|
// A shared parameter-plot stanza is placed back into the remembered-state
|
|
// map under the data-source key it travelled with. The plot window's own
|
|
// auto-restore then applies it whenever that source is opened again (a
|
|
// matching on-disk path or an identical inline parameter table), so the
|
|
// recipient's plot flow is indistinguishable from a saved local window --
|
|
// no dedicated repair path, and no divergence between shared and local
|
|
// configurations. Invalid stanzas are rejected by the shared validator
|
|
// above and never reach this point.
|
|
if (config.parameterPlot
|
|
&& typeof rememberParameterPlotState === "function"
|
|
&& typeof validateParameterPlotState === "function"
|
|
&& typeof parameterPlotStateStorage === "function"
|
|
&& validateParameterPlotState(config.parameterPlot)) {
|
|
rememberParameterPlotState(parameterPlotStateStorage(), config.parameterPlot);
|
|
}
|
|
// Pre-select the parameter-plot chips so "Plot parameters..." immediately
|
|
// offers the same set the sender plotted. The pending marker is consumed
|
|
// the first time a plot is opened: a self-contained shared stanza carries
|
|
// the sender's data, so it renders identically even when this machine
|
|
// cannot reproduce the sender's "*_par.dat" by file identity.
|
|
if (config.parameterPlot && typeof setPendingSharedParameterPlot === "function") {
|
|
setPendingSharedParameterPlot(config.parameterPlot);
|
|
}
|
|
if (config.parameterPlot && typeof parameterPlotNamesFromSnapshot === "function") {
|
|
let names = parameterPlotNamesFromSnapshot(config.parameterPlot);
|
|
if (names.length > 0) {
|
|
selectedParameterPlotNames = names;
|
|
if (typeof updateParameterPlotSelectionUI === "function") updateParameterPlotSelectionUI();
|
|
}
|
|
}
|
|
markMSREditorStaleAfterRestore();
|
|
return true;
|
|
} finally {
|
|
suppressSeriesGUIEditCapture = false;
|
|
}
|
|
}
|
|
|
|
// After a shared configuration restore, the GUI is authoritative. Keep any
|
|
// existing editor text visible for reference, but mark both documents stale so
|
|
// the next Generate/Fit/Plot creates a fresh MSR instead of silently carrying
|
|
// the old text forward. Electron and web call this through restoreSharedConfiguration(),
|
|
// so a restored edition never leaks editor-owned content into the imported GUI.
|
|
function markMSREditorStaleAfterRestore() {
|
|
if (typeof window === "undefined" || !window.MSREditor
|
|
|| typeof getMSRDocumentState !== "function") return;
|
|
let activeText = typeof getCurrentEditorText === "function" ? getCurrentEditorText() : "";
|
|
if (window.MSREditor.activeSource === "template") {
|
|
window.MSREditor.templateContent = activeText;
|
|
} else {
|
|
window.MSREditor.currentContent = activeText;
|
|
}
|
|
let currentText = String(window.MSREditor.currentContent || "");
|
|
let templateText = String(window.MSREditor.templateContent || "");
|
|
let currentState = getMSRDocumentState("current");
|
|
let templateState = getMSRDocumentState("template");
|
|
currentState.sourceOfTruth = "gui";
|
|
currentState.locked = false;
|
|
currentState.dirty = false;
|
|
currentState.stale = currentText.trim() !== "";
|
|
currentState.lastAcceptedHash = hashMSRText(currentText);
|
|
templateState.sourceOfTruth = "gui";
|
|
templateState.locked = false;
|
|
templateState.dirty = false;
|
|
templateState.stale = templateText.trim() !== "";
|
|
templateState.lastAcceptedHash = hashMSRText(templateText);
|
|
window.MSREditor.currentPath = "";
|
|
window.MSREditor.templatePath = "";
|
|
if (typeof syncMSREditorLegacyState === "function") syncMSREditorLegacyState();
|
|
if (typeof updateMSREditorSourceTabs === "function") updateMSREditorSourceTabs();
|
|
}
|
|
// Keep the same gamma_mu/(2*pi) constant used by musrfit (MHz/G).
|
|
var muonGammaBarMHzPerGauss = 1.355388094e-2;
|
|
// Header metadata is cached only for the first run. A new theory generation may
|
|
// reuse it, but adding runs never triggers another header-based guess.
|
|
var initialParameterGuessState = {
|
|
generation: 1,
|
|
appliedGeneration: 0,
|
|
firstRun: "",
|
|
metadataKey: "",
|
|
metadata: null,
|
|
pendingDownloadGuess: null
|
|
};
|
|
if (!window.MSREditor) {
|
|
window.MSREditor = {};
|
|
}
|
|
if (typeof window.MSREditor.currentPath === "undefined") {
|
|
window.MSREditor.currentPath = "";
|
|
}
|
|
if (typeof window.MSREditor.lastGenerated === "undefined") {
|
|
window.MSREditor.lastGenerated = "";
|
|
}
|
|
if (typeof window.MSREditor.activeSource === "undefined") {
|
|
window.MSREditor.activeSource = "current";
|
|
}
|
|
if (typeof window.MSREditor.currentContent === "undefined") {
|
|
window.MSREditor.currentContent = "";
|
|
}
|
|
if (typeof window.MSREditor.templateContent === "undefined") {
|
|
window.MSREditor.templateContent = "";
|
|
}
|
|
if (typeof window.MSREditor.templatePath === "undefined") {
|
|
window.MSREditor.templatePath = "";
|
|
}
|
|
if (typeof window.MSREditor.hasTemplateTab === "undefined") {
|
|
window.MSREditor.hasTemplateTab = false;
|
|
}
|
|
if (typeof window.MSREditor.currentDirty === "undefined") {
|
|
window.MSREditor.currentDirty = false;
|
|
}
|
|
if (typeof window.MSREditor.templateDirty === "undefined") {
|
|
window.MSREditor.templateDirty = false;
|
|
}
|
|
if (typeof window.MSREditor.dirty === "undefined") {
|
|
window.MSREditor.dirty = false;
|
|
}
|
|
if (typeof window.MSREditor.suppressInput === "undefined") {
|
|
window.MSREditor.suppressInput = false;
|
|
}
|
|
|
|
// The template and runnable/current MSR are separate editor documents. Each
|
|
// document keeps its own lock/ownership state so manual edits in one file never
|
|
// implicitly unlock, overwrite, or take ownership of the other file.
|
|
if (!window.MSREditor.documents) {
|
|
window.MSREditor.documents = {
|
|
current: {
|
|
sourceOfTruth: "gui",
|
|
locked: false,
|
|
dirty: window.MSREditor.currentDirty ? true : false,
|
|
lastGeneratedHash: "",
|
|
lastAcceptedHash: "",
|
|
stale: false
|
|
},
|
|
template: {
|
|
sourceOfTruth: "gui",
|
|
locked: false,
|
|
dirty: window.MSREditor.templateDirty ? true : false,
|
|
lastGeneratedHash: "",
|
|
lastAcceptedHash: "",
|
|
stale: false
|
|
}
|
|
};
|
|
}
|
|
|
|
// Keep the old scalar fields as mirrors of the active document for compatibility
|
|
// with older helper code and external scripts. New synchronization logic should
|
|
// read/write the per-document state through getMSRDocumentState().
|
|
if (typeof window.MSREditor.sourceOfTruth === "undefined") {
|
|
window.MSREditor.sourceOfTruth = "gui";
|
|
}
|
|
if (typeof window.MSREditor.locked === "undefined") {
|
|
window.MSREditor.locked = false;
|
|
}
|
|
if (typeof window.MSREditor.lastGeneratedHash === "undefined") {
|
|
window.MSREditor.lastGeneratedHash = "";
|
|
}
|
|
if (typeof window.MSREditor.lastAcceptedHash === "undefined") {
|
|
window.MSREditor.lastAcceptedHash = "";
|
|
}
|
|
if (!window.MusrfitJob) {
|
|
window.MusrfitJob = {
|
|
state: "Idle",
|
|
mode: "",
|
|
file: "",
|
|
directory: "",
|
|
message: "Idle",
|
|
messageDetail: "Idle",
|
|
noticeLevel: "none",
|
|
startedAt: "",
|
|
finishedAt: "",
|
|
exitCode: "",
|
|
lastCommand: "",
|
|
templatePath: "",
|
|
resultMSR: "",
|
|
logPath: "",
|
|
plotPath: "",
|
|
parameterDataPath: "",
|
|
packagePath: "",
|
|
parameterSync: "",
|
|
// Keep the last fitted statistic separate from the process message so a
|
|
// later musrview completion cannot overwrite the numerical fit quality.
|
|
fitStatistic: "",
|
|
fitConverged: null,
|
|
// Per-run fit quality for the current independent-series plan. Every
|
|
// selected data set appears here, including reused/skipped/stale ones;
|
|
// rows rebuilt by the last run are marked fresh. Absent/empty for single
|
|
// and global fits, whose status bar keeps the exact single statistic.
|
|
seriesStatistic: [],
|
|
preparedForRun: false,
|
|
log: []
|
|
};
|
|
}
|
|
if (!window.MusrfitAction) {
|
|
// One main action owns MSR generation and execution at a time. This state is
|
|
// independent of native musrview windows, which may remain open in parallel.
|
|
window.MusrfitAction = {
|
|
busy: false,
|
|
action: "",
|
|
phase: "idle"
|
|
};
|
|
}
|
|
if (!window.MusrfitRuntimeGate) {
|
|
// Before a Fit/Plot action touches any external tool, the shell may need to
|
|
// wait for its runtime to become usable. The web build and development
|
|
// checkouts leave this default, which resolves immediately; the Electron
|
|
// shell replaces ready() to await the first-run WSL2 import on Windows.
|
|
window.MusrfitRuntimeGate = {
|
|
ready: function () { return Promise.resolve(true); }
|
|
};
|
|
}
|
|
if (!window.MusrfitWebJob) {
|
|
// Web Plot/Fit actions reuse one server folder until the first run changes.
|
|
window.MusrfitWebJob = {
|
|
firstRun: "",
|
|
workPath: ""
|
|
};
|
|
}
|
|
if (!window.MusrfitSeriesEditedRuns) {
|
|
// Data sets whose GUI parameters or structural settings changed after their
|
|
// on-disk MSR last represented the same input. A marked data set is always
|
|
// rebuilt from the live GUI and refitted on the next independent-series run,
|
|
// overriding even an explicit reuse/skip chip choice. The marker clears when
|
|
// a refit successfully rebuilds that run.
|
|
window.MusrfitSeriesEditedRuns = {};
|
|
}
|
|
// Programmatic restores (MSR import, shared-configuration links) rebuild the
|
|
// same controls a user would edit. Their rebuilds must never be mistaken for
|
|
// user edits, so edit capture is suspended while they run.
|
|
var suppressSeriesGUIEditCapture = false;
|
|
|
|
// Supported instrument metadata. Generated data paths have the form
|
|
// <data root>/<folder>/his/<year>/<run file>.
|
|
var instPars = {
|
|
LEM : {
|
|
dataFolder: "lem",
|
|
beamLine : "MUE4",
|
|
defFormat : "MUSR-ROOT",
|
|
minYear : "2001"
|
|
},
|
|
GPS : {
|
|
dataFolder: "gps",
|
|
beamLine : "PIM3",
|
|
defFormat : "PSI-BIN",
|
|
minYear : "1993"
|
|
},
|
|
FLAME : {
|
|
dataFolder: "flame",
|
|
beamLine : "PIM3",
|
|
defFormat : "MUSR-ROOT",
|
|
minYear : "2020"
|
|
},
|
|
LTF : {
|
|
dataFolder: "ltf",
|
|
beamLine : "PIM3",
|
|
defFormat : "PSI-BIN",
|
|
minYear : "1995"
|
|
},
|
|
Dolly : {
|
|
dataFolder: "dolly",
|
|
beamLine : "PIE1",
|
|
defFormat : "PSI-BIN",
|
|
minYear : "1998"
|
|
},
|
|
VMS : {
|
|
dataFolder: "vms",
|
|
beamLine : "PIE1",
|
|
defFormat : "MUSR-ROOT",
|
|
minYear : "2025"
|
|
},
|
|
GPD : {
|
|
dataFolder: "gpd",
|
|
beamLine : "PIE1",
|
|
defFormat : "PSI-BIN",
|
|
minYear : "1993"
|
|
},
|
|
HAL : {
|
|
dataFolder: "hal",
|
|
beamLine : "PIE3",
|
|
defFormat : "PSI-MDU",
|
|
minYear : "2012"
|
|
}
|
|
};
|
|
|
|
// Theory-component catalogue. Add a component by defining its description and
|
|
// emitted THEORY lines; the referenced parameter names are derived below.
|
|
const funcDictionary = {
|
|
Asymmetry : {
|
|
descrip : "Constant Asymmetry",
|
|
theoryBlk : "asymmetry Asy"},
|
|
Exponential : {
|
|
descrip : "Exponential",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam"},
|
|
Gaussian : {
|
|
descrip : "Gaussian",
|
|
theoryBlk : "asymmetry Asy\nsimpleGss Sgm"},
|
|
Stretch : {
|
|
descrip : "Stretch Exponential",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet"},
|
|
SLKT : {
|
|
descrip : "Lorentzian KT",
|
|
theoryBlk : "asymmetry Asy\nstatExpKTLF BFrq Del"},
|
|
SGKT : {
|
|
descrip : "Gaussian KT",
|
|
theoryBlk : "asymmetry Asy\nstatGssKTLF BFrq Sgm"},
|
|
LGKT : {
|
|
descrip : "Combi Lorentzian/Gaussian KT",
|
|
theoryBlk : "asymmetry Asy\ncombiLGKT Del Sgm"},
|
|
STRKT : {
|
|
descrip : "Stretched KT",
|
|
theoryBlk : "asymmetry Asy\nstrKT Del Bet"},
|
|
GBGZF : {
|
|
descrip : "Gaussian Broadened Gaussian ZF",
|
|
theoryBlk : "asymmetry Asy\nstaticNKZF Del Rb"},
|
|
ExponentialCos : {
|
|
descrip : "Exponential Cosine",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nTFieldCos Phi Frq"},
|
|
GaussianCos : {
|
|
descrip : "Gaussian Cosine",
|
|
theoryBlk : "asymmetry Asy\nsimpleGss Sgm\nTFieldCos Phi Frq"},
|
|
StretchCos : {
|
|
descrip : "Stretch Cosine",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\nTFieldCos Phi Frq"},
|
|
AbragamCos : {
|
|
descrip : "Abragam Cosine",
|
|
theoryBlk : "asymmetry Asy\nabragam Del Lam\nTFieldCos Phi Frq"},
|
|
GBGCos : {
|
|
descrip : "Gaussian Broadened Gaussian Cosine",
|
|
theoryBlk : "asymmetry Asy\nstaticNKTF Phi Frq Del Rb"},
|
|
ExponentialBessel : {
|
|
descrip : "Exponential Bessel",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nBessel Phi Frq"},
|
|
GaussianBessel : {
|
|
descrip : "Gaussian Bessel",
|
|
theoryBlk : "asymmetry Asy\nsimpleGss Sgm\nBessel Phi Frq"},
|
|
LLFExp : {
|
|
descrip : "Lorentzian KT LF x Exp",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nstatExpKTLF BFrq Del"},
|
|
GLFExp : {
|
|
descrip : "Gaussian KT LF x Exp",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nstatGssKTLF BFrq Sgm"},
|
|
LGKTExp : {
|
|
descrip : "Combi Lorentzian/Gaussian KT x Exp",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\ncombiLGKT Del Sgm"},
|
|
GBGExp : {
|
|
descrip : "Gaussian Broadened Gaussian ZF x Exp",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nstaticNKZF Del Rb"},
|
|
STRKTExp : {
|
|
descrip : "Stretched KT x Exp",
|
|
theoryBlk : "asymmetry Asy\nsimplExpo Lam\nstrKT Del KTBet"},
|
|
LLFSExp : {
|
|
descrip : "Lorentzian KT LF x Str Exp",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\nstatExpKTLF BFrq Del"},
|
|
GLFSExp : {
|
|
descrip : "Gaussian KT LF x Str Exp",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\nstatGssKTLF BFrq Sgm" },
|
|
LGKTSExp : {
|
|
descrip : "Combi Lorentzian/Gaussian KT x Str Exp",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\ncombiLGKT Del Sgm"},
|
|
GBGSExp : {
|
|
descrip : "Gaussian Broadened Gaussian ZF x Str Exp",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\nstaticNKZF Del Rb"},
|
|
STRKTSExp : {
|
|
descrip : "Stretched KT x Str Exp",
|
|
theoryBlk : "asymmetry Asy\ngenerExpo Lam Bet\nstrKT Del KTBet" },
|
|
LDKTLF : {
|
|
descrip : "Lorentzian Dynamic KT LF",
|
|
theoryBlk : "asymmetry Asy\ndynExpKTLF BFrq Del Gam"},
|
|
GDKTLF : {
|
|
descrip : "Gaussian Dynamic KT LF",
|
|
theoryBlk : "asymmetry Asy\ndynGssKTLF BFrq Sgm Gam"}
|
|
};
|
|
|
|
const msrTemplate = `
|
|
# Run Numbers: RUN_NUMBERS
|
|
###############################################################
|
|
FITPARAMETER
|
|
###############################################################
|
|
# No Name Value Step PosErr Min Max
|
|
PARAMETER_BLOCK
|
|
###############################################################
|
|
THEORY
|
|
TEORY_BLOCK
|
|
FUNCTIONS_BLOCK
|
|
GLOBAL
|
|
GLOBAL_BLOCK
|
|
###############################################################
|
|
RUN_BLOCK
|
|
###############################################################
|
|
COMMANDS
|
|
COMMANDS_BLOCK
|
|
###############################################################
|
|
PLOT_BLOCK
|
|
###############################################################
|
|
FOURIER
|
|
FOURIER_BLOCK
|
|
###############################################################
|
|
# Created by muSRFlow (Zaher Salman; GNU GPL version 3 or later; https://musruser.psi.ch/muSRFlow/)
|
|
`
|
|
|
|
// Create additional property with an array of parameters. The catalogue itself
|
|
// lists the physical parameters first (asymmetry, then relaxation/lineshape,
|
|
// then precession frequency, then phase, then alphas/ratios, then
|
|
// normalization/background, custom last) so the parameter dropdown, the table
|
|
// and the generated FITPARAMETER block all start from the same physical
|
|
// sequence. Equal roles keep their theory-block order (stable sort).
|
|
for (let key in funcDictionary) {
|
|
let lines = funcDictionary[key].theoryBlk.split("\n");
|
|
let pars = [];
|
|
for (let line of lines) {
|
|
let tmp = line.trim().split(" ");
|
|
tmp.shift();
|
|
pars = pars.concat(tmp);
|
|
}
|
|
pars.sort(function(a, b) {
|
|
return physicalParameterRoleRank(a) - physicalParameterRoleRank(b);
|
|
});
|
|
funcDictionary[key].pars = pars;
|
|
}
|
|
|
|
// The parameter names that appear in the built-in theory blocks. Custom
|
|
// parameters must not shadow these so the generated FITPARAMETER block and
|
|
// FUNCTIONS constraints stay unambiguous. This set is derived from
|
|
// funcDictionary rather than defVals: defVals may also carry default-value
|
|
// entries (e.g. Field, Energy) that are not theory parameters and remain
|
|
// available as custom parameter names.
|
|
const musrfitBuiltinParameterNames = new Set();
|
|
for (let key in funcDictionary) {
|
|
for (let par of funcDictionary[key].pars) musrfitBuiltinParameterNames.add(par);
|
|
}
|
|
|
|
// This is the default values of parameters
|
|
// parName : {
|
|
// value : starting_value,
|
|
// err : starting_error or step, (we can use 5% of value)
|
|
// min : minimum_value, (optional)
|
|
// max : maximum_value}, (optional)
|
|
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 : {
|
|
value : 300},
|
|
NBg : {
|
|
value : 30},
|
|
Lam : {
|
|
value : 1.0},
|
|
Gam : {
|
|
value : 1.0},
|
|
Bet : {
|
|
value : 0.5},
|
|
KTBet : {
|
|
value : 0.5},
|
|
SBet : {
|
|
value : 0.5},
|
|
Two : {
|
|
value : 2.0},
|
|
Del : {
|
|
value : 0.1},
|
|
Rb : {
|
|
value : 1.0},
|
|
Sgm : {
|
|
value : 0.1},
|
|
Aa : {
|
|
value : 60.0},
|
|
q : {
|
|
value : 0.1},
|
|
Bg : {
|
|
value : 0.02},
|
|
Frq : {
|
|
value : 1.355},
|
|
BFrq : {
|
|
value : 0.0},
|
|
Field : {
|
|
value : 100.0},
|
|
Energy : {
|
|
value : 14},
|
|
Lambda : {
|
|
value : 120 },
|
|
Phi : {
|
|
value : 1.0 },
|
|
relPhi : {
|
|
value : 1.0 },
|
|
};
|
|
// Job/result status helpers.
|
|
|
|
// Build a readable command string for logs/status messages. The actual process
|
|
// still runs through spawn(command, args) without a shell, so this is display
|
|
// only and does not affect argument parsing.
|
|
function displayCommand(command, args) {
|
|
return [command].concat(args).map(function(part) {
|
|
if (/^[A-Za-z0-9_./:=+-]+$/.test(part)) return part;
|
|
return "'" + part.replace(/'/g, "'\\''") + "'";
|
|
}).join(" ");
|
|
}
|
|
|
|
// Extract the data-set identity (RUN/ADDRUN directives) from an MSR. Used to
|
|
// verify that post-fit MSRs retain the exact run set a series fit staged, so a
|
|
// malformed or accidental run change cannot be mistaken for a converged result.
|
|
function seriesRunDirectiveIdentity(msrText) {
|
|
let directives = [];
|
|
for (let line of String(msrText || "").split(/\r?\n/)) {
|
|
if (!/^\s*(?:RUN|ADDRUN)\b/i.test(line)) continue;
|
|
let fields = line.trim().split(/\s+/);
|
|
if (fields.length < 5) {
|
|
// Preserve malformed directives in the signature so they cannot
|
|
// accidentally compare equal to a valid RUN or ADDRUN.
|
|
directives.push("INVALID " + fields.join(" "));
|
|
continue;
|
|
}
|
|
// RUN and ADDRUN have five semantic fields. musrfit may append an
|
|
// explanatory parenthetical comment when it rewrites the fitted MSR;
|
|
// comments are not part of the data-set identity.
|
|
directives.push([
|
|
fields[0].toUpperCase(), fields[1], fields[2], fields[3], fields[4]
|
|
].join(" "));
|
|
}
|
|
return directives.join("\n");
|
|
}
|
|
|
|
// Normalize a msr2data parameter-table header so downstream plotting sees the
|
|
// logical parameter names. Global msr2data exports represent run-qualified
|
|
// parameters such as Asy_2274 as Asy_, while ordinary per-run exports retain
|
|
// the first run suffix as Asy_2274, Asy_2274PosErr, and Asy_2274NegErr. Strip
|
|
// only suffixes that match the supplied run list. Embedded underscores in names
|
|
// remain untouched. Pure text transformation: the caller supplies the column
|
|
// lines and receives normalized lines back.
|
|
function normalizeParameterDataHeaderLines(lines, runNumbers = []) {
|
|
let runs = new Set(runNumbers.map(function(run) {
|
|
return String(Number(run));
|
|
}).filter(function(run) {
|
|
return /^\d+$/.test(run);
|
|
}));
|
|
|
|
let result = lines.slice();
|
|
for (let i = 0; i < result.length; i++) {
|
|
let probe = result[i].trim();
|
|
if (!probe || probe.startsWith("#")) continue;
|
|
result[i] = result[i].replace(/\S+/g, function(column) {
|
|
let qualified = /^(.*)_([0-9]+)((?:_)?(?:PosErr|NegErr))?$/.exec(column);
|
|
if (qualified && runs.has(String(Number(qualified[2])))) {
|
|
return qualified[1] + (qualified[3] || "");
|
|
}
|
|
return column.endsWith("_") ? column.slice(0, -1) : column;
|
|
});
|
|
break;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
function jobTimestamp() {
|
|
let now = new Date();
|
|
return now.toLocaleString();
|
|
}
|
|
|
|
function firstStatusLine(message) {
|
|
let text = "";
|
|
if (message !== undefined && message !== null) {
|
|
text = message.toString();
|
|
}
|
|
let lines = text.split(/\r?\n/);
|
|
return lines[0];
|
|
}
|
|
|
|
// Keep execution locking and its visible controls in one place. Callers change
|
|
// phases, while this function owns button labels, disabled state, and the nearby
|
|
// activity announcement for both web and Electron.
|
|
function setMusrfitActionState(action = "", phase = "idle") {
|
|
let normalizedAction = action == "fit" || action == "plot" ? action : "";
|
|
let normalizedPhase = phase == "preparing" || phase == "running" ? phase : "idle";
|
|
let busy = normalizedAction !== "" && normalizedPhase !== "idle";
|
|
window.MusrfitAction.busy = busy;
|
|
window.MusrfitAction.action = busy ? normalizedAction : "";
|
|
window.MusrfitAction.phase = busy ? normalizedPhase : "idle";
|
|
|
|
if (typeof document === "undefined" || typeof document.getElementById !== "function") {
|
|
return window.MusrfitAction;
|
|
}
|
|
|
|
let fitButton = document.getElementById("FitMSR");
|
|
let plotButton = document.getElementById("PlotMSR");
|
|
let activity = document.getElementById("musrfitActionActivity");
|
|
let activityText = document.getElementById("musrfitActionActivityText");
|
|
let appShell = document.getElementById("appShell");
|
|
let fitIsActive = busy && normalizedAction == "fit";
|
|
let plotIsActive = busy && normalizedAction == "plot";
|
|
// Electron can kill the local process through the preload bridge, so the
|
|
// running button becomes an active "Abort". The Electron shim defines
|
|
// window.triggerMusrfitAbort at load time (before this library), so its
|
|
// presence is the capability signal; web jobs run server-side and the
|
|
// button stays disabled instead. The flag exists for tests and clarity.
|
|
let abortSupported = typeof window.triggerMusrfitAbort === "function"
|
|
|| window.MusrfitAction.abortSupported === true;
|
|
let fitAbortable = fitIsActive && normalizedPhase == "running" && abortSupported;
|
|
let plotAbortable = plotIsActive && normalizedPhase == "running" && abortSupported;
|
|
|
|
if (fitButton) {
|
|
fitButton.disabled = busy && !fitAbortable;
|
|
fitButton.textContent = fitAbortable ? "Abort" : "Fit";
|
|
fitButton.className = "action-btn action-btn-primary" + (fitIsActive ? " is-running" : "");
|
|
fitButton.setAttribute("aria-busy", fitIsActive ? "true" : "false");
|
|
setMusrfitAbortClick(fitButton, fitAbortable, "fit");
|
|
}
|
|
if (plotButton) {
|
|
plotButton.disabled = busy && !plotAbortable;
|
|
plotButton.textContent = plotAbortable ? "Abort" : "Plot";
|
|
plotButton.className = "action-btn action-btn-secondary" + (plotIsActive ? " is-running" : "");
|
|
plotButton.setAttribute("aria-busy", plotIsActive ? "true" : "false");
|
|
setMusrfitAbortClick(plotButton, plotAbortable, "plot");
|
|
}
|
|
|
|
let phaseMessage = "";
|
|
if (fitIsActive) {
|
|
phaseMessage = normalizedPhase == "preparing" ? "Preparing fit files" : "Running musrfit";
|
|
} else if (plotIsActive) {
|
|
phaseMessage = normalizedPhase == "preparing" ? "Preparing plot files" : "Running musrview";
|
|
}
|
|
if (activity) {
|
|
activity.hidden = !busy;
|
|
activity.dataset.action = busy ? normalizedAction : "";
|
|
activity.dataset.phase = busy ? normalizedPhase : "idle";
|
|
}
|
|
if (activityText) {
|
|
activityText.textContent = phaseMessage;
|
|
}
|
|
if (appShell) {
|
|
appShell.setAttribute("aria-busy", busy ? "true" : "false");
|
|
}
|
|
|
|
return window.MusrfitAction;
|
|
}
|
|
|
|
// Swap the running action button's click target to Abort and back. The original
|
|
// inline handler (startFit/startPlot) is captured on the first abortable render
|
|
// so it can be restored when the job finishes; without an original handler
|
|
// (tests, dynamic buttons) a null target simply disables the click.
|
|
function setMusrfitAbortClick(button, abortable, action) {
|
|
if (!abortable) {
|
|
if (button.__musrActionAbortAttached) {
|
|
button.__musrActionAbortAttached = false;
|
|
button.onclick = button.__musrOriginalClick || null;
|
|
}
|
|
return;
|
|
}
|
|
if (button.__musrActionAbortAttached) return;
|
|
if (!button.__musrOriginalClick) {
|
|
button.__musrOriginalClick = button.onclick;
|
|
}
|
|
button.__musrActionAbortAttached = true;
|
|
button.onclick = function(event) {
|
|
if (event && typeof event.preventDefault === "function") event.preventDefault();
|
|
if (typeof window.triggerMusrfitAbort === "function") {
|
|
window.triggerMusrfitAbort(action);
|
|
}
|
|
};
|
|
}
|
|
|
|
// musrfit and musrview use the same PRunDataHandler diagnostics when a RUN file
|
|
// cannot be resolved. Convert that verbose executable output into one structured
|
|
// workflow outcome while retaining every path for the detailed job log.
|
|
function classifyMissingDataOutput(output, options = {}) {
|
|
let text = output === undefined || output === null ? "" : output.toString();
|
|
let suppliedFiles = Array.isArray(options.missingFiles) ? options.missingFiles : [];
|
|
let missingFiles = [];
|
|
let seenFiles = new Set();
|
|
|
|
function rememberMissingFile(filePath) {
|
|
let path = filePath === undefined || filePath === null ? "" : filePath.toString().trim();
|
|
if (path !== "" && !seenFiles.has(path)) {
|
|
seenFiles.add(path);
|
|
missingFiles.push(path);
|
|
}
|
|
}
|
|
|
|
for (let suppliedFile of suppliedFiles) {
|
|
rememberMissingFile(suppliedFile);
|
|
}
|
|
|
|
let pathPattern = /Couldn't find\s+['"]([^'"\r\n]+)['"]\s+in any standard path/gi;
|
|
let pathMatch;
|
|
while ((pathMatch = pathPattern.exec(text)) !== null) {
|
|
rememberMissingFile(pathMatch[1]);
|
|
}
|
|
|
|
let detected = options.outcome == "missing-data"
|
|
|| missingFiles.length > 0
|
|
|| (
|
|
/PRunDataHandler::FileExistsCheck\(\)/i.test(text)
|
|
&& /Couldn't read all data files/i.test(text)
|
|
);
|
|
if (!detected) {
|
|
return {
|
|
outcome: "",
|
|
missingFiles: [],
|
|
summary: "",
|
|
details: ""
|
|
};
|
|
}
|
|
|
|
let summary = "Required data files were not found.";
|
|
if (missingFiles.length == 1) {
|
|
let pathParts = missingFiles[0].split(/[\\/]/);
|
|
summary = "Data file not found: " + pathParts[pathParts.length - 1];
|
|
} else if (missingFiles.length > 1) {
|
|
summary = missingFiles.length + " data files were not found.";
|
|
}
|
|
|
|
let details = summary;
|
|
if (missingFiles.length == 1) {
|
|
details += "\n\nExpected path:\n" + missingFiles[0];
|
|
} else if (missingFiles.length > 1) {
|
|
details += "\n\nMissing files:\n" + missingFiles.join("\n");
|
|
}
|
|
details += "\n\nCheck the instrument, year, run number, and configured data root.";
|
|
|
|
return {
|
|
outcome: "missing-data",
|
|
missingFiles: missingFiles,
|
|
summary: summary,
|
|
details: details
|
|
};
|
|
}
|
|
|
|
// Read the authoritative fit summary written by musrfit at the end of the MSR.
|
|
// The STATISTIC block has a stable one-line form for either chisq or maxLH and
|
|
// an explicit marker for non-convergence. Ignore expected/per-run statistics so
|
|
// the compact status bar always reports the overall fit result.
|
|
function parseMSRFitStatistic(msrText) {
|
|
let result = {
|
|
found: false,
|
|
converged: null,
|
|
kind: "",
|
|
value: "",
|
|
ndf: "",
|
|
text: ""
|
|
};
|
|
if (typeof msrText !== "string" || msrText === "") return result;
|
|
|
|
let lines = msrText.split(/\r?\n/);
|
|
let statisticStart = -1;
|
|
for (let i = 0; i < lines.length; i++) {
|
|
if (/^\s*STATISTIC(?:\s|$)/i.test(lines[i])) statisticStart = i;
|
|
}
|
|
if (statisticStart < 0) return result;
|
|
|
|
result.found = true;
|
|
let statisticLines = lines.slice(statisticStart + 1);
|
|
if (statisticLines.some(function(line) {
|
|
return /FIT\s+DID\s+NOT\s+CONVERGE/i.test(line);
|
|
})) {
|
|
result.converged = false;
|
|
result.text = "Fit did not converge";
|
|
return result;
|
|
}
|
|
|
|
// musrfit writes, for example,
|
|
// "chisq = 101.2, NDF = 100, chisq/NDF = 1.012000". Match only
|
|
// the leading overall line so "expected chisq" cannot be mistaken for it.
|
|
let numberPattern = "([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)";
|
|
let chisqPattern = new RegExp(
|
|
"^\\s*chisq\\s*=\\s*" + numberPattern
|
|
+ "\\s*,\\s*NDF\\s*=\\s*(\\d+)"
|
|
+ "\\s*,\\s*chisq/NDF\\s*=\\s*" + numberPattern, "i");
|
|
let maxLHPattern = new RegExp(
|
|
"^\\s*maxLH\\s*=\\s*" + numberPattern
|
|
+ "\\s*,\\s*NDF\\s*=\\s*(\\d+)"
|
|
+ "\\s*,\\s*maxLH/NDF\\s*=\\s*" + numberPattern, "i");
|
|
|
|
for (let line of statisticLines) {
|
|
let match = line.match(chisqPattern);
|
|
if (match) {
|
|
result.converged = true;
|
|
result.kind = "chisq";
|
|
result.ndf = match[2];
|
|
result.value = match[3];
|
|
let displayValue = Number(result.value);
|
|
result.text = "χ²/NDF " + (Number.isFinite(displayValue) ? displayValue.toString() : result.value);
|
|
return result;
|
|
}
|
|
match = line.match(maxLHPattern);
|
|
if (match) {
|
|
result.converged = true;
|
|
result.kind = "maxLH";
|
|
result.ndf = match[2];
|
|
result.value = match[3];
|
|
let displayValue = Number(result.value);
|
|
result.text = "maxLH/NDF " + (Number.isFinite(displayValue) ? displayValue.toString() : result.value);
|
|
return result;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
function normalizeSeriesDataSet(dataSet) {
|
|
if (!dataSet || !Number.isInteger(dataSet.main) || dataSet.main <= 0
|
|
|| !Array.isArray(dataSet.add)
|
|
|| dataSet.add.some(function(run) {
|
|
return !Number.isInteger(run) || run <= 0;
|
|
})) {
|
|
return null;
|
|
}
|
|
return {
|
|
main: dataSet.main,
|
|
add: dataSet.add.slice()
|
|
};
|
|
}
|
|
|
|
function seriesDataSetPhysicalRuns(dataSet) {
|
|
let normalized = normalizeSeriesDataSet(dataSet);
|
|
return normalized ? [normalized.main].concat(normalized.add) : [];
|
|
}
|
|
|
|
function inspectSeriesMSRIdentity(msrText, expectedDataSet, expectedInstrument, expectedYear) {
|
|
let expected = normalizeSeriesDataSet(expectedDataSet);
|
|
let result = {
|
|
matches: false,
|
|
reason: "invalid-msr",
|
|
runSelection: [],
|
|
instrument: "",
|
|
year: ""
|
|
};
|
|
if (!expected || typeof msrText !== "string" || msrText.trim() === "") {
|
|
return result;
|
|
}
|
|
|
|
let parsed = parseMSRGUISettings(msrText);
|
|
let parsedSelection = parseRunSelection(parsed.values.runNumbers || "");
|
|
result.runSelection = parsedSelection;
|
|
result.instrument = parsed.values.instrName || "";
|
|
result.year = parsed.values.selYear || "";
|
|
|
|
// An independently fitted MSR represents exactly one logical data set. A
|
|
// SingleHist file may contain several RUN blocks, but the settings parser
|
|
// deduplicates those blocks when they all refer to the same data set.
|
|
if (parsedSelection.length !== 1) {
|
|
result.reason = "run-selection-mismatch";
|
|
return result;
|
|
}
|
|
let actual = parsedSelection[0];
|
|
if (actual.main !== expected.main
|
|
|| actual.add.length !== expected.add.length
|
|
|| actual.add.some(function(run, index) {
|
|
return run !== expected.add[index];
|
|
})) {
|
|
result.reason = "run-selection-mismatch";
|
|
return result;
|
|
}
|
|
|
|
if (expectedInstrument
|
|
&& result.instrument.toUpperCase() !== String(expectedInstrument).toUpperCase()) {
|
|
result.reason = "instrument-mismatch";
|
|
return result;
|
|
}
|
|
if (expectedYear && result.year !== String(expectedYear)) {
|
|
result.reason = "year-mismatch";
|
|
return result;
|
|
}
|
|
|
|
result.matches = true;
|
|
result.reason = "matched";
|
|
return result;
|
|
}
|
|
|
|
// Classify an already existing per-data-set MSR without touching the filesystem.
|
|
// `availableDataRuns` must contain only run numbers whose data files have been
|
|
// positively verified by the platform adapter. Requiring two distinct newer
|
|
// data runs avoids treating a converged fit as proof that acquisition ended.
|
|
function classifySeriesFitResult(options = {}) {
|
|
let expectedDataSet = normalizeSeriesDataSet(options.expectedDataSet);
|
|
let physicalRuns = seriesDataSetPhysicalRuns(expectedDataSet);
|
|
let latestPhysicalRun = physicalRuns.length > 0 ? Math.max.apply(null, physicalRuns) : 0;
|
|
let requiredLaterRuns = Number.isInteger(options.requiredLaterRuns)
|
|
&& options.requiredLaterRuns >= 0 ? options.requiredLaterRuns : 2;
|
|
let availableDataRuns = Array.isArray(options.availableDataRuns)
|
|
? options.availableDataRuns : [];
|
|
let laterDataRuns = Array.from(new Set(availableDataRuns.filter(function(run) {
|
|
return Number.isInteger(run) && run > latestPhysicalRun;
|
|
}))).sort(function(a, b) { return a - b; });
|
|
let base = {
|
|
state: "invalid-request",
|
|
action: "blocked",
|
|
reusable: false,
|
|
reason: "invalid-expected-data-set",
|
|
expectedRun: expectedDataSet ? expectedDataSet.main : 0,
|
|
latestPhysicalRun: latestPhysicalRun,
|
|
laterDataRuns: laterDataRuns,
|
|
requiredLaterRuns: requiredLaterRuns,
|
|
statistic: {
|
|
found: false,
|
|
converged: null,
|
|
kind: "",
|
|
value: "",
|
|
ndf: "",
|
|
text: ""
|
|
}
|
|
};
|
|
if (!expectedDataSet) return base;
|
|
|
|
if (options.msrExists !== true) {
|
|
base.state = "missing-msr";
|
|
base.action = "fit";
|
|
base.reason = "msr-file-not-found";
|
|
return base;
|
|
}
|
|
if (typeof options.msrText !== "string" || options.msrText.trim() === "") {
|
|
base.state = "invalid-msr";
|
|
base.reason = "empty-msr";
|
|
return base;
|
|
}
|
|
|
|
let identity = inspectSeriesMSRIdentity(
|
|
options.msrText,
|
|
expectedDataSet,
|
|
options.expectedInstrument || "",
|
|
options.expectedYear || ""
|
|
);
|
|
if (!identity.matches) {
|
|
base.state = identity.reason == "invalid-msr" ? "invalid-msr" : "wrong-run";
|
|
base.reason = identity.reason;
|
|
return base;
|
|
}
|
|
|
|
base.statistic = parseMSRFitStatistic(options.msrText);
|
|
if (!base.statistic.found) {
|
|
base.state = "not-converged";
|
|
base.action = "retry";
|
|
base.reason = "statistic-not-found";
|
|
return base;
|
|
}
|
|
if (base.statistic.converged !== true) {
|
|
base.state = "not-converged";
|
|
base.action = "retry";
|
|
base.reason = base.statistic.converged === false
|
|
? "fit-did-not-converge" : "statistic-not-recognized";
|
|
return base;
|
|
}
|
|
|
|
if (laterDataRuns.length < requiredLaterRuns) {
|
|
base.state = "converged-recent";
|
|
base.action = "refit";
|
|
base.reason = "not-enough-newer-data-runs";
|
|
return base;
|
|
}
|
|
|
|
base.state = "converged-complete";
|
|
base.action = "skip";
|
|
base.reusable = true;
|
|
base.reason = "converged-with-newer-data-runs";
|
|
return base;
|
|
}
|
|
|
|
function joinSeriesWorkPath(workPath, fileName) {
|
|
let basePath = normalizeWorkPath(workPath);
|
|
if (basePath == "/") return "/" + fileName;
|
|
return basePath.replace(/\/+$/, "") + "/" + fileName;
|
|
}
|
|
|
|
function seriesDataFilePath(run, all) {
|
|
// Portable RUN naming emits RUN directives relative to a startup-XML
|
|
// <data_path>. The series inventory is keyed on absolute paths on both the
|
|
// browser and the CGI, so resolve the portable sub-path against the
|
|
// data_path it was found under (an absolute path that exists by
|
|
// construction), instead of sending a bare relative token that neither the
|
|
// CGI validator nor a subsequent existence check can use.
|
|
if (portableRunNamingEnabled) {
|
|
let portable = portableRunFileName(run, all.selYear, all.instrName, all.dataRoot);
|
|
if (portable) {
|
|
return portable.dataPath + "/" + portable.subPath;
|
|
}
|
|
}
|
|
let runDirective = runFileNameAuto(
|
|
run,
|
|
all.selYear,
|
|
all.instrName,
|
|
all.dataRoot
|
|
);
|
|
// RUN directives conventionally omit the extension and let musrfit infer it
|
|
// from the data format. Direct filesystem/HTTP inspection cannot do that, so
|
|
// use the same format mapping as dump_header to resolve the actual file.
|
|
let headerRequest = dumpHeaderRequestFromRunDirective(runDirective);
|
|
return headerRequest
|
|
? headerRequest.filePath : runFileTokenFromDirective(runDirective);
|
|
}
|
|
|
|
function summarizeSeriesFitEntries(entries) {
|
|
let summary = {
|
|
total: 0,
|
|
fit: 0,
|
|
retry: 0,
|
|
refit: 0,
|
|
skip: 0,
|
|
blocked: 0
|
|
};
|
|
for (let entry of (entries || [])) {
|
|
summary.total++;
|
|
if (Object.prototype.hasOwnProperty.call(summary, entry.action)) {
|
|
summary[entry.action]++;
|
|
} else {
|
|
summary.blocked++;
|
|
}
|
|
}
|
|
return summary;
|
|
}
|
|
|
|
// Inspect the selected series without creating, changing, or deleting files.
|
|
// Both platform implementations already expose fileExists()/readAsciiFile();
|
|
// tests inject the same two operations so the planning rules stay transport
|
|
// independent. startFit() calls this only after the pure route decision selects
|
|
// the series workflow.
|
|
async function inspectSeriesFitPlan(config = {}, fileAccess = {}) {
|
|
let all = config.all || {};
|
|
let runSelection = Array.isArray(config.runSelection)
|
|
? config.runSelection : parseRunSelection(all.runNumbers || config.runNumbers || "");
|
|
let actionOverrides = config.actionOverrides && typeof config.actionOverrides === "object"
|
|
? config.actionOverrides : {};
|
|
let execution = planFitExecution(
|
|
runSelection,
|
|
config.sharedFlags || {},
|
|
{ crossRunCoupling: config.crossRunCoupling === true }
|
|
);
|
|
let plan = {
|
|
ok: false,
|
|
mode: execution.mode,
|
|
reason: execution.reason,
|
|
execution: execution,
|
|
workPath: normalizeWorkPath(config.workPath || all.workPath || defaultWorkPath),
|
|
fileNameSuffix: "",
|
|
availableDataRuns: [],
|
|
entries: [],
|
|
summary: summarizeSeriesFitEntries([])
|
|
};
|
|
|
|
// Single and global workflows remain owned by their existing preparation
|
|
// paths. Avoid even read-only probing until the independent series route is
|
|
// selected explicitly by the planner.
|
|
if (execution.mode != "series") {
|
|
plan.reason = execution.mode == "invalid"
|
|
? execution.reason : "not-independent-series";
|
|
return plan;
|
|
}
|
|
|
|
let webMode = config.webMode === true;
|
|
let existsFn = fileAccess.msrFileExists || fileAccess.fileExists;
|
|
let dataExistsFn = fileAccess.dataFileExists;
|
|
let readFn = fileAccess.readAsciiFile;
|
|
if (typeof existsFn !== "function" && typeof fileExists === "function") {
|
|
existsFn = fileExists;
|
|
}
|
|
// Electron can inspect resolved data paths directly. In web mode those paths
|
|
// belong to the server filesystem rather than its HTTP document tree, so a
|
|
// later CGI adapter must be supplied explicitly instead of issuing a bogus
|
|
// browser HEAD request for /psi.ch/... .
|
|
if (typeof dataExistsFn !== "function" && !webMode) {
|
|
dataExistsFn = existsFn;
|
|
}
|
|
if (typeof readFn !== "function" && typeof readAsciiFile === "function") {
|
|
readFn = readAsciiFile;
|
|
}
|
|
if (typeof existsFn !== "function" || typeof dataExistsFn !== "function"
|
|
|| typeof readFn !== "function") {
|
|
plan.reason = "file-access-unavailable";
|
|
return plan;
|
|
}
|
|
|
|
plan.fileNameSuffix = config.fileNameSuffix
|
|
|| fitFileSuffix(all, webMode);
|
|
|
|
let physicalRuns = Array.from(new Set(runSelection.reduce(function(runs, dataSet) {
|
|
return runs.concat(seriesDataSetPhysicalRuns(dataSet));
|
|
}, []))).sort(function(a, b) { return a - b; });
|
|
let dataPathByRun = Object.create(null);
|
|
for (let run of physicalRuns) {
|
|
try {
|
|
dataPathByRun[run] = seriesDataFilePath(run, all);
|
|
} catch (error) {
|
|
plan.reason = error && error.message
|
|
? error.message : "could-not-resolve-data-path";
|
|
return plan;
|
|
}
|
|
}
|
|
|
|
let dataChecks = await Promise.all(physicalRuns.map(async function(run) {
|
|
let exists = await dataExistsFn(dataPathByRun[run]);
|
|
return { run: run, exists: Boolean(exists) };
|
|
}));
|
|
plan.availableDataRuns = dataChecks.filter(function(check) {
|
|
return check.exists;
|
|
}).map(function(check) {
|
|
return check.run;
|
|
});
|
|
let availableDataSet = new Set(plan.availableDataRuns);
|
|
|
|
let skippedMissingMsr = 0;
|
|
plan.entries = await Promise.all(runSelection.map(async function(dataSet) {
|
|
let msrName = dataSet.main + plan.fileNameSuffix + ".msr";
|
|
let msrPath = joinSeriesWorkPath(plan.workPath, msrName);
|
|
let msrExists = Boolean(await existsFn(msrPath));
|
|
let msrText = msrExists ? await readFn(msrPath) : "";
|
|
if (typeof msrText !== "string") msrText = "";
|
|
|
|
let classification = classifySeriesFitResult({
|
|
expectedDataSet: dataSet,
|
|
expectedInstrument: all.instrName || "",
|
|
expectedYear: all.selYear || "",
|
|
msrExists: msrExists,
|
|
msrText: msrText,
|
|
availableDataRuns: plan.availableDataRuns,
|
|
requiredLaterRuns: config.requiredLaterRuns
|
|
});
|
|
let requiredDataRuns = seriesDataSetPhysicalRuns(dataSet);
|
|
let missingDataRuns = requiredDataRuns.filter(function(run) {
|
|
return !availableDataSet.has(run);
|
|
});
|
|
|
|
// Per-run series action chips can override the natural classification.
|
|
// "reuse" accepts an existing, identity-checked converged result even
|
|
// when it is too recent for automatic reuse. "refit" regenerates the MSR
|
|
// from the live GUI, while "skip" leaves the run completely untouched.
|
|
let useGuiTemplate = false;
|
|
if (Object.prototype.hasOwnProperty.call(actionOverrides, dataSet.main)) {
|
|
let override = actionOverrides[dataSet.main];
|
|
if (override == "reuse" && msrExists
|
|
&& classification.statistic.converged === true) {
|
|
classification.state = "converged-complete";
|
|
classification.action = "skip";
|
|
classification.reusable = true;
|
|
classification.reason = "user-requested-reuse";
|
|
} else if (override == "refit") {
|
|
// "refit" means rebuild this run from the live GUI parameters and
|
|
// replace its on-disk MSR. Replacing nothing is contradictory, so
|
|
// when the MSR no longer exists (e.g. it was deleted) treat it as a
|
|
// create/fit instead and still honour the user's "rebuild" intent.
|
|
classification.action = "refit";
|
|
classification.reusable = false;
|
|
classification.useGuiTemplate = true;
|
|
useGuiTemplate = true;
|
|
classification.reason = msrExists
|
|
? "user-requested-refit" : "user-requested-refit-missing-msr";
|
|
if (!msrExists) classification.action = "fit";
|
|
} else if (override == "skip") {
|
|
classification.action = "skip";
|
|
classification.reusable = false;
|
|
classification.reason = "user-requested-skip";
|
|
// A skip leaves the run's on-disk MSR untouched. If that file no
|
|
// longer exists, skip would silently report a missing file as a
|
|
// healthy reuse, so record it and fail the plan below. The user can
|
|
// change that run back to a refit or remove it from the fit.
|
|
if (!msrExists) skippedMissingMsr = skippedMissingMsr || dataSet.main;
|
|
}
|
|
}
|
|
|
|
// A data set whose GUI parameters or structural settings changed since the
|
|
// saved MSR represented them is always rebuilt from the live GUI and
|
|
// refitted, regardless of chips or the saved file. The GUI is the state
|
|
// the user is looking at; reusing the stale file would silently drop
|
|
// their edits. This is the top-priority reason of the plan: it must beat
|
|
// even an explicit reuse/skip chip choice.
|
|
let guiEditedRuns = config.guiEditedRuns
|
|
&& typeof config.guiEditedRuns === "object" ? config.guiEditedRuns : {};
|
|
if (Object.prototype.hasOwnProperty.call(guiEditedRuns, dataSet.main)) {
|
|
classification.useGuiTemplate = true;
|
|
useGuiTemplate = true;
|
|
if (msrExists) {
|
|
classification.state = "gui-edited";
|
|
classification.action = "refit";
|
|
classification.reusable = false;
|
|
classification.reason = "gui-parameter-changed";
|
|
} else {
|
|
// No saved MSR to rebuild: create/fit from the live GUI instead.
|
|
classification.state = "missing-msr";
|
|
classification.action = "fit";
|
|
classification.reusable = false;
|
|
classification.reason = "gui-parameter-changed-missing-msr";
|
|
}
|
|
if (skippedMissingMsr === dataSet.main) skippedMissingMsr = 0;
|
|
}
|
|
|
|
// A completed result remains reusable without reopening its raw data.
|
|
// Every action that would run musrfit, including a requested refit, is
|
|
// blocked until all main and ADDRUN data files are positively available.
|
|
if (missingDataRuns.length > 0 && classification.action != "skip") {
|
|
classification.state = "missing-data";
|
|
classification.action = "blocked";
|
|
classification.reusable = false;
|
|
classification.reason = "required-data-not-found";
|
|
}
|
|
|
|
return {
|
|
dataSet: normalizeSeriesDataSet(dataSet),
|
|
run: dataSet.main,
|
|
dataPaths: requiredDataRuns.map(function(run) {
|
|
return dataPathByRun[run];
|
|
}),
|
|
missingDataRuns: missingDataRuns,
|
|
msrName: msrName,
|
|
msrPath: msrPath,
|
|
msrExists: msrExists,
|
|
msrText: msrExists ? msrText : "",
|
|
msrHash: msrExists ? hashMSRText(msrText) : "",
|
|
state: classification.state,
|
|
action: classification.action,
|
|
reusable: classification.reusable,
|
|
reason: classification.reason,
|
|
useGuiTemplate: useGuiTemplate,
|
|
classification: classification
|
|
};
|
|
}));
|
|
|
|
if (skippedMissingMsr) {
|
|
plan.ok = false;
|
|
plan.reason = "skipped-missing-msr";
|
|
plan.failed = { run: skippedMissingMsr };
|
|
plan.summary = summarizeSeriesFitEntries(plan.entries);
|
|
return plan;
|
|
}
|
|
plan.ok = true;
|
|
plan.reason = "series-inventory-ready";
|
|
plan.summary = summarizeSeriesFitEntries(plan.entries);
|
|
return plan;
|
|
}
|
|
|
|
function stripMSRStatisticBlocks(msrText) {
|
|
let output = [];
|
|
let droppingStatistic = false;
|
|
let blockPattern = /^\s*(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/i;
|
|
for (let line of String(msrText || "").split(/\r?\n/)) {
|
|
let blockMatch = line.match(blockPattern);
|
|
if (blockMatch && blockMatch[1].toUpperCase() == "STATISTIC") {
|
|
droppingStatistic = true;
|
|
continue;
|
|
}
|
|
if (droppingStatistic && blockMatch) {
|
|
droppingStatistic = false;
|
|
}
|
|
if (!droppingStatistic) output.push(line);
|
|
}
|
|
return output.join("\n").replace(/\s+$/, "") + "\n";
|
|
}
|
|
|
|
function replaceSeriesFitParameterSuffix(msrText, referenceSuffix, targetSuffix) {
|
|
let lines = String(msrText || "").split(/\r?\n/);
|
|
let inFitParameters = false;
|
|
let changed = 0;
|
|
let referenceEnding = "_" + referenceSuffix;
|
|
let targetEnding = "_" + targetSuffix;
|
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
let trimmed = lines[i].trim();
|
|
if (/^FITPARAMETER\b/i.test(trimmed)) {
|
|
inFitParameters = true;
|
|
continue;
|
|
}
|
|
if (inFitParameters
|
|
&& /^(THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/i.test(trimmed)) {
|
|
inFitParameters = false;
|
|
}
|
|
if (!inFitParameters || referenceSuffix == targetSuffix) continue;
|
|
|
|
let parameterMatch = lines[i].match(/^(\s*\d+\s+)(\S+)(.*)$/);
|
|
if (!parameterMatch || !parameterMatch[2].endsWith(referenceEnding)) continue;
|
|
let parameterName = parameterMatch[2].substring(
|
|
0, parameterMatch[2].length - referenceEnding.length
|
|
) + targetEnding;
|
|
lines[i] = parameterMatch[1] + parameterName + parameterMatch[3];
|
|
changed++;
|
|
}
|
|
return { text: lines.join("\n"), changed: changed };
|
|
}
|
|
|
|
function replaceSeriesRunDirectives(msrText, targetDataSet, all) {
|
|
let target = normalizeSeriesDataSet(targetDataSet);
|
|
if (!target) {
|
|
return { ok: false, text: "", runBlocks: 0, reason: "invalid-target-data-set" };
|
|
}
|
|
|
|
let runLine = "";
|
|
let addLines = [];
|
|
try {
|
|
runLine = runFileNameAuto(target.main, all.selYear, all.instrName, all.dataRoot);
|
|
addLines = target.add.map(function(run) {
|
|
return "ADD" + runFileNameAuto(run, all.selYear, all.instrName, all.dataRoot);
|
|
});
|
|
} catch (error) {
|
|
return {
|
|
ok: false,
|
|
text: "",
|
|
runBlocks: 0,
|
|
reason: error && error.message ? error.message : "could-not-resolve-target-run"
|
|
};
|
|
}
|
|
|
|
let output = [];
|
|
let runBlocks = 0;
|
|
for (let line of String(msrText || "").split(/\r?\n/)) {
|
|
if (/^\s*RUN\b/i.test(line)) {
|
|
output.push(runLine);
|
|
for (let addLine of addLines) output.push(addLine);
|
|
runBlocks++;
|
|
} else if (/^\s*ADDRUN\b/i.test(line)) {
|
|
// Every target RUN receives the target data set's ADDRUN members above.
|
|
// Never carry an addition from the immutable reference into a target.
|
|
continue;
|
|
} else {
|
|
output.push(line);
|
|
}
|
|
}
|
|
return {
|
|
ok: runBlocks > 0,
|
|
text: output.join("\n"),
|
|
runBlocks: runBlocks,
|
|
reason: runBlocks > 0 ? "target-runs-replaced" : "run-block-not-found"
|
|
};
|
|
}
|
|
|
|
function validateSeriesMSRCandidate(msrText, targetDataSet, all, expectedRunBlocks) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-runnable-msr",
|
|
runBlocks: 0,
|
|
parameters: []
|
|
};
|
|
if (!isValidGeneratedGlobalMSR(msrText)) return result;
|
|
if (/^\s*STATISTIC\b/im.test(msrText)) {
|
|
result.reason = "stale-statistic-block";
|
|
return result;
|
|
}
|
|
if (/\bundefined\b/i.test(msrText)) {
|
|
result.reason = "undefined-msr-value";
|
|
return result;
|
|
}
|
|
|
|
result.runBlocks = (msrText.match(/^\s*RUN\b/gim) || []).length;
|
|
if (Number.isInteger(expectedRunBlocks) && result.runBlocks !== expectedRunBlocks) {
|
|
result.reason = "run-block-count-changed";
|
|
return result;
|
|
}
|
|
|
|
let identity = inspectSeriesMSRIdentity(
|
|
msrText,
|
|
targetDataSet,
|
|
all.instrName || "",
|
|
all.selYear || ""
|
|
);
|
|
if (!identity.matches) {
|
|
result.reason = identity.reason;
|
|
return result;
|
|
}
|
|
|
|
result.parameters = parseMSRParameters(msrText);
|
|
if (result.parameters.length === 0) {
|
|
result.reason = "fit-parameters-not-found";
|
|
return result;
|
|
}
|
|
result.ok = true;
|
|
result.reason = "candidate-valid";
|
|
return result;
|
|
}
|
|
|
|
// Reconcile the PLOT block of a series MSR with the live GUI's lifetime-correction
|
|
// preference for single-histogram fits. Single/global fits regenerate their PLOT
|
|
// block from the GUI on every invocation (buildPlotBlock), so lifetimecorrection is
|
|
// always re-emitted. A series derives runs after the first from the previously
|
|
// FITTED reference MSR, whose PLOT block may have lost that display-only directive
|
|
// when the fit was written back. This helper re-applies (or removes) the directive
|
|
// so a series behaves like a single/global fit instead of depending on what survived
|
|
// the fit round-trip. Non-SingleHist fits are returned unchanged because lifetime
|
|
// correction is a single-histogram concept only.
|
|
function applySeriesPlotLifetimeCorrection(msrText, all) {
|
|
if (!all || all.fitAsyType != "SingleHist") return msrText;
|
|
let wantLifetime = all.plotLifetimeCorrection === true
|
|
|| all.plotLifetimeCorrection === "1" || all.plotLifetimeCorrection === 1;
|
|
|
|
let lines = String(msrText || "").split(/\r?\n/);
|
|
let blockRe = /^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/i;
|
|
|
|
// Locate the PLOT block: starts at the PLOT keyword and ends at the next
|
|
// block keyword, skipping blank and comment lines that may separate blocks.
|
|
let plotStart = -1, plotEnd = lines.length;
|
|
for (let i = 0; i < lines.length; i++) {
|
|
let t = lines[i].trim();
|
|
if (plotStart < 0) {
|
|
if (/^PLOT\b/i.test(t)) plotStart = i;
|
|
continue;
|
|
}
|
|
if (t === "" || /^#/.test(t)) continue;
|
|
if (blockRe.test(t) && !/^PLOT\b/i.test(t)) { plotEnd = i; break; }
|
|
}
|
|
if (plotStart < 0) return msrText;
|
|
|
|
// Rebuild the block without a stray directive, then append it if requested.
|
|
let plotLines = lines.slice(plotStart, plotEnd).filter(function(line) {
|
|
return !/^\s*lifetimecorrection\s*$/i.test(line);
|
|
});
|
|
if (wantLifetime) plotLines.push("lifetimecorrection");
|
|
return lines.slice(0, plotStart).concat(plotLines, lines.slice(plotEnd)).join("\n");
|
|
}
|
|
|
|
// Derive one target from the same immutable fitted reference used for every
|
|
// other target. Only structural run identity and run-qualified FITPARAMETER
|
|
// names change; fitted values remain as the common starting values.
|
|
function transformSeriesReferenceMSR(referenceMSRText, referenceDataSet, targetDataSet, all = {}) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-reference-msr",
|
|
text: "",
|
|
parameterNamesChanged: 0,
|
|
runBlocks: 0
|
|
};
|
|
let reference = normalizeSeriesDataSet(referenceDataSet);
|
|
let target = normalizeSeriesDataSet(targetDataSet);
|
|
if (!reference || !target || typeof referenceMSRText !== "string") return result;
|
|
if (!isValidGeneratedGlobalMSR(referenceMSRText)) return result;
|
|
|
|
let referenceIdentity = inspectSeriesMSRIdentity(
|
|
referenceMSRText,
|
|
reference,
|
|
all.instrName || "",
|
|
all.selYear || ""
|
|
);
|
|
if (!referenceIdentity.matches) {
|
|
result.reason = "reference-" + referenceIdentity.reason;
|
|
return result;
|
|
}
|
|
let referenceParameters = parseMSRParameters(referenceMSRText);
|
|
if (referenceParameters.length === 0) {
|
|
result.reason = "reference-fit-parameters-not-found";
|
|
return result;
|
|
}
|
|
|
|
let referenceRunBlocks = (referenceMSRText.match(/^\s*RUN\b/gim) || []).length;
|
|
let referenceSuffix = runSuffixFromFile(
|
|
reference.main, all.instrName, all.selYear, all.dataRoot
|
|
);
|
|
let targetSuffix = runSuffixFromFile(
|
|
target.main, all.instrName, all.selYear, all.dataRoot
|
|
);
|
|
|
|
let withoutStatistic = stripMSRStatisticBlocks(referenceMSRText);
|
|
let parameters = replaceSeriesFitParameterSuffix(
|
|
withoutStatistic, referenceSuffix, targetSuffix
|
|
);
|
|
let runReplacement = replaceSeriesRunDirectives(parameters.text, target, all);
|
|
if (!runReplacement.ok) {
|
|
result.reason = runReplacement.reason;
|
|
return result;
|
|
}
|
|
// The fitted reference may have dropped the display-only lifetimecorrection
|
|
// directive. Re-apply it from the live GUI so every derived run plots like a
|
|
// single/global fit rather than inheriting whatever survived the fit output.
|
|
let reconciledText = applySeriesPlotLifetimeCorrection(runReplacement.text, all);
|
|
let validation = validateSeriesMSRCandidate(
|
|
reconciledText, target, all, referenceRunBlocks
|
|
);
|
|
if (!validation.ok) {
|
|
result.reason = validation.reason;
|
|
return result;
|
|
}
|
|
if (validation.parameters.length !== referenceParameters.length) {
|
|
result.reason = "fit-parameter-count-changed";
|
|
return result;
|
|
}
|
|
|
|
result.ok = true;
|
|
result.reason = "candidate-prepared";
|
|
result.text = reconciledText;
|
|
result.parameterNamesChanged = parameters.changed;
|
|
result.runBlocks = validation.runBlocks;
|
|
return result;
|
|
}
|
|
|
|
// Build a single series candidate's MSR from the live GUI parameters for a
|
|
// specific data set. This is used when the user force-refits one run through
|
|
// the series action chips: the model comes from the current GUI model/parameter
|
|
// state rather than from the already-fitted series reference.
|
|
function buildSeriesGUITemplate(entry, all) {
|
|
let result = { ok: false, reason: "invalid-series-entry", text: "", runBlocks: [] };
|
|
if (!entry || !entry.dataSet) return result;
|
|
let entryAll = Object.assign({}, all || {});
|
|
entryAll.runNumbers = seriesDataSetText(entry.dataSet);
|
|
let generatedConfig = Object.assign({}, collectFitConfigFromDOM(), {
|
|
all: entryAll,
|
|
sharedFlags: {}
|
|
});
|
|
let templateMSR = "";
|
|
try {
|
|
templateMSR = applySeriesPlotLifetimeCorrection(buildMSR(generatedConfig), entryAll);
|
|
} catch (error) {
|
|
result.reason = error && error.message
|
|
? error.message : "template-generation-failed";
|
|
return result;
|
|
}
|
|
let validation = validateSeriesMSRCandidate(templateMSR, entry.dataSet, entryAll);
|
|
if (!validation.ok) {
|
|
result.reason = validation.reason || "template-invalid";
|
|
return result;
|
|
}
|
|
result.ok = true;
|
|
result.reason = "gui-template-ready";
|
|
result.text = templateMSR;
|
|
result.parameterNamesChanged = 0;
|
|
result.runBlocks = validation.runBlocks;
|
|
return result;
|
|
}
|
|
|
|
// Build and validate every pending document in memory. Writing/renaming is kept
|
|
// for the later platform staging patch, so reusable and existing MSRs cannot be
|
|
// overwritten by merely preparing a series.
|
|
async function prepareSeriesMSRCandidates(plan, config = {}, fileAccess = {}) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-series-plan",
|
|
referenceRun: 0,
|
|
referencePath: "",
|
|
candidates: [],
|
|
excluded: [],
|
|
errors: []
|
|
};
|
|
if (!plan || !plan.ok || plan.mode != "series" || !Array.isArray(plan.entries)) {
|
|
return result;
|
|
}
|
|
|
|
let requestedReferenceRun = Number(config.referenceRun || 0);
|
|
let referenceEntry = plan.entries.find(function(entry) {
|
|
return requestedReferenceRun > 0 && entry.run === requestedReferenceRun;
|
|
});
|
|
if (!referenceEntry && requestedReferenceRun <= 0) {
|
|
referenceEntry = plan.entries.find(function(entry) {
|
|
return entry.reusable === true && entry.action == "skip" && entry.msrExists === true;
|
|
});
|
|
}
|
|
if (!referenceEntry || referenceEntry.reusable !== true
|
|
|| referenceEntry.action != "skip" || referenceEntry.msrExists !== true) {
|
|
result.reason = "reusable-reference-not-found";
|
|
return result;
|
|
}
|
|
|
|
let referenceMSRText = typeof config.referenceMSRText === "string"
|
|
? config.referenceMSRText : "";
|
|
if (referenceMSRText === "") {
|
|
let readFn = fileAccess.readAsciiFile;
|
|
if (typeof readFn !== "function" && typeof readAsciiFile === "function") {
|
|
readFn = readAsciiFile;
|
|
}
|
|
if (typeof readFn !== "function") {
|
|
result.reason = "reference-file-access-unavailable";
|
|
return result;
|
|
}
|
|
referenceMSRText = await readFn(referenceEntry.msrPath);
|
|
}
|
|
if (typeof referenceMSRText !== "string" || referenceMSRText.trim() === "") {
|
|
result.reason = "reference-msr-not-readable";
|
|
return result;
|
|
}
|
|
if (parseMSRFitStatistic(referenceMSRText).converged !== true) {
|
|
result.reason = "reference-msr-not-converged";
|
|
return result;
|
|
}
|
|
|
|
result.referenceRun = referenceEntry.run;
|
|
result.referencePath = referenceEntry.msrPath;
|
|
let all = config.all || {};
|
|
let pendingActions = new Set(["fit", "retry", "refit"]);
|
|
let candidates = [];
|
|
let errors = [];
|
|
for (let entry of plan.entries) {
|
|
if (!pendingActions.has(entry.action)) {
|
|
result.excluded.push({
|
|
run: entry.run,
|
|
action: entry.action,
|
|
reason: entry.reason
|
|
});
|
|
continue;
|
|
}
|
|
let transformed;
|
|
if (entry.useGuiTemplate === true) {
|
|
// User forced a refit of this run via the series action chips: the MSR
|
|
// must come from the live GUI parameters, not from the fitted series
|
|
// reference, so the per-run adjustments are honoured.
|
|
transformed = buildSeriesGUITemplate(entry, all);
|
|
if (!transformed.ok) {
|
|
errors.push({ run: entry.run, reason: transformed.reason });
|
|
continue;
|
|
}
|
|
} else {
|
|
transformed = transformSeriesReferenceMSR(
|
|
referenceMSRText,
|
|
referenceEntry.dataSet,
|
|
entry.dataSet,
|
|
all
|
|
);
|
|
if (!transformed.ok) {
|
|
errors.push({ run: entry.run, reason: transformed.reason });
|
|
continue;
|
|
}
|
|
}
|
|
candidates.push({
|
|
run: entry.run,
|
|
dataSet: normalizeSeriesDataSet(entry.dataSet),
|
|
action: entry.action,
|
|
targetName: entry.msrName,
|
|
targetPath: entry.msrPath,
|
|
expectedTargetText: entry.msrExists ? entry.msrText : "",
|
|
expectedTargetHash: entry.msrExists ? entry.msrHash : "",
|
|
text: transformed.text,
|
|
parameterNamesChanged: transformed.parameterNamesChanged || 0,
|
|
runBlocks: transformed.runBlocks,
|
|
useGuiTemplate: entry.useGuiTemplate === true
|
|
});
|
|
}
|
|
|
|
if (errors.length > 0) {
|
|
result.reason = "candidate-validation-failed";
|
|
result.errors = errors;
|
|
return result;
|
|
}
|
|
result.ok = true;
|
|
result.reason = "series-candidates-ready";
|
|
result.candidates = candidates;
|
|
return result;
|
|
}
|
|
|
|
function normalizeSeriesTransactionId(value) {
|
|
let normalized = String(value || "")
|
|
.replace(/[^A-Za-z0-9-]+/g, "-")
|
|
.replace(/^-+|-+$/g, "")
|
|
.substring(0, 64);
|
|
if (normalized !== "") return normalized;
|
|
return Date.now().toString(36) + "-"
|
|
+ Math.random().toString(36).substring(2, 10);
|
|
}
|
|
|
|
function seriesTransactionPath(targetPath, kind, transactionId) {
|
|
let path = String(targetPath || "");
|
|
let suffix = ".musrflow-" + kind + "-" + transactionId + ".msr";
|
|
return /\.msr$/i.test(path) ? path.replace(/\.msr$/i, suffix) : path + suffix;
|
|
}
|
|
|
|
function seriesTransactionError(error, fallback) {
|
|
return error && error.message ? error.message : String(error || fallback || "operation-failed");
|
|
}
|
|
|
|
function isValidPreparedSeriesCandidate(candidate) {
|
|
return candidate && Number.isInteger(candidate.run) && candidate.run > 0
|
|
&& new Set(["fit", "retry", "refit"]).has(candidate.action)
|
|
&& typeof candidate.targetPath === "string" && candidate.targetPath !== ""
|
|
&& typeof candidate.text === "string"
|
|
&& (candidate.action == "fit"
|
|
|| (typeof candidate.expectedTargetText === "string"
|
|
&& candidate.expectedTargetText !== "")
|
|
|| (typeof candidate.expectedTargetHash === "string"
|
|
&& candidate.expectedTargetHash !== ""));
|
|
}
|
|
|
|
async function discardSeriesTransactionStages(adapter, staged, errors) {
|
|
for (let index = staged.length - 1; index >= 0; index--) {
|
|
let item = staged[index];
|
|
try {
|
|
if (await adapter.exists(item.stagePath)) {
|
|
await adapter.discard(item.stagePath);
|
|
}
|
|
} catch (error) {
|
|
errors.push({
|
|
run: item.candidate.run,
|
|
operation: "discard-stage",
|
|
path: item.stagePath,
|
|
message: seriesTransactionError(error, "could-not-discard-stage")
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Persist an already validated batch as one filesystem transaction. Every
|
|
// candidate is first written exclusively under a transaction-owned name and
|
|
// read back byte-for-byte. Promotion starts only after the entire batch passes.
|
|
// The platform adapter is responsible for no-clobber promotion and recoverable
|
|
// replacement; the shared coordinator owns ordering and reverse rollback.
|
|
// The sequential series coordinator reaches this helper with exactly one
|
|
// candidate per transaction.
|
|
async function stageAndPromoteSeriesMSRCandidates(prepared, adapter, options = {}) {
|
|
let transactionId = normalizeSeriesTransactionId(options.transactionId);
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-prepared-series",
|
|
transactionId: transactionId,
|
|
staged: [],
|
|
receipts: [],
|
|
backups: [],
|
|
errors: [],
|
|
rollbackErrors: []
|
|
};
|
|
if (!prepared || prepared.ok !== true || !Array.isArray(prepared.candidates)) {
|
|
return result;
|
|
}
|
|
let requiredMethods = ["exists", "createExclusive", "read", "promote", "rollback", "discard"];
|
|
let remoteBatchAdapter = adapter && typeof adapter.transactBatch === "function";
|
|
let localFileAdapter = adapter && requiredMethods.every(function(method) {
|
|
return typeof adapter[method] === "function";
|
|
});
|
|
if (!remoteBatchAdapter && !localFileAdapter) {
|
|
result.reason = "transaction-adapter-unavailable";
|
|
return result;
|
|
}
|
|
if (prepared.candidates.length === 0) {
|
|
result.ok = true;
|
|
result.reason = "nothing-to-stage";
|
|
return result;
|
|
}
|
|
|
|
let targets = new Set();
|
|
let items = [];
|
|
for (let candidate of prepared.candidates) {
|
|
if (!isValidPreparedSeriesCandidate(candidate)) {
|
|
result.reason = "invalid-series-candidate";
|
|
return result;
|
|
}
|
|
if (targets.has(candidate.targetPath)) {
|
|
result.reason = "duplicate-series-target";
|
|
return result;
|
|
}
|
|
targets.add(candidate.targetPath);
|
|
items.push({
|
|
candidate: candidate,
|
|
stagePath: seriesTransactionPath(candidate.targetPath, "stage", transactionId),
|
|
backupPath: candidate.action == "fit" ? ""
|
|
: seriesTransactionPath(candidate.targetPath, "backup", transactionId),
|
|
replace: candidate.action != "fit"
|
|
});
|
|
}
|
|
|
|
// Browser transactions execute in one CGI process. Keeping staging,
|
|
// promotion, and rollback on the server prevents a dropped HTTP connection
|
|
// from leaving a browser-coordinated partial batch behind.
|
|
if (remoteBatchAdapter) {
|
|
try {
|
|
let remote = await adapter.transactBatch({
|
|
transactionId: transactionId,
|
|
candidates: items.map(function(item) {
|
|
return {
|
|
run: item.candidate.run,
|
|
action: item.candidate.action,
|
|
targetName: item.candidate.targetName || "",
|
|
targetPath: item.candidate.targetPath,
|
|
expectedTargetText: item.candidate.expectedTargetText || "",
|
|
expectedTargetHash: item.candidate.expectedTargetHash || "",
|
|
text: item.candidate.text
|
|
};
|
|
})
|
|
});
|
|
if (!remote || typeof remote !== "object") {
|
|
result.reason = "remote-transaction-response-invalid";
|
|
return result;
|
|
}
|
|
result.ok = remote.ok === true;
|
|
result.reason = remote.reason || (result.ok
|
|
? "series-candidates-promoted" : "remote-series-transaction-failed");
|
|
result.staged = Array.isArray(remote.staged) ? remote.staged : [];
|
|
result.receipts = Array.isArray(remote.receipts) ? remote.receipts : [];
|
|
result.backups = Array.isArray(remote.backups) ? remote.backups : [];
|
|
result.errors = Array.isArray(remote.errors) ? remote.errors : [];
|
|
result.rollbackErrors = Array.isArray(remote.rollbackErrors)
|
|
? remote.rollbackErrors : [];
|
|
return result;
|
|
} catch (error) {
|
|
result.reason = "remote-series-transaction-failed";
|
|
result.errors.push({
|
|
run: 0,
|
|
operation: "remote-transaction",
|
|
path: "",
|
|
message: seriesTransactionError(error, "series-transaction-request-failed")
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
|
|
// Recheck the assumptions made by the read-only inventory immediately
|
|
// before writing anything. This prevents a stale plan from changing a file
|
|
// that appeared, disappeared, or was already backed up in the meantime.
|
|
for (let item of items) {
|
|
try {
|
|
let targetExists = Boolean(await adapter.exists(item.candidate.targetPath));
|
|
if ((!item.replace && targetExists) || (item.replace && !targetExists)) {
|
|
result.reason = "series-target-state-changed";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "preflight",
|
|
path: item.candidate.targetPath,
|
|
message: item.replace ? "replacement-target-not-found" : "new-target-already-exists"
|
|
});
|
|
return result;
|
|
}
|
|
if (item.replace) {
|
|
let currentText = await adapter.read(item.candidate.targetPath);
|
|
let targetMatches = typeof currentText === "string";
|
|
if (targetMatches && typeof item.candidate.expectedTargetText === "string"
|
|
&& item.candidate.expectedTargetText !== "") {
|
|
targetMatches = currentText === item.candidate.expectedTargetText;
|
|
} else if (targetMatches) {
|
|
targetMatches = hashMSRText(currentText) === item.candidate.expectedTargetHash;
|
|
}
|
|
if (!targetMatches) {
|
|
result.reason = "series-target-state-changed";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "preflight",
|
|
path: item.candidate.targetPath,
|
|
message: "replacement-target-content-changed"
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
if (await adapter.exists(item.stagePath)
|
|
|| (item.backupPath !== "" && await adapter.exists(item.backupPath))) {
|
|
result.reason = "transaction-path-collision";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "preflight",
|
|
path: item.stagePath,
|
|
message: "transaction-owned-path-already-exists"
|
|
});
|
|
return result;
|
|
}
|
|
} catch (error) {
|
|
result.reason = "transaction-preflight-failed";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "preflight",
|
|
path: item.candidate.targetPath,
|
|
message: seriesTransactionError(error, "could-not-check-target")
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
|
|
let staged = [];
|
|
for (let item of items) {
|
|
try {
|
|
await adapter.createExclusive(item.stagePath, item.candidate.text);
|
|
staged.push(item);
|
|
let readBack = await adapter.read(item.stagePath);
|
|
if (readBack !== item.candidate.text) {
|
|
throw new Error("staged-content-mismatch");
|
|
}
|
|
result.staged.push({
|
|
run: item.candidate.run,
|
|
stagePath: item.stagePath,
|
|
targetPath: item.candidate.targetPath
|
|
});
|
|
} catch (error) {
|
|
result.reason = seriesTransactionError(error) == "staged-content-mismatch"
|
|
? "staged-content-mismatch" : "series-staging-failed";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "stage",
|
|
path: item.stagePath,
|
|
message: seriesTransactionError(error, "could-not-stage-candidate")
|
|
});
|
|
await discardSeriesTransactionStages(adapter, staged, result.rollbackErrors);
|
|
if (result.rollbackErrors.length > 0) result.reason = "stage-cleanup-failed";
|
|
return result;
|
|
}
|
|
}
|
|
|
|
let receipts = [];
|
|
for (let item of items) {
|
|
try {
|
|
let receipt = await adapter.promote({
|
|
run: item.candidate.run,
|
|
action: item.candidate.action,
|
|
stagePath: item.stagePath,
|
|
targetPath: item.candidate.targetPath,
|
|
backupPath: item.backupPath,
|
|
replace: item.replace,
|
|
expectedText: item.candidate.text
|
|
});
|
|
if (!receipt || typeof receipt !== "object") {
|
|
throw new Error("promotion-receipt-not-returned");
|
|
}
|
|
receipt.run = item.candidate.run;
|
|
receipts.push(receipt);
|
|
} catch (error) {
|
|
result.reason = "series-promotion-failed";
|
|
result.errors.push({
|
|
run: item.candidate.run,
|
|
operation: "promote",
|
|
path: item.candidate.targetPath,
|
|
message: seriesTransactionError(error, "could-not-promote-candidate")
|
|
});
|
|
for (let index = receipts.length - 1; index >= 0; index--) {
|
|
let receipt = receipts[index];
|
|
try {
|
|
await adapter.rollback(receipt);
|
|
} catch (rollbackError) {
|
|
result.rollbackErrors.push({
|
|
run: receipt.run || 0,
|
|
operation: "rollback",
|
|
path: receipt.targetPath || "",
|
|
message: seriesTransactionError(rollbackError, "could-not-rollback-promotion")
|
|
});
|
|
}
|
|
}
|
|
await discardSeriesTransactionStages(adapter, staged, result.rollbackErrors);
|
|
if (result.rollbackErrors.length > 0) result.reason = "promotion-rollback-failed";
|
|
return result;
|
|
}
|
|
}
|
|
|
|
result.ok = true;
|
|
result.reason = "series-candidates-promoted";
|
|
result.receipts = receipts;
|
|
result.backups = receipts.filter(function(receipt) {
|
|
return receipt.replaced === true && receipt.backupPath;
|
|
}).map(function(receipt) {
|
|
return { run: receipt.run, path: receipt.backupPath };
|
|
});
|
|
return result;
|
|
}
|
|
|
|
// Complete or undo a promoted batch. A commit is intentionally stricter than
|
|
// promotion: every target must now contain a converged fit before recoverable
|
|
// backups are deleted. Rollback restores a prior target, while retain keeps a
|
|
// newly created failed result for inspection. Platform adapters verify the
|
|
// transaction receipt/manifest before any finalization decision.
|
|
async function finalizeSeriesMSRTransaction(transaction, adapter, decision) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-series-transaction",
|
|
decision: decision,
|
|
transactionId: transaction && transaction.transactionId
|
|
? transaction.transactionId : "",
|
|
finalized: [],
|
|
errors: []
|
|
};
|
|
if (!transaction || transaction.ok !== true
|
|
|| !Array.isArray(transaction.receipts)
|
|
|| !["commit", "rollback", "retain"].includes(decision)) {
|
|
return result;
|
|
}
|
|
if (transaction.receipts.length === 0) {
|
|
result.ok = true;
|
|
result.reason = "nothing-to-finalize";
|
|
return result;
|
|
}
|
|
|
|
if (adapter && typeof adapter.finalizeBatch === "function") {
|
|
try {
|
|
let remote = await adapter.finalizeBatch(transaction, decision);
|
|
if (!remote || typeof remote !== "object") {
|
|
result.reason = "remote-finalization-response-invalid";
|
|
return result;
|
|
}
|
|
result.ok = remote.ok === true;
|
|
result.reason = remote.reason || (result.ok
|
|
? (decision == "commit"
|
|
? "series-transaction-committed"
|
|
: (decision == "rollback"
|
|
? "series-transaction-rolled-back" : "series-transaction-retained"))
|
|
: "remote-series-finalization-failed");
|
|
result.finalized = Array.isArray(remote.finalized) ? remote.finalized : [];
|
|
result.errors = Array.isArray(remote.errors) ? remote.errors : [];
|
|
return result;
|
|
} catch (error) {
|
|
result.reason = "remote-series-finalization-failed";
|
|
result.errors.push({
|
|
run: 0,
|
|
operation: decision,
|
|
path: "",
|
|
message: seriesTransactionError(error, "series-finalization-request-failed")
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
|
|
let finalizerName = decision == "commit"
|
|
? "commit" : (decision == "rollback" ? "rollback" : "retain");
|
|
if (!adapter || typeof adapter.verifyFinalize !== "function"
|
|
|| typeof adapter[finalizerName] !== "function") {
|
|
result.reason = "finalization-adapter-unavailable";
|
|
return result;
|
|
}
|
|
|
|
// Verify the whole batch before removing any backup or restoring any file.
|
|
for (let receipt of transaction.receipts) {
|
|
try {
|
|
await adapter.verifyFinalize(receipt, decision);
|
|
} catch (error) {
|
|
result.reason = "series-finalization-preflight-failed";
|
|
result.errors.push({
|
|
run: receipt.run || 0,
|
|
operation: "finalize-preflight",
|
|
path: receipt.targetPath || "",
|
|
message: seriesTransactionError(error, "could-not-verify-finalization")
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
|
|
let ordered = decision == "rollback"
|
|
? transaction.receipts.slice().reverse() : transaction.receipts.slice();
|
|
for (let receipt of ordered) {
|
|
try {
|
|
await adapter[finalizerName](receipt, { allowChangedTarget: true });
|
|
result.finalized.push({
|
|
run: receipt.run || 0,
|
|
action: receipt.action || "",
|
|
targetPath: receipt.targetPath || "",
|
|
decision: decision
|
|
});
|
|
} catch (error) {
|
|
result.reason = "series-finalization-partial";
|
|
result.errors.push({
|
|
run: receipt.run || 0,
|
|
operation: decision,
|
|
path: receipt.targetPath || "",
|
|
message: seriesTransactionError(error, "could-not-finalize-target")
|
|
});
|
|
return result;
|
|
}
|
|
}
|
|
|
|
result.ok = true;
|
|
result.reason = decision == "commit"
|
|
? "series-transaction-committed"
|
|
: (decision == "rollback"
|
|
? "series-transaction-rolled-back" : "series-transaction-retained");
|
|
return result;
|
|
}
|
|
|
|
// Run prepared independent fits in strict sequence. Each candidate gets its
|
|
// own transaction so a successfully committed prefix survives a later failure.
|
|
// The injected runner is the only operation that may execute musrfit; this
|
|
// shared helper itself has no process, CGI, UI, or platform dependency.
|
|
// startFit() reaches this helper through runIndependentSeriesFit(), which adds
|
|
// the platform runner adapters and user-facing progress reporting.
|
|
async function runPreparedSeriesFitSequence(
|
|
prepared, transactionAdapter, runCandidate, options = {}
|
|
) {
|
|
let sequenceId = normalizeSeriesTransactionId(options.transactionId);
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-prepared-series",
|
|
sequenceId: sequenceId,
|
|
completed: [],
|
|
excluded: prepared && Array.isArray(prepared.excluded)
|
|
? prepared.excluded.slice() : [],
|
|
failed: null
|
|
};
|
|
if (!prepared || prepared.ok !== true || !Array.isArray(prepared.candidates)) {
|
|
return result;
|
|
}
|
|
if (typeof runCandidate !== "function") {
|
|
result.reason = "series-runner-unavailable";
|
|
return result;
|
|
}
|
|
|
|
// Validate the complete sequence before staging the first run. Per-run
|
|
// transactions would otherwise allow malformed later input to be discovered
|
|
// only after an earlier fit had already committed.
|
|
let targets = new Set();
|
|
for (let candidate of prepared.candidates) {
|
|
if (!isValidPreparedSeriesCandidate(candidate)
|
|
|| targets.has(candidate.targetPath)) {
|
|
result.reason = targets.has(candidate && candidate.targetPath)
|
|
? "duplicate-series-target" : "invalid-series-candidate";
|
|
return result;
|
|
}
|
|
targets.add(candidate.targetPath);
|
|
}
|
|
|
|
let blocked = result.excluded.filter(function(entry) {
|
|
return entry && entry.action == "blocked";
|
|
});
|
|
if (prepared.candidates.length === 0) {
|
|
result.ok = blocked.length === 0;
|
|
result.reason = blocked.length > 0
|
|
? "series-no-runnable-candidates" : "series-already-complete";
|
|
return result;
|
|
}
|
|
|
|
for (let index = 0; index < prepared.candidates.length; index++) {
|
|
let candidate = prepared.candidates[index];
|
|
let suffix = "-" + (index + 1) + "-" + candidate.run;
|
|
let transactionId = normalizeSeriesTransactionId(
|
|
sequenceId.substring(0, Math.max(1, 64 - suffix.length)) + suffix
|
|
);
|
|
let transaction = await stageAndPromoteSeriesMSRCandidates(
|
|
{ ok: true, candidates: [candidate] },
|
|
transactionAdapter,
|
|
{ transactionId: transactionId }
|
|
);
|
|
if (!transaction.ok) {
|
|
result.reason = "series-candidate-staging-failed";
|
|
result.failed = {
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
targetPath: candidate.targetPath,
|
|
phase: "stage",
|
|
transaction: transaction
|
|
};
|
|
return result;
|
|
}
|
|
|
|
let receipt = transaction.receipts[0];
|
|
if (transaction.receipts.length !== 1 || !receipt
|
|
|| receipt.run !== candidate.run
|
|
|| receipt.targetPath !== candidate.targetPath) {
|
|
result.reason = "series-candidate-stage-uncertain";
|
|
result.failed = {
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
targetPath: candidate.targetPath,
|
|
phase: "stage",
|
|
transaction: transaction
|
|
};
|
|
return result;
|
|
}
|
|
let runResult;
|
|
try {
|
|
runResult = await runCandidate(receipt, candidate, {
|
|
index: index,
|
|
position: index + 1,
|
|
total: prepared.candidates.length,
|
|
sequenceId: sequenceId,
|
|
transactionId: transaction.transactionId,
|
|
referenceRun: prepared.referenceRun || 0
|
|
});
|
|
} catch (error) {
|
|
runResult = {
|
|
ok: false,
|
|
code: null,
|
|
error: seriesTransactionError(error, "series-runner-failed")
|
|
};
|
|
}
|
|
|
|
// A successful run must report ok and a zero exit code, with no signal and
|
|
// no explicit failure outcome.
|
|
let runSucceeded = runResult && typeof runResult === "object"
|
|
&& (runResult.ok === true || runResult.ok === 1)
|
|
&& (runResult.code === undefined || runResult.code === null
|
|
|| Number(runResult.code) === 0)
|
|
&& !runResult.signal
|
|
&& (!runResult.outcome || runResult.outcome == "success");
|
|
if (!runSucceeded) {
|
|
let finalizationDecision = candidate.action == "fit" ? "retain" : "rollback";
|
|
let finalization = await finalizeSeriesMSRTransaction(
|
|
transaction, transactionAdapter, finalizationDecision
|
|
);
|
|
result.reason = finalization.ok
|
|
? (finalizationDecision == "retain"
|
|
? "series-candidate-run-failed-retained" : "series-candidate-run-failed")
|
|
: (finalizationDecision == "retain"
|
|
? "series-candidate-retention-failed" : "series-candidate-rollback-failed");
|
|
result.failed = {
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
targetPath: candidate.targetPath,
|
|
phase: "run",
|
|
transactionId: transaction.transactionId,
|
|
runResult: runResult,
|
|
finalization: finalization,
|
|
retained: finalizationDecision == "retain" && finalization.ok
|
|
};
|
|
return result;
|
|
}
|
|
|
|
let commit = await finalizeSeriesMSRTransaction(
|
|
transaction, transactionAdapter, "commit"
|
|
);
|
|
if (!commit.ok) {
|
|
// A failed preflight is known to be mutation-free and can therefore
|
|
// be rolled back automatically. Transport and partial-finalization
|
|
// failures are ambiguous; preserve their manifest/backup for explicit
|
|
// recovery rather than guessing which side completed.
|
|
let recovery = null;
|
|
if (commit.reason == "series-finalization-preflight-failed") {
|
|
let recoveryDecision = candidate.action == "fit" ? "retain" : "rollback";
|
|
recovery = await finalizeSeriesMSRTransaction(
|
|
transaction, transactionAdapter, recoveryDecision
|
|
);
|
|
}
|
|
result.reason = recovery
|
|
? (recovery.ok
|
|
? (candidate.action == "fit"
|
|
? "series-candidate-result-invalid-retained"
|
|
: "series-candidate-result-invalid")
|
|
: (candidate.action == "fit"
|
|
? "series-candidate-retention-failed"
|
|
: "series-candidate-rollback-failed"))
|
|
: "series-candidate-commit-uncertain";
|
|
result.failed = {
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
targetPath: candidate.targetPath,
|
|
phase: "commit",
|
|
transactionId: transaction.transactionId,
|
|
runResult: runResult,
|
|
commit: commit,
|
|
recovery: recovery,
|
|
retained: candidate.action == "fit" && recovery && recovery.ok
|
|
};
|
|
return result;
|
|
}
|
|
|
|
result.completed.push({
|
|
run: candidate.run,
|
|
action: candidate.action,
|
|
targetPath: candidate.targetPath,
|
|
transactionId: transaction.transactionId,
|
|
runResult: runResult
|
|
});
|
|
}
|
|
|
|
result.ok = blocked.length === 0;
|
|
result.reason = blocked.length > 0
|
|
? "series-sequence-completed-with-blocked-runs"
|
|
: "series-sequence-completed";
|
|
return result;
|
|
}
|
|
|
|
// Store only presentation-ready fit quality in the job state. Both web and
|
|
// Electron call this after reading the fitted MSR, keeping parsing independent
|
|
// of the transport used to run musrfit.
|
|
function updateFitStatisticFromMSR(msrText) {
|
|
let statistic = parseMSRFitStatistic(msrText);
|
|
if (!statistic.found) return statistic;
|
|
|
|
updateJobStatus({
|
|
fitStatistic: statistic.text,
|
|
fitConverged: statistic.converged
|
|
});
|
|
return statistic;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Series per-run fit quality
|
|
// ---------------------------------------------------------------------------
|
|
//
|
|
// A single "χ²/NDF 1.012" hides how the rest of a series performed, so series
|
|
// plans carry one parsed statistic per data set (plan entries already parse
|
|
// them from the MSR on disk). These helpers turn that row list into a terse
|
|
// status-bar aggregate and, on demand, the full per-run table.
|
|
|
|
// Runs whose statistic cannot be compared numerically (missing, blocked, or a
|
|
// non-converged fit) are still counted but never form part of the worst/best
|
|
// spread.
|
|
function seriesStatisticValue(row) {
|
|
if (!row || row.found !== true || row.converged !== true) return null;
|
|
let value = Number(row.value);
|
|
if (!row.kind || !Number.isFinite(value)) return null;
|
|
return value;
|
|
}
|
|
|
|
function seriesFitStatisticText(rows) {
|
|
if (!Array.isArray(rows) || rows.length === 0) return "";
|
|
// A non-converged fit is the strongest signal a series can carry; surface it
|
|
// before any spread so the red status bar always leads with the failure.
|
|
if (rows.some(function(row) { return row && row.converged === false; })) {
|
|
return "Series did not converge";
|
|
}
|
|
let metrics = [];
|
|
let kind = "";
|
|
let mixed = false;
|
|
for (let row of rows) {
|
|
let value = seriesStatisticValue(row);
|
|
if (value === null) continue;
|
|
if (kind === "") kind = row.kind;
|
|
if (row.kind !== kind) mixed = true;
|
|
metrics.push({ value: value, text: row.text || "" });
|
|
}
|
|
if (mixed || metrics.length === 0) {
|
|
// Not comparable (mixed fit objectives or nothing converged), but the
|
|
// cohort is still worth stating.
|
|
return rows.length + " series runs";
|
|
}
|
|
if (metrics.length === 1) return metrics[0].text;
|
|
let values = metrics.map(function(m) { return m.value; });
|
|
let worst = Math.max.apply(null, values);
|
|
let best = Math.min.apply(null, values);
|
|
let label = kind == "chisq" ? "χ²/NDF" : "maxLH/NDF";
|
|
return label + " worst " + worst + " / best " + best + " · " + metrics.length + " runs";
|
|
}
|
|
|
|
function seriesFitConverged(rows) {
|
|
let foundAny = false;
|
|
for (let row of Array.isArray(rows) ? rows : []) {
|
|
if (!row) continue;
|
|
// Any explicit "did not converge" wins, matching the failure the summary
|
|
// text reports, even if the row has no numerical value.
|
|
if (row.converged === false) return false;
|
|
if (row.found === true) foundAny = true;
|
|
}
|
|
if (!foundAny) return null;
|
|
return true;
|
|
}
|
|
|
|
// Store the per-run rows and the derived aggregate as the status-bar statistic.
|
|
function applySeriesFitStatistic(rows) {
|
|
let normalized = Array.isArray(rows) ? rows.slice() : [];
|
|
updateJobStatus({
|
|
fitStatistic: seriesFitStatisticText(normalized),
|
|
fitConverged: seriesFitConverged(normalized),
|
|
seriesStatistic: normalized
|
|
});
|
|
return normalized;
|
|
}
|
|
|
|
// Snapshot every selected data set before anything runs. Plan entries already
|
|
// carry the parsed statistic from the existing MSR on disk, so reused and
|
|
// skipped runs appear too, not only the ones scheduled to refit.
|
|
function collectSeriesStatisticRows(plan) {
|
|
if (!plan || !Array.isArray(plan.entries)) return [];
|
|
return plan.entries.map(function(entry) {
|
|
// The plan classifies every selected data set and caches its parsed on-disk
|
|
// statistic there; skip/reuse rows keep the values from the MSR used for
|
|
// plotting so the per-run table shows them too.
|
|
let classification = entry.classification || {};
|
|
let stat = classification.statistic && typeof classification.statistic === "object"
|
|
? classification.statistic : (entry.statistic || {});
|
|
return {
|
|
run: entry.run,
|
|
action: entry.action || "fit",
|
|
kind: stat.kind || "",
|
|
value: stat.value || "",
|
|
ndf: stat.ndf || "",
|
|
text: stat.text || "",
|
|
converged: stat.converged === undefined ? null : stat.converged,
|
|
found: stat.found === true,
|
|
path: entry.msrPath || entry.targetPath || "",
|
|
fresh: false
|
|
};
|
|
});
|
|
}
|
|
|
|
// After the sequence, re-parse the freshly written MSR for each completed run
|
|
// and update its row, so the stored table reflects what was actually fitted.
|
|
async function synchronizeSeriesStatistics(sequence, options = {}) {
|
|
let read = options.readAsciiFile;
|
|
if (typeof read !== "function") {
|
|
read = typeof readAsciiFile === "function" ? readAsciiFile : null;
|
|
}
|
|
let rows = (Array.isArray(options.rows)
|
|
? options.rows : window.MusrfitJob.seriesStatistic || []).slice();
|
|
if (!sequence || !Array.isArray(sequence.completed)) return rows;
|
|
let rowByRun = {};
|
|
for (let row of rows) rowByRun[String(row.run)] = row;
|
|
for (let completed of sequence.completed) {
|
|
let run = completed && completed.run;
|
|
if (run === undefined || run === null) continue;
|
|
let row = rowByRun[String(run)];
|
|
if (!row) continue;
|
|
// Whatever the plan predicted, a run that actually rebuilt this data set
|
|
// is now fitted. Skipped runs stay skipped.
|
|
row.action = "fit";
|
|
row.fresh = true;
|
|
let resultRun = completed.runResult || {};
|
|
let path = resultRun.targetPath || completed.targetPath || "";
|
|
if (path) row.path = path;
|
|
if (typeof read !== "function" || path === "") continue;
|
|
let text = await read(path);
|
|
if (typeof text !== "string" || text === "") continue;
|
|
let stat = parseMSRFitStatistic(text);
|
|
row.found = stat.found;
|
|
row.converged = stat.converged;
|
|
row.kind = stat.kind;
|
|
row.value = stat.value;
|
|
row.ndf = stat.ndf;
|
|
row.text = stat.text;
|
|
}
|
|
return rows;
|
|
}
|
|
|
|
function appendJobLog(message) {
|
|
let text = "";
|
|
if (message !== undefined && message !== null) {
|
|
text = message.toString();
|
|
}
|
|
if (text === "") {
|
|
return;
|
|
}
|
|
|
|
window.MusrfitJob.log.push("[" + jobTimestamp() + "] " + text);
|
|
if (window.MusrfitJob.log.length > 500) {
|
|
window.MusrfitJob.log.shift();
|
|
}
|
|
renderJobStatus();
|
|
}
|
|
|
|
function updateJobStatus(fields) {
|
|
let hasMessage = Object.prototype.hasOwnProperty.call(fields, "message");
|
|
let hasMessageDetail = Object.prototype.hasOwnProperty.call(fields, "messageDetail");
|
|
let hasNoticeLevel = Object.prototype.hasOwnProperty.call(fields, "noticeLevel");
|
|
for (let key in fields) {
|
|
if (Object.prototype.hasOwnProperty.call(fields, key)) {
|
|
window.MusrfitJob[key] = fields[key];
|
|
}
|
|
}
|
|
// Direct status updates are normally one line. Mirror them into the tooltip
|
|
// detail unless the caller supplied a longer diagnostic explicitly.
|
|
if (hasMessage && !hasMessageDetail) {
|
|
let message = fields.message;
|
|
window.MusrfitJob.messageDetail = message === undefined || message === null
|
|
? "" : message.toString();
|
|
}
|
|
if (hasMessage && !hasNoticeLevel) {
|
|
window.MusrfitJob.noticeLevel = "info";
|
|
}
|
|
renderJobStatus();
|
|
}
|
|
|
|
function normalizeNoticeLevel(level) {
|
|
return ["none", "info", "success", "warning", "error"].includes(level)
|
|
? level : "info";
|
|
}
|
|
|
|
function statusLogTooltip(text, hasLog) {
|
|
let tooltip = text === undefined || text === null ? "" : text.toString();
|
|
if (hasLog) {
|
|
if (tooltip) tooltip += "\n\n";
|
|
tooltip += "Open run log.";
|
|
}
|
|
return tooltip;
|
|
}
|
|
|
|
function setStatusControlLabel(element, text, hasLog) {
|
|
if (!element) return;
|
|
let label = text === undefined || text === null ? "" : text.toString();
|
|
if (hasLog) {
|
|
if (label && !/[.!?]$/.test(label)) label += ".";
|
|
label += (label ? " " : "") + "Open run log.";
|
|
}
|
|
element.setAttribute("aria-label", label);
|
|
}
|
|
|
|
function renderArtifactValue(elementId, value) {
|
|
// Result artifacts are local filesystem paths in Electron and web URLs in CGI
|
|
// mode. The status bar already shows the directory, so keep this list compact
|
|
// by displaying only the filename while retaining the full path as a tooltip.
|
|
let el = document.getElementById(elementId);
|
|
if (!el) {
|
|
return;
|
|
}
|
|
|
|
let text = "-";
|
|
if (value) {
|
|
let pathWithoutQuery = value.split(/[?#]/)[0];
|
|
text = pathWithoutQuery.split(/[\\/]/).pop() || value;
|
|
}
|
|
el.textContent = text;
|
|
el.title = value || "";
|
|
|
|
if (value && (amIWeb() || /^https?:\/\//.test(value))) {
|
|
el.href = value;
|
|
} else {
|
|
el.removeAttribute("href");
|
|
}
|
|
|
|
let row = el.closest ? el.closest("[data-artifact-row]") : null;
|
|
if (row) {
|
|
row.hidden = !value;
|
|
}
|
|
}
|
|
|
|
function jobLogLineKind(text) {
|
|
let line = (text || "").trim();
|
|
if (/^===.*===$/.test(line)) return "section";
|
|
if (/^\$\s+/.test(line)) return "command";
|
|
if (/^\[exit code\s+0\]$/i.test(line) || /\bexited with code 0\b/i.test(line)) {
|
|
return "success";
|
|
}
|
|
if (/^\[(?:exit code\s+[1-9]\d*|failed|terminated)/i.test(line)
|
|
|| /\b(?:error|failed|failure|cannot|could not|did not|invalid|not found|permission denied|stderr)\b/i.test(line)) {
|
|
return "error";
|
|
}
|
|
if (/\b(?:warnings?|warn|non-zero|returned code|cancelled)\b/i.test(line)) {
|
|
return "warning";
|
|
}
|
|
if (/\b(?:completed|finished|prepared|saved|synchronized|copied)\b/i.test(line)) {
|
|
return "success";
|
|
}
|
|
return "output";
|
|
}
|
|
|
|
// Render log text with DOM text nodes only. Tool output may contain arbitrary
|
|
// characters, so no log content is ever interpreted as HTML.
|
|
function renderJobLogElement(element, logText) {
|
|
if (!element || typeof document === "undefined") return;
|
|
element.textContent = "";
|
|
let lines = (logText || "").split("\n");
|
|
for (let index = 0; index < lines.length; index++) {
|
|
let lineText = lines[index];
|
|
let line = document.createElement("span");
|
|
let timestamp = lineText.match(/^(\[(?=[^\]]*\d:\d)[^\]]+\]\s*)(.*)$/);
|
|
let semanticText = timestamp ? timestamp[2] : lineText;
|
|
line.className = "job-log-line job-log-" + jobLogLineKind(semanticText);
|
|
if (timestamp) {
|
|
let timestampSpan = document.createElement("span");
|
|
timestampSpan.className = "job-log-timestamp";
|
|
timestampSpan.textContent = timestamp[1];
|
|
line.appendChild(timestampSpan);
|
|
}
|
|
let content = document.createElement("span");
|
|
content.textContent = semanticText;
|
|
line.appendChild(content);
|
|
element.appendChild(line);
|
|
if (index < lines.length - 1) {
|
|
element.appendChild(document.createTextNode("\n"));
|
|
}
|
|
}
|
|
}
|
|
|
|
function renderJobStatus() {
|
|
if (typeof document === "undefined") {
|
|
return;
|
|
}
|
|
|
|
let job = window.MusrfitJob;
|
|
let statusBar = document.getElementById("appStatusBar");
|
|
if (statusBar) {
|
|
statusBar.dataset.state = job.state.toLowerCase().replace(/\s+/g, "-");
|
|
statusBar.dataset.noticeLevel = normalizeNoticeLevel(job.noticeLevel || "none");
|
|
}
|
|
|
|
let stateText = job.state || "Idle";
|
|
let stateEl = document.getElementById("jobStatusState");
|
|
let hasLog = Array.isArray(job.log) && job.log.length > 0;
|
|
if (stateEl) {
|
|
stateEl.textContent = stateText;
|
|
stateEl.disabled = !hasLog;
|
|
stateEl.title = statusLogTooltip(stateText, hasLog);
|
|
setStatusControlLabel(stateEl, stateText, hasLog);
|
|
}
|
|
|
|
// Fit quality is a durable result, unlike the transient process message. It
|
|
// stays visible while musrview runs so users do not lose chisq/maxLH feedback.
|
|
// For an independent series the text is the worst/best aggregate and the
|
|
// control opens the full per-run table.
|
|
let statisticEl = document.getElementById("jobStatusStatistic");
|
|
if (statisticEl) {
|
|
let statisticText = job.fitStatistic || "";
|
|
let hasSeriesRows = Array.isArray(job.seriesStatistic) && job.seriesStatistic.length > 0;
|
|
statisticEl.textContent = statisticText;
|
|
statisticEl.title = statisticText || "";
|
|
statisticEl.hidden = !statisticText;
|
|
if (typeof statisticEl.disabled === "boolean") {
|
|
statisticEl.disabled = !(statisticText && hasSeriesRows);
|
|
}
|
|
if (typeof statisticEl.classList !== "undefined"
|
|
&& typeof statisticEl.classList.toggle === "function") {
|
|
statisticEl.classList.toggle("status-log-button", hasSeriesRows && statisticText !== "");
|
|
}
|
|
if (typeof statisticEl.setAttribute === "function") {
|
|
let label = statisticText;
|
|
if (hasSeriesRows && statisticText) {
|
|
label += (label && !/[.!?]$/.test(label) ? "." : "") + " Show per-run statistics.";
|
|
}
|
|
statisticEl.setAttribute("aria-label", label);
|
|
}
|
|
}
|
|
if (statusBar) {
|
|
statusBar.dataset.fitState = job.fitConverged === false
|
|
? "not-converged" : (job.fitStatistic ? "converged" : "none");
|
|
}
|
|
|
|
// The persistent bar should not repeat "Idle" or duplicate the state text.
|
|
// Reveal optional context only when it adds information to "Mode · State".
|
|
let messageText = job.message || "";
|
|
let messageDetail = job.messageDetail || messageText;
|
|
let messageEl = document.getElementById("jobStatusMessage");
|
|
let showMessage = messageText !== "" && messageText !== "Idle" && messageText !== stateText;
|
|
if (messageEl) {
|
|
messageEl.textContent = showMessage ? messageText : "";
|
|
messageEl.title = showMessage ? statusLogTooltip(messageDetail, hasLog) : "";
|
|
messageEl.disabled = !hasLog;
|
|
setStatusControlLabel(messageEl, showMessage ? messageDetail : "", hasLog && showMessage);
|
|
messageEl.hidden = !showMessage;
|
|
}
|
|
|
|
let fileEl = document.getElementById("jobStatusFile");
|
|
if (fileEl) {
|
|
fileEl.textContent = job.file || "";
|
|
fileEl.title = job.resultMSR || job.file || "";
|
|
fileEl.hidden = !job.file;
|
|
}
|
|
|
|
let directoryEl = document.getElementById("jobStatusDirectory");
|
|
if (directoryEl) {
|
|
directoryEl.textContent = job.directory || "";
|
|
directoryEl.title = job.directory || "";
|
|
directoryEl.hidden = !job.directory;
|
|
}
|
|
|
|
// Keep live announcements concise and free of filesystem paths. The full
|
|
// message remains available from the visible control and its tooltip.
|
|
let announcementEl = document.getElementById("jobStatusAnnouncement");
|
|
if (announcementEl) {
|
|
let announcementParts = [stateText];
|
|
if (job.fitStatistic) announcementParts.push(job.fitStatistic);
|
|
if (showMessage) announcementParts.push(messageText);
|
|
let announcement = announcementParts.join(". ");
|
|
if (announcementEl.textContent !== announcement) {
|
|
announcementEl.textContent = announcement;
|
|
}
|
|
}
|
|
|
|
let detailStartedEl = document.getElementById("jobDetailStarted");
|
|
if (detailStartedEl) {
|
|
detailStartedEl.textContent = job.startedAt || "-";
|
|
}
|
|
|
|
let detailFinishedEl = document.getElementById("jobDetailFinished");
|
|
if (detailFinishedEl) {
|
|
detailFinishedEl.textContent = job.finishedAt || "-";
|
|
}
|
|
|
|
let detailExitCodeEl = document.getElementById("jobDetailExitCode");
|
|
if (detailExitCodeEl) {
|
|
detailExitCodeEl.textContent = job.exitCode !== "" ? job.exitCode : "-";
|
|
}
|
|
|
|
let resultMSR = job.resultMSR || job.file;
|
|
let templatePath = job.templatePath;
|
|
if (templatePath === resultMSR) {
|
|
templatePath = "";
|
|
}
|
|
renderArtifactValue("resultTemplatePath", templatePath);
|
|
renderArtifactValue("resultMSRPath", resultMSR);
|
|
renderArtifactValue("resultLogPath", job.logPath);
|
|
renderArtifactValue("resultPlotPath", job.plotPath);
|
|
renderArtifactValue("resultParameterDataPath", job.parameterDataPath);
|
|
renderArtifactValue("resultPackagePath", job.packagePath);
|
|
|
|
// The fitted MSR is the only artifact kept permanently visible. ROOT plots are
|
|
// generated companion files, so group them with logs/packages under Other files.
|
|
let hasPrimaryArtifacts = Boolean(resultMSR);
|
|
let hasSecondaryArtifacts = Boolean(job.plotPath || templatePath || job.logPath
|
|
|| job.parameterDataPath || job.packagePath);
|
|
let hasArtifacts = hasPrimaryArtifacts || hasSecondaryArtifacts;
|
|
let artifactListEl = document.getElementById("resultArtifactList");
|
|
if (artifactListEl) {
|
|
artifactListEl.hidden = !hasArtifacts;
|
|
}
|
|
let primaryFilesEl = document.getElementById("resultPrimaryFiles");
|
|
if (primaryFilesEl) {
|
|
primaryFilesEl.hidden = !hasPrimaryArtifacts;
|
|
}
|
|
let otherFilesEl = document.getElementById("resultOtherFiles");
|
|
if (otherFilesEl) {
|
|
// Keep generated companion artifacts available without giving them the same
|
|
// permanent visual weight as the fitted MSR.
|
|
otherFilesEl.hidden = !hasSecondaryArtifacts;
|
|
}
|
|
let artifactEmptyEl = document.getElementById("resultArtifactEmpty");
|
|
if (artifactEmptyEl) {
|
|
artifactEmptyEl.hidden = hasArtifacts;
|
|
}
|
|
|
|
let parameterSyncEl = document.getElementById("resultParameterSync");
|
|
if (parameterSyncEl) {
|
|
parameterSyncEl.textContent = job.parameterSync || "-";
|
|
}
|
|
|
|
let logText = job.log.length > 0 ? job.log.join("\n") : "No job has been started.";
|
|
for (let logId of ["jobLogText", "jobLogPopupText"]) {
|
|
let logEl = document.getElementById(logId);
|
|
if (logEl) renderJobLogElement(logEl, logText);
|
|
}
|
|
|
|
updateParameterPlotSelectionUI();
|
|
}
|
|
|
|
// Per-run series statistics dialog ----------------------------------------
|
|
|
|
function showSeriesStatisticsDialog() {
|
|
if (typeof document === "undefined") return;
|
|
let dialog = document.getElementById("seriesStatisticDialog");
|
|
if (!dialog) return;
|
|
renderSeriesStatisticsTable(window.MusrfitJob.seriesStatistic);
|
|
if (typeof dialog.showModal === "function") {
|
|
if (!dialog.open) dialog.showModal();
|
|
} else if ("hidden" in dialog) {
|
|
dialog.hidden = false;
|
|
}
|
|
}
|
|
|
|
function renderSeriesStatisticsTable(rows) {
|
|
if (typeof document === "undefined") return;
|
|
let container = document.getElementById("seriesStatisticTable");
|
|
if (!container || typeof container.appendChild !== "function") return;
|
|
|
|
let comparable = [];
|
|
for (let row of Array.isArray(rows) ? rows : []) {
|
|
let value = seriesStatisticValue(row);
|
|
if (value !== null) comparable.push(value);
|
|
}
|
|
// Median-based outliers call out the runs a worst/best spread might hide.
|
|
let median = null;
|
|
if (comparable.length > 0) {
|
|
let sorted = comparable.slice().sort(function(a, b) { return a - b; });
|
|
let mid = Math.floor(sorted.length / 2);
|
|
median = sorted.length % 2
|
|
? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
|
|
}
|
|
|
|
let ordered = (Array.isArray(rows) ? rows : []).slice();
|
|
ordered.sort(function(a, b) {
|
|
let runA = Number(a && a.run) || 0;
|
|
let runB = Number(b && b.run) || 0;
|
|
return runA - runB;
|
|
});
|
|
|
|
container.textContent = "";
|
|
if (ordered.length === 0) {
|
|
let emptyRow = document.createElement("tr");
|
|
let emptyCell = document.createElement("td");
|
|
emptyCell.colSpan = 5;
|
|
emptyCell.textContent = "No series statistics available.";
|
|
emptyRow.appendChild(emptyCell);
|
|
container.appendChild(emptyRow);
|
|
return;
|
|
}
|
|
for (let row of ordered) {
|
|
let value = seriesStatisticValue(row);
|
|
let classes = [];
|
|
if (row && row.converged === false) classes.push("series-stat-notconverged");
|
|
if (value !== null && median !== null && value > 2 * median) {
|
|
classes.push("series-stat-outlier");
|
|
}
|
|
if (row && row.fresh === false && value !== null) classes.push("series-stat-stale");
|
|
let tr = document.createElement("tr");
|
|
tr.className = classes.join(" ");
|
|
function cell(text, title) {
|
|
let td = document.createElement("td");
|
|
td.textContent = text === undefined ? "" : text;
|
|
if (title) td.title = String(title);
|
|
return td;
|
|
}
|
|
tr.appendChild(cell(row ? String(row.run) : "-", ""));
|
|
tr.appendChild(cell(row && row.action ? row.action : "-", ""));
|
|
tr.appendChild(cell(row && row.text ? row.text
|
|
: (row && row.converged === false ? "Fit did not converge" : "-"), ""));
|
|
tr.appendChild(cell(row && row.found ? (row.converged === true ? "yes" : "no") : "-", ""));
|
|
tr.appendChild(cell(row && row.path ? row.path : "-",
|
|
row && row.path ? row.path : ""));
|
|
container.appendChild(tr);
|
|
}
|
|
}
|
|
|
|
// All browser modeless windows share one monotonically increasing layer. This
|
|
// lets any active ROOT plot, parameter plot, Help or Run Log window come to the
|
|
// front regardless of which window type happened to open first.
|
|
if (typeof window.MusrfitFloatingWindowZIndex !== "number") {
|
|
window.MusrfitFloatingWindowZIndex = 1100;
|
|
}
|
|
|
|
function bringMusrfitFloatingWindowToFront(floatingWindow) {
|
|
if (!floatingWindow || !floatingWindow.style) return 0;
|
|
window.MusrfitFloatingWindowZIndex++;
|
|
floatingWindow.style.zIndex = String(window.MusrfitFloatingWindowZIndex);
|
|
return window.MusrfitFloatingWindowZIndex;
|
|
}
|
|
|
|
// Reuse the floating-window drag behaviour for lightweight modeless dialogs
|
|
// such as the run log and browser Quick Start window.
|
|
function makeModelessDialogDraggable(dialog) {
|
|
if (!dialog || dialog.dataset.dragReady) return;
|
|
|
|
let header = dialog.querySelector(".web-plot-header");
|
|
let controls = dialog.querySelector(".web-plot-controls");
|
|
let drag = null;
|
|
dialog.addEventListener("pointerdown", function() {
|
|
bringMusrfitFloatingWindowToFront(dialog);
|
|
});
|
|
if (header) {
|
|
header.addEventListener("pointerdown", function(event) {
|
|
if (controls && controls.contains(event.target)) return;
|
|
let bounds = dialog.getBoundingClientRect();
|
|
drag = { x: event.clientX, y: event.clientY, left: bounds.left, top: bounds.top };
|
|
header.setPointerCapture(event.pointerId);
|
|
event.preventDefault();
|
|
});
|
|
header.addEventListener("pointermove", function(event) {
|
|
if (!drag) return;
|
|
let maxX = Math.max(0, window.innerWidth - dialog.offsetWidth);
|
|
let maxY = Math.max(0, window.innerHeight - header.offsetHeight);
|
|
dialog.style.left = Math.min(maxX, Math.max(0, drag.left + event.clientX - drag.x)) + "px";
|
|
dialog.style.top = Math.min(maxY, Math.max(0, drag.top + event.clientY - drag.y)) + "px";
|
|
});
|
|
header.addEventListener("pointerup", function(event) {
|
|
drag = null;
|
|
if (header.hasPointerCapture(event.pointerId)) header.releasePointerCapture(event.pointerId);
|
|
});
|
|
}
|
|
dialog.dataset.dragReady = "1";
|
|
}
|
|
|
|
// Open the status-bar explanation without forcing the user to switch to Results.
|
|
// The same log remains available in Results as the persistent job history.
|
|
function showJobLogWindow() {
|
|
let job = window.MusrfitJob || {};
|
|
if (!Array.isArray(job.log) || job.log.length === 0) return;
|
|
|
|
let logWindow = document.getElementById("jobLogWindow");
|
|
if (!logWindow) return;
|
|
let logText = document.getElementById("jobLogPopupText");
|
|
if (logText) {
|
|
renderJobLogElement(logText, job.log.join("\n"));
|
|
logText.scrollTop = logText.scrollHeight;
|
|
}
|
|
|
|
makeModelessDialogDraggable(logWindow);
|
|
|
|
if (!logWindow.open) {
|
|
logWindow.show();
|
|
let left = Math.max(12, (window.innerWidth - logWindow.offsetWidth) / 2);
|
|
logWindow.style.left = left + "px";
|
|
logWindow.style.top = "48px";
|
|
}
|
|
bringMusrfitFloatingWindowToFront(logWindow);
|
|
setJobLogExpanded(true);
|
|
logWindow.focus();
|
|
}
|
|
|
|
function setJobLogExpanded(expanded) {
|
|
for (let triggerId of ["jobStatusState", "jobStatusMessage"]) {
|
|
let trigger = document.getElementById(triggerId);
|
|
if (trigger) trigger.setAttribute("aria-expanded", expanded ? "true" : "false");
|
|
}
|
|
}
|
|
|
|
function closeJobLogWindow() {
|
|
let logWindow = document.getElementById("jobLogWindow");
|
|
if (logWindow && logWindow.open) logWindow.close();
|
|
setJobLogExpanded(false);
|
|
}
|
|
|
|
function beginJobPreparation(actionLabel) {
|
|
let mode = amIWeb() ? "Web" : "Electron";
|
|
let state = "Preparing " + actionLabel.toLowerCase();
|
|
window.MusrfitJob.log = [];
|
|
updateJobStatus({
|
|
state: state,
|
|
mode: mode,
|
|
file: "",
|
|
directory: "",
|
|
message: state,
|
|
messageDetail: state,
|
|
noticeLevel: "info",
|
|
startedAt: jobTimestamp(),
|
|
finishedAt: "",
|
|
exitCode: "",
|
|
lastCommand: "",
|
|
templatePath: "",
|
|
resultMSR: "",
|
|
logPath: "",
|
|
plotPath: "",
|
|
// A new fit invalidates the previous parameter data until it produces a
|
|
// fresh table. Plot-only actions intentionally preserve both the statistic
|
|
// and the existing parameter data because they do not change the fit.
|
|
parameterDataPath: actionLabel.toLowerCase() === "fit"
|
|
? "" : window.MusrfitJob.parameterDataPath,
|
|
packagePath: "",
|
|
parameterSync: "",
|
|
// Starting a new fit invalidates the previous numerical result. Plot-only
|
|
// actions intentionally preserve it because they do not change the fit.
|
|
fitStatistic: actionLabel.toLowerCase() === "fit" ? "" : window.MusrfitJob.fitStatistic,
|
|
fitConverged: actionLabel.toLowerCase() === "fit" ? null : window.MusrfitJob.fitConverged,
|
|
preparedForRun: true
|
|
});
|
|
appendJobLog(state);
|
|
}
|
|
|
|
function beginJobStatus(actionName, fullPath, options) {
|
|
let fitName = fullPath.split(/[\\/]/).pop();
|
|
let fitDir = fullPath.substring(0, fullPath.length - fitName.length).replace(/[\\/]$/, "");
|
|
if (!fitDir || fitDir === "" || fitDir === ".") {
|
|
fitDir = amIWeb() ? "." : platformCurrentDirectory();
|
|
}
|
|
|
|
let startedAt = window.MusrfitJob.startedAt;
|
|
if (!window.MusrfitJob.preparedForRun) {
|
|
window.MusrfitJob.log = [];
|
|
startedAt = jobTimestamp();
|
|
}
|
|
|
|
let mode = amIWeb() ? "Web" : "Electron";
|
|
let state = options.plotOnly ? "Running musrview" : "Running musrfit";
|
|
updateJobStatus({
|
|
state: state,
|
|
mode: mode,
|
|
file: fitName,
|
|
directory: fitDir,
|
|
message: actionName,
|
|
messageDetail: actionName,
|
|
noticeLevel: "info",
|
|
startedAt: startedAt,
|
|
finishedAt: "",
|
|
exitCode: "",
|
|
resultMSR: fullPath,
|
|
lastCommand: "",
|
|
// beginJobPreparation normally clears this first; keep the direct-call path
|
|
// safe as well, while allowing Plot to retain the last fit statistic.
|
|
fitStatistic: options.plotOnly ? window.MusrfitJob.fitStatistic : "",
|
|
fitConverged: options.plotOnly ? window.MusrfitJob.fitConverged : null,
|
|
preparedForRun: false
|
|
});
|
|
appendJobLog(actionName + ": " + fitName + " in " + fitDir);
|
|
}
|
|
|
|
function finishJobStatus(ok, code, message, outcome = "") {
|
|
let missingData = outcome == "missing-data";
|
|
let aborted = outcome == "aborted";
|
|
let state = missingData ? "Missing data" : (aborted ? "Aborted" : (ok ? "Finished" : "Failed"));
|
|
let exitCode = "";
|
|
if (code !== undefined && code !== null) {
|
|
exitCode = code;
|
|
}
|
|
updateJobStatus({
|
|
state: state,
|
|
message: message ? firstStatusLine(message) : state,
|
|
messageDetail: message ? message.toString() : state,
|
|
noticeLevel: missingData ? "warning" : (aborted ? "warning" : (ok ? "success" : "error")),
|
|
finishedAt: jobTimestamp(),
|
|
exitCode: exitCode,
|
|
preparedForRun: false
|
|
});
|
|
if (message) {
|
|
appendJobLog(message);
|
|
}
|
|
|
|
// A blocking problem must not rely on the compact status bar alone. Keep the
|
|
// notice concise and let users open the complete command log only if needed.
|
|
if (!ok && typeof document !== "undefined"
|
|
&& typeof document.getElementById === "function") {
|
|
let dialog = document.getElementById("jobOutcomeDialog");
|
|
let title = document.getElementById("jobOutcomeTitle");
|
|
let summary = document.getElementById("jobOutcomeSummary");
|
|
let details = document.getElementById("jobOutcomeDetails");
|
|
let summaryText = message ? firstStatusLine(message) : state;
|
|
let detailText = message ? message.toString() : state;
|
|
if (dialog && title && summary && details) {
|
|
dialog.dataset.level = missingData ? "warning" : (aborted ? "warning" : "error");
|
|
title.textContent = missingData ? "Data file not found" : (aborted ? "Action aborted" : "Action could not be completed");
|
|
summary.textContent = summaryText;
|
|
details.textContent = detailText;
|
|
details.hidden = detailText == summaryText;
|
|
if (!dialog.open && typeof dialog.showModal === "function") {
|
|
dialog.showModal();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function setAppNotice(summary, options = {}) {
|
|
let text = summary === undefined || summary === null ? "" : summary.toString();
|
|
let details = options.details === undefined || options.details === null
|
|
? text : options.details.toString();
|
|
let level = normalizeNoticeLevel(options.level || "info");
|
|
|
|
console.log(details);
|
|
if (options.log !== false) appendJobLog(details);
|
|
updateJobStatus({
|
|
message: firstStatusLine(text),
|
|
messageDetail: details,
|
|
noticeLevel: level
|
|
});
|
|
}
|
|
|
|
// Match TRIMSP-NL's lightweight confirmation beside the control that caused an
|
|
// action. Reusing one element prevents repeated share clicks from stacking notices.
|
|
var transientWarningTimeout = null;
|
|
function showTransientWarning(message, targetElement, duration = 4000) {
|
|
let warning = document.getElementById("transientWarning");
|
|
if (!warning) {
|
|
warning = document.createElement("div");
|
|
warning.id = "transientWarning";
|
|
warning.className = "transient-warning";
|
|
document.body.appendChild(warning);
|
|
}
|
|
|
|
warning.textContent = message;
|
|
if (targetElement) {
|
|
let rect = targetElement.getBoundingClientRect();
|
|
let viewportMargin = 12;
|
|
let targetGap = 8;
|
|
let maximumLeft = Math.max(
|
|
viewportMargin,
|
|
window.innerWidth - warning.offsetWidth - viewportMargin
|
|
);
|
|
let left = Math.min(Math.max(viewportMargin, rect.left), maximumLeft);
|
|
let top = rect.bottom + targetGap;
|
|
|
|
// Keep the fixed notification visible when the share button is close to
|
|
// the right or bottom edge of a compact Electron window.
|
|
if (top + warning.offsetHeight > window.innerHeight - viewportMargin) {
|
|
top = rect.top - warning.offsetHeight - targetGap;
|
|
}
|
|
top = Math.max(
|
|
viewportMargin,
|
|
Math.min(top, window.innerHeight - warning.offsetHeight - viewportMargin)
|
|
);
|
|
warning.style.left = left + "px";
|
|
warning.style.top = top + "px";
|
|
}
|
|
warning.classList.add("visible");
|
|
|
|
if (transientWarningTimeout) clearTimeout(transientWarningTimeout);
|
|
transientWarningTimeout = setTimeout(function() {
|
|
warning.classList.remove("visible");
|
|
}, duration);
|
|
}
|
|
|
|
// Compatibility entry point for integrations that still call the old helper.
|
|
// Application code uses setAppNotice() so severity and detailed text are explicit.
|
|
function setFitStatus(message, options = {}) {
|
|
// Older callers used a boolean append flag. It had no visible effect after
|
|
// the legacy status textarea was removed, so treat it as an informational notice.
|
|
if (!options || typeof options !== "object") options = {};
|
|
setAppNotice(message, options);
|
|
}
|
|
|
|
function initRunModeStatus() {
|
|
let mode = amIWeb() ? "Web" : "Electron";
|
|
updateJobStatus({
|
|
mode: mode,
|
|
state: window.MusrfitJob.state || "Idle",
|
|
message: window.MusrfitJob.message || "Idle",
|
|
noticeLevel: window.MusrfitJob.noticeLevel || "none"
|
|
});
|
|
}
|
|
|
|
function hashMSRText(msrText) {
|
|
// A small deterministic hash is enough for editor bookkeeping. It is not used
|
|
// for security; it only distinguishes known programmatic text from user edits.
|
|
let text = msrText !== undefined && msrText !== null ? msrText.toString() : "";
|
|
let hash = 2166136261;
|
|
for (let i = 0; i < text.length; i++) {
|
|
hash ^= text.charCodeAt(i);
|
|
hash = Math.imul(hash, 16777619);
|
|
}
|
|
return (hash >>> 0).toString(16);
|
|
}
|
|
|
|
function getMSRDocumentState(source = window.MSREditor.activeSource) {
|
|
// "current" is the runnable MSR. In global mode it is the expanded global
|
|
// file; in single-run mode it is the only MSR document shown to the user.
|
|
let key = source == "template" ? "template" : "current";
|
|
if (!window.MSREditor.documents[key]) {
|
|
window.MSREditor.documents[key] = {
|
|
sourceOfTruth: "gui",
|
|
locked: false,
|
|
dirty: false,
|
|
lastGeneratedHash: "",
|
|
lastAcceptedHash: "",
|
|
stale: false
|
|
};
|
|
}
|
|
return window.MSREditor.documents[key];
|
|
}
|
|
|
|
function syncMSREditorLegacyState() {
|
|
// Mirror the active document into legacy scalar fields. This keeps older code
|
|
// working while ownership decisions are made from the document-specific state.
|
|
let active = getMSRDocumentState();
|
|
let current = getMSRDocumentState("current");
|
|
let template = getMSRDocumentState("template");
|
|
window.MSREditor.sourceOfTruth = active.sourceOfTruth;
|
|
window.MSREditor.locked = active.locked;
|
|
window.MSREditor.lastGeneratedHash = active.lastGeneratedHash;
|
|
window.MSREditor.lastAcceptedHash = active.lastAcceptedHash;
|
|
window.MSREditor.currentDirty = current.dirty;
|
|
window.MSREditor.templateDirty = template.dirty;
|
|
window.MSREditor.dirty = current.dirty || template.dirty;
|
|
}
|
|
|
|
function rememberGeneratedMSR(msrText, source = window.MSREditor.activeSource) {
|
|
let text = msrText !== undefined && msrText !== null ? msrText.toString() : "";
|
|
let state = getMSRDocumentState(source);
|
|
state.lastGeneratedHash = hashMSRText(text);
|
|
if (source != "template") {
|
|
window.MSREditor.lastGenerated = text;
|
|
}
|
|
syncMSREditorLegacyState();
|
|
}
|
|
|
|
function acceptMSRTextAsKnown(msrText, source = window.MSREditor.activeSource) {
|
|
getMSRDocumentState(source).lastAcceptedHash = hashMSRText(msrText);
|
|
syncMSREditorLegacyState();
|
|
}
|
|
|
|
function isMSREditorSourceAuthoritative(source = window.MSREditor.activeSource) {
|
|
let state = getMSRDocumentState(source);
|
|
return state.sourceOfTruth == "editor" && state.locked;
|
|
}
|
|
|
|
function isActiveMSREditorAuthoritative() {
|
|
return isMSREditorSourceAuthoritative(window.MSREditor.activeSource);
|
|
}
|
|
|
|
function setMSREditorSourceOfTruth(sourceOfTruth, locked, source = window.MSREditor.activeSource) {
|
|
let state = getMSRDocumentState(source);
|
|
state.sourceOfTruth = sourceOfTruth == "editor" ? "editor" : "gui";
|
|
state.locked = locked ? true : false;
|
|
syncMSREditorLegacyState();
|
|
updateMSREditorSourceState();
|
|
}
|
|
|
|
function setGlobalMSRStale(isStale) {
|
|
// "stale" means the current/global MSR no longer corresponds to the template
|
|
// from which it was generated. The file is preserved; this is only a warning
|
|
// flag until the user explicitly regenerates or runs from the template.
|
|
getMSRDocumentState("current").stale = isStale ? true : false;
|
|
updateMSREditorSourceTabs();
|
|
}
|
|
|
|
function unlockMSREditorSource() {
|
|
let source = window.MSREditor.activeSource;
|
|
setMSREditorSourceOfTruth("gui", false, source);
|
|
acceptMSRTextAsKnown(getCurrentEditorText(), source);
|
|
let details = (source == "template" ? "Template" : "MSR")
|
|
+ " editor unlocked. GUI generation may replace this document on the next regeneration.";
|
|
setFitStatus("Editor unlocked; GUI generation is active.", {
|
|
level: "warning",
|
|
details: details
|
|
});
|
|
}
|
|
|
|
function updateMSREditorSourceState() {
|
|
if (typeof document === "undefined") {
|
|
return;
|
|
}
|
|
let stateBar = document.getElementById("msrSourceState");
|
|
let label = document.getElementById("msrSourceStateLabel");
|
|
let unlockButton = document.getElementById("msrUnlockButton");
|
|
if (!stateBar) {
|
|
return;
|
|
}
|
|
|
|
let source = window.MSREditor.activeSource;
|
|
let state = getMSRDocumentState(source);
|
|
let stale = source == "current" && window.MSREditor.hasTemplateTab && state.stale;
|
|
|
|
// MSR-to-GUI synchronization is useful only for an editor-locked document. A
|
|
// stale generated global is indicated compactly on the Global selector itself.
|
|
stateBar.hidden = !state.locked;
|
|
if (unlockButton) {
|
|
// The lock is also a persistent ownership indicator. It becomes an action
|
|
// only while the editor owns the document and can be returned to GUI control.
|
|
unlockButton.disabled = !state.locked;
|
|
unlockButton.className = state.locked
|
|
? "editor-icon-button editor-lock-button locked"
|
|
: "editor-icon-button editor-lock-button";
|
|
unlockButton.title = state.locked
|
|
? "Editor controls this MSR; click to return control to the GUI"
|
|
: "GUI controls this MSR; editing the text will lock it";
|
|
unlockButton.setAttribute(
|
|
"aria-label",
|
|
state.locked ? "Editor source locked; unlock" : "Editor source unlocked"
|
|
);
|
|
}
|
|
if (label) {
|
|
label.textContent = state.locked && stale ? "Editor source · stale" : "Editor source";
|
|
}
|
|
}
|
|
|
|
function markMSREditorAsGUIOwned(msrText, source = window.MSREditor.activeSource) {
|
|
acceptMSRTextAsKnown(msrText, source);
|
|
setMSREditorSourceOfTruth("gui", false, source);
|
|
if (source == "current") {
|
|
// A freshly generated/fitted runnable MSR is current with respect to the
|
|
// template that produced it, so clear the stale marker.
|
|
getMSRDocumentState("current").stale = false;
|
|
}
|
|
updateMSREditorSourceTabs();
|
|
}
|
|
|
|
function markMSREditorAsEditorOwned(msrText, source = window.MSREditor.activeSource) {
|
|
acceptMSRTextAsKnown(msrText, source);
|
|
setMSREditorSourceOfTruth("editor", true, source);
|
|
}
|
|
|
|
function setMSREditorDirty(isDirty, source = window.MSREditor.activeSource) {
|
|
getMSRDocumentState(source).dirty = isDirty ? true : false;
|
|
syncMSREditorLegacyState();
|
|
}
|
|
|
|
function handleMSREditorKeydown(event) {
|
|
// The editor is a contenteditable pre. Its default Enter handling inserts a
|
|
// <br> element (and execCommand insertText can too), and a <br> contributes
|
|
// no text to textContent: the highlight re-render on the following input
|
|
// event would read the content back without the line break and drop it.
|
|
// Intercept Enter, insert a literal "\n" text node at the caret instead, and
|
|
// dispatch the input event so highlighting and dirty/ownership handling run
|
|
// as for any other edit.
|
|
if (!event || event.key !== "Enter") {
|
|
return;
|
|
}
|
|
let editor = document.getElementById("msrEditorText");
|
|
if (!editor || !window.getSelection) {
|
|
return;
|
|
}
|
|
let selection = window.getSelection();
|
|
if (!selection || selection.rangeCount === 0) {
|
|
return;
|
|
}
|
|
let range = selection.getRangeAt(0);
|
|
if (!editor.contains(range.commonAncestorContainer)) {
|
|
return;
|
|
}
|
|
event.preventDefault();
|
|
range.deleteContents();
|
|
let textNode = document.createTextNode("\n");
|
|
range.insertNode(textNode);
|
|
range.setStartAfter(textNode);
|
|
range.collapse(true);
|
|
selection.removeAllRanges();
|
|
selection.addRange(range);
|
|
|
|
let inputEvent = null;
|
|
if (document.createEvent) {
|
|
inputEvent = document.createEvent("Event");
|
|
inputEvent.initEvent("input", true, false);
|
|
} else if (typeof Event === "function") {
|
|
inputEvent = new Event("input", { bubbles: true });
|
|
}
|
|
if (inputEvent) {
|
|
editor.dispatchEvent(inputEvent);
|
|
}
|
|
}
|
|
|
|
function handleMSREditorInput() {
|
|
highlightMSREditor();
|
|
if (window.MSREditor.suppressInput) {
|
|
return;
|
|
}
|
|
|
|
let source = window.MSREditor.activeSource;
|
|
let state = getMSRDocumentState(source);
|
|
setMSREditorDirty(true, source);
|
|
let editorHash = hashMSRText(getCurrentEditorText());
|
|
if (editorHash !== state.lastGeneratedHash
|
|
&& editorHash !== state.lastAcceptedHash) {
|
|
// Manual editing transfers ownership only for the document being edited.
|
|
// Editing a template also marks the downstream global file as stale.
|
|
setMSREditorSourceOfTruth("editor", true, source);
|
|
if (source == "template" && window.MSREditor.hasTemplateTab) {
|
|
setGlobalMSRStale(true);
|
|
}
|
|
}
|
|
updateMSREditorSourceTabs();
|
|
}
|
|
|
|
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 || 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);
|
|
setMSREditorDirty(false, source);
|
|
if (isMSREditorSourceAuthoritative(source)) {
|
|
setMSREditorSourceOfTruth("editor", true, source);
|
|
} else {
|
|
updateMSREditorSourceState();
|
|
}
|
|
setFitStatus("MSR fields synchronized to the GUI.", {
|
|
level: "success",
|
|
details: "Synchronized recognized MSR fields. Editor remains the source of truth until unlocked."
|
|
});
|
|
return(1);
|
|
}
|
|
|
|
setFitStatus("No supported MSR fields could be synchronized.", {
|
|
level: "error",
|
|
details: "Could not synchronize the editor MSR with the current GUI fields."
|
|
});
|
|
return(0);
|
|
}
|
|
|
|
function regenerateEditorFromGUI() {
|
|
// GUI regeneration needs a concrete run because the generated MSR filename
|
|
// and RUN block are both derived from the first selected run.
|
|
if (!validateRunSelection("Generate")) {
|
|
return(0);
|
|
}
|
|
if (!validateRRFSettings("Generate")) {
|
|
return(0);
|
|
}
|
|
|
|
let source = window.MSREditor.activeSource;
|
|
if (isMSREditorSourceAuthoritative(source) && typeof confirm === "function") {
|
|
let label = source == "template" ? "template" : "MSR";
|
|
let ok = confirm("Regenerate the " + label + " from the GUI and replace the editor text?");
|
|
if (!ok) {
|
|
return(0);
|
|
}
|
|
}
|
|
|
|
if (source == "template" && window.MSREditor.hasTemplateTab) {
|
|
// Regenerating only the template must not discard a manually edited global
|
|
// file. Instead, replace the template and mark the existing global stale.
|
|
prepCFG();
|
|
let templateMSR = createMSR();
|
|
let txt = document.getElementById("msrEditorText");
|
|
window.MSREditor.templateContent = templateMSR;
|
|
setMSREditorText(txt, templateMSR);
|
|
rememberGeneratedMSR(templateMSR, "template");
|
|
markMSREditorAsGUIOwned(templateMSR, "template");
|
|
setMSREditorDirty(false, "template");
|
|
setGlobalMSRStale(true);
|
|
setFitStatus("Template regenerated; Global MSR is stale.", {
|
|
level: "warning",
|
|
details: "Template regenerated from GUI. Global MSR is now stale until regenerated."
|
|
});
|
|
return(1);
|
|
}
|
|
|
|
openEditorWithGeneratedMSR();
|
|
return(1);
|
|
}
|
|
|
|
function confirmOverwriteDirtyEditor(actionLabel) {
|
|
// An editor-owned active document is intentionally the source for this action;
|
|
// do not ask a generic overwrite question before the preparation code handles it.
|
|
if (isActiveMSREditorAuthoritative()
|
|
|| (window.MSREditor.hasTemplateTab && isMSREditorSourceAuthoritative("template"))) {
|
|
// A locked template is also safe when the Global tab is selected: global
|
|
// preparation will regenerate from that template rather than from GUI state.
|
|
return true;
|
|
}
|
|
|
|
let current = getMSRDocumentState("current");
|
|
let template = getMSRDocumentState("template");
|
|
if (!current.dirty && !template.dirty && !window.MSREditor.dirty) {
|
|
return true;
|
|
}
|
|
|
|
let message = "The MSR editor has manual changes. "
|
|
+ actionLabel + " will regenerate the MSR file from GUI-owned content. Continue?";
|
|
if (typeof confirm === "function") {
|
|
return confirm(message);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// MSR parsing and GUI synchronization helpers.
|
|
function parseMSRRunFileToken(fileToken) {
|
|
// Reverse the filename rules used by runFileNameAuto(). The surrounding path
|
|
// is deliberately optional because musrfit accepts absolute, relative, and
|
|
// search-path based RUN filenames.
|
|
let token = fileToken !== undefined && fileToken !== null
|
|
? String(fileToken).trim() : "";
|
|
let basename = token.split(/[\\/]/).pop().replace(/\.(?:root|bin|mdu|msr)$/i, "");
|
|
let pathYears = token.match(/(?:^|[\\/])((?:19|20)\d{2})(?=[\\/]|$)/g) || [];
|
|
let pathYear = "";
|
|
if (pathYears.length > 0) {
|
|
let yearMatch = pathYears[pathYears.length - 1].match(/((?:19|20)\d{2})/);
|
|
pathYear = yearMatch ? yearMatch[1] : "";
|
|
}
|
|
|
|
let match = null;
|
|
let instrument = "";
|
|
let filenameYear = "";
|
|
let run = "";
|
|
|
|
if ((match = basename.match(/^lem(\d{2})_his_(\d+)$/i))) {
|
|
instrument = "LEM";
|
|
filenameYear = "20" + match[1];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^flame(\d{2})_his_(\d+)$/i))) {
|
|
instrument = "FLAME";
|
|
filenameYear = "20" + match[1];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^deltatbc_tdc_(gps|gpd)_(\d{4})_(\d+)$/i))) {
|
|
instrument = { gps: "GPS", gpd: "GPD" }[match[1].toLowerCase()];
|
|
filenameYear = match[2];
|
|
run = match[3];
|
|
} else if ((match = basename.match(/^deltat_tdc_(gps|gpd|ltf|dolly)(?:_(\d{4}))?_(\d+)$/i))) {
|
|
instrument = { gps: "GPS", gpd: "GPD", ltf: "LTF", dolly: "Dolly" }[match[1].toLowerCase()];
|
|
filenameYear = match[2] || "";
|
|
run = match[3];
|
|
} else if ((match = basename.match(/^deltat_pta_(gps|gpd|ltf|dolly)_(\d+)$/i))) {
|
|
instrument = { gps: "GPS", gpd: "GPD", ltf: "LTF", dolly: "Dolly" }[match[1].toLowerCase()];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^deltat_tdc_hifi_(\d{4})_(\d+)$/i))) {
|
|
instrument = "HAL";
|
|
filenameYear = match[1];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^deltat_tdc_vms_(\d{4})_(\d+)$/i))) {
|
|
instrument = "VMS";
|
|
filenameYear = match[1];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^tdc_hifi_(\d{4})_(\d+)$/i))) {
|
|
instrument = "HAL";
|
|
filenameYear = match[1];
|
|
run = match[2];
|
|
} else if ((match = basename.match(/^deltat_tdc_flame_(\d{4})_(\d+)$/i))) {
|
|
instrument = "FLAME";
|
|
filenameYear = match[1];
|
|
run = match[2];
|
|
}
|
|
|
|
if (run !== "") {
|
|
run = String(parseInt(run, 10));
|
|
}
|
|
return {
|
|
fileToken: token,
|
|
instrument: instrument,
|
|
year: filenameYear || pathYear,
|
|
yearConflict: Boolean(filenameYear && pathYear && filenameYear != pathYear),
|
|
run: run
|
|
};
|
|
}
|
|
|
|
function uniqueMSRValues(values) {
|
|
return Array.from(new Set(values.filter(function(value) {
|
|
return value !== undefined && value !== null && value !== "";
|
|
})));
|
|
}
|
|
|
|
function parseMSRGUISettings(msrText) {
|
|
// 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: {},
|
|
warnings: [],
|
|
recognized: []
|
|
};
|
|
if (!msrText || typeof msrText !== "string") return parsed;
|
|
|
|
let section = "";
|
|
let runBlocks = [];
|
|
let currentRun = null;
|
|
let globalFitType = null;
|
|
let plotFitType = null;
|
|
let commandLines = [];
|
|
let plotSeen = false;
|
|
let fourierSeen = false;
|
|
let plotFlags = { logx: false, logy: false, lifetime: false };
|
|
let plotRangeSeen = false;
|
|
|
|
function remember(id, value) {
|
|
parsed.values[id] = value;
|
|
if (!parsed.recognized.includes(id)) parsed.recognized.push(id);
|
|
}
|
|
|
|
for (let rawLine of msrText.split(/\r?\n/)) {
|
|
let line = rawLine.split("#", 1)[0].replace(/\s+\(.*$/, "").trim();
|
|
if (line === "") continue;
|
|
|
|
// `plot` is also a directive inside FOURIER. Once that block is active,
|
|
// do not mistake its display-type line for the start of the PLOT block.
|
|
let blockMatch = section == "FOURIER" && /^plot\b/i.test(line)
|
|
? null
|
|
: line.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b\s*(.*)$/i);
|
|
if (blockMatch) {
|
|
section = blockMatch[1].toUpperCase();
|
|
let blockTail = blockMatch[2].trim();
|
|
currentRun = null;
|
|
if (section == "RUN") {
|
|
let runFields = blockTail.split(/\s+/);
|
|
currentRun = {
|
|
fileToken: runFields[0] || "",
|
|
beamLine: runFields[1] || "",
|
|
format: runFields[3] || "",
|
|
addRuns: [],
|
|
forward: null,
|
|
backward: null
|
|
};
|
|
runBlocks.push(currentRun);
|
|
} else if (section == "PLOT") {
|
|
plotSeen = true;
|
|
let typeMatch = blockTail.match(/^([0-3])\b/);
|
|
if (typeMatch) plotFitType = parseInt(typeMatch[1], 10);
|
|
} else if (section == "FOURIER") {
|
|
fourierSeen = true;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
let parts = line.split(/\s+/);
|
|
let directive = parts[0].toLowerCase();
|
|
let values = parts.slice(1);
|
|
if (section == "GLOBAL") {
|
|
if (directive == "fittype" && /^[0-3]$/.test(values[0] || "")) {
|
|
globalFitType = parseInt(values[0], 10);
|
|
} else if (directive == "fit" && values.length >= 2) {
|
|
remember("Tis", values[0]);
|
|
remember("Tfs", values[1]);
|
|
} else if (directive == "packing" && values.length >= 1) {
|
|
remember("BINS", values[0]);
|
|
} else if (directive == "data") {
|
|
let nums = values.filter(function(v) { return /^\d+$/.test(v); });
|
|
if (nums.length >= 2) remember("globalDataRange", nums);
|
|
}
|
|
} else if (section == "RUN" && currentRun) {
|
|
if (directive == "addrun" && values.length >= 1) {
|
|
currentRun.addRuns.push(values[0]);
|
|
} else if (directive == "forward" && values.length >= 1) {
|
|
currentRun.forward = values.join(" ");
|
|
} else if (directive == "backward" && values.length >= 1) {
|
|
currentRun.backward = values.join(" ");
|
|
}
|
|
} else if (section == "COMMANDS") {
|
|
commandLines.push(parts.map(function(part) { return part.toUpperCase(); }));
|
|
} else if (section == "PLOT") {
|
|
if (directive == "runs" && values.length >= 1) {
|
|
let plotRuns = values.filter(function(v) { return /^\d+$/.test(v); });
|
|
if (plotRuns.length > 0) remember("plotRuns", plotRuns);
|
|
} else if (directive == "range" && values.length >= 2) {
|
|
plotRangeSeen = true;
|
|
remember("Tpis", values[0]);
|
|
remember("Tpfs", values[1]);
|
|
remember("Ypis", values.length >= 4 ? values[2] : "");
|
|
remember("Ypfs", values.length >= 4 ? values[3] : "");
|
|
} else if (directive == "use_fit_ranges") {
|
|
plotRangeSeen = true;
|
|
remember("Tpis", "");
|
|
remember("Tpfs", "");
|
|
remember("Ypis", "");
|
|
remember("Ypfs", "");
|
|
} else if (directive == "view_packing" && values.length >= 1) {
|
|
remember("VIEWBINS", values[0]);
|
|
} else if (directive == "logx") {
|
|
plotFlags.logx = true;
|
|
} else if (directive == "logy") {
|
|
plotFlags.logy = true;
|
|
} else if (directive == "lifetimecorrection") {
|
|
plotFlags.lifetime = true;
|
|
} else if (directive == "rrf_freq" && values.length >= 1) {
|
|
remember("rrfEnabled", true);
|
|
remember("rrfFrq", values[0]);
|
|
if (values.length >= 2) {
|
|
let rrfUnitMap = {
|
|
"khz": "kHz", "mhz": "MHz", "mc/s": "Mc/s",
|
|
"g": "G", "gauss": "G", "t": "T", "tesla": "T"
|
|
};
|
|
let rrfUnit = rrfUnitMap[values[1].toLowerCase()];
|
|
if (rrfUnit) remember("rrfUnits", rrfUnit);
|
|
}
|
|
} else if (directive == "rrf_packing" && values.length >= 1) {
|
|
remember("rrfEnabled", true);
|
|
remember("rrfPack", values[0]);
|
|
} else if (directive == "rrf_phase" && values.length >= 1) {
|
|
remember("rrfEnabled", true);
|
|
remember("rrfPhase", values.join(" "));
|
|
}
|
|
} else if (section == "FOURIER") {
|
|
if (directive == "units" && values.length >= 1) {
|
|
let fftUnitMap = {
|
|
"mhz": "MHz", "gauss": "Gauss", "g": "Gauss",
|
|
"tesla": "Tesla", "t": "Tesla", "mc/s": "Mc/s"
|
|
};
|
|
let fftUnit = fftUnitMap[values[0].toLowerCase()];
|
|
if (fftUnit) remember("fftUnits", fftUnit);
|
|
} else if (directive == "fourier_power" && values.length >= 1) {
|
|
remember("fftPower", values[0]);
|
|
} else if (directive == "apodization" && values.length >= 1) {
|
|
let apodization = values[0].toUpperCase();
|
|
if (["NONE", "WEAK", "MEDIUM", "STRONG"].includes(apodization)) {
|
|
remember("fftApod", apodization);
|
|
}
|
|
} else if (directive == "plot" && values.length >= 1) {
|
|
let fftType = values[0].toLowerCase();
|
|
if (["power", "real", "imag", "real_and_imag", "phase"].includes(fftType)) {
|
|
remember("fftType", fftType);
|
|
} else {
|
|
parsed.warnings.push("FOURIER plot type " + values[0] + " is not represented by the GUI.");
|
|
}
|
|
} else if (directive == "phase" && values.length >= 1) {
|
|
remember("fftPhase", values.join(" "));
|
|
} else if (directive == "dc-corrected" && values.length >= 1) {
|
|
remember("fftDCCorrect", /^(?:true|1|yes)$/i.test(values[0]));
|
|
} else if (directive == "range" && values.length >= 2) {
|
|
remember("fftxi", values[0]);
|
|
remember("fftxf", values[1]);
|
|
} else if (directive == "range_for_phase_correction" && values.length >= 1) {
|
|
if (values[0].toLowerCase() == "all") {
|
|
remember("fftPhaseCorrection", "all");
|
|
} else if (values.length >= 2) {
|
|
remember("fftPhaseCorrection", "custom");
|
|
remember("fftPhaseCorrectionStart", values[0]);
|
|
remember("fftPhaseCorrectionEnd", values[1]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function compactRunSelectionDataSetStrings(dataSetStrings) {
|
|
if (!Array.isArray(dataSetStrings) || dataSetStrings.length === 0) return "";
|
|
let dataSets = dataSetStrings.map(function(text) {
|
|
let parts = String(text || "").split("+").filter(function(part) { return part !== ""; });
|
|
return {
|
|
main: parseInt(parts[0], 10),
|
|
add: parts.slice(1).map(function(part) { return parseInt(part, 10); })
|
|
};
|
|
}).filter(function(dataSet) {
|
|
return Number.isInteger(dataSet.main) && dataSet.main > 0
|
|
&& dataSet.add.every(function(run) { return Number.isInteger(run) && run > 0; });
|
|
});
|
|
let terms = [];
|
|
let i = 0;
|
|
while (i < dataSets.length) {
|
|
let dataSet = dataSets[i];
|
|
if (Array.isArray(dataSet.add) && dataSet.add.length > 0) {
|
|
terms.push([String(dataSet.main)].concat(dataSet.add.map(function(run) { return String(run); })).join("+"));
|
|
i++;
|
|
continue;
|
|
}
|
|
let j = i + 1;
|
|
while (j < dataSets.length
|
|
&& (!Array.isArray(dataSets[j].add) || dataSets[j].add.length === 0)
|
|
&& dataSets[j].main === dataSet.main + (j - i)) {
|
|
j++;
|
|
}
|
|
if (j - i >= 3) {
|
|
// Prefer a step sequence when it exactly matches the contiguous range,
|
|
// but keep a simple range as the canonical compact form.
|
|
terms.push(String(dataSet.main) + "-" + String(dataSets[j - 1].main));
|
|
} else {
|
|
for (let k = i; k < j; k++) terms.push(String(dataSets[k].main));
|
|
}
|
|
i = j;
|
|
}
|
|
return terms.join(",");
|
|
}
|
|
|
|
let fitTypes = uniqueMSRValues([globalFitType, plotFitType]);
|
|
if (fitTypes.length == 1 && (fitTypes[0] === 0 || fitTypes[0] === 2)) {
|
|
remember("fitAsyType", fitTypes[0] === 0 ? "SingleHist" : "AsymmetryGLB");
|
|
} else if (fitTypes.length > 1) {
|
|
parsed.warnings.push("GLOBAL and PLOT use different fit types; fit type was not synchronized.");
|
|
}
|
|
|
|
if (runBlocks.length > 0) {
|
|
let dataSets = [];
|
|
let instruments = [];
|
|
let years = [];
|
|
let unresolvedRunBlock = false;
|
|
let runMetadataConflict = false;
|
|
for (let runBlock of runBlocks) {
|
|
let main = parseMSRRunFileToken(runBlock.fileToken);
|
|
if (main.run === "") {
|
|
unresolvedRunBlock = true;
|
|
continue;
|
|
}
|
|
if (main.yearConflict) runMetadataConflict = true;
|
|
if (main.instrument && runBlock.beamLine
|
|
&& instPars[main.instrument]
|
|
&& instPars[main.instrument].beamLine.toUpperCase() != runBlock.beamLine.toUpperCase()) {
|
|
runMetadataConflict = true;
|
|
}
|
|
if (main.instrument) instruments.push(main.instrument);
|
|
if (main.year) years.push(main.year);
|
|
let addRuns = [];
|
|
let addValid = true;
|
|
for (let addToken of runBlock.addRuns) {
|
|
let add = parseMSRRunFileToken(addToken);
|
|
if (add.run === "") {
|
|
addValid = false;
|
|
break;
|
|
}
|
|
if (add.yearConflict) runMetadataConflict = true;
|
|
if (add.instrument) instruments.push(add.instrument);
|
|
if (add.year) years.push(add.year);
|
|
addRuns.push(add.run);
|
|
}
|
|
if (!addValid) continue;
|
|
let dataSet = [main.run].concat(addRuns).join("+");
|
|
if (!dataSets.includes(dataSet)) dataSets.push(dataSet);
|
|
}
|
|
instruments = uniqueMSRValues(instruments);
|
|
years = uniqueMSRValues(years);
|
|
if (dataSets.length > 0 && !unresolvedRunBlock) remember("runNumbers", compactRunSelectionDataSetStrings(dataSets));
|
|
if (instruments.length == 1) remember("instrName", instruments[0]);
|
|
if (years.length == 1) remember("selYear", years[0]);
|
|
if (instruments.length > 1 || years.length > 1 || runMetadataConflict) {
|
|
parsed.warnings.push("RUN blocks span more than one instrument or year; those fields were not synchronized.");
|
|
delete parsed.values.instrName;
|
|
delete parsed.values.selYear;
|
|
parsed.recognized = parsed.recognized.filter(function(id) {
|
|
return id != "instrName" && id != "selYear";
|
|
});
|
|
}
|
|
|
|
let fitType = fitTypes.length == 1 ? fitTypes[0] : null;
|
|
if (fitType === 0) {
|
|
let histogramGroups = Object.create(null);
|
|
for (let runBlock of runBlocks) {
|
|
let main = parseMSRRunFileToken(runBlock.fileToken);
|
|
if (main.run === "" || runBlock.forward === null) continue;
|
|
if (!histogramGroups[main.run]) histogramGroups[main.run] = [];
|
|
if (!histogramGroups[main.run].includes(runBlock.forward)) {
|
|
histogramGroups[main.run].push(runBlock.forward);
|
|
}
|
|
}
|
|
let layouts = uniqueMSRValues(Object.keys(histogramGroups).map(function(run) {
|
|
return histogramGroups[run].join(",");
|
|
}));
|
|
if (layouts.length == 1) remember("LRBF", layouts[0]);
|
|
} else if (fitType === 2) {
|
|
let layouts = uniqueMSRValues(runBlocks.map(function(runBlock) {
|
|
if (runBlock.forward === null || runBlock.backward === null) return "";
|
|
return runBlock.forward + "," + runBlock.backward;
|
|
}));
|
|
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("/"));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (commandLines.length > 0) {
|
|
let commandNames = commandLines.map(function(parts) { return parts[0]; });
|
|
let minimizers = uniqueMSRValues(commandNames.filter(function(name) {
|
|
return ["MINIMIZE", "MIGRAD", "SIMPLEX"].includes(name);
|
|
}));
|
|
if (minimizers.length == 1) remember("minType", minimizers[0]);
|
|
if (minimizers.length > 1) {
|
|
parsed.warnings.push("COMMANDS contains more than one minimizer; minimizer was not synchronized.");
|
|
}
|
|
let hasHesse = commandNames.includes("HESSE");
|
|
let hasMinos = commandNames.includes("MINOS");
|
|
remember("errEst", hasHesse && hasMinos ? "HESSE_MINOS" : (hasHesse ? "HESSE" : (hasMinos ? "MINOS" : "NONE")));
|
|
remember("fitObjective", commandNames.includes("MAX_LIKELIHOOD") ? "MAX_LIKELIHOOD" : "CHI2");
|
|
remember("saveMinuit", commandNames.includes("SAVE"));
|
|
let strategies = uniqueMSRValues(commandLines.filter(function(parts) {
|
|
return parts[0] == "STRATEGY" && /^[0-2]$/.test(parts[1] || "");
|
|
}).map(function(parts) { return parts[1]; }));
|
|
if (strategies.length == 1) remember("minStrategy", strategies[0]);
|
|
else if (strategies.length === 0) remember("minStrategy", "");
|
|
}
|
|
|
|
if (plotSeen) {
|
|
if (!plotRangeSeen) {
|
|
remember("Tpis", "");
|
|
remember("Tpfs", "");
|
|
remember("Ypis", "");
|
|
remember("Ypfs", "");
|
|
}
|
|
remember("plotLogX", plotFlags.logx);
|
|
remember("plotLogY", plotFlags.logy);
|
|
// Lifetime correction is on by default for single-histogram fits. A PLOT
|
|
// block without the directive (e.g. a fitted reference written back by
|
|
// musrfit) must not silently switch the GUI default off.
|
|
let plotDefaultLifetime = parsed.values.fitAsyType == "SingleHist"
|
|
|| plotFitType === 0;
|
|
remember("plotLifetimeCorrection", plotFlags.lifetime || plotDefaultLifetime);
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "VIEWBINS")) remember("VIEWBINS", "");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "rrfEnabled")) remember("rrfEnabled", false);
|
|
}
|
|
if (fourierSeen) {
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftUnits")) remember("fftUnits", "Gauss");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftPower")) remember("fftPower", "12");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftApod")) remember("fftApod", "STRONG");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftType")) remember("fftType", "power");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftPhase")) remember("fftPhase", "");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftDCCorrect")) remember("fftDCCorrect", false);
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftxi")) remember("fftxi", "");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftxf")) remember("fftxf", "");
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, "fftPhaseCorrection")) {
|
|
remember("fftPhaseCorrection", "off");
|
|
}
|
|
if (parsed.values.fftPhaseCorrection != "custom") {
|
|
remember("fftPhaseCorrectionStart", "");
|
|
remember("fftPhaseCorrectionEnd", "");
|
|
}
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
function applyMSRGUISettings(parsed, all = All) {
|
|
if (!parsed || !parsed.values || parsed.recognized.length === 0 || !all) return(0);
|
|
for (let id of parsed.recognized) {
|
|
if (!Object.prototype.hasOwnProperty.call(parsed.values, id)) continue;
|
|
let value = parsed.values[id];
|
|
let element = typeof document !== "undefined" ? document.getElementById(id) : null;
|
|
|
|
if (id == "runNumbers" && typeof value === "string") {
|
|
// A global MSR necessarily contains one expanded RUN block per data set.
|
|
// Keep an equivalent compact user expression such as 2407-2410 instead of
|
|
// replacing it with 2407,2408,2409,2410 after every fit.
|
|
let existingValue = element && typeof element.value === "string"
|
|
? element.value : String(all.runNumbers || "");
|
|
let existingSelection = parseRunSelection(existingValue);
|
|
let importedSelection = parseRunSelection(value);
|
|
let sameSelection = existingSelection.length > 0
|
|
&& existingSelection.length == importedSelection.length;
|
|
if (sameSelection) {
|
|
for (let index = 0; index < existingSelection.length; index++) {
|
|
let existingDataSet = existingSelection[index];
|
|
let importedDataSet = importedSelection[index];
|
|
if (existingDataSet.main != importedDataSet.main
|
|
|| existingDataSet.add.length != importedDataSet.add.length
|
|
|| existingDataSet.add.some(function(run, addIndex) {
|
|
return run != importedDataSet.add[addIndex];
|
|
})) {
|
|
sameSelection = false;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (sameSelection) value = existingValue;
|
|
}
|
|
|
|
all[id] = typeof value === "boolean" ? (value ? "1" : "") : value;
|
|
if (typeof document === "undefined") continue;
|
|
if (!element) continue;
|
|
if (typeof value === "boolean") {
|
|
element.checked = value;
|
|
} else {
|
|
element.value = value;
|
|
}
|
|
}
|
|
|
|
if (typeof updateInitialParameterGuessFirstRun === "function" && all.runNumbers) {
|
|
let runs = arrayRunNumbers(all.runNumbers);
|
|
if (runs.length > 0) updateInitialParameterGuessFirstRun(runs[0]);
|
|
}
|
|
if (typeof document !== "undefined") {
|
|
if (typeof updatePlotOptionVisibility === "function") updatePlotOptionVisibility();
|
|
if (typeof cfgFFTRRF === "function") cfgFFTRRF();
|
|
if (typeof updatePlotOptionsIndicator === "function") updatePlotOptionsIndicator();
|
|
if (typeof updateFFTOptionsIndicator === "function") updateFFTOptionsIndicator();
|
|
if (typeof updateResolvedDataPathPreview === "function") updateResolvedDataPathPreview();
|
|
if (typeof updateSeriesActionVisibility === "function") updateSeriesActionVisibility();
|
|
}
|
|
return(1);
|
|
}
|
|
|
|
function syncSettingsFromMSR(msrText, all = All) {
|
|
return applyMSRGUISettings(parseMSRGUISettings(msrText), all);
|
|
}
|
|
|
|
function sanitizedMSRParameterNumber(raw, fallback) {
|
|
// A non-finite token (NaN, nan, inf, ...) is never a usable fit parameter
|
|
// value, error, or boundary. Keep the original formatting for genuine
|
|
// numbers so imported files round-trip unchanged.
|
|
let fallbackText = fallback === undefined || fallback === null ? "" : String(fallback);
|
|
if (raw === undefined || raw === null) return fallbackText;
|
|
let text = String(raw).trim();
|
|
if (text === "") return fallbackText;
|
|
let lowered = text.toLowerCase();
|
|
if (lowered === "nan" || lowered === "inf" || lowered === "-inf"
|
|
|| lowered === "+inf" || lowered === "infinity" || lowered === "-infinity"
|
|
|| /^[+-]?inf$/.test(lowered)) {
|
|
return fallbackText;
|
|
}
|
|
if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(text)) {
|
|
return fallbackText;
|
|
}
|
|
return text;
|
|
}
|
|
|
|
function sanitizedMSRParameterError(errorText, valueText) {
|
|
// After a failed fit (e.g. a non-converged error matrix) musrfit can write
|
|
// NaN into parameter errors. A NaN step is never a usable fit parameter:
|
|
// fall back to 1% of the value so the next fit restarts from a sensible
|
|
// step instead of carrying the failure into every later regeneration.
|
|
let finiteError = sanitizedMSRParameterNumber(errorText);
|
|
if (finiteError !== "") return finiteError;
|
|
let raw = errorText === undefined || errorText === null
|
|
? "" : String(errorText).trim();
|
|
if (raw === "") return "";
|
|
let value = parseFloat(sanitizedMSRParameterNumber(valueText, "1"));
|
|
if (isNaN(value)) value = 1;
|
|
if (value === 0) value = 1;
|
|
return String(parseFloat((value * 0.01).toPrecision(12)));
|
|
}
|
|
|
|
function sanitizedMSRParameterValue(valueText, fallback) {
|
|
// A fitted value that musrfit could not determine (NaN) must not erase the
|
|
// GUI's last good value. Keep the parsed number when it is finite, otherwise
|
|
// fall back to the supplied default (a previous value or a catalogue value).
|
|
let finite = sanitizedMSRParameterNumber(valueText);
|
|
if (finite !== "") return finite;
|
|
let fallbackText = fallback === undefined || fallback === null ? "" : String(fallback);
|
|
let finiteFallback = sanitizedMSRParameterNumber(fallbackText);
|
|
return finiteFallback !== "" ? finiteFallback : fallbackText;
|
|
}
|
|
|
|
function parseMSRParameters(msrText) {
|
|
// Parse only the FITPARAMETER block. This keeps the editor free-form while
|
|
// giving the GUI a stable way to refresh fitted values after musrfit runs.
|
|
let params = [];
|
|
if (!msrText || typeof msrText !== "string") return params;
|
|
|
|
let lines = msrText.split(/\r?\n/);
|
|
let inBlock = false;
|
|
for (let line of lines) {
|
|
let trimmed = line.trim();
|
|
if (trimmed === "FITPARAMETER") {
|
|
inBlock = true;
|
|
continue;
|
|
}
|
|
if (!inBlock) continue;
|
|
if (/^(THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/.test(trimmed)) {
|
|
break;
|
|
}
|
|
if (trimmed === "" || trimmed[0] === "#" || /^#+$/.test(trimmed)) continue;
|
|
|
|
let parts = trimmed.split(/\s+/);
|
|
if (parts.length < 4 || isNaN(parseInt(parts[0]))) continue;
|
|
|
|
// FITPARAMETER lines use either
|
|
// No Name Value Step
|
|
// or, with boundaries,
|
|
// No Name Value Step PosError Lower Upper.
|
|
// A free fitted parameter can have a fifth PosError field. Keep support
|
|
// for the old six-field GUI form so older files can still be imported,
|
|
// even though new bounded lines are always written with PosError=none.
|
|
let min = "";
|
|
let max = "";
|
|
if (parts.length === 6) {
|
|
min = parts[4] || "";
|
|
max = parts[5] || "";
|
|
} else if (parts.length >= 7) {
|
|
min = parts[5] || "";
|
|
max = parts[6] || "";
|
|
}
|
|
params.push({
|
|
order: parts[0],
|
|
name: parts[1],
|
|
value: sanitizedMSRParameterNumber(parts[2]),
|
|
error: sanitizedMSRParameterError(parts[3], parts[2]),
|
|
min: sanitizedMSRParameterNumber(min),
|
|
max: sanitizedMSRParameterNumber(max)
|
|
});
|
|
}
|
|
return params;
|
|
}
|
|
|
|
// Remember the parameter structure of an imported MSR: the FITPARAMETER order
|
|
// (stripped of the "_runnumber" suffix) and any comment lines interleaved with
|
|
// the parameters. The GUI regenerates MSRs in catalogue order, which silently
|
|
// renumbers parameters the moment a file is imported and a fit or series is
|
|
// run. Capturing the file's own ordering and comments lets regeneration replay
|
|
// them, so the round-trip preserves the structure the author wrote. Structural
|
|
// changes (adding/removing/components/custom parameters) reset this via
|
|
// resetImportedMSRParameterStructure, because the file's order then describes a
|
|
// model the GUI no longer has.
|
|
function captureImportedMSRFitParameterStructure(msrText) {
|
|
resetImportedMSRParameterStructure();
|
|
if (!msrText || typeof msrText !== "string") return;
|
|
let lines = msrText.split(/\r?\n/);
|
|
let inBlock = false;
|
|
let pending = [];
|
|
let order = [];
|
|
let comments = [];
|
|
let lastIndex = -1;
|
|
for (let rawLine of lines) {
|
|
let line = rawLine.replace(/\r$/, "");
|
|
let trimmed = line.trim();
|
|
if (trimmed === "FITPARAMETER") {
|
|
inBlock = true;
|
|
pending = [];
|
|
continue;
|
|
}
|
|
if (!inBlock) continue;
|
|
if (/^(THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/.test(trimmed)) break;
|
|
if (trimmed === "") {
|
|
// A blank line inside the block is not a parameter; keep any pending
|
|
// comments attached to the next parameter so a labelled group is not
|
|
// accidentally associated with the wrong entry.
|
|
continue;
|
|
}
|
|
if (trimmed[0] === "#" || /^#+$/.test(trimmed)) {
|
|
// FITPARAMETER structural decorations belong to the generator, not to
|
|
// the replayed comment stream: the column header (No/Name/Value/Step/
|
|
// PosErr) and pure ### separators surround a block that the template
|
|
// always writes exactly once. Fitted files repeat that header before
|
|
// every parameter, so replaying it per parameter multiplies it on each
|
|
// round-trip. Drop those two shapes while capturing; meaningful author
|
|
// comments (# text...) are still kept and replayed.
|
|
if (/^#+\s*$/.test(trimmed)) {
|
|
continue;
|
|
}
|
|
if (/^#.*?\bNo\b\s+\bName\b\s+\bValue\b\s+\bStep\b\s+\bPosErr\b/i.test(trimmed)) {
|
|
continue;
|
|
}
|
|
pending.push(trimmed);
|
|
continue;
|
|
}
|
|
let parts = trimmed.split(/\s+/);
|
|
if (parts.length < 4 || isNaN(parseInt(parts[0]))) continue;
|
|
// The runtime suffix belongs to the data set, not to the parameter name.
|
|
let baseName = parts[1].replace(/_\d+$/, "");
|
|
order.push(baseName);
|
|
comments.push({ before: pending.slice(), after: [] });
|
|
pending = [];
|
|
lastIndex++;
|
|
}
|
|
if (order.length === 0) return;
|
|
// Trailing comments that open the block or follow the last parameter stay
|
|
// attached to the last entry so nothing is dropped.
|
|
if (pending.length > 0 && lastIndex >= 0) {
|
|
for (let text of pending) comments[lastIndex].after.push(text);
|
|
}
|
|
importedMSRFitParameterOrder = order;
|
|
importedMSRFitParameterComments = comments;
|
|
}
|
|
|
|
function resetImportedMSRParameterStructure() {
|
|
importedMSRFitParameterOrder = null;
|
|
importedMSRFitParameterComments = null;
|
|
}
|
|
|
|
// Reorder a FITPARAMETER dropdown so the parameters an imported MSR listed in
|
|
// its own sequence keep that relative order. Parameters not present in the
|
|
// imported file (e.g. newly added components) keep their catalogue position at
|
|
// the end. Names are matched after stripping the "_runnumber" suffix, which is
|
|
// exactly how captureImportedMSRFitParameterStructure stores them; called before
|
|
// the table is rendered and before MSR generation, so both the GUI and every
|
|
// single-fit/series MSR follow the imported order.
|
|
function applyImportedMSRParameterOrder(funSel) {
|
|
if (!funSel || !importedMSRFitParameterOrder || !importedMSRFitParameterOrder.length) return;
|
|
let available = Array.from(funSel.options);
|
|
let placed = new Set();
|
|
let ordered = [];
|
|
for (let name of importedMSRFitParameterOrder) {
|
|
if (placed.has(name)) continue;
|
|
let option = null;
|
|
for (let candidate of available) {
|
|
if (candidate.value === name && !placed.has(candidate.value)) {
|
|
option = candidate;
|
|
break;
|
|
}
|
|
}
|
|
if (option) {
|
|
ordered.push(option);
|
|
placed.add(option.value);
|
|
}
|
|
}
|
|
if (ordered.length === 0) return;
|
|
for (let option of available) {
|
|
if (placed.has(option.value)) continue;
|
|
ordered.push(option);
|
|
placed.add(option.value);
|
|
}
|
|
for (let option of ordered) funSel.appendChild(option);
|
|
}
|
|
|
|
// Rank a parameter name by its physical role: initial asymmetry first, then
|
|
// relaxation/lineshape, then precession frequency, then phase, then the
|
|
// asymmetry alphas/group ratios, then detector normalization/background, then
|
|
// custom parameters last. Indices are stripped via defaultParameterKey so
|
|
// component/histogram suffixes (Phi1, Phi2H3, No2, Alpha1, rN, ...) map to the
|
|
// same role as their base name.
|
|
function physicalParameterRoleRank(parName) {
|
|
switch (defaultParameterKey(parName)) {
|
|
case "Asy": return 0;
|
|
case "Lam": case "Sgm": case "Bet": case "Del": case "Rb":
|
|
case "KTBet": case "Gam": return 1;
|
|
case "Frq": case "BFrq": return 2;
|
|
case "Phi": return 3;
|
|
case "Alpha": case "One": case "r": return 4;
|
|
case "No": case "NBg": return 5;
|
|
default: return 6;
|
|
}
|
|
}
|
|
|
|
// Partition parameters for the display order: physical model parameters of the
|
|
// components come first, fit/detector-global ones (alpha normalization, the
|
|
// fixed ratio One, group ratios rN, and the histogram normalizations No/NBg)
|
|
// follow after every component block, unlinked custom parameters last.
|
|
function physicalParameterGroupClass(parName) {
|
|
switch (defaultParameterKey(parName)) {
|
|
case "Alpha": case "One": case "r": case "No": case "NBg": return 1;
|
|
default: return 0;
|
|
}
|
|
}
|
|
|
|
// Component index of a parameter name. Physical model parameters carry their
|
|
// component as a numeric suffix (Asy2, Lam3, Frq1, Phi2), with detector-phase
|
|
// names keeping the component before the histogram marker (Phi2H3 -> 2,
|
|
// PhiH2 -> 1). Fit/detector-global names do not belong to a component.
|
|
function physicalParameterComponentIndex(parName) {
|
|
let name = parName === undefined || parName === null ? "" : String(parName);
|
|
if (physicalParameterGroupClass(parName) === 1) return 1;
|
|
let histPhase = name.match(/^Phi(\d*)H(\d+)$/);
|
|
if (histPhase) return histPhase[1] ? parseInt(histPhase[1], 10) : 1;
|
|
let digits = name.match(/(\d+)$/);
|
|
return digits ? parseInt(digits[1], 10) : 1;
|
|
}
|
|
|
|
// Reorder a FITPARAMETER dropdown so the parameter table, the generated
|
|
// FITPARAMETER block and therefore the msr2data column order present the
|
|
// measurable quantities first. The ordering is component-major: the physical
|
|
// parameters of each component stay grouped in component order (Asy1 Lam1 Frq1
|
|
// Phi1 Asy2 Lam2 Frq2 Phi2, ...) with the role sequence within one component,
|
|
// then the fit/detector-global parameters (Alpha, One, rN, No/NBg), then
|
|
// unlinked custom parameters. Parameters introduced through a constraint
|
|
// (e.g. "Frq = gamma_mu * Bfield") inherit both the rank and the component of
|
|
// the built-in parameter they are linked to; a parameter linked to several of
|
|
// them takes the highest-priority (lowest) rank among them. A stored import
|
|
// order always wins over this physical ordering.
|
|
function applyPhysicalParameterOrder(funSel, constraints) {
|
|
if (!funSel || !funSel.options || !funSel.options.length) return;
|
|
if (importedMSRFitParameterOrder && importedMSRFitParameterOrder.length) return;
|
|
|
|
let lines = constraints;
|
|
if (!lines) {
|
|
lines = [];
|
|
if (typeof document !== "undefined" && document.getElementsByClassName) {
|
|
for (let line of document.getElementsByClassName("funLine")) {
|
|
lines.push(String(line.innerText || line.textContent || "").trim());
|
|
}
|
|
}
|
|
}
|
|
|
|
// Union-Find over parameters that co-occur in a constraint line: a custom
|
|
// parameter written as a function of (or replaced by) a built-in one joins
|
|
// that parameter's rank group.
|
|
let parent = Object.create(null);
|
|
for (let opt of funSel.options) parent[opt.value] = opt.value;
|
|
function find(name) {
|
|
if (!(name in parent)) return name;
|
|
while (parent[name] !== name) name = parent[name];
|
|
return name;
|
|
}
|
|
function union(a, b) {
|
|
let ra = find(a);
|
|
let rb = find(b);
|
|
if (ra !== rb) parent[rb] = ra;
|
|
}
|
|
|
|
let valueSet = new Set();
|
|
for (let opt of funSel.options) valueSet.add(opt.value);
|
|
for (let line of lines) {
|
|
let eq = line.indexOf("=");
|
|
if (eq < 0) continue;
|
|
let target = line.slice(0, eq).trim();
|
|
if (!valueSet.has(target)) continue;
|
|
let linked = [target];
|
|
let expressionTokens = line.slice(eq + 1).match(/[A-Za-z_]\w*/g) || [];
|
|
for (let token of expressionTokens) {
|
|
if (valueSet.has(token) && linked.indexOf(token) < 0) linked.push(token);
|
|
}
|
|
for (let i = 1; i < linked.length; i++) union(linked[0], linked[i]);
|
|
}
|
|
|
|
// Each rank group resolves to the lowest (highest-priority) member rank.
|
|
// Custom parameters (role rank 6) inherit that group rank and the component
|
|
// of the built-in they parametrize; built-in parameters keep their own
|
|
// physical role rank and component.
|
|
let rootRank = {};
|
|
let rootComponent = {};
|
|
let ownRank = {};
|
|
let ownComponent = {};
|
|
for (let opt of funSel.options) {
|
|
let root = find(opt.value);
|
|
let r = physicalParameterRoleRank(opt.value);
|
|
let c = physicalParameterComponentIndex(opt.value);
|
|
ownRank[opt.value] = r;
|
|
ownComponent[opt.value] = c;
|
|
if (r >= 6) {
|
|
continue;
|
|
}
|
|
if (!(root in rootRank) || r < rootRank[root]) {
|
|
rootRank[root] = r;
|
|
rootComponent[root] = c;
|
|
}
|
|
}
|
|
// Signal of a multi-group asymmetry fit: alpha normalizations carry a per-
|
|
// group index (Alpha1, Alpha2, ...). Every parameter belongs to the single
|
|
// component then, so group-indexed names must not be split across
|
|
// "components" while grouping the physical parameters.
|
|
let multiGroup = false;
|
|
for (let opt of funSel.options) {
|
|
if (/^Alpha\d+$/.test(opt.value)) {
|
|
multiGroup = true;
|
|
break;
|
|
}
|
|
}
|
|
let rank = {};
|
|
let componentIndex = {};
|
|
let paramClass = {};
|
|
for (let opt of funSel.options) {
|
|
let root = find(opt.value);
|
|
let r = ownRank[opt.value];
|
|
let c = ownComponent[opt.value];
|
|
if (r >= 6) {
|
|
// A custom parameter linked to built-ins through a constraint ranks and
|
|
// groups with them; an unlinked one stays after every physical block.
|
|
if (root in rootRank) {
|
|
paramClass[opt.value] = 0;
|
|
rank[opt.value] = rootRank[root];
|
|
componentIndex[opt.value] = rootComponent[root];
|
|
} else {
|
|
paramClass[opt.value] = 2;
|
|
rank[opt.value] = r;
|
|
componentIndex[opt.value] = 1;
|
|
}
|
|
} else if (physicalParameterGroupClass(opt.value) === 1) {
|
|
// Fit/detector-global parameters (Alpha, One, ratios rN, No/NBg) sort
|
|
// after every component block.
|
|
paramClass[opt.value] = 1;
|
|
rank[opt.value] = r;
|
|
componentIndex[opt.value] = 1;
|
|
} else {
|
|
paramClass[opt.value] = 0;
|
|
rank[opt.value] = r;
|
|
componentIndex[opt.value] = multiGroup ? 1 : c;
|
|
}
|
|
}
|
|
|
|
// Stable component-major sort: the physical parameters of each component
|
|
// stay grouped in component order (Asy1 Lam1 Frq1 Phi1 Asy2 Lam2 Frq2 Phi2,
|
|
// ...) with the measurable quantity sequence within one component, then the
|
|
// fit/detector-global parameters, then unlinked custom parameters.
|
|
let ordered = Array.from(funSel.options);
|
|
ordered.sort(function(a, b) {
|
|
if (paramClass[a.value] !== paramClass[b.value]) {
|
|
return paramClass[a.value] - paramClass[b.value];
|
|
}
|
|
if (componentIndex[a.value] !== componentIndex[b.value]) {
|
|
return componentIndex[a.value] - componentIndex[b.value];
|
|
}
|
|
return rank[a.value] - rank[b.value];
|
|
});
|
|
let unchanged = ordered.every(function(opt, index) {
|
|
return opt === funSel.options[index];
|
|
});
|
|
if (unchanged) return;
|
|
for (let opt of ordered) funSel.appendChild(opt);
|
|
}
|
|
|
|
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 = theoryComponents.length > 1
|
|
? templateParts[argumentIndex] + (componentIndex + 1)
|
|
: templateParts[argumentIndex];
|
|
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;
|
|
}
|
|
// 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";
|
|
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;
|
|
} else if (multiGroup) {
|
|
targetName += 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);
|
|
let alphaTarget = multiGroup ? "Alpha" + histogramIndex : "Alpha";
|
|
if (alphaFunction) functionTargets[alphaFunction[1]] = alphaTarget;
|
|
else if (!assignImportedParameterTarget(parsed, runBlock.alpha, alphaTarget)) 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 && !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) {
|
|
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;
|
|
}
|
|
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) {
|
|
if (!functions[functionNo]) {
|
|
parsed.error = "fun" + functionNo + " is referenced but not defined.";
|
|
return parsed;
|
|
}
|
|
}
|
|
|
|
parsed.ok = true;
|
|
return parsed;
|
|
}
|
|
|
|
function applyMSRTheoryModel(parsed, all = All) {
|
|
if (!parsed || !parsed.ok || parsed.components.length === 0 || !all) return(0);
|
|
markFitModelExplicit();
|
|
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();
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
|
|
suppressSeriesGUIEditCapture = true;
|
|
try {
|
|
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();
|
|
}
|
|
} finally {
|
|
suppressSeriesGUIEditCapture = false;
|
|
}
|
|
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.
|
|
let parsed = {
|
|
fitType: null,
|
|
runBlocks: [],
|
|
ok: true,
|
|
error: ""
|
|
};
|
|
if (!msrText || typeof msrText !== "string") {
|
|
return parsed;
|
|
}
|
|
|
|
let section = "";
|
|
let currentRun = null;
|
|
let lines = msrText.split(/\r?\n/);
|
|
for (let rawLine of lines) {
|
|
let line = rawLine.trim();
|
|
if (line === "" || line[0] === "#") {
|
|
continue;
|
|
}
|
|
|
|
// musrfit commonly appends either # comments or parenthesized descriptions.
|
|
// Remove those before counting directive values.
|
|
line = line.split("#", 1)[0].replace(/\s+\(.*$/, "").trim();
|
|
let blockMatch = line.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/i);
|
|
if (blockMatch) {
|
|
section = blockMatch[1].toUpperCase();
|
|
if (section == "RUN") {
|
|
currentRun = {
|
|
t0: null,
|
|
background: null,
|
|
backgrFix: null,
|
|
backgrFit: null,
|
|
dataRange: null
|
|
};
|
|
parsed.runBlocks.push(currentRun);
|
|
} else {
|
|
currentRun = null;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (section == "GLOBAL") {
|
|
let fitTypeMatch = line.match(/^fittype\s+([02])\b/i);
|
|
if (fitTypeMatch) {
|
|
parsed.fitType = parseInt(fitTypeMatch[1]);
|
|
}
|
|
continue;
|
|
}
|
|
if (section != "RUN" || !currentRun) {
|
|
continue;
|
|
}
|
|
|
|
let directiveMatch = line.match(/^(t0|background|backgr\.fix|backgr\.fit|data)\b\s*(.*)$/i);
|
|
if (!directiveMatch) {
|
|
continue;
|
|
}
|
|
|
|
let directive = directiveMatch[1].toLowerCase();
|
|
let valuesText = directiveMatch[2].trim();
|
|
|
|
if (directive == "data") {
|
|
let nums = valuesText.split(/\s+/).filter(function(v) { return /^\d+$/.test(v); });
|
|
if (nums.length >= 2 && currentRun.dataRange === null) {
|
|
currentRun.dataRange = nums;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
let propertyName = directive;
|
|
if (directive == "backgr.fix") {
|
|
propertyName = "backgrFix";
|
|
} else if (directive == "backgr.fit") {
|
|
propertyName = "backgrFit";
|
|
}
|
|
|
|
if (currentRun[propertyName] !== null || valuesText === "") {
|
|
parsed.ok = false;
|
|
parsed.error = "Ambiguous or empty " + directive + " directive in RUN block " + parsed.runBlocks.length + ".";
|
|
return parsed;
|
|
}
|
|
currentRun[propertyName] = valuesText.split(/\s+/);
|
|
}
|
|
|
|
return parsed;
|
|
}
|
|
|
|
function syncT0BgFromMSR(msrText, all = All) {
|
|
let parsed = parseMSRT0BgRunBlocks(msrText);
|
|
if (!parsed.ok || parsed.runBlocks.length === 0 || !all) {
|
|
return(0);
|
|
}
|
|
|
|
let guiFitType = getFitType(all);
|
|
if (parsed.fitType !== null && parsed.fitType !== guiFitType) {
|
|
// Updating the fit type from editor text requires rebuilding more than this
|
|
// tab, so leave the GUI untouched until full settings import is available.
|
|
return(0);
|
|
}
|
|
let fitType = parsed.fitType !== null ? parsed.fitType : guiFitType;
|
|
if (fitType !== 0 && fitType !== 2) {
|
|
return(0);
|
|
}
|
|
|
|
let multiGroup = isMultiAsymmetryFit(all);
|
|
|
|
// RUN order maps to histogram order for SingleHist, physical-run order for
|
|
// asymmetry, and asymmetry-group order for a multi-group fit (one RUN block
|
|
// per forward,backward pair of the same physical run). Refuse a partial
|
|
// mapping when the current GUI selection differs.
|
|
let expectedRows = 0;
|
|
if (fitType === 0 && all.LRBF) {
|
|
expectedRows = all.LRBF.split(",").filter(function(hist) {
|
|
return hist.trim() !== "";
|
|
}).length;
|
|
} else if (fitType === 2 && all.runNumbers) {
|
|
if (multiGroup) {
|
|
expectedRows = multiAsymmetryGroupCount(all);
|
|
} else {
|
|
expectedRows = arrayRunNumbers(all.runNumbers).length;
|
|
}
|
|
}
|
|
if (expectedRows > 0 && expectedRows !== parsed.runBlocks.length) {
|
|
return(0);
|
|
}
|
|
|
|
let rangeValueCount = fitType === 0 ? 2 : 4;
|
|
let fixedValueCount = fitType === 0 ? 1 : 2;
|
|
let runStates = [];
|
|
for (let runBlock of parsed.runBlocks) {
|
|
let backgroundDirectives = [runBlock.background, runBlock.backgrFix, runBlock.backgrFit];
|
|
let activeBackgroundDirectives = backgroundDirectives.filter(function(values) {
|
|
return values !== null;
|
|
}).length;
|
|
if (activeBackgroundDirectives > 1
|
|
|| (runBlock.background !== null && runBlock.background.length !== rangeValueCount)
|
|
|| (runBlock.backgrFix !== null && runBlock.backgrFix.length !== fixedValueCount)
|
|
|| (runBlock.backgrFit !== null && runBlock.backgrFit.length !== 1)
|
|
|| (fitType === 2 && runBlock.backgrFit !== null)) {
|
|
return(0);
|
|
}
|
|
|
|
let state = {
|
|
t0: null,
|
|
bgMode: "auto",
|
|
bgValues: []
|
|
};
|
|
if (runBlock.t0 !== null) {
|
|
if (fitType === 0) {
|
|
// A grouped SingleHist RUN still has one GUI field, containing its t0 list.
|
|
state.t0 = [runBlock.t0.join(" ")];
|
|
} else {
|
|
if (runBlock.t0.length < 2 || runBlock.t0.length % 2 !== 0) {
|
|
return(0);
|
|
}
|
|
// musrfit stores grouped asymmetry values as F1 B1 F2 B2. The GUI
|
|
// presents separate forward and backward lists, so split alternating items.
|
|
let forwardT0 = [];
|
|
let backwardT0 = [];
|
|
for (let valueIndex = 0; valueIndex < runBlock.t0.length; valueIndex += 2) {
|
|
forwardT0.push(runBlock.t0[valueIndex]);
|
|
backwardT0.push(runBlock.t0[valueIndex + 1]);
|
|
}
|
|
state.t0 = [forwardT0.join(" "), backwardT0.join(" ")];
|
|
}
|
|
}
|
|
if (runBlock.background !== null) {
|
|
state.bgMode = "range";
|
|
state.bgValues = runBlock.background;
|
|
} else if (runBlock.backgrFix !== null) {
|
|
state.bgMode = "fixed";
|
|
state.bgValues = runBlock.backgrFix;
|
|
} else if (runBlock.backgrFit !== null) {
|
|
// The parameter number comes from the corresponding NBg parameter table row.
|
|
state.bgMode = "fit";
|
|
}
|
|
runStates.push(state);
|
|
}
|
|
|
|
// A multi-group asymmetry read-back validates and mutates on its own so a
|
|
// partial/illegal mapping never wipes previously stored GUI values first.
|
|
if (multiGroup) {
|
|
return syncMultiGroupT0BgFromMSR(all, fitType, runStates, parsed);
|
|
}
|
|
|
|
// Validation above completes before any mutation. This prevents a malformed
|
|
// expert edit from leaving half of the GUI synchronized and half unchanged.
|
|
for (let key in all) {
|
|
if (Object.prototype.hasOwnProperty.call(all, key) && key.indexOf("t0Bg") === 0) {
|
|
delete all[key];
|
|
}
|
|
}
|
|
|
|
let t0Fields = fitType === 0 ? ["T0"] : ["T0F", "T0B"];
|
|
let firstT0 = JSON.stringify(runStates[0].t0);
|
|
let allT0Equal = runStates.every(function(state) {
|
|
return JSON.stringify(state.t0) == firstT0;
|
|
});
|
|
if (allT0Equal && runStates[0].t0 !== null) {
|
|
for (let fieldIndex = 0; fieldIndex < t0Fields.length; fieldIndex++) {
|
|
all["t0BgCommon" + t0Fields[fieldIndex]] = runStates[0].t0[fieldIndex];
|
|
}
|
|
} else if (!allT0Equal) {
|
|
for (let rowIndex = 0; rowIndex < runStates.length; rowIndex++) {
|
|
if (runStates[rowIndex].t0 === null) {
|
|
continue;
|
|
}
|
|
for (let fieldIndex = 0; fieldIndex < t0Fields.length; fieldIndex++) {
|
|
all["t0Bg" + t0Fields[fieldIndex] + "_" + rowIndex] = runStates[rowIndex].t0[fieldIndex];
|
|
}
|
|
}
|
|
}
|
|
|
|
let backgroundFields = fitType === 0
|
|
? { range: ["BgStart", "BgEnd"], fixed: ["BgFix"] }
|
|
: { range: ["BgFStart", "BgFEnd", "BgBStart", "BgBEnd"], fixed: ["BgFixF", "BgFixB"] };
|
|
let firstBackground = JSON.stringify({
|
|
mode: runStates[0].bgMode,
|
|
values: runStates[0].bgValues
|
|
});
|
|
let allBackgroundsEqual = runStates.every(function(state) {
|
|
return JSON.stringify({ mode: state.bgMode, values: state.bgValues }) == firstBackground;
|
|
});
|
|
if (allBackgroundsEqual) {
|
|
all.t0BgCommonBgMode = runStates[0].bgMode;
|
|
let commonFields = backgroundFields[runStates[0].bgMode] || [];
|
|
for (let fieldIndex = 0; fieldIndex < commonFields.length; fieldIndex++) {
|
|
all["t0BgCommon" + commonFields[fieldIndex]] = runStates[0].bgValues[fieldIndex];
|
|
}
|
|
} else {
|
|
all.t0BgCommonBgMode = defaultT0BgMode(fitType);
|
|
for (let rowIndex = 0; rowIndex < runStates.length; rowIndex++) {
|
|
all["t0BgBgMode_" + rowIndex] = runStates[rowIndex].bgMode;
|
|
let rowFields = backgroundFields[runStates[rowIndex].bgMode] || [];
|
|
for (let fieldIndex = 0; fieldIndex < rowFields.length; fieldIndex++) {
|
|
all["t0Bg" + rowFields[fieldIndex] + "_" + rowIndex] = runStates[rowIndex].bgValues[fieldIndex];
|
|
}
|
|
}
|
|
}
|
|
|
|
// Data good-bin ranges are GUI-editable like t0/background: store a common
|
|
// pair when every RUN block agrees, otherwise per-row overrides.
|
|
let dataFields = fitType === 0
|
|
? { range: ["DataStart", "DataEnd"] }
|
|
: { range: ["DataFStart", "DataFEnd", "DataBStart", "DataBEnd"] };
|
|
let dataValueCount = fitType === 0 ? 2 : 4;
|
|
let firstData = parsed.runBlocks[0].dataRange;
|
|
let allDataEqual = parsed.runBlocks.every(function(block) {
|
|
return JSON.stringify(block.dataRange) == JSON.stringify(firstData);
|
|
});
|
|
if (allDataEqual && firstData !== null && firstData.length === dataValueCount) {
|
|
let commonFields = dataFields.range;
|
|
for (let fieldIndex = 0; fieldIndex < commonFields.length; fieldIndex++) {
|
|
all["t0BgCommon" + commonFields[fieldIndex]] = firstData[fieldIndex];
|
|
}
|
|
} else if (!allDataEqual) {
|
|
for (let rowIndex = 0; rowIndex < parsed.runBlocks.length; rowIndex++) {
|
|
let range = parsed.runBlocks[rowIndex].dataRange;
|
|
if (range === null || range.length !== dataValueCount) {
|
|
continue;
|
|
}
|
|
let rowFields = dataFields.range;
|
|
for (let fieldIndex = 0; fieldIndex < rowFields.length; fieldIndex++) {
|
|
all["t0Bg" + rowFields[fieldIndex] + "_" + rowIndex] = range[fieldIndex];
|
|
}
|
|
}
|
|
}
|
|
|
|
if (all === All && typeof document !== "undefined" && document.getElementById("t0Bg")) {
|
|
// Rebuild from All without first reading stale controls from the old table.
|
|
cfgt0Bg(true);
|
|
}
|
|
return(1);
|
|
}
|
|
|
|
function syncMultiGroupT0BgFromMSR(all, fitType, runStates, parsed) {
|
|
// Multi-group asymmetry groups share the single GUI row of their one physical
|
|
// run. A field holds one token per group, in group order; agreeing values
|
|
// collapse into the common fields. Presence and shape must be consistent
|
|
// across groups because a missing token would silently shift every later one.
|
|
// All consistency checks run before any mutation so a bad read-back keeps the
|
|
// previously stored GUI values intact.
|
|
|
|
// t0 presence must be uniform across groups.
|
|
let anyT0 = runStates.some(function(state) { return state.t0 !== null; });
|
|
let allT0 = runStates.every(function(state) { return state.t0 !== null; });
|
|
if (anyT0 && !allT0) {
|
|
return(0);
|
|
}
|
|
|
|
// Background mode must agree across groups; one GUI row cannot mix range and
|
|
// fixed modes for different groups.
|
|
let firstMode = runStates[0].bgMode;
|
|
let allModesEqual = runStates.every(function(state) {
|
|
return state.bgMode === firstMode;
|
|
});
|
|
if (!allModesEqual) {
|
|
return(0);
|
|
}
|
|
let backgroundFields = fitType === 0
|
|
? { range: ["BgStart", "BgEnd"], fixed: ["BgFix"] }
|
|
: { range: ["BgFStart", "BgFEnd", "BgBStart", "BgBEnd"], fixed: ["BgFixF", "BgFixB"] };
|
|
let modeFields = backgroundFields[firstMode] || [];
|
|
let allBackground = false;
|
|
if (modeFields.length > 0) {
|
|
let anyBackground = runStates.some(function(state) {
|
|
return state.bgValues.length === modeFields.length;
|
|
});
|
|
allBackground = runStates.every(function(state) {
|
|
return state.bgValues.length === modeFields.length;
|
|
});
|
|
if (anyBackground && !allBackground) {
|
|
return(0);
|
|
}
|
|
}
|
|
|
|
// Data good-bin ranges must be uniformly present.
|
|
let dataFields = fitType === 0
|
|
? ["DataStart", "DataEnd"]
|
|
: ["DataFStart", "DataFEnd", "DataBStart", "DataBEnd"];
|
|
let dataValueCount = fitType === 0 ? 2 : 4;
|
|
let anyData = parsed.runBlocks.some(function(block) {
|
|
return block.dataRange !== null && block.dataRange.length === dataValueCount;
|
|
});
|
|
let allData = parsed.runBlocks.every(function(block) {
|
|
return block.dataRange !== null && block.dataRange.length === dataValueCount;
|
|
});
|
|
if (anyData && !allData) {
|
|
return(0);
|
|
}
|
|
|
|
// Validation done; now replace whatever the GUI previously stored.
|
|
for (let key in all) {
|
|
if (Object.prototype.hasOwnProperty.call(all, key) && key.indexOf("t0Bg") === 0) {
|
|
delete all[key];
|
|
}
|
|
}
|
|
|
|
if (allT0) {
|
|
let forwardTokens = [];
|
|
let backwardTokens = [];
|
|
for (let state of runStates) {
|
|
forwardTokens.push(state.t0[0]);
|
|
backwardTokens.push(state.t0[1]);
|
|
}
|
|
let firstForward = forwardTokens[0];
|
|
let firstBackward = backwardTokens[0];
|
|
let allEqualT0 = forwardTokens.every(function(value) { return value === firstForward; })
|
|
&& backwardTokens.every(function(value) { return value === firstBackward; });
|
|
if (allEqualT0) {
|
|
all.t0BgCommonT0F = firstForward;
|
|
all.t0BgCommonT0B = firstBackward;
|
|
} else {
|
|
all.t0BgT0F_0 = forwardTokens.join(" ");
|
|
all.t0BgT0B_0 = backwardTokens.join(" ");
|
|
}
|
|
}
|
|
|
|
if (modeFields.length > 0 && allBackground) {
|
|
let perFieldTokens = modeFields.map(function(fieldName, fieldIndex) {
|
|
return runStates.map(function(state) { return state.bgValues[fieldIndex]; });
|
|
});
|
|
let allEqualBackground = perFieldTokens.every(function(tokens) {
|
|
let firstToken = tokens[0];
|
|
return tokens.every(function(token) { return token === firstToken; });
|
|
});
|
|
if (allEqualBackground) {
|
|
all.t0BgCommonBgMode = firstMode;
|
|
for (let fieldIndex = 0; fieldIndex < modeFields.length; fieldIndex++) {
|
|
all["t0BgCommon" + modeFields[fieldIndex]] = perFieldTokens[fieldIndex][0];
|
|
}
|
|
} else {
|
|
all.t0BgBgMode_0 = firstMode;
|
|
for (let fieldIndex = 0; fieldIndex < modeFields.length; fieldIndex++) {
|
|
all["t0Bg" + modeFields[fieldIndex] + "_0"] = perFieldTokens[fieldIndex].join(" ");
|
|
}
|
|
}
|
|
}
|
|
|
|
if (allData) {
|
|
let perFieldTokens = dataFields.map(function(fieldName, fieldIndex) {
|
|
return parsed.runBlocks.map(function(block) { return block.dataRange[fieldIndex]; });
|
|
});
|
|
let allDataEqual = perFieldTokens.every(function(tokens) {
|
|
let firstToken = tokens[0];
|
|
return tokens.every(function(token) { return token === firstToken; });
|
|
});
|
|
if (allDataEqual) {
|
|
for (let fieldIndex = 0; fieldIndex < dataFields.length; fieldIndex++) {
|
|
all["t0BgCommon" + dataFields[fieldIndex]] = perFieldTokens[fieldIndex][0];
|
|
}
|
|
} else {
|
|
for (let fieldIndex = 0; fieldIndex < dataFields.length; fieldIndex++) {
|
|
all["t0Bg" + dataFields[fieldIndex] + "_0"] = perFieldTokens[fieldIndex].join(" ");
|
|
}
|
|
}
|
|
}
|
|
|
|
if (all === All && typeof document !== "undefined" && document.getElementById("t0Bg")) {
|
|
cfgt0Bg(true);
|
|
}
|
|
return(1);
|
|
}
|
|
|
|
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) {
|
|
// 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);
|
|
// A NaN value must not clobber the GUI's last good value.
|
|
let valueText = sanitizedMSRParameterValue(
|
|
param.value, All["val" + guiName] === undefined
|
|
? "" : All["val" + guiName]
|
|
);
|
|
let errorText = sanitizedMSRParameterError(param.error, valueText);
|
|
All["val" + guiName] = valueText;
|
|
All["err" + guiName] = errorText;
|
|
All["min" + guiName] = sanitizedMSRParameterNumber(param.min);
|
|
All["max" + guiName] = sanitizedMSRParameterNumber(param.max);
|
|
let el = document.getElementById("val" + guiName);
|
|
if (el) el.value = valueText;
|
|
el = document.getElementById("err" + guiName);
|
|
if (el) el.value = errorText;
|
|
el = document.getElementById("min" + guiName);
|
|
if (el) el.value = All["min" + guiName];
|
|
el = document.getElementById("max" + guiName);
|
|
if (el) el.value = All["max" + guiName];
|
|
}
|
|
setFitStatus("Parameter table updated from fitted MSR.", {
|
|
level: "success",
|
|
details: "Updated parameter table from fitted MSR (" + params.length + " parameters)."
|
|
});
|
|
return(1);
|
|
}
|
|
|
|
function syncParametersFromMSR(msrText) {
|
|
let params = parseMSRParameters(msrText);
|
|
let theory = parseMSRTheoryModel(msrText);
|
|
let applied = applyMSRParametersToGUI(
|
|
params, theory.ok ? theory.parameterTargets : null
|
|
);
|
|
if (applied) {
|
|
updateJobStatus({
|
|
parameterSync: "Updated from MSR (" + params.length + " parameters)"
|
|
});
|
|
} else {
|
|
updateJobStatus({
|
|
parameterSync: "No fit parameters found in current MSR"
|
|
});
|
|
}
|
|
return applied;
|
|
}
|
|
|
|
// Fill the parameter table from the combined `+global` MSR that musrview
|
|
// displays. Its merged FITPARAMETER already carries the fitted values for every
|
|
// run (shared parameters once, run-specific ones under their `_RRRR` names),
|
|
// so the GUI rows are matched by exact name rather than through a THEORY model
|
|
// whose map slots are not meaningful for a multi-run table.
|
|
function syncSeriesParametersToGUI(msrText) {
|
|
let params = parseMSRParameters(msrText || "");
|
|
if (!params || params.length === 0) return 0;
|
|
if (typeof applyMSRParametersToGUI !== "function") return 0;
|
|
let applied = applyMSRParametersToGUI(params, null);
|
|
if (applied) {
|
|
updateJobStatus({
|
|
parameterSync: "Updated from combined series MSR (" + params.length + " parameters)"
|
|
});
|
|
}
|
|
return applied;
|
|
}
|
|
// Snapshot the parameter rows that are actually present in the GUI. Keep the
|
|
// names exactly as displayed (including _runnumber suffixes); the generated MSR
|
|
// decides which of them apply.
|
|
function buildFitParameterSyncSpec(all) {
|
|
all = all || {};
|
|
let parameters = [];
|
|
let names = [];
|
|
let table = document.getElementById("Params");
|
|
if (table && typeof table.querySelectorAll === "function") {
|
|
for (let input of table.querySelectorAll("input[id^='val']")) {
|
|
if (input && input.id && input.id.length > 3) names.push(input.id.substring(3));
|
|
}
|
|
} else {
|
|
// Test/non-browser fallback. The real GUI path above avoids stale All keys.
|
|
names = Object.keys(all).filter(function(key) { return /^val.+/.test(key); })
|
|
.map(function(key) { return key.substring(3); });
|
|
}
|
|
|
|
let seen = Object.create(null);
|
|
for (let name of names) {
|
|
if (!name || seen[name]) continue;
|
|
seen[name] = true;
|
|
let valueEl = document.getElementById("val" + name);
|
|
let stepEl = document.getElementById("err" + name);
|
|
let minEl = document.getElementById("min" + name);
|
|
let maxEl = document.getElementById("max" + name);
|
|
let value = Object.prototype.hasOwnProperty.call(all, "val" + name)
|
|
? all["val" + name] : (valueEl ? valueEl.value : "");
|
|
let step = Object.prototype.hasOwnProperty.call(all, "err" + name)
|
|
? all["err" + name] : (stepEl ? stepEl.value : "");
|
|
if (value === undefined || step === undefined || value === "" || step === "") continue;
|
|
// Never forward a NaN value or step into a generated MSR; without the
|
|
// parameter's default value there is nothing meaningful to write instead.
|
|
let safeValue = sanitizedMSRParameterNumber(value);
|
|
let safeStep = sanitizedMSRParameterNumber(step);
|
|
if (safeValue === "" || safeStep === "") continue;
|
|
parameters.push({
|
|
name: name,
|
|
value: String(value),
|
|
step: String(step),
|
|
min: Object.prototype.hasOwnProperty.call(all, "min" + name)
|
|
? String(all["min" + name] || "") : (minEl ? String(minEl.value || "") : ""),
|
|
max: Object.prototype.hasOwnProperty.call(all, "max" + name)
|
|
? String(all["max" + name] || "") : (maxEl ? String(maxEl.value || "") : "")
|
|
});
|
|
}
|
|
return { parameters: parameters };
|
|
}
|
|
|
|
// Old CGI rule: walk the FITPARAMETER block in the MSR and replace a line only
|
|
// when a GUI parameter with exactly the same name exists. Extra GUI rows are
|
|
// irrelevant and parameters not represented in the GUI are left untouched.
|
|
function applyFitParameterSpecToMSR(msrText, spec) {
|
|
let entries = spec && Array.isArray(spec.parameters) ? spec.parameters : [];
|
|
if (!msrText || typeof msrText !== "string" || entries.length === 0) return msrText;
|
|
|
|
let byName = Object.create(null);
|
|
for (let entry of entries) {
|
|
if (entry && entry.name) byName[entry.name] = entry;
|
|
}
|
|
|
|
let lines = msrText.split(/\r?\n/);
|
|
let inFit = false;
|
|
for (let i = 0; i < lines.length; i++) {
|
|
let trimmed = lines[i].trim();
|
|
if (/^FITPARAMETER\b/i.test(trimmed)) {
|
|
inFit = true;
|
|
continue;
|
|
}
|
|
if (!inFit) continue;
|
|
if (/^(THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/i.test(trimmed)) break;
|
|
if (trimmed === "" || trimmed[0] === "#") continue;
|
|
|
|
let parts = trimmed.split(/\s+/);
|
|
if (parts.length < 4 || !/^\d+$/.test(parts[0])) continue;
|
|
let entry = byName[parts[1]];
|
|
if (!entry) continue;
|
|
lines[i] = formatFitParameterLine(
|
|
parts[0], parts[1], entry.value, entry.step, entry.min, entry.max
|
|
).replace(/\n$/, "");
|
|
}
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function formatFitParameterLine(order, name, value, step, min, max) {
|
|
// Non-finite values (NaN from a failed fit, inf boundaries, ...) must never
|
|
// be written into a generated MSR; drop them so downstream musrfit never
|
|
// sees a token it cannot parse. An empty value is replaced by the caller
|
|
// with a sensible default before this formatter runs.
|
|
let valueText = sanitizedMSRParameterNumber(value);
|
|
let stepText = sanitizedMSRParameterNumber(step);
|
|
let fields = [" " + order, name, valueText, stepText];
|
|
let minText = normalizeFitParameterBoundary(min);
|
|
let maxText = normalizeFitParameterBoundary(max);
|
|
if (minText !== "" || maxText !== "") {
|
|
// musrfit bounded FITPARAMETER syntax is
|
|
// No Name Value Step PosError Lower Upper
|
|
// Before a fit there is no positive MINOS error yet, so keep its slot
|
|
// explicitly as "none" before writing the boundaries.
|
|
fields.push("none");
|
|
fields.push(minText === "" ? "none" : minText);
|
|
fields.push(maxText === "" ? "none" : maxText);
|
|
}
|
|
return fields.join(" ") + "\n";
|
|
}
|
|
|
|
function normalizeFitParameterBoundary(value) {
|
|
if (value === undefined || value === null) return "";
|
|
return sanitizedMSRParameterNumber(value);
|
|
}
|
|
|
|
function isValidGeneratedGlobalMSR(msrText) {
|
|
// msr2data does not provide a reliable process-status contract on all systems.
|
|
// Treat the generated global MSR itself as the success artifact, but require
|
|
// the minimum blocks needed before we pass the file to musrfit/musrview.
|
|
if (!msrText || typeof msrText !== "string") {
|
|
return false;
|
|
}
|
|
|
|
if (!/\S/.test(msrText)) {
|
|
return false;
|
|
}
|
|
|
|
let requiredBlocks = ["FITPARAMETER", "THEORY", "GLOBAL", "RUN", "COMMANDS", "PLOT"];
|
|
for (let blockName of requiredBlocks) {
|
|
let blockRe = new RegExp("^\\s*" + blockName + "\\b", "m");
|
|
if (!blockRe.test(msrText)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
function getExpectedPlotRuns(all, runs) {
|
|
// The `runs` line in the PLOT block lists MSR RUN-block indices, not the
|
|
// physical PSI run numbers. For a global fit generated by msr2data, selected
|
|
// runs 414,415,416 therefore become `runs 1 2 3`.
|
|
let plotRuns = [];
|
|
|
|
if (all && all.fitAsyType == "SingleHist") {
|
|
// SingleHist produces one RUN block per histogram, so plotting follows
|
|
// histogram count rather than run-number count.
|
|
let hists = (all.LRBF || "").split(",");
|
|
for (let iHist = 0; iHist < hists.length; iHist++) {
|
|
if (hists[iHist].trim() !== "") {
|
|
plotRuns.push((iHist + 1).toString());
|
|
}
|
|
}
|
|
} else {
|
|
let numRuns = runs && runs.length ? runs.length : 1;
|
|
for (let iRun = 1; iRun <= numRuns; iRun++) {
|
|
plotRuns.push(iRun.toString());
|
|
}
|
|
}
|
|
|
|
if (plotRuns.length === 0) {
|
|
plotRuns.push("1");
|
|
}
|
|
|
|
return plotRuns;
|
|
}
|
|
|
|
function normalizeMSRPlotRuns(msrText, all, runs) {
|
|
// msr2data/musrfit may leave or reset the PLOT block to `runs 1`. Normalize
|
|
// that line before the file is shown in the editor or handed to musrview.
|
|
// Prefer the RUN blocks that are actually present in the MSR over GUI-side
|
|
// estimates. This matters for SingleHist global files: msr2data expands each
|
|
// physical run into one RUN block per histogram, so a two-run/two-histogram
|
|
// fit has four plot indices (1 2 3 4), not merely the two histogram indices
|
|
// that appear in the template.
|
|
if (!msrText || typeof msrText !== "string") {
|
|
return msrText;
|
|
}
|
|
|
|
if (!/^PLOT\b/m.test(msrText)) {
|
|
return msrText;
|
|
}
|
|
|
|
let runBlocks = msrText.match(/^\s*RUN\b/gm) || [];
|
|
let expectedRuns = getExpectedPlotRuns(all, runs);
|
|
|
|
// Use whichever source tells us that more RUN blocks should be visible. The
|
|
// GUI-derived count protects partially assembled/test MSRs, while the actual
|
|
// block count captures msr2data expansion (especially physical runs times
|
|
// histogram groups in SingleHist global files).
|
|
let numPlotRuns = Math.max(runBlocks.length, expectedRuns.length);
|
|
let plotRuns = [];
|
|
for (let iRun = 1; iRun <= numPlotRuns; iRun++) {
|
|
plotRuns.push(iRun.toString());
|
|
}
|
|
|
|
let runsLine = "runs " + plotRuns.join(" ");
|
|
return msrText.replace(/^(runs\s+).*$/m, runsLine);
|
|
}
|
|
|
|
|
|
// Merge the fitted per-run MSR files produced by an independent series fit
|
|
// into a single display-only global MSR. msr2data is deliberately not used for
|
|
// this: it only writes the +global file from a template and, in every mode that
|
|
// populates per-run values, re-fits each run with musrfit. The merged file here
|
|
// keeps each run's already-fitted parameter values and lets every RUN block
|
|
// select its own parameters through the same mapN/alpha/norm mechanism that a
|
|
// genuine msr2data global file uses.
|
|
//
|
|
// The per-run files are expected to be structurally identical apart from the
|
|
// run-qualified parameter names/values and the RUN data paths (this is exactly
|
|
// what the series staging produces). Shared parameters keep a single entry in
|
|
// the merged FITPARAMETER; run-specific parameters are collected per run and
|
|
// referenced from THEORY through map slots.
|
|
const SERIES_MSR_RUN_PARAM_DIRECTIVES = { alpha: 1, norm: 1, "backgr.fit": 1, beta: 1 };
|
|
const SERIES_MSR_MAX_MAP_SLOTS = 10;
|
|
|
|
function splitSeriesMSRBlocks(msrText) {
|
|
let sections = [];
|
|
let current = null;
|
|
let lines = String(msrText || "").split(/\r?\n/);
|
|
for (let line of lines) {
|
|
// Recognize a block header line. The FOURIER block uses a lowercase
|
|
// `plot <type>` directive that would otherwise look like a PLOT header, so
|
|
// a genuine PLOT header must carry a numeric plot id ("PLOT 2");
|
|
// non-numeric `plot` lines stay inside FOURIER.
|
|
let trimmedLine = line.trim();
|
|
let match = trimmedLine.match(/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)(?:[ \t]|$)/i);
|
|
let name = match ? match[1].toUpperCase() : null;
|
|
if (name === "PLOT") {
|
|
let arg = trimmedLine.slice(match[0].length).trim();
|
|
if (!/^\d/.test(arg)) name = null;
|
|
}
|
|
if (name) {
|
|
current = {
|
|
name: name,
|
|
header: trimmedLine,
|
|
lines: []
|
|
};
|
|
sections.push(current);
|
|
} else if (current) {
|
|
current.lines.push(line);
|
|
} else {
|
|
if (!sections.length) {
|
|
current = { name: "HEADER", header: "", lines: [] };
|
|
sections.push(current);
|
|
}
|
|
current.lines.push(line);
|
|
}
|
|
}
|
|
return sections;
|
|
}
|
|
|
|
// Detach every THEORY/FUNCTIONS integer that refers to a fit parameter. Falls
|
|
// back to carrying the current per-run text through for anything that is not a
|
|
// simple parameter reference. Returns { ok, lines } and a lookup for the merged
|
|
// numbers of each run's local parameter positions.
|
|
function mapSeriesMergedParameters(perRun, fail) {
|
|
let numRuns = perRun.length;
|
|
let first = perRun[0];
|
|
|
|
let nameCounts = Object.create(null);
|
|
for (let pr of perRun) {
|
|
for (let p of pr.params) nameCounts[p.name] = (nameCounts[p.name] || 0) + 1;
|
|
}
|
|
for (let name in nameCounts) {
|
|
if (nameCounts[name] !== 1 && nameCounts[name] !== numRuns) {
|
|
return fail("series-merge-parameter-inconsistency");
|
|
}
|
|
}
|
|
|
|
let mergedParams = [];
|
|
let sharedNameNo = Object.create(null);
|
|
for (let p of first.params) {
|
|
if (nameCounts[p.name] === numRuns && sharedNameNo[p.name] === undefined) {
|
|
sharedNameNo[p.name] = mergedParams.length + 1;
|
|
mergedParams.push({ name: p.name, rest: p.rest });
|
|
}
|
|
}
|
|
let noMap = perRun.map(function() { return Object.create(null); });
|
|
for (let runIndex = 0; runIndex < numRuns; runIndex++) {
|
|
for (let p of perRun[runIndex].params) {
|
|
if (nameCounts[p.name] === numRuns) {
|
|
noMap[runIndex][p.no] = sharedNameNo[p.name];
|
|
} else {
|
|
noMap[runIndex][p.no] = mergedParams.length + 1;
|
|
mergedParams.push({ name: p.name, rest: p.rest });
|
|
}
|
|
}
|
|
}
|
|
return {
|
|
mergedParams: mergedParams,
|
|
nameCounts: nameCounts,
|
|
noMap: noMap,
|
|
sharedNameNo: sharedNameNo
|
|
};
|
|
}
|
|
|
|
// The FOURIER block is shared by all RUN blocks in the merged file. musrview
|
|
// refuses any plot other than POWER unless the phase line carries one reference
|
|
// per run (parR7 par9 ...), which a display file assembled from shared
|
|
// parameters cannot express. Mirror msr2data's own global output by forcing the
|
|
// plot to POWER; the fitted per-run Fourier phases are deliberately left to the
|
|
// individual run files.
|
|
function normalizeSeriesFourierForDisplay(fourierLines) {
|
|
let normalized = [];
|
|
let sawPlot = false;
|
|
for (let line of fourierLines) {
|
|
let match = line.trim().match(/^plot\b/i);
|
|
if (match) {
|
|
sawPlot = true;
|
|
if (!/^plot\s+POWER\b/i.test(line.trim())) {
|
|
normalized.push("plot POWER");
|
|
} else {
|
|
normalized.push(line);
|
|
}
|
|
} else {
|
|
normalized.push(line);
|
|
}
|
|
}
|
|
if (!sawPlot) normalized.push("plot POWER");
|
|
return normalized;
|
|
}
|
|
|
|
function buildSeriesGlobalMSR(msrTexts, runs) {
|
|
let fail = function(reason) {
|
|
return { ok: false, reason: reason, text: "" };
|
|
};
|
|
if (!Array.isArray(msrTexts) || msrTexts.length < 2
|
|
|| !Array.isArray(runs) || msrTexts.length !== runs.length) {
|
|
return fail("series-merge-invalid-input");
|
|
}
|
|
|
|
let perRun = [];
|
|
for (let index = 0; index < msrTexts.length; index++) {
|
|
let sections = splitSeriesMSRBlocks(msrTexts[index]);
|
|
let byName = {};
|
|
for (let section of sections) {
|
|
if (!byName[section.name]) {
|
|
byName[section.name] = section;
|
|
} else if (section.name === "RUN") {
|
|
// RUN is the one repeatable top-level MSR block. Keep subsequent
|
|
// headers inside the first collected section so the normal RUN
|
|
// parser can reconstruct every detector block. Treating RUN like
|
|
// the singleton blocks silently discarded all but the first
|
|
// detector of a SingleHist source.
|
|
byName.RUN.lines.push(section.header);
|
|
byName.RUN.lines.push.apply(byName.RUN.lines, section.lines);
|
|
}
|
|
}
|
|
if (!byName.FITPARAMETER || !byName.THEORY || !byName.RUN) {
|
|
return fail("series-merge-source-incomplete");
|
|
}
|
|
let params = [];
|
|
for (let line of byName.FITPARAMETER.lines) {
|
|
let trimmed = String(line).trim();
|
|
if (!trimmed || trimmed.charAt(0) === "#") continue;
|
|
let match = trimmed.match(/^(\d+)\s+(\S+)\s*(.*)$/);
|
|
if (!match) continue;
|
|
params.push({
|
|
no: parseInt(match[1], 10),
|
|
name: match[2],
|
|
rest: match[3].trim().split(/\s+/).join(" ")
|
|
});
|
|
}
|
|
if (params.length === 0) {
|
|
return fail("series-merge-parameters-incomplete");
|
|
}
|
|
let runBlocks = [];
|
|
{
|
|
let current = null;
|
|
for (let line of [byName.RUN.header].concat(byName.RUN.lines)) {
|
|
if (/^RUN\b/i.test(String(line).trim())) {
|
|
current = { header: line, lines: [] };
|
|
runBlocks.push(current);
|
|
} else if (current) {
|
|
current.lines.push(line);
|
|
}
|
|
}
|
|
}
|
|
if (runBlocks.length === 0) {
|
|
return fail("series-merge-run-blocks-incomplete");
|
|
}
|
|
perRun.push({
|
|
run: String(runs[index]),
|
|
params: params,
|
|
runBlocks: runBlocks,
|
|
theory: byName.THEORY.lines,
|
|
functions: byName.FUNCTIONS ? byName.FUNCTIONS.lines : [],
|
|
global: byName.GLOBAL ? byName.GLOBAL.lines : [],
|
|
commands: byName.COMMANDS ? byName.COMMANDS.lines : [],
|
|
plot: byName.PLOT ? byName.PLOT.lines : [],
|
|
plotHeader: byName.PLOT ? byName.PLOT.header : "PLOT 0",
|
|
fourier: byName.FOURIER ? byName.FOURIER.lines : [],
|
|
statistic: byName.STATISTIC ? byName.STATISTIC.lines.join("\n") : ""
|
|
});
|
|
}
|
|
|
|
let numRuns = perRun.length;
|
|
let first = perRun[0];
|
|
for (let pr of perRun) {
|
|
if (pr.params.length !== first.params.length) {
|
|
return fail("series-merge-parameter-count-mismatch");
|
|
}
|
|
}
|
|
|
|
// Every run must describe the same model: the non-numeric token shape of the
|
|
// THEORY and FUNCTIONS blocks must be identical, since parameter numbers are
|
|
// the only thing allowed to differ between fits of the same model.
|
|
let tokenShape = function(lines) {
|
|
return lines.map(function(line) {
|
|
return line.split(/\s+/).map(function(token) {
|
|
return /^\d+$/.test(token) ? "#" : token;
|
|
}).join(" ");
|
|
}).join("\n");
|
|
};
|
|
for (let pr of perRun) {
|
|
if (tokenShape(pr.theory) !== tokenShape(first.theory)) {
|
|
return fail("series-merge-theory-mismatch");
|
|
}
|
|
if (tokenShape(pr.functions) !== tokenShape(first.functions)) {
|
|
return fail("series-merge-functions-mismatch");
|
|
}
|
|
}
|
|
|
|
let numbering = mapSeriesMergedParameters(perRun, fail);
|
|
if (!numbering.ok && numbering.ok !== undefined) return numbering;
|
|
if (numbering.reason) return numbering;
|
|
let mergedParams = numbering.mergedParams;
|
|
let nameCounts = numbering.nameCounts;
|
|
let noMap = numbering.noMap;
|
|
let sharedNameNo = numbering.sharedNameNo;
|
|
|
|
let byNumber = perRun.map(function(pr) {
|
|
let map = Object.create(null);
|
|
for (let p of pr.params) map[p.no] = p;
|
|
return map;
|
|
});
|
|
|
|
// Rewrite THEORY. Existing mapN/funN tokens stay verbatim; direct integer
|
|
// references to run-specific parameters become map slots so every RUN block
|
|
// can select its own fitted value. Preserve explicit zeros as-is (musrfit
|
|
// uses 0 for "no parameter" in e.g. lifetime).
|
|
let occupiedSlots = new Set();
|
|
let gatherSlots = function(lines) {
|
|
if (lines) {
|
|
for (let line of lines) {
|
|
for (let token of line.split(/\s+/)) {
|
|
let mapMatch = token.match(/^map(\d+)$/i);
|
|
if (mapMatch) occupiedSlots.add(parseInt(mapMatch[1], 10));
|
|
}
|
|
}
|
|
}
|
|
};
|
|
gatherSlots(first.theory);
|
|
gatherSlots(first.functions);
|
|
let nextSlot = 1;
|
|
while (occupiedSlots.has(nextSlot)) nextSlot++;
|
|
let slotRoleName = Object.create(null);
|
|
let slotPosition = Object.create(null); // slot -> { section, lineIndex, tokenIndex }
|
|
|
|
function slotForParam(name, section, lineIndex, tokenIndex) {
|
|
if (slotRoleName[name] !== undefined) return slotRoleName[name];
|
|
if (nextSlot > SERIES_MSR_MAX_MAP_SLOTS) return 0;
|
|
let slot = nextSlot++;
|
|
slotRoleName[name] = slot;
|
|
slotPosition[slot] = {
|
|
section: section,
|
|
lineIndex: lineIndex,
|
|
tokenIndex: tokenIndex
|
|
};
|
|
return slot;
|
|
}
|
|
|
|
let mergedTheory = first.theory.map(function(line, lineIndex) {
|
|
let out = [];
|
|
let tokenIndex = 0;
|
|
let tokens = line.split(/\s+/);
|
|
for (let token of tokens) {
|
|
if (/^\d+$/.test(token) && token !== "0") {
|
|
let localNo = parseInt(token, 10);
|
|
let p = byNumber[0][localNo];
|
|
if (!p) return fail("series-merge-theory-param-missing");
|
|
if (nameCounts[p.name] === numRuns) {
|
|
out.push(String(sharedNameNo[p.name]));
|
|
} else {
|
|
let slot = slotForParam(p.name, "theory", lineIndex, tokenIndex);
|
|
if (slot === 0) return fail("series-merge-map-slots-exhausted");
|
|
out.push("map" + slot);
|
|
}
|
|
} else {
|
|
out.push(token);
|
|
}
|
|
tokenIndex++;
|
|
}
|
|
return out.join(" ");
|
|
});
|
|
for (let line of mergedTheory) {
|
|
if (line && typeof line == "object" && line.ok === false) return fail(line.reason);
|
|
}
|
|
|
|
// FUNCTIONS can select run-specific parameters through mapN just like
|
|
// THEORY. Allocate a RUN map slot for each such parN reference; genuinely
|
|
// shared parameters keep a direct parN reference.
|
|
let mergedFunctions = first.functions.map(function(line, lineIndex) {
|
|
let out = [];
|
|
let tokenIndex = 0;
|
|
for (let token of line.split(/\s+/)) {
|
|
let parMatch = token.match(/^par(\d+)$/i);
|
|
if (parMatch) {
|
|
let localNo = parseInt(parMatch[1], 10);
|
|
let p = byNumber[0][localNo];
|
|
if (!p) return fail("series-merge-functions-param-missing");
|
|
if (nameCounts[p.name] === numRuns) {
|
|
out.push("par" + sharedNameNo[p.name]);
|
|
} else {
|
|
let slot = slotForParam(p.name, "functions", lineIndex, tokenIndex);
|
|
if (slot === 0) return fail("series-merge-map-slots-exhausted");
|
|
out.push("map" + slot);
|
|
}
|
|
} else {
|
|
out.push(token);
|
|
}
|
|
tokenIndex++;
|
|
}
|
|
return out.join(" ");
|
|
});
|
|
for (let line of mergedFunctions) {
|
|
if (line && typeof line == "object" && line.ok === false) return fail(line.reason);
|
|
}
|
|
|
|
// Rebuild RUN blocks. RUN headers and the non-parameter directives are kept
|
|
// verbatim; parameter-number directives are renumbered and a map line covers
|
|
// the THEORY role slots resolved above. Nested function arguments must refer
|
|
// to the same shared parameter numbering, so FUNCTIONS is emitted untouched
|
|
// apart from the parN renumbering.
|
|
let maxSlot = 0;
|
|
for (let slot in slotPosition) maxSlot = Math.max(maxSlot, parseInt(slot, 10));
|
|
|
|
function mergedMapEntries(runIndex, block) {
|
|
let existing = null;
|
|
let mapLineIndex = -1;
|
|
for (let i = 0; i < block.lines.length; i++) {
|
|
if (/^map\b/i.test(block.lines[i].trim())) { mapLineIndex = i; break; }
|
|
}
|
|
if (mapLineIndex >= 0) {
|
|
existing = block.lines[mapLineIndex].trim().split(/\s+/).slice(1);
|
|
}
|
|
let entries = {};
|
|
let slotMax = Math.max(maxSlot, existing ? existing.length : 0);
|
|
for (let slot = 1; slot <= slotMax; slot++) {
|
|
let value = 0;
|
|
if (existing && existing[slot - 1] && /^\d+$/.test(existing[slot - 1])
|
|
&& parseInt(existing[slot - 1], 10) > 0) {
|
|
let localNo = parseInt(existing[slot - 1], 10);
|
|
value = (localNo > 0 && noMap[runIndex][localNo] !== undefined)
|
|
? noMap[runIndex][localNo] : localNo;
|
|
} else if (slotPosition[slot]) {
|
|
let position = slotPosition[slot];
|
|
let sourceLines = position.section === "functions"
|
|
? perRun[runIndex].functions : perRun[runIndex].theory;
|
|
let localTokens = sourceLines[position.lineIndex]
|
|
? sourceLines[position.lineIndex].split(/\s+/)
|
|
: [];
|
|
let localToken = localTokens[position.tokenIndex];
|
|
let functionPar = position.section === "functions"
|
|
? String(localToken || "").match(/^par(\d+)$/i) : null;
|
|
let localNo = functionPar
|
|
? parseInt(functionPar[1], 10)
|
|
: (/^\d+$/.test(localToken || "") ? parseInt(localToken, 10) : 0);
|
|
if (localNo > 0 && noMap[runIndex][localNo] !== undefined) {
|
|
value = noMap[runIndex][localNo];
|
|
}
|
|
}
|
|
entries[slot] = value;
|
|
}
|
|
let values = [];
|
|
for (let slot = 1; slot <= slotMax; slot++) values.push(String(entries[slot]));
|
|
while (values.length && values[values.length - 1] === "0") values.pop();
|
|
return { values: values, mapLineIndex: mapLineIndex };
|
|
}
|
|
|
|
let output = [];
|
|
output.push("# Independent series display MSR for the runs: " + runs.join(" "));
|
|
output.push("# Fitted per-run parameters collected without re-fitting; "
|
|
+ "msr2data handles parameter extraction separately.");
|
|
output.push("###############################################################");
|
|
output.push("FITPARAMETER");
|
|
output.push("###############################################################");
|
|
output.push("# Common parameters for all runs");
|
|
for (let i = 0; i < mergedParams.length; i++) {
|
|
if (nameCounts[mergedParams[i].name] !== numRuns) continue;
|
|
output.push(formatSeriesMergedParameterLine(i + 1, mergedParams[i].name, mergedParams[i].rest));
|
|
}
|
|
for (let runIndex = 0; runIndex < numRuns; runIndex++) {
|
|
output.push("# Specific parameters for run " + perRun[runIndex].run);
|
|
for (let p of perRun[runIndex].params) {
|
|
if (nameCounts[p.name] === numRuns) continue;
|
|
output.push(formatSeriesMergedParameterLine(noMap[runIndex][p.no], p.name, p.rest));
|
|
}
|
|
}
|
|
output.push("###############################################################");
|
|
output.push("THEORY");
|
|
output.push(mergedTheory.join("\n"));
|
|
if (first.functions.length) {
|
|
output.push("###############################################################");
|
|
output.push("FUNCTIONS");
|
|
output.push(mergedFunctions.join("\n"));
|
|
}
|
|
output.push("###############################################################");
|
|
output.push("GLOBAL");
|
|
output.push(first.global.length ? first.global.join("\n") : "fittype 0");
|
|
for (let runIndex = 0; runIndex < numRuns; runIndex++) {
|
|
output.push("###############################################################");
|
|
output.push("# RUN blocks for run " + perRun[runIndex].run);
|
|
for (let block of perRun[runIndex].runBlocks) {
|
|
output.push(block.header);
|
|
let hadMap = false;
|
|
let hadSlot = maxSlot > 0;
|
|
for (let line of block.lines) {
|
|
let trimmed = line.trim();
|
|
let directive = trimmed.split(/\s+/)[0];
|
|
if (!directive || trimmed.charAt(0) === "#") {
|
|
output.push(line);
|
|
continue;
|
|
}
|
|
if (/^map$/i.test(directive)) { hadMap = true; continue; }
|
|
if (SERIES_MSR_RUN_PARAM_DIRECTIVES[directive.toLowerCase()]) {
|
|
let rest = trimmed.slice(directive.length).trim();
|
|
let renumbered = rest.split(/\s+/).map(function(token) {
|
|
if (/^\d+$/.test(token)) {
|
|
let n = parseInt(token, 10);
|
|
return (n > 0 && noMap[runIndex][n] !== undefined)
|
|
? String(noMap[runIndex][n]) : token;
|
|
}
|
|
return token;
|
|
}).join(" ");
|
|
output.push(directive + " " + renumbered);
|
|
} else {
|
|
output.push(line);
|
|
}
|
|
}
|
|
if (hadMap || hadSlot) {
|
|
let mapInfo = mergedMapEntries(runIndex, block);
|
|
if (mapInfo.values.length) {
|
|
output.push("map " + mapInfo.values.join(" "));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
output.push("###############################################################");
|
|
output.push("COMMANDS");
|
|
output.push(first.commands.length ? first.commands.join("\n") : "MINIMIZE");
|
|
if (first.fourier.length) {
|
|
output.push("###############################################################");
|
|
output.push("FOURIER");
|
|
output.push(normalizeSeriesFourierForDisplay(first.fourier).join("\n"));
|
|
}
|
|
output.push("###############################################################");
|
|
output.push(first.plotHeader);
|
|
for (let line of first.plot) {
|
|
if (/^runs\s+/i.test(line.trim())) continue;
|
|
output.push(line);
|
|
}
|
|
let plotRuns = [];
|
|
for (let i = 1; i <= numRuns; i++) plotRuns.push(String(i));
|
|
output.push("runs " + plotRuns.join(" "));
|
|
|
|
// The display MSR is not re-fitted. When every source has the same objective,
|
|
// report the sum of its independently fitted statistic and NDF. Never emit a
|
|
// partial or mixed-objective aggregate.
|
|
let statistics = [];
|
|
let statisticKind = "";
|
|
for (let pr of perRun) {
|
|
let match = pr.statistic.match(
|
|
/(chisq|maxLH)\s*=\s*([^\s,]+).*?NDF\s*=\s*([^\s,]+)/i
|
|
);
|
|
if (!match) continue;
|
|
let kind = match[1].toLowerCase() === "maxlh" ? "maxLH" : "chisq";
|
|
let runValue = parseFloat(match[2]);
|
|
let runNDF = parseFloat(match[3]);
|
|
if (isNaN(runValue) || isNaN(runNDF) || runNDF <= 0) continue;
|
|
if (statisticKind && statisticKind !== kind) {
|
|
statistics = [];
|
|
statisticKind = "";
|
|
break;
|
|
}
|
|
statisticKind = kind;
|
|
statistics.push({ value: runValue, ndf: runNDF });
|
|
}
|
|
if (statistics.length === numRuns) {
|
|
let total = 0;
|
|
let ndf = 0;
|
|
for (let s of statistics) { total += s.value; ndf += s.ndf; }
|
|
let date = new Date();
|
|
let timestamp = date.getFullYear() + "-"
|
|
+ String(date.getMonth() + 1).padStart(2, "0") + "-"
|
|
+ String(date.getDate()).padStart(2, "0") + " "
|
|
+ String(date.getHours()).padStart(2, "0") + ":"
|
|
+ String(date.getMinutes()).padStart(2, "0") + ":"
|
|
+ String(date.getSeconds()).padStart(2, "0");
|
|
let formattedTotal = parseFloat(total.toFixed(4)).toString();
|
|
let formattedNDF = Math.round(ndf).toString();
|
|
let formattedReduced = parseFloat((total / ndf).toFixed(6)).toString();
|
|
output.push("###############################################################");
|
|
output.push("STATISTIC --- " + timestamp);
|
|
output.push(" " + statisticKind + " = " + formattedTotal + ", NDF = "
|
|
+ formattedNDF + ", " + statisticKind + "/NDF = " + formattedReduced);
|
|
}
|
|
|
|
return {
|
|
ok: true,
|
|
reason: "series-merge-ready",
|
|
text: output.join("\n") + "\n"
|
|
};
|
|
}
|
|
|
|
function formatSeriesMergedParameterLine(no, name, rest) {
|
|
let line = " " + no + " " + name;
|
|
if (rest && rest !== "") {
|
|
line += " " + rest;
|
|
}
|
|
return line;
|
|
}
|
|
|
|
function applyFittedMSRToGUI(msrText, filePath, options = {}) {
|
|
if (!msrText || typeof msrText !== "string") return msrText;
|
|
|
|
let runs = [];
|
|
if (typeof arrayRunNumbers === "function") {
|
|
runs = arrayRunNumbers(All.runNumbers);
|
|
}
|
|
let normalized = normalizeMSRPlotRuns(msrText, All, runs);
|
|
|
|
// Plot-only requests must not replace the fit-quality indicator with a
|
|
// possibly stale STATISTIC block from an older fit.
|
|
if (!options.plotOnly && typeof updateFitStatisticFromMSR === "function") {
|
|
updateFitStatisticFromMSR(normalized);
|
|
}
|
|
|
|
if (typeof loadMSRIntoEditor === "function") {
|
|
loadMSRIntoEditor(normalized, filePath, true, {
|
|
editorOwned: options.editorSource ? true : false,
|
|
guiOwned: options.editorSource ? false : true
|
|
});
|
|
}
|
|
|
|
// Keep the expanded/global editor cache aligned in both deployment modes.
|
|
if (window.MSREditor) {
|
|
if (window.MSREditor.globalContent !== undefined || window.MSREditor.hasTemplateTab) {
|
|
window.MSREditor.globalContent = normalized;
|
|
}
|
|
if (window.MSREditor.hasTemplateTab) {
|
|
window.MSREditor.currentContent = normalized;
|
|
}
|
|
}
|
|
|
|
return normalized;
|
|
}
|
|
|
|
// MSR editor highlighting helpers. Highlighting changes presentation only; the
|
|
// underlying text returned by getCurrentEditorText() remains plain MSR content.
|
|
function escapeHTML(text) {
|
|
let escaped = text.replace(/&/g, "&");
|
|
escaped = escaped.replace(/</g, "<");
|
|
escaped = escaped.replace(/>/g, ">");
|
|
return escaped;
|
|
}
|
|
|
|
const msrBlockKeywords = new Set([
|
|
"FITPARAMETER", "THEORY", "FUNCTIONS", "GLOBAL", "RUN",
|
|
"COMMANDS", "PLOT", "FOURIER", "STATISTIC"
|
|
]);
|
|
|
|
const msrDirectives = new Set([
|
|
"addrun", "fittype", "alpha", "beta", "norm", "backgr.fit",
|
|
"backgr.fix", "background", "lifetime", "lifetimecorrection", "map",
|
|
"forward", "backward", "data", "t0", "addt0", "xy-data",
|
|
"deadtime-cor", "fit", "packing", "rrf_freq", "rrf_packing", "rrf_phase",
|
|
"units", "fourier_power", "dc-corrected", "apodization", "plot", "phase",
|
|
"range_for_phase_correction", "range", "runs", "sub_ranges",
|
|
"use_fit_ranges", "view_packing", "logx", "logy"
|
|
]);
|
|
|
|
const msrCommands = new Set([
|
|
"strategy", "migrad", "simplex", "minimize", "minos", "hesse", "save",
|
|
"set", "batch", "end", "return", "max_likelihood", "print_level", "scan",
|
|
"contours", "mnplot", "fix", "release", "restore", "fit_range",
|
|
"scale_n0_bkg", "sector", "openmp", "cuda", "opencl-cpu", "opencl-gpu"
|
|
]);
|
|
|
|
const msrTheoryFunctions = new Set([
|
|
"const", "c", "asymmetry", "a", "simplexpo", "se", "generexpo", "ge",
|
|
"simplegss", "sg", "statgsskt", "stg", "statgssktlf", "sgktlf",
|
|
"dyngssktlf", "dgktlf", "statexpkt", "sekt", "statexpktlf", "sektlf",
|
|
"dynexpktlf", "dektlf", "dynglkt_f_zf", "dglktfzf", "dynglkt_f_lf",
|
|
"dglktflf", "dynglkt_lf", "dglktlf", "combilgkt", "lgkt", "strkt", "skt",
|
|
"spinglass", "spg", "rdanisohf", "rahf", "tfieldcos", "tf", "internfld",
|
|
"ifld", "bessel", "b", "internbsl", "ib", "internfldgk", "ifgk",
|
|
"internfldll", "ifll", "f_mu_f", "fmuf", "abragam", "ab", "skewedgss",
|
|
"skg", "staticnkzf", "snkzf", "staticnktf", "snktf", "dynamicnkzf",
|
|
"dnkzf", "dynamicnktf", "dnktf", "muminusexptf", "mmsetf", "polynom", "p",
|
|
"userfcn"
|
|
]);
|
|
|
|
const msrFunctionBuiltins = new Set([
|
|
"cos", "sin", "tan", "acos", "asin", "atan", "cosh", "sinh", "tanh",
|
|
"acosh", "asinh", "atanh", "exp", "log", "ln", "sqrt", "pow"
|
|
]);
|
|
|
|
const msrFunctionConstants = new Set([
|
|
"gamma_mu", "pi"
|
|
]);
|
|
|
|
const msrLiteralValues = new Set([
|
|
"none", "true", "false", "reset", "all", "weak", "medium", "strong",
|
|
"real", "imag", "real_and_imag", "power", "no", "file", "estimate"
|
|
]);
|
|
|
|
function highlightMSRTokens(text, section, parameterNames, parameterNumberContext) {
|
|
// Scan raw text and escape each unmatched fragment before adding markup. This
|
|
// avoids later regular expressions matching class names in generated spans.
|
|
let tokenPattern = /parR?\([^)]*\)|parR\d+|(?:par|map|fun)\d+|[A-Za-z_][A-Za-z0-9_.-]*|[+-]?(?:(?:\d+\.\d*|\d+|\.\d+)(?:[eE][+-]?\d+)?)|[=+*/<>-]/gi;
|
|
let output = "";
|
|
let previousIndex = 0;
|
|
let tokenMatch = null;
|
|
|
|
while ((tokenMatch = tokenPattern.exec(text)) !== null) {
|
|
output += escapeHTML(text.substring(previousIndex, tokenMatch.index));
|
|
let token = tokenMatch[0];
|
|
let tokenLower = token.toLowerCase();
|
|
let tokenClass = "";
|
|
|
|
if (/^fun\d+$/i.test(token) || msrFunctionBuiltins.has(tokenLower)) {
|
|
tokenClass = "msr-function";
|
|
} else if (/^(?:parR?\(|parR?\d+$|map\d+$)/i.test(token)
|
|
|| parameterNames.has(tokenLower)) {
|
|
tokenClass = "msr-parameter";
|
|
} else if (section == "FUNCTIONS"
|
|
&& (msrFunctionConstants.has(tokenLower) || /^(?:b|en|t\d+)$/i.test(token))) {
|
|
tokenClass = "msr-value";
|
|
} else if (/^[+-]?(?:(?:\d+\.\d*|\d+|\.\d+)(?:e[+-]?\d+)?)$/i.test(token)) {
|
|
tokenClass = parameterNumberContext ? "msr-parameter" : "msr-number";
|
|
} else if (msrLiteralValues.has(tokenLower)) {
|
|
tokenClass = "msr-value";
|
|
} else if (/^[=+*/<>-]$/.test(token)
|
|
&& (section == "FUNCTIONS" || section == "THEORY" || section == "FITPARAMETER")) {
|
|
tokenClass = "msr-operator";
|
|
}
|
|
|
|
if (tokenClass !== "") {
|
|
output += "<span class=\"" + tokenClass + "\">" + escapeHTML(token) + "</span>";
|
|
} else {
|
|
output += escapeHTML(token);
|
|
}
|
|
previousIndex = tokenPattern.lastIndex;
|
|
}
|
|
|
|
output += escapeHTML(text.substring(previousIndex));
|
|
return output;
|
|
}
|
|
|
|
function highlightMSRLine(line, section, parameterNames) {
|
|
let trimmed = line.trim();
|
|
if (trimmed.startsWith("#") || trimmed.startsWith("***")) {
|
|
return "<span class=\"msr-comment\">" + escapeHTML(line) + "</span>";
|
|
}
|
|
|
|
// Separate inline comments before token scanning so comment text can never be
|
|
// mistaken for directives, parameter names, or numbers.
|
|
let comment = "";
|
|
let code = line;
|
|
let commentIndex = line.indexOf("#");
|
|
if (commentIndex >= 0) {
|
|
code = line.substring(0, commentIndex);
|
|
comment = line.substring(commentIndex);
|
|
}
|
|
|
|
let annotation = "";
|
|
if (section != "FUNCTIONS") {
|
|
let annotationMatch = code.match(/^(.*?)(\s+\([^()]*\)\s*)$/);
|
|
if (annotationMatch) {
|
|
code = annotationMatch[1];
|
|
annotation = annotationMatch[2];
|
|
}
|
|
}
|
|
|
|
let highlightedCode = "";
|
|
let parameterMatch = section == "FITPARAMETER"
|
|
? code.match(/^(\s*)(\d+)(\s+)(\S+)(.*)$/) : null;
|
|
if (parameterMatch) {
|
|
highlightedCode = escapeHTML(parameterMatch[1])
|
|
+ "<span class=\"msr-number\">" + parameterMatch[2] + "</span>"
|
|
+ escapeHTML(parameterMatch[3])
|
|
+ "<span class=\"msr-parameter\">" + escapeHTML(parameterMatch[4]) + "</span>"
|
|
+ highlightMSRTokens(parameterMatch[5], section, parameterNames, false);
|
|
} else {
|
|
let firstTokenMatch = code.match(/^(\s*)([A-Za-z_][A-Za-z0-9_.-]*)(.*)$/);
|
|
if (!firstTokenMatch) {
|
|
highlightedCode = highlightMSRTokens(code, section, parameterNames, false);
|
|
} else {
|
|
let firstToken = firstTokenMatch[2];
|
|
let firstTokenLower = firstToken.toLowerCase();
|
|
let firstTokenClass = "";
|
|
if (msrBlockKeywords.has(firstToken)) {
|
|
firstTokenClass = "msr-keyword";
|
|
} else if (section == "COMMANDS" && msrCommands.has(firstTokenLower)) {
|
|
firstTokenClass = "msr-command";
|
|
} else if (/^(?:GLOBAL|RUN|FOURIER|PLOT)$/.test(section)
|
|
&& msrDirectives.has(firstTokenLower)) {
|
|
firstTokenClass = "msr-directive";
|
|
} else if ((section == "THEORY" && msrTheoryFunctions.has(firstTokenLower))
|
|
|| /^fun\d+$/i.test(firstToken)) {
|
|
firstTokenClass = "msr-function";
|
|
}
|
|
|
|
let parameterNumberContext = section == "THEORY"
|
|
|| /^(alpha|beta|norm|backgr\.fit|lifetime)$/i.test(firstToken)
|
|
|| (section == "COMMANDS" && /^(fix|release|scan|contours)$/i.test(firstToken));
|
|
highlightedCode = escapeHTML(firstTokenMatch[1]);
|
|
if (firstTokenClass !== "") {
|
|
highlightedCode += "<span class=\"" + firstTokenClass + "\">"
|
|
+ escapeHTML(firstToken) + "</span>";
|
|
} else {
|
|
highlightedCode += escapeHTML(firstToken);
|
|
}
|
|
highlightedCode += highlightMSRTokens(
|
|
firstTokenMatch[3], section, parameterNames, parameterNumberContext
|
|
);
|
|
}
|
|
}
|
|
|
|
if (annotation !== "") {
|
|
highlightedCode += "<span class=\"msr-comment\">" + escapeHTML(annotation) + "</span>";
|
|
}
|
|
if (comment !== "") {
|
|
highlightedCode += "<span class=\"msr-comment\">" + escapeHTML(comment) + "</span>";
|
|
}
|
|
return highlightedCode;
|
|
}
|
|
|
|
function highlightMSRText(msrText) {
|
|
let text = "";
|
|
if (msrText !== undefined && msrText !== null) {
|
|
text = msrText.toString();
|
|
}
|
|
|
|
let lines = text.split("\n");
|
|
let highlighted = [];
|
|
let section = "";
|
|
let parameterNames = new Set();
|
|
let fitParameters = parseMSRParameters(text);
|
|
for (let parameter of fitParameters) {
|
|
parameterNames.add(parameter.name.toLowerCase());
|
|
}
|
|
for (let line of lines) {
|
|
let lineWithoutComment = line.split("#", 1)[0].trim();
|
|
let blockMatch = lineWithoutComment.match(
|
|
/^(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|RUN|COMMANDS|PLOT|FOURIER|STATISTIC)\b/
|
|
);
|
|
if (blockMatch) {
|
|
section = blockMatch[1];
|
|
}
|
|
highlighted.push(highlightMSRLine(line, section, parameterNames));
|
|
}
|
|
return highlighted.join("\n");
|
|
}
|
|
|
|
function getMSREditorTextFromElement(editor) {
|
|
if (!editor) {
|
|
return "";
|
|
}
|
|
if (typeof editor.value === "string") {
|
|
return editor.value;
|
|
}
|
|
return editor.textContent || "";
|
|
}
|
|
|
|
function getEditorCaretOffset(editor) {
|
|
if (!window.getSelection) {
|
|
return null;
|
|
}
|
|
|
|
let selection = window.getSelection();
|
|
if (!selection || selection.rangeCount === 0) {
|
|
return null;
|
|
}
|
|
|
|
let range = selection.getRangeAt(0);
|
|
if (!editor.contains(range.endContainer)) {
|
|
return null;
|
|
}
|
|
|
|
let preRange = range.cloneRange();
|
|
preRange.selectNodeContents(editor);
|
|
preRange.setEnd(range.endContainer, range.endOffset);
|
|
return preRange.toString().length;
|
|
}
|
|
|
|
function restoreEditorCaretOffset(editor, offset) {
|
|
if (offset === null || offset === undefined) {
|
|
return;
|
|
}
|
|
if (!window.getSelection || !document.createRange) {
|
|
return;
|
|
}
|
|
|
|
let range = document.createRange();
|
|
let textNodeFilter = window.NodeFilter ? window.NodeFilter.SHOW_TEXT : 4;
|
|
let walker = document.createTreeWalker(editor, textNodeFilter, null);
|
|
let currentOffset = 0;
|
|
let found = false;
|
|
let node = walker.nextNode();
|
|
|
|
while (node) {
|
|
let nextOffset = currentOffset + node.textContent.length;
|
|
if (offset <= nextOffset) {
|
|
range.setStart(node, offset - currentOffset);
|
|
range.collapse(true);
|
|
found = true;
|
|
break;
|
|
}
|
|
currentOffset = nextOffset;
|
|
node = walker.nextNode();
|
|
}
|
|
|
|
if (!found) {
|
|
range.selectNodeContents(editor);
|
|
range.collapse(false);
|
|
}
|
|
|
|
let selection = window.getSelection();
|
|
selection.removeAllRanges();
|
|
selection.addRange(range);
|
|
}
|
|
|
|
function highlightMSREditor(preserveCaret = true) {
|
|
let editor = document.getElementById("msrEditorText");
|
|
if (!editor) {
|
|
return;
|
|
}
|
|
if (typeof editor.value === "string") {
|
|
return;
|
|
}
|
|
|
|
let caretOffset = null;
|
|
if (preserveCaret) {
|
|
caretOffset = getEditorCaretOffset(editor);
|
|
}
|
|
|
|
let text = getMSREditorTextFromElement(editor);
|
|
editor.innerHTML = highlightMSRText(text);
|
|
|
|
if (preserveCaret) {
|
|
restoreEditorCaretOffset(editor, caretOffset);
|
|
}
|
|
}
|
|
|
|
function setMSREditorText(editor, content) {
|
|
let text = "";
|
|
if (content !== undefined && content !== null) {
|
|
text = content.toString();
|
|
}
|
|
|
|
window.MSREditor.suppressInput = true;
|
|
try {
|
|
if (typeof editor.value === "string") {
|
|
editor.value = text;
|
|
return;
|
|
}
|
|
|
|
editor.textContent = text;
|
|
highlightMSREditor(false);
|
|
} finally {
|
|
window.MSREditor.suppressInput = false;
|
|
}
|
|
}
|
|
|
|
function initMSREditor() {
|
|
let txt = document.getElementById("msrEditorText");
|
|
if (!txt) {
|
|
return;
|
|
}
|
|
if (getMSREditorTextFromElement(txt).trim() === "") {
|
|
setMSREditorText(txt, "# MSR editor\n# Open an MSR file or use \"Generate from GUI\" to create one.\n");
|
|
} else {
|
|
highlightMSREditor(false);
|
|
}
|
|
updateMSREditorSourceTabs();
|
|
updateMSREditorSourceState();
|
|
}
|
|
|
|
function loadMSRIntoEditor(content, filePath = "", markClean = true, options = {}) {
|
|
let txt = document.getElementById("msrEditorText");
|
|
if (!txt) {
|
|
return;
|
|
}
|
|
let text = content !== undefined && content !== null ? content.toString() : "";
|
|
window.MSREditor.activeSource = "current";
|
|
window.MSREditor.currentContent = text;
|
|
syncMSREditorLegacyState();
|
|
setMSREditorText(txt, text);
|
|
if (filePath) {
|
|
window.MSREditor.currentPath = filePath;
|
|
}
|
|
if (markClean) {
|
|
setMSREditorDirty(false, "current");
|
|
} else {
|
|
syncMSREditorLegacyState();
|
|
}
|
|
|
|
// Switching between cached editor documents must not change ownership. Fresh
|
|
// loads can explicitly mark the runnable file as GUI- or editor-owned.
|
|
if (options.preserveOwnership) {
|
|
syncMSREditorLegacyState();
|
|
} else if (options.editorOwned) {
|
|
markMSREditorAsEditorOwned(text, "current");
|
|
} else if (options.guiOwned || !getMSRDocumentState("current").locked) {
|
|
markMSREditorAsGUIOwned(text, "current");
|
|
} else {
|
|
acceptMSRTextAsKnown(text, "current");
|
|
}
|
|
|
|
updateMSREditorSourceTabs();
|
|
updateMSREditorSourceState();
|
|
if (options.syncGUI !== false) {
|
|
// Remember the file's parameter order and comment lines so the next MSR
|
|
// regeneration (single fit or series) preserves the structure the author
|
|
// wrote instead of renumbering in catalogue order.
|
|
if (typeof captureImportedMSRFitParameterStructure === "function") {
|
|
captureImportedMSRFitParameterStructure(text);
|
|
}
|
|
syncSettingsFromMSR(text);
|
|
syncTheoryFromMSR(text);
|
|
syncParametersFromMSR(text);
|
|
syncT0BgFromMSR(text);
|
|
}
|
|
}
|
|
|
|
function getCurrentEditorText() {
|
|
let txt = document.getElementById("msrEditorText");
|
|
if (!txt) {
|
|
return "";
|
|
}
|
|
return getMSREditorTextFromElement(txt);
|
|
}
|
|
|
|
function openEditorWithGeneratedMSR() {
|
|
prepCFG();
|
|
let msr = createMSR();
|
|
window.MSREditor.currentContent = msr;
|
|
window.MSREditor.templateContent = "";
|
|
window.MSREditor.templatePath = "";
|
|
window.MSREditor.activeSource = "current";
|
|
window.MSREditor.hasTemplateTab = false;
|
|
|
|
// Starting a new GUI-generated single/current document resets both document
|
|
// states because there is no longer a template/global pair to preserve.
|
|
window.MSREditor.documents.current = {
|
|
sourceOfTruth: "gui", locked: false, dirty: false,
|
|
lastGeneratedHash: hashMSRText(msr), lastAcceptedHash: hashMSRText(msr), stale: false
|
|
};
|
|
window.MSREditor.documents.template = {
|
|
sourceOfTruth: "gui", locked: false, dirty: false,
|
|
lastGeneratedHash: "", lastAcceptedHash: "", stale: false
|
|
};
|
|
syncMSREditorLegacyState();
|
|
rememberGeneratedMSR(msr, "current");
|
|
loadMSRIntoEditor(msr, "", true, { guiOwned: true });
|
|
openTab(null, "Editor");
|
|
}
|
|
|
|
function updateMSREditorSourceTabs() {
|
|
let tabs = document.getElementById("editorSourceTabs");
|
|
let currentBtn = document.getElementById("btnEditorCurrent");
|
|
let templateBtn = document.getElementById("btnEditorTemplate");
|
|
let hasPair = window.MSREditor.hasTemplateTab;
|
|
let currentStale = getMSRDocumentState("current").stale;
|
|
let templateStale = getMSRDocumentState("template").stale;
|
|
|
|
// Always show the current-document selector in the toolbar. In single-file
|
|
// mode it reads "MSR"; global fits simply reveal the adjacent Template tab.
|
|
if (tabs) {
|
|
tabs.style.display = "inline-flex";
|
|
}
|
|
if (currentBtn) {
|
|
currentBtn.className = "editor-source-tab" + (window.MSREditor.activeSource == "current" ? " active" : "");
|
|
// Imported GUI state can make either a single MSR or a global/template pair
|
|
// stale, so keep that mismatch visible until the next regeneration.
|
|
currentBtn.textContent = hasPair
|
|
? (currentStale ? "Global · stale" : "Global")
|
|
: (currentStale ? "MSR · stale" : "MSR");
|
|
}
|
|
if (templateBtn) {
|
|
templateBtn.hidden = !hasPair;
|
|
templateBtn.className = "editor-source-tab" + (window.MSREditor.activeSource == "template" ? " active" : "");
|
|
templateBtn.textContent = templateStale ? "Template · stale" : "Template";
|
|
}
|
|
syncMSREditorLegacyState();
|
|
updateMSREditorSourceState();
|
|
}
|
|
|
|
function showMSREditorSource(source) {
|
|
if (source == window.MSREditor.activeSource) {
|
|
return;
|
|
}
|
|
if (source == "template" && !window.MSREditor.hasTemplateTab) {
|
|
return;
|
|
}
|
|
|
|
let txt = document.getElementById("msrEditorText");
|
|
if (!txt) {
|
|
return;
|
|
}
|
|
|
|
// Preserve the text in the document being left. Ownership/dirty state belongs
|
|
// to that document and is restored independently when the user switches back.
|
|
let currentText = getCurrentEditorText();
|
|
if (window.MSREditor.activeSource == "template") {
|
|
window.MSREditor.templateContent = currentText;
|
|
} else {
|
|
window.MSREditor.currentContent = currentText;
|
|
}
|
|
|
|
window.MSREditor.activeSource = source;
|
|
syncMSREditorLegacyState();
|
|
if (source == "template") {
|
|
setMSREditorText(txt, window.MSREditor.templateContent);
|
|
updateMSREditorSourceTabs();
|
|
return;
|
|
}
|
|
|
|
loadMSRIntoEditor(window.MSREditor.currentContent, window.MSREditor.currentPath, false, {
|
|
preserveOwnership: true
|
|
});
|
|
}
|
|
|
|
async function saveCurrentMSRFile() {
|
|
let editorText = getCurrentEditorText();
|
|
if (!editorText || editorText.trim() === "") {
|
|
alert("Editor is empty.");
|
|
return(0);
|
|
}
|
|
let path = window.MSREditor.currentPath;
|
|
if (window.MSREditor.activeSource == "template") {
|
|
path = window.MSREditor.templatePath;
|
|
}
|
|
if (!path) {
|
|
prepCFG();
|
|
let runs = arrayRunNumbers(All.runNumbers);
|
|
let firstRun = runs.length > 0 ? runs[0] : "musrfit";
|
|
let suffix = fitFileSuffix(All, amIWeb());
|
|
let basePath = All.workPath && All.workPath !== "" ? All.workPath : defaultWorkPath;
|
|
path = [basePath, firstRun + suffix + ".msr"].join("/");
|
|
}
|
|
if (!await writeAsciiFile(path, editorText)) {
|
|
return(0);
|
|
}
|
|
if (window.MSREditor.activeSource == "template") {
|
|
window.MSREditor.templatePath = path;
|
|
window.MSREditor.templateContent = editorText;
|
|
} else {
|
|
window.MSREditor.currentPath = path;
|
|
window.MSREditor.currentContent = editorText;
|
|
}
|
|
setMSREditorDirty(false);
|
|
acceptMSRTextAsKnown(editorText);
|
|
updateMSREditorSourceState();
|
|
setFitStatus("MSR file saved.", {
|
|
level: "success",
|
|
details: "Saved editor file: " + path
|
|
});
|
|
return(1);
|
|
}
|
|
|
|
async function runCurrentMSRFile() {
|
|
if (window.MSREditor.activeSource == "template") {
|
|
if (!await saveCurrentMSRFile()) {
|
|
return(0);
|
|
}
|
|
// A template is an msr2data input, not the runnable expanded global file.
|
|
setFitStatus("Template saved; switch to Global to run.", {
|
|
level: "info",
|
|
details: "Template saved. Switch to Global to run the current global MSR."
|
|
});
|
|
return(0);
|
|
}
|
|
|
|
if (!await saveCurrentMSRFile()) {
|
|
return(0);
|
|
}
|
|
let fullPath = window.MSREditor.currentPath;
|
|
if (!fullPath) return(0);
|
|
return await runMSRFile(fullPath);
|
|
}
|
|
|
|
async function runMSRFile(fullPath, options = {}) {
|
|
// Shared entry point for both deployment modes. The UI calls this function
|
|
// without caring whether the work is done by Electron or by a web CGI. The
|
|
// platform adapter registers the concrete runner at load time (Electron
|
|
// local binaries, or the web delegate backed by a CGI endpoint).
|
|
let actionName = options.plotOnly ? "Plotting" : "Running fit";
|
|
beginJobStatus(actionName, fullPath, options);
|
|
let platform = typeof window !== "undefined" ? window.MusRFlowPlatform : null;
|
|
if (platform && typeof platform.msrFileRunner === "function") {
|
|
return await platform.msrFileRunner(fullPath, options);
|
|
}
|
|
|
|
// No adapter registered (embedded/test context): preserve the legacy
|
|
// heuristic dispatch so behavior does not depend on script load order.
|
|
if (!amIWeb() && typeof runMSRFileLocal === "function") {
|
|
return await runMSRFileLocal(fullPath, options);
|
|
}
|
|
if (amIWeb() && typeof runMSRFileWeb === "function") {
|
|
// Web mode cannot execute local binaries directly. It delegates the same
|
|
// logical job to muSRFitweb.js, which will be backed by a CGI endpoint.
|
|
let webRes = await runMSRFileWeb(fullPath, options);
|
|
finishJobStatus(
|
|
webRes && webRes.ok,
|
|
webRes ? webRes.code : 1,
|
|
webRes ? webRes.statusText : "Web fit request failed.",
|
|
webRes ? webRes.outcome : ""
|
|
);
|
|
return(webRes && webRes.ok ? 1 : 0);
|
|
}
|
|
finishJobStatus(0, 1, amIWeb()
|
|
? "No web runner is configured." : "No local runner is configured.");
|
|
return(0);
|
|
}
|
|
|
|
|
|
// Main GUI construction and tab helpers.
|
|
function defaultHistograms(force)
|
|
{
|
|
let instruments = ["LEM", "GPS", "LTF", "FLAME", "Dolly", "VMS", "GPD", "HAL"];
|
|
let defltHists = ["21 25,23 27", "2,1", "2,1", "2,1", "1,2", "1,2", "1,2", "4 5 6,8 9 2"];
|
|
let instrName = document.getElementById('instrName').value;
|
|
let init_LRBF = '';
|
|
// If LRBF is empty or you get a force=1 put default valuer of beamline
|
|
if (force) {
|
|
// get value in HTML
|
|
let asyLRBF = document.getElementById('LRBF');
|
|
// which beamline is selected
|
|
let iofInstr = instruments.indexOf(instrName);
|
|
if (iofInstr >= 0) {
|
|
asyLRBF.value = defltHists[iofInstr];
|
|
}
|
|
}
|
|
}
|
|
|
|
function clearTabs(reinitializeInitialGuesses)
|
|
{
|
|
// A user-initiated rebuild of the fit model or its dependent views is a
|
|
// structural GUI change that must be carried into every series MSR. The
|
|
// header-guess auto-model-swap calls clearTabs(false) and is deliberately
|
|
// excluded: it only mirrors the reference run, it does not edit the analysis.
|
|
if (reinitializeInitialGuesses || reinitializeInitialGuesses === undefined) {
|
|
markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
// A model/theory change deliberately rebuilds the parameter model. Allow the
|
|
// first-run metadata to seed any newly introduced parameters again.
|
|
if (reinitializeInitialGuesses) {
|
|
initialParameterGuessState.generation++;
|
|
}
|
|
|
|
// Rebuilding the model invalidates any FITPARAMETER order/comments captured
|
|
// from an imported MSR: the file described a model the GUI no longer has,
|
|
// so catalogue ordering takes over again. The header-guess auto-swap path
|
|
// (clearTabs(false)) keeps the imported structure because it only mirrors
|
|
// the reference run.
|
|
if (reinitializeInitialGuesses
|
|
&& typeof resetImportedMSRParameterStructure === "function") {
|
|
resetImportedMSRParameterStructure();
|
|
}
|
|
|
|
// 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");
|
|
if (shareTab) {
|
|
shareTab.innerHTML = "";
|
|
}
|
|
document.getElementById("Params").innerHTML = "";
|
|
let t0BgTab = document.getElementById("t0Bg");
|
|
if (t0BgTab) {
|
|
t0BgTab.innerHTML = "";
|
|
clearStoredT0BgValues();
|
|
}
|
|
adjustComps();
|
|
updateTheoryBlock();
|
|
cfgParams();
|
|
}
|
|
|
|
function markFitModelExplicit()
|
|
{
|
|
automaticInitialFitModel = false;
|
|
}
|
|
|
|
// Model choices are grouped for faster scanning without changing the function
|
|
// identifiers stored in the GUI or written to the MSR. Any future dictionary
|
|
// entry that is not listed here is appended automatically under "Other".
|
|
const fitFunctionGroups = [
|
|
{ label: "Relaxation", functions: ["Asymmetry", "Exponential", "Gaussian", "Stretch"] },
|
|
{ label: "Static KT", functions: ["SLKT", "SGKT", "LGKT", "STRKT", "GBGZF"] },
|
|
{ label: "Oscillating", functions: ["ExponentialCos", "GaussianCos", "StretchCos", "AbragamCos", "GBGCos", "ExponentialBessel", "GaussianBessel"] },
|
|
{ label: "KT x relaxation", functions: ["LLFExp", "GLFExp", "LGKTExp", "GBGExp", "STRKTExp", "LLFSExp", "GLFSExp", "LGKTSExp", "GBGSExp", "STRKTSExp"] },
|
|
{ label: "Dynamic KT", functions: ["LDKTLF", "GDKTLF"] }
|
|
];
|
|
|
|
function appendFitFunctionOption(parent, funcName)
|
|
{
|
|
if (!funcDictionary[funcName]) return;
|
|
let option = document.createElement("option");
|
|
option.textContent = funcDictionary[funcName].descrip;
|
|
option.value = funcName;
|
|
parent.appendChild(option);
|
|
}
|
|
|
|
function populateFitFunctionSelect(select)
|
|
{
|
|
// Optgroups make the long model list easier to scan while the fallback keeps
|
|
// newly added funcDictionary entries available even before they are categorized.
|
|
let grouped = new Set();
|
|
for (let groupInfo of fitFunctionGroups) {
|
|
let group = document.createElement("optgroup");
|
|
group.label = groupInfo.label;
|
|
for (let funcName of groupInfo.functions) {
|
|
if (!funcDictionary[funcName]) continue;
|
|
appendFitFunctionOption(group, funcName);
|
|
grouped.add(funcName);
|
|
}
|
|
if (group.children.length) select.appendChild(group);
|
|
}
|
|
|
|
let uncategorized = Object.keys(funcDictionary).filter(function(funcName) {
|
|
return !grouped.has(funcName);
|
|
});
|
|
if (uncategorized.length) {
|
|
let otherGroup = document.createElement("optgroup");
|
|
otherGroup.label = "Other";
|
|
for (let funcName of uncategorized) appendFitFunctionOption(otherGroup, funcName);
|
|
select.appendChild(otherGroup);
|
|
}
|
|
}
|
|
|
|
function getFitComponentValues()
|
|
{
|
|
let values = [];
|
|
let compRows = document.getElementById("compRows");
|
|
if (!compRows) return values;
|
|
let selects = compRows.querySelectorAll("select[id^='fitFunc']");
|
|
for (let select of selects) values.push(select.value);
|
|
return values;
|
|
}
|
|
|
|
function renderFitComponents(values)
|
|
{
|
|
let compRows = document.getElementById("compRows");
|
|
if (!compRows) return;
|
|
compRows.innerHTML = "";
|
|
|
|
for (let index = 0; index < values.length; index++) {
|
|
let componentNo = index + 1;
|
|
let row = document.createElement("div");
|
|
row.className = "fit-model-component";
|
|
|
|
let marker = document.createElement("span");
|
|
marker.className = componentNo == 1 ? "fit-model-component-label" : "fit-model-component-index";
|
|
marker.textContent = componentNo == 1 ? "Model" : String(componentNo);
|
|
row.appendChild(marker);
|
|
|
|
let select = document.createElement("select");
|
|
select.id = "fitFunc" + componentNo;
|
|
select.setAttribute("aria-label", "Fit model component " + componentNo);
|
|
populateFitFunctionSelect(select);
|
|
select.value = values[index];
|
|
// Changing the model invalidates parameter/function tabs, not only THEORY.
|
|
// clearTabs() rebuilds those dependent views from the selected components.
|
|
select.addEventListener("change", function() {
|
|
markFitModelExplicit();
|
|
clearTabs(true);
|
|
});
|
|
row.appendChild(select);
|
|
|
|
if (componentNo > 1) {
|
|
let remove = document.createElement("button");
|
|
remove.type = "button";
|
|
remove.className = "fit-model-remove";
|
|
remove.textContent = "\u00d7";
|
|
remove.title = "Remove component " + componentNo;
|
|
remove.setAttribute("aria-label", remove.title);
|
|
remove.addEventListener("click", function() {
|
|
let countInput = document.getElementById("numComps");
|
|
if (!countInput) return;
|
|
|
|
// Preserve the remaining model choices when removing a middle component,
|
|
// then renumber them densely so downstream code can continue using
|
|
// fitFunc1..N.
|
|
let fitFuncs = getFitComponentValues();
|
|
if (fitFuncs.length <= 1 || componentNo < 2 || componentNo > fitFuncs.length) return;
|
|
markFitModelExplicit();
|
|
fitFuncs.splice(componentNo - 1, 1);
|
|
countInput.value = String(fitFuncs.length);
|
|
renderFitComponents(fitFuncs);
|
|
clearTabs(true);
|
|
});
|
|
row.appendChild(remove);
|
|
}
|
|
|
|
compRows.appendChild(row);
|
|
}
|
|
}
|
|
|
|
function adjustComps()
|
|
{
|
|
let countInput = document.getElementById("numComps");
|
|
if (!countInput) return;
|
|
|
|
// numComps remains a hidden compatibility field for existing MSR-generation
|
|
// code. The visible component list is the only user-facing source of count.
|
|
let numComps = parseInt(countInput.value, 10);
|
|
if (!Number.isFinite(numComps) || numComps < 1) numComps = 1;
|
|
if (numComps > 100) numComps = 100;
|
|
countInput.value = String(numComps);
|
|
|
|
let fitFuncs = getFitComponentValues();
|
|
while (fitFuncs.length < numComps) {
|
|
fitFuncs.push(fitFuncs.length == 0 ? "ExponentialCos" : "Exponential");
|
|
}
|
|
fitFuncs = fitFuncs.slice(0, numComps);
|
|
renderFitComponents(fitFuncs);
|
|
}
|
|
|
|
function addFitComponent()
|
|
{
|
|
let countInput = document.getElementById("numComps");
|
|
if (!countInput) return;
|
|
let count = parseInt(countInput.value, 10);
|
|
if (!Number.isFinite(count) || count < 1) count = 1;
|
|
if (count >= 100) return;
|
|
markFitModelExplicit();
|
|
countInput.value = String(count + 1);
|
|
clearTabs(true);
|
|
}
|
|
|
|
// Deployment mode is a platform fact registered by muSRFitelec.js /
|
|
// muSRFitweb.js at load time, not a property to sniff from the user agent or
|
|
// module globals. The heuristic below only covers embedded or test contexts
|
|
// that never load a platform adapter.
|
|
function amIWeb() {
|
|
let platform = typeof window !== "undefined" ? window.MusRFlowPlatform : null;
|
|
if (platform && typeof platform.webMode === "boolean") {
|
|
return platform.webMode ? 1 : 0;
|
|
}
|
|
// Electron renderer identifies itself in the user agent even under
|
|
// contextIsolation, where Node globals (module/require/process) no longer
|
|
// leak into the page context.
|
|
if (typeof navigator !== 'undefined' && /Electron/i.test(navigator.userAgent || "")) {
|
|
return 0;
|
|
}
|
|
if (typeof module !== 'undefined' && module.exports) {
|
|
// Run as standalone app (legacy fallback)
|
|
return 0;
|
|
}
|
|
// Run as a web app
|
|
return 1;
|
|
}
|
|
|
|
// The Electron renderer once reached for process.cwd() directly. That Node
|
|
// global is not available in every sandboxed renderer, so the adapter now
|
|
// registers the real working directory and the browser registers ".".
|
|
function platformCurrentDirectory() {
|
|
let platform = typeof window !== "undefined" ? window.MusRFlowPlatform : null;
|
|
if (platform && typeof platform.currentDirectory === "function") {
|
|
try {
|
|
let directory = platform.currentDirectory();
|
|
if (typeof directory === "string") return directory;
|
|
} catch (error) {
|
|
// Fall through to the legacy resolution or ".".
|
|
}
|
|
}
|
|
try {
|
|
if (typeof process !== "undefined" && typeof process.cwd === "function") {
|
|
return process.cwd();
|
|
}
|
|
} catch (error) {
|
|
// The node bridge does not expose cwd in this context.
|
|
}
|
|
return ".";
|
|
}
|
|
|
|
function showQuickStartHelp() {
|
|
// Quick Start is one guide for the whole application. The active tab only
|
|
// determines which section is brought into view when the user opens it.
|
|
let sectionId = ({
|
|
Runs: "helpRuns",
|
|
Params: "helpParams",
|
|
Functions: "helpConstraints",
|
|
t0Bg: "helpT0Bg",
|
|
Editor: "helpEditor",
|
|
Jobs: "helpResults"
|
|
})[window.muSRFlowActiveTab || "Runs"] || "helpRuns";
|
|
|
|
// Electron uses the same auxiliary-window request path as parameter plots.
|
|
// This helper exists only in the Electron renderer, so do not rely on the
|
|
// generic amIWeb() test here.
|
|
if (typeof window.openElectronAuxiliaryWindow === "function") {
|
|
let options = { sectionId: sectionId };
|
|
if (typeof window.getMuSRFlowBuildInfo === "function") {
|
|
options.buildInfo = window.getMuSRFlowBuildInfo();
|
|
}
|
|
if (window.openElectronAuxiliaryWindow("quickStart", options)) return;
|
|
}
|
|
|
|
// The browser keeps Help modeless so the main application remains usable.
|
|
let dialog = document.getElementById("quickStartDialog");
|
|
let frame = document.getElementById("quickStartFrame");
|
|
if (!dialog || !frame) return;
|
|
|
|
let source = "quick-start.html#" + sectionId;
|
|
if (frame.getAttribute("src") !== source) frame.setAttribute("src", source);
|
|
makeModelessDialogDraggable(dialog);
|
|
|
|
if (!dialog.open) {
|
|
dialog.show();
|
|
let left = Math.max(12, (window.innerWidth - dialog.offsetWidth) / 2);
|
|
dialog.style.left = left + "px";
|
|
dialog.style.top = "48px";
|
|
}
|
|
bringMusrfitFloatingWindowToFront(dialog);
|
|
dialog.focus();
|
|
}
|
|
|
|
function closeQuickStartHelp() {
|
|
let dialog = document.getElementById("quickStartDialog");
|
|
if (!dialog) return;
|
|
if (typeof dialog.close === "function" && dialog.open) dialog.close();
|
|
else dialog.removeAttribute("open");
|
|
}
|
|
|
|
function openTab(event, tabName) {
|
|
// Remember the current context so the Help button can focus the matching
|
|
// Quick Start section even when a tab is opened programmatically.
|
|
window.muSRFlowActiveTab = tabName;
|
|
|
|
// Declare all variables
|
|
var i, tabcontent, tablinks;
|
|
// Get all elements with class="tabcontent" and hide them
|
|
tabcontent = document.getElementsByClassName("tabcontent");
|
|
for (i = 0; i < tabcontent.length; i++) {
|
|
tabcontent[i].style.display = "none";
|
|
}
|
|
|
|
// Get all elements with class="tablinks" and remove the class "active"
|
|
tablinks = document.getElementsByClassName("tablinks");
|
|
for (i = 0; i < tablinks.length; i++) {
|
|
tablinks[i].className = tablinks[i].className.replace(" active", "");
|
|
}
|
|
|
|
// Show the current tab, and add an "active" class to the button that opened the tab
|
|
let selectedTab = document.getElementById(tabName);
|
|
if (selectedTab) {
|
|
selectedTab.style.display = (tabName == "Editor" || tabName == "Jobs") ? "flex" : "block";
|
|
}
|
|
if (event) event.currentTarget.className += " active";
|
|
}
|
|
|
|
function updatePlotOptionVisibility() {
|
|
let fitTypeEl = document.getElementById("fitAsyType");
|
|
let lifetimeWrap = document.getElementById("plotLifetimeCorrectionWrap");
|
|
let lifetimeInput = document.getElementById("plotLifetimeCorrection");
|
|
if (!fitTypeEl || !lifetimeWrap || !lifetimeInput) {
|
|
return;
|
|
}
|
|
|
|
if (fitTypeEl.value == "SingleHist") {
|
|
lifetimeWrap.style.display = "";
|
|
lifetimeInput.disabled = false;
|
|
} else {
|
|
lifetimeWrap.style.display = "none";
|
|
lifetimeInput.disabled = true;
|
|
}
|
|
|
|
// The Plot disclosure is normally collapsed, so keep its small state marker
|
|
// in sync whenever the fit type changes the set of applicable plot options.
|
|
updatePlotOptionsIndicator();
|
|
}
|
|
|
|
function updatePlotOptionsIndicator() {
|
|
let disclosure = document.getElementById("plotOptionsDisclosure");
|
|
if (!disclosure) {
|
|
return;
|
|
}
|
|
|
|
// Empty plot limits mean "use_fit_ranges" and an empty/zero view packing
|
|
// means no plot-specific rebinning. Only departures from those defaults need
|
|
// to be advertised while the compact Plot disclosure is closed.
|
|
let plotStart = document.getElementById("Tpis");
|
|
let plotEnd = document.getElementById("Tpfs");
|
|
let plotYMin = document.getElementById("Ypis");
|
|
let plotYMax = document.getElementById("Ypfs");
|
|
let viewPacking = document.getElementById("VIEWBINS");
|
|
let logX = document.getElementById("plotLogX");
|
|
let logY = document.getElementById("plotLogY");
|
|
let fitType = document.getElementById("fitAsyType");
|
|
let lifetime = document.getElementById("plotLifetimeCorrection");
|
|
|
|
let hasCustomRange = Boolean(
|
|
(plotStart && plotStart.value.trim()) || (plotEnd && plotEnd.value.trim())
|
|
|| (plotYMin && plotYMin.value.trim()) || (plotYMax && plotYMax.value.trim())
|
|
);
|
|
let packingValue = viewPacking ? viewPacking.value.trim() : "";
|
|
let hasViewPacking = packingValue !== "" && packingValue !== "0";
|
|
let hasLogScale = Boolean((logX && logX.checked) || (logY && logY.checked));
|
|
|
|
// Lifetime correction is enabled by default for single-histogram plots. An
|
|
// unchecked box is therefore the exceptional state worth surfacing here.
|
|
let lifetimeChanged = Boolean(
|
|
fitType && fitType.value == "SingleHist" && lifetime && !lifetime.checked
|
|
);
|
|
|
|
disclosure.classList.toggle(
|
|
"has-overrides",
|
|
hasCustomRange || hasViewPacking || hasLogScale || lifetimeChanged
|
|
);
|
|
}
|
|
|
|
// t0/background override collection, validation, and MSR rewriting.
|
|
function readT0BgField(all, fieldName, rowIndex) {
|
|
let key = "t0Bg" + fieldName + "_" + rowIndex;
|
|
let value = "";
|
|
if (all && all[key] !== undefined && all[key] !== null) {
|
|
value = all[key].toString().trim();
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function readT0BgCommonField(all, fieldName) {
|
|
let key = "t0BgCommon" + fieldName;
|
|
let value = "";
|
|
if (all && all[key] !== undefined && all[key] !== null) {
|
|
value = all[key].toString().trim();
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function clearStoredT0BgValues() {
|
|
for (let key in All) {
|
|
if (Object.prototype.hasOwnProperty.call(All, key) && key.indexOf("t0Bg") === 0) {
|
|
delete All[key];
|
|
}
|
|
}
|
|
}
|
|
|
|
function defaultT0BgMode(fitType) {
|
|
// Preserve the current SingleHist behavior: background is fitted through
|
|
// the generated NBg parameter unless the expert tab explicitly changes it.
|
|
if (fitType === 0) {
|
|
return "fit";
|
|
}
|
|
|
|
return "auto";
|
|
}
|
|
|
|
function t0BgModeForRow(all, fitType, rowIndex) {
|
|
let mode = readT0BgField(all, "BgMode", rowIndex);
|
|
if (mode !== "" && mode != "common") {
|
|
return mode;
|
|
}
|
|
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode !== "") {
|
|
return commonMode;
|
|
}
|
|
|
|
return defaultT0BgMode(fitType);
|
|
}
|
|
|
|
function buildT0BgRunLines(all, fitType, rowIndex, defaultBackgrFitParam) {
|
|
let lines = [];
|
|
|
|
if (fitType === 0) {
|
|
let t0Value = readT0BgField(all, "T0", rowIndex);
|
|
if (t0Value === "") {
|
|
t0Value = readT0BgCommonField(all, "T0");
|
|
}
|
|
if (t0Value !== "") {
|
|
lines.push("t0 " + t0Value);
|
|
}
|
|
|
|
// A row set to "Use common" must not leak stale hidden background fields
|
|
// into the generated RUN block. Only explicit row modes can override Bg.
|
|
let rowMode = readT0BgField(all, "BgMode", rowIndex);
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode === "") {
|
|
commonMode = defaultT0BgMode(fitType);
|
|
}
|
|
|
|
let bgMode = t0BgModeForRow(all, fitType, rowIndex);
|
|
let rowCanOverrideBg = rowMode !== "" && rowMode != "common";
|
|
if (bgMode == "range") {
|
|
let bgStart = rowCanOverrideBg ? readT0BgField(all, "BgStart", rowIndex) : "";
|
|
let bgEnd = rowCanOverrideBg ? readT0BgField(all, "BgEnd", rowIndex) : "";
|
|
if (bgStart === "" && commonMode == bgMode) {
|
|
bgStart = readT0BgCommonField(all, "BgStart");
|
|
}
|
|
if (bgEnd === "" && commonMode == bgMode) {
|
|
bgEnd = readT0BgCommonField(all, "BgEnd");
|
|
}
|
|
if (bgStart !== "" && bgEnd !== "") {
|
|
lines.push("background " + bgStart + " " + bgEnd);
|
|
}
|
|
} else if (bgMode == "fixed") {
|
|
let fixedBg = rowCanOverrideBg ? readT0BgField(all, "BgFix", rowIndex) : "";
|
|
if (fixedBg === "" && commonMode == bgMode) {
|
|
fixedBg = readT0BgCommonField(all, "BgFix");
|
|
}
|
|
if (fixedBg !== "") {
|
|
lines.push("backgr.fix " + fixedBg);
|
|
}
|
|
} else if (bgMode == "fit" && defaultBackgrFitParam !== undefined && defaultBackgrFitParam !== null) {
|
|
lines.push("backgr.fit " + defaultBackgrFitParam);
|
|
}
|
|
|
|
let dataStart = readT0BgField(all, "DataStart", rowIndex);
|
|
let dataEnd = readT0BgField(all, "DataEnd", rowIndex);
|
|
if (dataStart === "") {
|
|
dataStart = readT0BgCommonField(all, "DataStart");
|
|
}
|
|
if (dataEnd === "") {
|
|
dataEnd = readT0BgCommonField(all, "DataEnd");
|
|
}
|
|
if (dataStart !== "" && dataEnd !== "") {
|
|
lines.push("data " + dataStart + " " + dataEnd);
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
let t0Forward = readT0BgField(all, "T0F", rowIndex);
|
|
let t0Backward = readT0BgField(all, "T0B", rowIndex);
|
|
if (t0Forward === "") {
|
|
t0Forward = readT0BgCommonField(all, "T0F");
|
|
}
|
|
if (t0Backward === "") {
|
|
t0Backward = readT0BgCommonField(all, "T0B");
|
|
}
|
|
if (t0Forward !== "" && t0Backward !== "") {
|
|
// For grouped asymmetry histograms musrfit expects F1 B1 F2 B2, while
|
|
// separate GUI fields are easier to read and edit.
|
|
let forwardValues = t0Forward.split(/\s+/);
|
|
let backwardValues = t0Backward.split(/\s+/);
|
|
if (forwardValues.length == backwardValues.length) {
|
|
let orderedT0 = [];
|
|
for (let valueIndex = 0; valueIndex < forwardValues.length; valueIndex++) {
|
|
orderedT0.push(forwardValues[valueIndex]);
|
|
orderedT0.push(backwardValues[valueIndex]);
|
|
}
|
|
lines.push("t0 " + orderedT0.join(" "));
|
|
}
|
|
}
|
|
|
|
// A row set to "Use common" must not leak stale hidden background fields
|
|
// into the generated RUN block. Only explicit row modes can override Bg.
|
|
let rowMode = readT0BgField(all, "BgMode", rowIndex);
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode === "") {
|
|
commonMode = defaultT0BgMode(fitType);
|
|
}
|
|
|
|
let bgMode = t0BgModeForRow(all, fitType, rowIndex);
|
|
let rowCanOverrideBg = rowMode !== "" && rowMode != "common";
|
|
if (bgMode == "range") {
|
|
let fStart = rowCanOverrideBg ? readT0BgField(all, "BgFStart", rowIndex) : "";
|
|
let fEnd = rowCanOverrideBg ? readT0BgField(all, "BgFEnd", rowIndex) : "";
|
|
let bStart = rowCanOverrideBg ? readT0BgField(all, "BgBStart", rowIndex) : "";
|
|
let bEnd = rowCanOverrideBg ? readT0BgField(all, "BgBEnd", rowIndex) : "";
|
|
if (fStart === "" && commonMode == bgMode) {
|
|
fStart = readT0BgCommonField(all, "BgFStart");
|
|
}
|
|
if (fEnd === "" && commonMode == bgMode) {
|
|
fEnd = readT0BgCommonField(all, "BgFEnd");
|
|
}
|
|
if (bStart === "" && commonMode == bgMode) {
|
|
bStart = readT0BgCommonField(all, "BgBStart");
|
|
}
|
|
if (bEnd === "" && commonMode == bgMode) {
|
|
bEnd = readT0BgCommonField(all, "BgBEnd");
|
|
}
|
|
if (fStart !== "" && fEnd !== "" && bStart !== "" && bEnd !== "") {
|
|
lines.push("background " + fStart + " " + fEnd + " " + bStart + " " + bEnd);
|
|
}
|
|
} else if (bgMode == "fixed") {
|
|
let fixedForward = rowCanOverrideBg ? readT0BgField(all, "BgFixF", rowIndex) : "";
|
|
let fixedBackward = rowCanOverrideBg ? readT0BgField(all, "BgFixB", rowIndex) : "";
|
|
if (fixedForward === "" && commonMode == bgMode) {
|
|
fixedForward = readT0BgCommonField(all, "BgFixF");
|
|
}
|
|
if (fixedBackward === "" && commonMode == bgMode) {
|
|
fixedBackward = readT0BgCommonField(all, "BgFixB");
|
|
}
|
|
if (fixedForward !== "" && fixedBackward !== "") {
|
|
lines.push("backgr.fix " + fixedForward + " " + fixedBackward);
|
|
}
|
|
}
|
|
|
|
let dataFStart = readT0BgField(all, "DataFStart", rowIndex);
|
|
let dataFEnd = readT0BgField(all, "DataFEnd", rowIndex);
|
|
let dataBStart = readT0BgField(all, "DataBStart", rowIndex);
|
|
let dataBEnd = readT0BgField(all, "DataBEnd", rowIndex);
|
|
if (dataFStart === "") {
|
|
dataFStart = readT0BgCommonField(all, "DataFStart");
|
|
}
|
|
if (dataFEnd === "") {
|
|
dataFEnd = readT0BgCommonField(all, "DataFEnd");
|
|
}
|
|
if (dataBStart === "") {
|
|
dataBStart = readT0BgCommonField(all, "DataBStart");
|
|
}
|
|
if (dataBEnd === "") {
|
|
dataBEnd = readT0BgCommonField(all, "DataBEnd");
|
|
}
|
|
if (dataFStart !== "" && dataFEnd !== "" && dataBStart !== "" && dataBEnd !== "") {
|
|
lines.push("data " + dataFStart + " " + dataFEnd + " " + dataBStart + " " + dataBEnd);
|
|
}
|
|
|
|
return lines;
|
|
}
|
|
|
|
function hasCommonT0BgOverride(all, fitType) {
|
|
if (fitType === 0) {
|
|
if (readT0BgCommonField(all, "T0") !== "") {
|
|
return true;
|
|
}
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode !== "" && commonMode != defaultT0BgMode(fitType)) {
|
|
return true;
|
|
}
|
|
return readT0BgCommonField(all, "BgStart") !== ""
|
|
|| readT0BgCommonField(all, "BgEnd") !== ""
|
|
|| readT0BgCommonField(all, "BgFix") !== ""
|
|
|| readT0BgCommonField(all, "DataStart") !== ""
|
|
|| readT0BgCommonField(all, "DataEnd") !== "";
|
|
}
|
|
|
|
if (readT0BgCommonField(all, "T0F") !== "" || readT0BgCommonField(all, "T0B") !== "") {
|
|
return true;
|
|
}
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode !== "" && commonMode != defaultT0BgMode(fitType)) {
|
|
return true;
|
|
}
|
|
return readT0BgCommonField(all, "BgFStart") !== ""
|
|
|| readT0BgCommonField(all, "BgFEnd") !== ""
|
|
|| readT0BgCommonField(all, "BgBStart") !== ""
|
|
|| readT0BgCommonField(all, "BgBEnd") !== ""
|
|
|| readT0BgCommonField(all, "BgFixF") !== ""
|
|
|| readT0BgCommonField(all, "BgFixB") !== ""
|
|
|| readT0BgCommonField(all, "DataFStart") !== ""
|
|
|| readT0BgCommonField(all, "DataFEnd") !== ""
|
|
|| readT0BgCommonField(all, "DataBStart") !== ""
|
|
|| readT0BgCommonField(all, "DataBEnd") !== "";
|
|
}
|
|
|
|
function hasAnyT0BgOverride(all, fitType, rowCount) {
|
|
if (hasCommonT0BgOverride(all, fitType)) {
|
|
return true;
|
|
}
|
|
|
|
let totalRows = rowCount || 0;
|
|
for (let rowIndex = 0; rowIndex < totalRows; rowIndex++) {
|
|
if (fitType === 0) {
|
|
if (readT0BgField(all, "T0", rowIndex) !== "") {
|
|
return true;
|
|
}
|
|
let mode = readT0BgField(all, "BgMode", rowIndex);
|
|
if (mode !== "" && mode != "common" && mode != defaultT0BgMode(fitType)) {
|
|
return true;
|
|
}
|
|
if (mode !== "" && mode != "common"
|
|
&& (readT0BgField(all, "BgStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgEnd", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgFix", rowIndex) !== "")) {
|
|
return true;
|
|
}
|
|
if (readT0BgField(all, "DataStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "DataEnd", rowIndex) !== "") {
|
|
return true;
|
|
}
|
|
} else {
|
|
if (readT0BgField(all, "T0F", rowIndex) !== "" || readT0BgField(all, "T0B", rowIndex) !== "") {
|
|
return true;
|
|
}
|
|
let mode = readT0BgField(all, "BgMode", rowIndex);
|
|
if (mode !== "" && mode != "common" && mode != defaultT0BgMode(fitType)) {
|
|
return true;
|
|
}
|
|
if (mode !== "" && mode != "common"
|
|
&& (readT0BgField(all, "BgFStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgFEnd", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgBStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgBEnd", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgFixF", rowIndex) !== ""
|
|
|| readT0BgField(all, "BgFixB", rowIndex) !== "")) {
|
|
return true;
|
|
}
|
|
if (readT0BgField(all, "DataFStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "DataFEnd", rowIndex) !== ""
|
|
|| readT0BgField(all, "DataBStart", rowIndex) !== ""
|
|
|| readT0BgField(all, "DataBEnd", rowIndex) !== "") {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function appendT0BgPairValidation(errors, label, fields, requireComplete) {
|
|
let hasAnyValue = false;
|
|
let missingLabels = [];
|
|
|
|
for (let field of fields) {
|
|
if (field.value !== "") {
|
|
hasAnyValue = true;
|
|
} else {
|
|
missingLabels.push(field.label);
|
|
}
|
|
}
|
|
|
|
if ((requireComplete || hasAnyValue) && missingLabels.length > 0) {
|
|
errors.push(label + " is incomplete; missing " + missingLabels.join(", ") + ".");
|
|
}
|
|
}
|
|
|
|
function validateT0BgOverrides(all, runs) {
|
|
let errors = [];
|
|
if (!all) {
|
|
return({
|
|
ok: 1,
|
|
message: ""
|
|
});
|
|
}
|
|
|
|
let fitType = getFitType(all);
|
|
let runList = runs || arrayRunNumbers(all.runNumbers || "");
|
|
let histList = [];
|
|
if (all.LRBF) {
|
|
histList = all.LRBF.split(",");
|
|
}
|
|
|
|
let commonMode = readT0BgCommonField(all, "BgMode");
|
|
if (commonMode === "") {
|
|
commonMode = defaultT0BgMode(fitType);
|
|
}
|
|
|
|
if (fitType === 0) {
|
|
// Single-histogram backgrounds use one value/range per generated RUN.
|
|
// Common values are checked first because rows may inherit from them.
|
|
if (commonMode == "range") {
|
|
appendT0BgPairValidation(errors, "Common single-histogram background range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "BgStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "BgEnd") }
|
|
], true);
|
|
} else if (commonMode == "fixed" && readT0BgCommonField(all, "BgFix") === "") {
|
|
errors.push("Common single-histogram fixed background needs a value.");
|
|
}
|
|
|
|
appendT0BgPairValidation(errors, "Common single-histogram data range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "DataStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "DataEnd") }
|
|
], false);
|
|
|
|
for (let rowIndex = 0; rowIndex < histList.length; rowIndex++) {
|
|
let rowLabel = "Histogram " + histList[rowIndex].trim();
|
|
let rowMode = readT0BgField(all, "BgMode", rowIndex);
|
|
|
|
// Data ranges are independent of the background mode: a row either
|
|
// overrides the common pair or inherits it, and a partial pair is shown.
|
|
let rowDataStart = readT0BgField(all, "DataStart", rowIndex);
|
|
let rowDataEnd = readT0BgField(all, "DataEnd", rowIndex);
|
|
appendT0BgPairValidation(errors, rowLabel + " data range override", [
|
|
{ label: "first bin", value: rowDataStart },
|
|
{ label: "last bin", value: rowDataEnd }
|
|
], false);
|
|
if (rowDataStart === "") {
|
|
rowDataStart = readT0BgCommonField(all, "DataStart");
|
|
}
|
|
if (rowDataEnd === "") {
|
|
rowDataEnd = readT0BgCommonField(all, "DataEnd");
|
|
}
|
|
appendT0BgPairValidation(errors, rowLabel + " effective data range", [
|
|
{ label: "first bin", value: rowDataStart },
|
|
{ label: "last bin", value: rowDataEnd }
|
|
], false);
|
|
|
|
// With "Use common", row background fields are intentionally ignored.
|
|
if (rowMode === "" || rowMode == "common") {
|
|
continue;
|
|
}
|
|
|
|
if (rowMode == "range") {
|
|
let rowStart = readT0BgField(all, "BgStart", rowIndex);
|
|
let rowEnd = readT0BgField(all, "BgEnd", rowIndex);
|
|
appendT0BgPairValidation(errors, rowLabel + " background range override", [
|
|
{ label: "first bin", value: rowStart },
|
|
{ label: "last bin", value: rowEnd }
|
|
], false);
|
|
|
|
if (rowStart === "" && commonMode == rowMode) {
|
|
rowStart = readT0BgCommonField(all, "BgStart");
|
|
}
|
|
if (rowEnd === "" && commonMode == rowMode) {
|
|
rowEnd = readT0BgCommonField(all, "BgEnd");
|
|
}
|
|
appendT0BgPairValidation(errors, rowLabel + " effective background range", [
|
|
{ label: "first bin", value: rowStart },
|
|
{ label: "last bin", value: rowEnd }
|
|
], true);
|
|
} else if (rowMode == "fixed") {
|
|
let fixedBg = readT0BgField(all, "BgFix", rowIndex);
|
|
if (fixedBg === "" && commonMode == rowMode) {
|
|
fixedBg = readT0BgCommonField(all, "BgFix");
|
|
}
|
|
if (fixedBg === "") {
|
|
errors.push(rowLabel + " fixed background override needs a value.");
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
// Asymmetry t0/background settings are paired forward/backward values.
|
|
// Partial pairs are almost always accidental, so they block generation.
|
|
appendT0BgPairValidation(errors, "Common asymmetry t0", [
|
|
{ label: "forward", value: readT0BgCommonField(all, "T0F") },
|
|
{ label: "backward", value: readT0BgCommonField(all, "T0B") }
|
|
], false);
|
|
let commonForwardT0 = readT0BgCommonField(all, "T0F");
|
|
let commonBackwardT0 = readT0BgCommonField(all, "T0B");
|
|
if (commonForwardT0 !== "" && commonBackwardT0 !== ""
|
|
&& commonForwardT0.split(/\s+/).length != commonBackwardT0.split(/\s+/).length) {
|
|
errors.push("Common asymmetry t0 needs the same number of forward and backward values.");
|
|
}
|
|
|
|
if (commonMode == "range") {
|
|
appendT0BgPairValidation(errors, "Common forward background range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "BgFStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "BgFEnd") }
|
|
], true);
|
|
appendT0BgPairValidation(errors, "Common backward background range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "BgBStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "BgBEnd") }
|
|
], true);
|
|
} else if (commonMode == "fixed") {
|
|
appendT0BgPairValidation(errors, "Common fixed background", [
|
|
{ label: "forward", value: readT0BgCommonField(all, "BgFixF") },
|
|
{ label: "backward", value: readT0BgCommonField(all, "BgFixB") }
|
|
], true);
|
|
}
|
|
|
|
appendT0BgPairValidation(errors, "Common forward data range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "DataFStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "DataFEnd") }
|
|
], false);
|
|
appendT0BgPairValidation(errors, "Common backward data range", [
|
|
{ label: "first bin", value: readT0BgCommonField(all, "DataBStart") },
|
|
{ label: "last bin", value: readT0BgCommonField(all, "DataBEnd") }
|
|
], false);
|
|
|
|
for (let rowIndex = 0; rowIndex < runList.length; rowIndex++) {
|
|
let rowLabel = "Run " + runList[rowIndex];
|
|
appendT0BgPairValidation(errors, rowLabel + " t0 override", [
|
|
{ label: "forward", value: readT0BgField(all, "T0F", rowIndex) },
|
|
{ label: "backward", value: readT0BgField(all, "T0B", rowIndex) }
|
|
], false);
|
|
let rowForwardT0 = readT0BgField(all, "T0F", rowIndex);
|
|
let rowBackwardT0 = readT0BgField(all, "T0B", rowIndex);
|
|
if (rowForwardT0 !== "" && rowBackwardT0 !== ""
|
|
&& rowForwardT0.split(/\s+/).length != rowBackwardT0.split(/\s+/).length) {
|
|
errors.push(rowLabel + " t0 override needs the same number of forward and backward values.");
|
|
}
|
|
|
|
// Data ranges are independent of the background mode: a row either
|
|
// overrides the common pairs or inherits them, and a partial pair is shown.
|
|
let rowFStart = readT0BgField(all, "DataFStart", rowIndex);
|
|
let rowFEnd = readT0BgField(all, "DataFEnd", rowIndex);
|
|
let rowBStart = readT0BgField(all, "DataBStart", rowIndex);
|
|
let rowBEnd = readT0BgField(all, "DataBEnd", rowIndex);
|
|
appendT0BgPairValidation(errors, rowLabel + " forward data range override", [
|
|
{ label: "first bin", value: rowFStart },
|
|
{ label: "last bin", value: rowFEnd }
|
|
], false);
|
|
appendT0BgPairValidation(errors, rowLabel + " backward data range override", [
|
|
{ label: "first bin", value: rowBStart },
|
|
{ label: "last bin", value: rowBEnd }
|
|
], false);
|
|
if (rowFStart === "") {
|
|
rowFStart = readT0BgCommonField(all, "DataFStart");
|
|
}
|
|
if (rowFEnd === "") {
|
|
rowFEnd = readT0BgCommonField(all, "DataFEnd");
|
|
}
|
|
if (rowBStart === "") {
|
|
rowBStart = readT0BgCommonField(all, "DataBStart");
|
|
}
|
|
if (rowBEnd === "") {
|
|
rowBEnd = readT0BgCommonField(all, "DataBEnd");
|
|
}
|
|
appendT0BgPairValidation(errors, rowLabel + " effective forward data range", [
|
|
{ label: "first bin", value: rowFStart },
|
|
{ label: "last bin", value: rowFEnd }
|
|
], false);
|
|
appendT0BgPairValidation(errors, rowLabel + " effective backward data range", [
|
|
{ label: "first bin", value: rowBStart },
|
|
{ label: "last bin", value: rowBEnd }
|
|
], false);
|
|
|
|
let rowMode = readT0BgField(all, "BgMode", rowIndex);
|
|
// With "Use common", row background fields are intentionally ignored.
|
|
if (rowMode === "" || rowMode == "common") {
|
|
continue;
|
|
}
|
|
|
|
if (rowMode == "range") {
|
|
let fStart = readT0BgField(all, "BgFStart", rowIndex);
|
|
let fEnd = readT0BgField(all, "BgFEnd", rowIndex);
|
|
let bStart = readT0BgField(all, "BgBStart", rowIndex);
|
|
let bEnd = readT0BgField(all, "BgBEnd", rowIndex);
|
|
appendT0BgPairValidation(errors, rowLabel + " forward background range override", [
|
|
{ label: "first bin", value: fStart },
|
|
{ label: "last bin", value: fEnd }
|
|
], false);
|
|
appendT0BgPairValidation(errors, rowLabel + " backward background range override", [
|
|
{ label: "first bin", value: bStart },
|
|
{ label: "last bin", value: bEnd }
|
|
], false);
|
|
|
|
if (fStart === "" && commonMode == rowMode) {
|
|
fStart = readT0BgCommonField(all, "BgFStart");
|
|
}
|
|
if (fEnd === "" && commonMode == rowMode) {
|
|
fEnd = readT0BgCommonField(all, "BgFEnd");
|
|
}
|
|
if (bStart === "" && commonMode == rowMode) {
|
|
bStart = readT0BgCommonField(all, "BgBStart");
|
|
}
|
|
if (bEnd === "" && commonMode == rowMode) {
|
|
bEnd = readT0BgCommonField(all, "BgBEnd");
|
|
}
|
|
appendT0BgPairValidation(errors, rowLabel + " effective forward background range", [
|
|
{ label: "first bin", value: fStart },
|
|
{ label: "last bin", value: fEnd }
|
|
], true);
|
|
appendT0BgPairValidation(errors, rowLabel + " effective backward background range", [
|
|
{ label: "first bin", value: bStart },
|
|
{ label: "last bin", value: bEnd }
|
|
], true);
|
|
} else if (rowMode == "fixed") {
|
|
let fixedForward = readT0BgField(all, "BgFixF", rowIndex);
|
|
let fixedBackward = readT0BgField(all, "BgFixB", rowIndex);
|
|
appendT0BgPairValidation(errors, rowLabel + " fixed background override", [
|
|
{ label: "forward", value: fixedForward },
|
|
{ label: "backward", value: fixedBackward }
|
|
], false);
|
|
|
|
if (fixedForward === "" && commonMode == rowMode) {
|
|
fixedForward = readT0BgCommonField(all, "BgFixF");
|
|
}
|
|
if (fixedBackward === "" && commonMode == rowMode) {
|
|
fixedBackward = readT0BgCommonField(all, "BgFixB");
|
|
}
|
|
appendT0BgPairValidation(errors, rowLabel + " effective fixed background", [
|
|
{ label: "forward", value: fixedForward },
|
|
{ label: "backward", value: fixedBackward }
|
|
], true);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (errors.length > 0) {
|
|
return({
|
|
ok: 0,
|
|
message: "Fix t0/Bg overrides before continuing:\n- " + errors.join("\n- ")
|
|
});
|
|
}
|
|
|
|
return({
|
|
ok: 1,
|
|
message: ""
|
|
});
|
|
}
|
|
|
|
function applyT0BgOverridesToMSR(msrText, all, runs) {
|
|
if (!msrText || typeof msrText !== "string") {
|
|
return msrText;
|
|
}
|
|
|
|
let fitType = getFitType(all || {});
|
|
let runList = runs || arrayRunNumbers(all ? all.runNumbers : "");
|
|
if (fitType !== 2 || !runList || runList.length < 2) {
|
|
return msrText;
|
|
}
|
|
if (!hasAnyT0BgOverride(all, fitType, runList.length)) {
|
|
return msrText;
|
|
}
|
|
|
|
let lines = msrText.split(/\r?\n/);
|
|
let output = [];
|
|
let runIndex = -1;
|
|
let replacingRunOverrides = false;
|
|
|
|
for (let line of lines) {
|
|
if (/^\s*RUN\b/.test(line)) {
|
|
runIndex++;
|
|
replacingRunOverrides = runIndex < runList.length;
|
|
output.push(line);
|
|
let overrideLines = buildT0BgRunLines(all, fitType, runIndex);
|
|
for (let overrideLine of overrideLines) {
|
|
output.push(overrideLine);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (/^\s*(FITPARAMETER|THEORY|FUNCTIONS|GLOBAL|COMMANDS|PLOT|FOURIER|STATISTIC)\b/.test(line)) {
|
|
replacingRunOverrides = false;
|
|
}
|
|
|
|
if (replacingRunOverrides && /^(t0|background|backgr\.fix|backgr\.fit|data)\b/.test(line.trim())) {
|
|
continue;
|
|
}
|
|
|
|
output.push(line);
|
|
}
|
|
|
|
return output.join("\n");
|
|
}
|
|
|
|
function clearT0BgOverrides() {
|
|
let tab = document.getElementById("t0Bg");
|
|
if (!tab) {
|
|
return;
|
|
}
|
|
|
|
let commonMode = document.getElementById("t0BgCommonBgMode");
|
|
if (commonMode) {
|
|
if (All.fitAsyType == "SingleHist") {
|
|
commonMode.value = "fit";
|
|
} else {
|
|
commonMode.value = "auto";
|
|
}
|
|
}
|
|
|
|
let rowModeSelects = tab.querySelectorAll("select[id^='t0BgBgMode_']");
|
|
for (let modeSelect of rowModeSelects) {
|
|
modeSelect.value = "common";
|
|
}
|
|
|
|
let inputs = tab.querySelectorAll("input[id^='t0Bg']");
|
|
for (let input of inputs) {
|
|
input.value = "";
|
|
}
|
|
refreshT0BgModeFields();
|
|
prepCFG();
|
|
markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function copyFirstT0BgRowDown() {
|
|
let tab = document.getElementById("t0Bg");
|
|
if (!tab) {
|
|
return;
|
|
}
|
|
|
|
let rows = tab.querySelectorAll("tr[data-t0bg-row]");
|
|
if (rows.length < 2) {
|
|
return;
|
|
}
|
|
|
|
let firstRow = rows[0];
|
|
let firstControls = firstRow.querySelectorAll("input, select");
|
|
for (let rowIndex = 1; rowIndex < rows.length; rowIndex++) {
|
|
let rowControls = rows[rowIndex].querySelectorAll("input, select");
|
|
for (let controlIndex = 0; controlIndex < firstControls.length; controlIndex++) {
|
|
if (rowControls[controlIndex]) {
|
|
rowControls[controlIndex].value = firstControls[controlIndex].value;
|
|
}
|
|
}
|
|
}
|
|
refreshT0BgModeFields();
|
|
prepCFG();
|
|
markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function refreshT0BgModeFields() {
|
|
let tab = document.getElementById("t0Bg");
|
|
if (!tab) {
|
|
return;
|
|
}
|
|
|
|
// The inactive fields are kept in the DOM so switching modes does not erase
|
|
// expert input, but hidden groups are ignored by the MSR generation logic.
|
|
let modeSelects = tab.querySelectorAll("[data-t0bg-mode-source]");
|
|
let detailGroups = tab.querySelectorAll("[data-t0bg-detail]");
|
|
for (let modeSelect of modeSelects) {
|
|
let groupName = modeSelect.getAttribute("data-t0bg-group");
|
|
let selectedMode = modeSelect.value;
|
|
|
|
for (let detailGroup of detailGroups) {
|
|
if (detailGroup.getAttribute("data-t0bg-group") != groupName) {
|
|
continue;
|
|
}
|
|
|
|
let detailMode = detailGroup.getAttribute("data-t0bg-detail");
|
|
let shouldShow = detailMode == selectedMode;
|
|
detailGroup.style.display = shouldShow ? "" : "none";
|
|
|
|
let controls = detailGroup.querySelectorAll("input, select, textarea");
|
|
for (let control of controls) {
|
|
control.disabled = !shouldShow;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function cfgt0Bg(useStoredValues) {
|
|
if (!useStoredValues) {
|
|
prepCFG();
|
|
}
|
|
|
|
let tab = document.getElementById("t0Bg");
|
|
if (!tab) {
|
|
return;
|
|
}
|
|
installSeriesGUIEditCapture();
|
|
|
|
let runs = arrayRunNumbers(All.runNumbers);
|
|
let hists = [];
|
|
if (All.LRBF) {
|
|
hists = All.LRBF.split(",");
|
|
}
|
|
|
|
if (runs.length === 0) {
|
|
tab.innerHTML = "<div class=\"expert-panel\"><strong>No valid runs.</strong>"
|
|
+ "<p>Enter run numbers before configuring t0/background overrides.</p></div>";
|
|
return;
|
|
}
|
|
|
|
let fitType = getFitType(All);
|
|
let html = "<div class=\"expert-panel\">"
|
|
+ "<div class=\"expert-panel-header\">"
|
|
+ "<div><span class=\"action-bar-eyebrow\">Expert overrides</span>"
|
|
+ "<strong>t0 / Background / Data range</strong>"
|
|
+ "<p>Leave fields empty to let musrfit or the data file provide values. "
|
|
+ "Common values are applied to every generated RUN block unless a row overrides them. "
|
|
+ "For grouped histograms, enter space-separated t0 values in histogram order and "
|
|
+ "forward/backward pairs for the data range.</p></div>"
|
|
+ "<div class=\"expert-actions\">"
|
|
+ "<button type=\"button\" onclick=\"copyFirstT0BgRowDown();\">Copy first override down</button>"
|
|
+ "<button type=\"button\" onclick=\"clearT0BgOverrides();\">Clear overrides</button>"
|
|
+ "</div></div>";
|
|
|
|
if (fitType === 0) {
|
|
let commonMode = readT0BgCommonField(All, "BgMode");
|
|
if (commonMode === "") {
|
|
commonMode = defaultT0BgMode(fitType);
|
|
}
|
|
|
|
html += "<div class=\"t0bg-section-title\">Common for all single-histogram RUN blocks</div>"
|
|
+ "<div class=\"t0bg-common-grid\">"
|
|
+ "<label class=\"t0bg-field\">t0"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonT0\" value=\"" + escapeHTML(readT0BgCommonField(All, "T0")) + "\">"
|
|
+ "</label>"
|
|
+ "<label class=\"t0bg-field\">Background mode"
|
|
+ "<select class=\"w100\" id=\"t0BgCommonBgMode\" data-t0bg-mode-source data-t0bg-group=\"common\" onchange=\"refreshT0BgModeFields();\">"
|
|
+ "<option value=\"fit\"" + (commonMode == "fit" ? " selected" : "") + ">Fit NBg parameter</option>"
|
|
+ "<option value=\"auto\"" + (commonMode == "auto" ? " selected" : "") + ">Auto / no line</option>"
|
|
+ "<option value=\"range\"" + (commonMode == "range" ? " selected" : "") + ">Range</option>"
|
|
+ "<option value=\"fixed\"" + (commonMode == "fixed" ? " selected" : "") + ">Fixed</option>"
|
|
+ "</select></label>"
|
|
+ "<label class=\"t0bg-field\" data-t0bg-detail=\"range\" data-t0bg-group=\"common\">Background range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgEnd")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\" data-t0bg-detail=\"fixed\" data-t0bg-group=\"common\">Fixed background"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgFix\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgFix")) + "\">"
|
|
+ "</label>"
|
|
+ "<label class=\"t0bg-field\">Data range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataEnd")) + "\">"
|
|
+ "</span></label></div>"
|
|
+ "<div class=\"t0bg-section-title\">Per-histogram overrides</div>"
|
|
+ "<div class=\"t0bg-table-wrap\"><table class=\"full-table t0bg-table t0bg-table-compact\">"
|
|
+ "<thead><tr><th>Histogram</th><th>t0 override</th><th>Background override</th><th>Data range override</th></tr></thead><tbody>";
|
|
|
|
for (let iHist = 0; iHist < hists.length; iHist++) {
|
|
let rowIndex = iHist;
|
|
let bgMode = readT0BgField(All, "BgMode", rowIndex);
|
|
if (bgMode === "") {
|
|
bgMode = "common";
|
|
}
|
|
let rowGroup = "row-" + rowIndex;
|
|
html += "<tr data-t0bg-row=\"" + rowIndex + "\">"
|
|
+ "<td>" + escapeHTML(hists[iHist].trim()) + "</td>"
|
|
+ "<td><input class=\"input-full\" type=\"text\" id=\"t0BgT0_" + rowIndex + "\" value=\"" + escapeHTML(readT0BgField(All, "T0", rowIndex)) + "\"></td>"
|
|
+ "<td><div class=\"t0bg-bg-control\">"
|
|
+ "<select class=\"w100\" id=\"t0BgBgMode_" + rowIndex + "\" data-t0bg-mode-source data-t0bg-group=\"" + rowGroup + "\" onchange=\"refreshT0BgModeFields();\">"
|
|
+ "<option value=\"common\"" + (bgMode == "common" ? " selected" : "") + ">Use common</option>"
|
|
+ "<option value=\"fit\"" + (bgMode == "fit" ? " selected" : "") + ">Fit NBg parameter</option>"
|
|
+ "<option value=\"auto\"" + (bgMode == "auto" ? " selected" : "") + ">Auto / no line</option>"
|
|
+ "<option value=\"range\"" + (bgMode == "range" ? " selected" : "") + ">Range</option>"
|
|
+ "<option value=\"fixed\"" + (bgMode == "fixed" ? " selected" : "") + ">Fixed</option>"
|
|
+ "</select>"
|
|
+ "<div class=\"t0bg-bg-details\" data-t0bg-detail=\"range\" data-t0bg-group=\"" + rowGroup + "\">"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgStart_" + rowIndex + "\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgField(All, "BgStart", rowIndex)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgEnd_" + rowIndex + "\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgField(All, "BgEnd", rowIndex)) + "\">"
|
|
+ "</span></div>"
|
|
+ "<div class=\"t0bg-bg-details\" data-t0bg-detail=\"fixed\" data-t0bg-group=\"" + rowGroup + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgFix_" + rowIndex + "\" placeholder=\"fixed background\" value=\"" + escapeHTML(readT0BgField(All, "BgFix", rowIndex)) + "\">"
|
|
+ "</div></div></td>"
|
|
+ "<td><span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgDataStart_" + rowIndex + "\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgField(All, "DataStart", rowIndex)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgDataEnd_" + rowIndex + "\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgField(All, "DataEnd", rowIndex)) + "\">"
|
|
+ "</span></td>"
|
|
+ "</tr>";
|
|
}
|
|
html += "</tbody></table></div>";
|
|
} else {
|
|
let commonMode = readT0BgCommonField(All, "BgMode");
|
|
if (commonMode === "") {
|
|
commonMode = defaultT0BgMode(fitType);
|
|
}
|
|
|
|
html += "<div class=\"t0bg-section-title\">Common for all asymmetry RUN blocks</div>"
|
|
+ "<div class=\"t0bg-common-grid\">"
|
|
+ "<label class=\"t0bg-field\">t0"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonT0F\" placeholder=\"forward t0(s)\" value=\"" + escapeHTML(readT0BgCommonField(All, "T0F")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonT0B\" placeholder=\"backward t0(s)\" value=\"" + escapeHTML(readT0BgCommonField(All, "T0B")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\">Background mode"
|
|
+ "<select class=\"w100\" id=\"t0BgCommonBgMode\" data-t0bg-mode-source data-t0bg-group=\"common\" onchange=\"refreshT0BgModeFields();\">"
|
|
+ "<option value=\"auto\"" + (commonMode == "auto" ? " selected" : "") + ">Auto / no line</option>"
|
|
+ "<option value=\"range\"" + (commonMode == "range" ? " selected" : "") + ">Range</option>"
|
|
+ "<option value=\"fixed\"" + (commonMode == "fixed" ? " selected" : "") + ">Fixed</option>"
|
|
+ "</select></label>"
|
|
+ "<label class=\"t0bg-field\" data-t0bg-detail=\"range\" data-t0bg-group=\"common\">Forward background range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgFStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgFStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgFEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgFEnd")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\" data-t0bg-detail=\"range\" data-t0bg-group=\"common\">Backward background range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgBStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgBStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgBEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgBEnd")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\" data-t0bg-detail=\"fixed\" data-t0bg-group=\"common\">Fixed background"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgFixF\" placeholder=\"forward\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgFixF")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonBgFixB\" placeholder=\"backward\" value=\"" + escapeHTML(readT0BgCommonField(All, "BgFixB")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\">Forward data range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataFStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataFStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataFEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataFEnd")) + "\">"
|
|
+ "</span></label>"
|
|
+ "<label class=\"t0bg-field\">Backward data range"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataBStart\" placeholder=\"first\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataBStart")) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgCommonDataBEnd\" placeholder=\"last\" value=\"" + escapeHTML(readT0BgCommonField(All, "DataBEnd")) + "\">"
|
|
+ "</span></label></div>"
|
|
+ "<div class=\"t0bg-section-title\">Per-run overrides</div>"
|
|
+ "<div class=\"t0bg-table-wrap\"><table class=\"full-table t0bg-table t0bg-table-compact\">"
|
|
+ "<thead><tr><th>Run</th><th>t0 override</th><th>Background override</th><th>Data range override</th></tr></thead><tbody>";
|
|
|
|
for (let iRun = 0; iRun < runs.length; iRun++) {
|
|
let bgMode = readT0BgField(All, "BgMode", iRun);
|
|
if (bgMode === "") {
|
|
bgMode = "common";
|
|
}
|
|
let rowGroup = "row-" + iRun;
|
|
html += "<tr data-t0bg-row=\"" + iRun + "\">"
|
|
+ "<td>" + escapeHTML(runs[iRun].toString()) + "</td>"
|
|
+ "<td><span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgT0F_" + iRun + "\" placeholder=\"forward t0(s)\" value=\"" + escapeHTML(readT0BgField(All, "T0F", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgT0B_" + iRun + "\" placeholder=\"backward t0(s)\" value=\"" + escapeHTML(readT0BgField(All, "T0B", iRun)) + "\">"
|
|
+ "</span></td>"
|
|
+ "<td><div class=\"t0bg-bg-control\">"
|
|
+ "<select class=\"w100\" id=\"t0BgBgMode_" + iRun + "\" data-t0bg-mode-source data-t0bg-group=\"" + rowGroup + "\" onchange=\"refreshT0BgModeFields();\">"
|
|
+ "<option value=\"common\"" + (bgMode == "common" ? " selected" : "") + ">Use common</option>"
|
|
+ "<option value=\"auto\"" + (bgMode == "auto" ? " selected" : "") + ">Auto / no line</option>"
|
|
+ "<option value=\"range\"" + (bgMode == "range" ? " selected" : "") + ">Range</option>"
|
|
+ "<option value=\"fixed\"" + (bgMode == "fixed" ? " selected" : "") + ">Fixed</option>"
|
|
+ "</select>"
|
|
+ "<div class=\"t0bg-bg-details\" data-t0bg-detail=\"range\" data-t0bg-group=\"" + rowGroup + "\">"
|
|
+ "<div class=\"t0bg-stack\">"
|
|
+ "<span class=\"t0bg-pair\"><input class=\"input-full\" type=\"text\" id=\"t0BgBgFStart_" + iRun + "\" placeholder=\"F first\" value=\"" + escapeHTML(readT0BgField(All, "BgFStart", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgFEnd_" + iRun + "\" placeholder=\"F last\" value=\"" + escapeHTML(readT0BgField(All, "BgFEnd", iRun)) + "\"></span>"
|
|
+ "<span class=\"t0bg-pair\"><input class=\"input-full\" type=\"text\" id=\"t0BgBgBStart_" + iRun + "\" placeholder=\"B first\" value=\"" + escapeHTML(readT0BgField(All, "BgBStart", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgBEnd_" + iRun + "\" placeholder=\"B last\" value=\"" + escapeHTML(readT0BgField(All, "BgBEnd", iRun)) + "\"></span>"
|
|
+ "</div></div>"
|
|
+ "<div class=\"t0bg-bg-details\" data-t0bg-detail=\"fixed\" data-t0bg-group=\"" + rowGroup + "\">"
|
|
+ "<span class=\"t0bg-pair\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgFixF_" + iRun + "\" placeholder=\"forward\" value=\"" + escapeHTML(readT0BgField(All, "BgFixF", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgBgFixB_" + iRun + "\" placeholder=\"backward\" value=\"" + escapeHTML(readT0BgField(All, "BgFixB", iRun)) + "\">"
|
|
+ "</span></div></div></td>"
|
|
+ "<td><div class=\"t0bg-stack\">"
|
|
+ "<span class=\"t0bg-pair\"><input class=\"input-full\" type=\"text\" id=\"t0BgDataFStart_" + iRun + "\" placeholder=\"F first\" value=\"" + escapeHTML(readT0BgField(All, "DataFStart", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgDataFEnd_" + iRun + "\" placeholder=\"F last\" value=\"" + escapeHTML(readT0BgField(All, "DataFEnd", iRun)) + "\"></span>"
|
|
+ "<span class=\"t0bg-pair\"><input class=\"input-full\" type=\"text\" id=\"t0BgDataBStart_" + iRun + "\" placeholder=\"B first\" value=\"" + escapeHTML(readT0BgField(All, "DataBStart", iRun)) + "\">"
|
|
+ "<input class=\"input-full\" type=\"text\" id=\"t0BgDataBEnd_" + iRun + "\" placeholder=\"B last\" value=\"" + escapeHTML(readT0BgField(All, "DataBEnd", iRun)) + "\"></span>"
|
|
+ "</div></td>"
|
|
+ "</tr>";
|
|
}
|
|
html += "</tbody></table></div>";
|
|
}
|
|
|
|
html += "</div>";
|
|
tab.innerHTML = html;
|
|
refreshT0BgModeFields();
|
|
}
|
|
|
|
// Run-selection parsing. A data set has one main run and may have ADDRUN
|
|
// members joined with +. Commas/ranges create separate data sets.
|
|
function parseRunSelection(runNumbers) {
|
|
// Parse the Runs field into logical data sets. A comma/range/sequence creates
|
|
// independent data sets, while `+` groups physical runs that musrfit should add
|
|
// through ADDRUN. Keeping this structured representation separate prevents an
|
|
// added run from accidentally becoming another msr2data/global-fit run.
|
|
let dataSets = [];
|
|
if (typeof runNumbers !== "string") {
|
|
return dataSets;
|
|
}
|
|
|
|
let text = runNumbers.trim();
|
|
if (text === "") {
|
|
return dataSets;
|
|
}
|
|
|
|
// Whitespace around separators is harmless. Whitespace between two run numbers
|
|
// is not: in URLs an unescaped '+' is decoded as a space, and silently turning
|
|
// `514 515` into run 514515 would be especially dangerous.
|
|
text = text.replace(/\s*([,+:-])\s*/g, "$1");
|
|
if (/\s/.test(text) || /[^\d,:+\-]/.test(text)) {
|
|
return([]);
|
|
}
|
|
|
|
let parts = text.split(',');
|
|
for (let part of parts) {
|
|
if (part === "") {
|
|
return([]);
|
|
}
|
|
|
|
if (part.includes("+")) {
|
|
// Keep summed groups deliberately simple. Ranges/sequences remain valid
|
|
// as independent comma-separated terms, but constructs such as
|
|
// `514-516+520` are rejected instead of assigning an ambiguous meaning.
|
|
let summedRuns = part.split('+');
|
|
if (summedRuns.length < 2
|
|
|| summedRuns.some(function(value) { return !/^\d+$/.test(value); })) {
|
|
return([]);
|
|
}
|
|
let physicalRuns = summedRuns.map(function(value) { return parseInt(value, 10); });
|
|
if (physicalRuns.some(function(run) { return run <= 0; })) {
|
|
return([]);
|
|
}
|
|
dataSets.push({
|
|
main: physicalRuns[0],
|
|
add: physicalRuns.slice(1)
|
|
});
|
|
continue;
|
|
}
|
|
|
|
if (part.includes("-")) {
|
|
let tmp = part.split('-');
|
|
if (tmp.length !== 2 || !/^\d+$/.test(tmp[0]) || !/^\d+$/.test(tmp[1])) {
|
|
return([]);
|
|
}
|
|
let start = parseInt(tmp[0], 10);
|
|
let end = parseInt(tmp[1], 10);
|
|
if (start <= 0 || end < start) {
|
|
return([]);
|
|
}
|
|
for (let run = start; run <= end; run++) {
|
|
dataSets.push({ main: run, add: [] });
|
|
}
|
|
} else if (part.includes(":")) {
|
|
let tmp = part.split(':');
|
|
if (tmp.length !== 3 || tmp.some(function(value) { return !/^\d+$/.test(value); })) {
|
|
return([]);
|
|
}
|
|
let start = parseInt(tmp[0], 10);
|
|
let end = parseInt(tmp[1], 10);
|
|
let step = parseInt(tmp[2], 10);
|
|
// Reject a zero step explicitly; otherwise the expansion loop would
|
|
// never advance. Descending ranges are intentionally not supported.
|
|
if (start <= 0 || end < start || step <= 0) {
|
|
return([]);
|
|
}
|
|
for (let run = start; run <= end; run += step) {
|
|
dataSets.push({ main: run, add: [] });
|
|
}
|
|
} else {
|
|
if (!/^\d+$/.test(part)) {
|
|
return([]);
|
|
}
|
|
let run = parseInt(part, 10);
|
|
if (run <= 0) {
|
|
return([]);
|
|
}
|
|
dataSets.push({ main: run, add: [] });
|
|
}
|
|
}
|
|
|
|
// As before, duplicate run numbers are not rejected. They may be useful for
|
|
// unusual workflows and are best left to musrfit/msr2data to diagnose.
|
|
return dataSets;
|
|
}
|
|
|
|
// Describe how a run selection should be executed without starting any file or
|
|
// process work. Keeping this decision pure lets startFit() route independent
|
|
// series before the legacy template/global preparation path is entered.
|
|
// A `+` group is one logical data set; only comma/range-separated data sets can
|
|
// be coupled through shared fit parameters.
|
|
function planFitExecution(runSelection, sharedFlags, options = {}) {
|
|
let dataSets = typeof runSelection === "string"
|
|
? parseRunSelection(runSelection) : runSelection;
|
|
let validSelection = Array.isArray(dataSets) && dataSets.length > 0
|
|
&& dataSets.every(function(dataSet) {
|
|
return dataSet && Number.isInteger(dataSet.main) && dataSet.main > 0
|
|
&& Array.isArray(dataSet.add)
|
|
&& dataSet.add.every(function(run) {
|
|
return Number.isInteger(run) && run > 0;
|
|
});
|
|
});
|
|
|
|
let sharedParameters = [];
|
|
if (sharedFlags && typeof sharedFlags === "object") {
|
|
sharedParameters = Object.keys(sharedFlags).filter(function(name) {
|
|
return sharedFlags[name] === true;
|
|
});
|
|
}
|
|
sharedParameters.sort();
|
|
|
|
if (!validSelection) {
|
|
return {
|
|
mode: "invalid",
|
|
dataSetCount: 0,
|
|
sharedParameters: sharedParameters,
|
|
reason: "invalid-run-selection"
|
|
};
|
|
}
|
|
|
|
if (dataSets.length === 1) {
|
|
return {
|
|
mode: "single",
|
|
dataSetCount: 1,
|
|
sharedParameters: sharedParameters,
|
|
reason: "one-logical-data-set"
|
|
};
|
|
}
|
|
|
|
// Explicit cross-run constraints are another form of coupling even if they
|
|
// did not originate from a GUI Shared checkbox. This hook will be used for
|
|
// editor-owned/custom MSRs when their constraint inspection is added.
|
|
if (sharedParameters.length > 0 || options.crossRunCoupling === true) {
|
|
return {
|
|
mode: "global",
|
|
dataSetCount: dataSets.length,
|
|
sharedParameters: sharedParameters,
|
|
reason: sharedParameters.length > 0
|
|
? "shared-fit-parameters" : "cross-run-constraint"
|
|
};
|
|
}
|
|
|
|
return {
|
|
mode: "series",
|
|
dataSetCount: dataSets.length,
|
|
sharedParameters: [],
|
|
reason: "independent-data-sets"
|
|
};
|
|
}
|
|
|
|
// Select the Fit-button route from the current GUI state. Editor-owned input is
|
|
// deliberately treated as potentially coupled: arbitrary MSR text can express
|
|
// cross-run relationships that are not represented by the Shared checkboxes.
|
|
function currentFitExecution() {
|
|
if (typeof prepCFG === "function") prepCFG();
|
|
let runSelection = parseRunSelection(All.runNumbers || "");
|
|
let editorOwned = typeof isActiveMSREditorAuthoritative === "function"
|
|
&& isActiveMSREditorAuthoritative();
|
|
return planFitExecution(
|
|
runSelection,
|
|
collectSharedParameterControls(),
|
|
{ crossRunCoupling: editorOwned }
|
|
);
|
|
}
|
|
|
|
function arrayRunNumbers(runNumbers) {
|
|
// Existing callers need the list of logical/main runs. Added physical runs are
|
|
// deliberately omitted here so parameter tables, msr2data, and PLOT indexing
|
|
// continue to operate on data sets rather than on every file being summed.
|
|
return parseRunSelection(runNumbers).map(function(dataSet) {
|
|
return dataSet.main;
|
|
});
|
|
}
|
|
|
|
function legalRunNumbers(runNumbers) {
|
|
// Keystrokes should not open modal alerts. This lightweight character check
|
|
// is used while typing; full structural validation happens when an action is
|
|
// requested so an unfinished value such as "520+" is not treated as an error.
|
|
if (typeof runNumbers !== "string") {
|
|
return false;
|
|
}
|
|
return !/[^\d,:+\-\s]/.test(runNumbers);
|
|
}
|
|
|
|
function legalFunLine(funLine,params) {
|
|
// Validate the expression lexically and leave operator precedence and function
|
|
// arity to musrfit. Tokenizing is important here: deleting '-' would split the
|
|
// valid scientific-notation value 1e-3 into the invalid identifiers "1e" and "3".
|
|
let knowFunctions = ["cos", "sin", "tan", "acos", "asin", "atan", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "exp", "log", "ln", "sqrt", "pow"];
|
|
let knowConstants = ["gamma_mu","pi"];
|
|
let knownNames = [...(Array.isArray(params) ? params : []), ...customParams];
|
|
let allComparisons = [...knowFunctions, ...knowConstants, ...knownNames];
|
|
let expression = typeof funLine === "string" ? funLine.replaceAll(/\s+/g, "") : "";
|
|
let tokenPattern = /(?:(?:\d+\.\d*|\d+|\.\d+)(?:[eE][+\-]?\d+)?|[A-Za-z_][A-Za-z0-9_]*|[+\-*/(),])/y;
|
|
let identifierPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
let offset = 0;
|
|
let valid = expression.length > 0;
|
|
|
|
while (valid && offset < expression.length) {
|
|
tokenPattern.lastIndex = offset;
|
|
let match = tokenPattern.exec(expression);
|
|
if (!match || match.index !== offset) {
|
|
valid = false;
|
|
break;
|
|
}
|
|
|
|
let token = match[0];
|
|
offset = tokenPattern.lastIndex;
|
|
if (!identifierPattern.test(token)) continue;
|
|
|
|
// parN and mapN refer to numbered fit parameters and detector maps. B, En,
|
|
// and Tn are run metadata values supported by the musrfit FUNCTIONS block.
|
|
if (/^par\d+$/i.test(token) || /^(?:b|en|t\d+)$/i.test(token)) continue;
|
|
let mapMatch = token.match(/^map(\d+)$/i);
|
|
if (mapMatch && All.msrFunctionMaps && All.msrFunctionMaps[mapMatch[1]]) continue;
|
|
if (allComparisons.indexOf(token) < 0) valid = false;
|
|
}
|
|
|
|
if (!valid) alert("Function line is not valid.\nPlease check!");
|
|
return valid;
|
|
}
|
|
|
|
// Parameter-table and constraint editors.
|
|
function addCustomParam() {
|
|
let input = document.getElementById("newParamName");
|
|
if (!input) return;
|
|
let name = input.value.trim();
|
|
let funSel = document.getElementById("funSel");
|
|
if (!name) {
|
|
alert("Please enter a parameter name.");
|
|
return;
|
|
}
|
|
if (!/^[a-zA-Z]\w*$/.test(name)) {
|
|
alert("Parameter name must start with a letter and contain only letters, digits and underscores.");
|
|
return;
|
|
}
|
|
// Check for duplicates against built-in params (funSel options) and existing custom params
|
|
if (funSel) {
|
|
for (let opt of funSel.options) {
|
|
if (opt.value === name) {
|
|
alert("Parameter '" + name + "' already exists.");
|
|
input.value = "";
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
if (customParams.indexOf(name) >= 0) {
|
|
alert("Parameter '" + name + "' already exists.");
|
|
input.value = "";
|
|
return;
|
|
}
|
|
// Prevent collision with built-in parameter names. Only names that actually
|
|
// appear in a built-in theory block are reserved; defVals-only default-value
|
|
// entries (e.g. Field, Energy) are not theory parameters and may be reused.
|
|
if (musrfitBuiltinParameterNames.has(name)) {
|
|
alert("'" + name + "' is a built-in parameter name. Choose a different name.");
|
|
input.value = "";
|
|
return;
|
|
}
|
|
|
|
customParams.push(name);
|
|
// Set sensible defaults so cfgParams and buildModelBlocks have values to work with
|
|
All["val" + name] = "1.0";
|
|
All["err" + name] = "0.01";
|
|
All["min" + name] = "";
|
|
All["max" + name] = "";
|
|
|
|
// Add option to funSel so it participates in numbering, FITPARAMETER generation,
|
|
// and can be referenced by NAME in function expressions (the parN resolution
|
|
// happens in buildModelBlocks).
|
|
let e = document.createElement("option");
|
|
e.textContent = name;
|
|
e.value = name;
|
|
e.id = "fn" + name;
|
|
funSel.appendChild(e);
|
|
|
|
// Regenerate the parameter table — the new param appears as a row
|
|
cfgParams();
|
|
|
|
updateCustomParamList();
|
|
|
|
input.value = "";
|
|
input.focus();
|
|
if (!suppressSeriesGUIEditCapture) markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function updateCustomParamList() {
|
|
let container = document.getElementById("customParamList");
|
|
if (!container) return;
|
|
container.innerHTML = customParams.map(function(name) {
|
|
return '<span class="custom-param-badge">'
|
|
+ name
|
|
+ ' <button type="button" class="cp-remove" onclick="removeCustomParam(\'' + name + '\')" aria-label="Remove ' + name + '">×</button>'
|
|
+ '</span> ';
|
|
}).join("");
|
|
}
|
|
|
|
function removeCustomParam(name) {
|
|
if (!name) return;
|
|
let idx = customParams.indexOf(name);
|
|
if (idx < 0) return;
|
|
customParams.splice(idx, 1);
|
|
|
|
// Clean up All entries
|
|
delete All["val" + name];
|
|
delete All["err" + name];
|
|
delete All["min" + name];
|
|
delete All["max" + name];
|
|
|
|
// Remove from funSel
|
|
let opt = document.getElementById("fn" + name);
|
|
if (opt) opt.remove();
|
|
|
|
// Remove any function lines that reference this custom param
|
|
// (they would be invalid after the param is gone)
|
|
let funLines = document.getElementsByClassName("funLine");
|
|
let toRemove = [];
|
|
for (let fl of funLines) {
|
|
if (fl.innerText.split("=")[0].trim() === name) {
|
|
toRemove.push(fl);
|
|
}
|
|
}
|
|
for (let fl of toRemove) {
|
|
let selID = "fn" + fl.id.substring(3);
|
|
let optEl = document.getElementById(selID);
|
|
if (optEl) optEl.disabled = false;
|
|
fl.parentNode.remove();
|
|
}
|
|
|
|
// Regenerate parameter table
|
|
cfgParams();
|
|
updateCustomParamList();
|
|
if (!suppressSeriesGUIEditCapture) markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function prepCFG() {
|
|
// Extract IDs and values of relevant parameters from the GUI and store in object All
|
|
let allElem = [];
|
|
allElem = [...document.getElementsByTagName("input"), ...document.getElementsByTagName("select"), ...document.getElementsByTagName("pre")];
|
|
for (let e of allElem) {
|
|
if (e.type == "checkbox") {
|
|
All[e.id] = e.checked ? "1" : "";
|
|
continue;
|
|
}
|
|
if (e.value) {
|
|
All[e.id]=e.value;
|
|
} else {
|
|
All[e.id]=e.innerHTML.replaceAll("<br>","\n").replaceAll(/^\s*\n/gm,"");
|
|
}
|
|
}
|
|
}
|
|
|
|
function cfgConstraints() {
|
|
let funBlock = document.getElementById("funBlock");
|
|
if (funBlock.innerHTML != "") return(1);
|
|
|
|
// update from GUI
|
|
prepCFG();
|
|
let hists = All.LRBF.split(",");
|
|
|
|
let r = document.getElementById("funLineContainer");
|
|
let funLine = document.getElementById("funLine");
|
|
let funSel = document.getElementById("funSel");
|
|
// Clear old lines
|
|
funSel.options.length = 0;
|
|
|
|
for (let i=1; i<=All.numComps; i++) {
|
|
let fitFunc = All["fitFunc"+i];
|
|
if (fitFunc && fitFunc != "") {
|
|
let pars = funcDictionary[fitFunc].pars.slice();
|
|
if ((All.fitAsyType == "Asymmetry" || All.fitAsyType == "AsymmetryGLB") && i == 1 ) {
|
|
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
|
|
// parameters are shared between histograms. Phase is the exception:
|
|
// detector groups can have different electronic/geometric phases, so add
|
|
// one extra phase parameter per additional histogram whenever this model
|
|
// component actually contains Phi. The RUN-block map generated later
|
|
// selects the correct phase for each histogram.
|
|
if (i == 1) {
|
|
for (let iHist = 1; iHist <= hists.length; iHist++) {
|
|
pars.push("NBg"+iHist);
|
|
pars.push("No"+iHist);
|
|
}
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
for (let par of pars) {
|
|
if (All.numComps > 1 && !(par == "Alpha" || /^No\d*$/.test(par) || /^NBg\d*$/.test(par))) {
|
|
// Component indexing normally appends the component number. Preserve
|
|
// the histogram marker on detector-specific phase parameters so, e.g.,
|
|
// component 2 / histogram 3 becomes Phi2H3 rather than PhiH32.
|
|
let histPhase = par.match(/^PhiH(\d+)$/);
|
|
par = histPhase ? "Phi" + i + "H" + histPhase[1] : par + i;
|
|
}
|
|
var e = document.createElement("option");
|
|
e.textContent = par;
|
|
e.value = par;
|
|
e.id = "fn" + par;
|
|
funSel.appendChild(e);
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
function updateTheoryBlock() {
|
|
// update from GUI
|
|
prepCFG();
|
|
let theoryBlock = "";
|
|
for (let i=1; i<=All.numComps; i++) {
|
|
if (i>1) theoryBlock += "\n+\n";
|
|
let fitFunc = All["fitFunc"+i];
|
|
if (fitFunc && fitFunc != "") {
|
|
var theoryBlk1 = funcDictionary[fitFunc].theoryBlk;
|
|
if (All.numComps > 1) {
|
|
// Add index to parameters
|
|
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;
|
|
}
|
|
}
|
|
|
|
document.getElementById("theoFunBlock").innerText = theoryBlock;
|
|
// Update also function line
|
|
cfgConstraints();
|
|
}
|
|
|
|
function addFunLine () {
|
|
let funLine = document.getElementById("funLine").value;
|
|
let funSel = document.getElementById("funSel");
|
|
let params = [];
|
|
for (let opt of funSel.options) {
|
|
params.push(opt.value);
|
|
}
|
|
if (!legalFunLine(funLine,params)) return;
|
|
if (!suppressSeriesGUIEditCapture) markAllCurrentSeriesRunsEdited();
|
|
|
|
if (editingFunId) {
|
|
let funLineEl = document.getElementById(editingFunId);
|
|
let paramName = funLineEl.innerText.split("=")[0].trim();
|
|
funLineEl.innerText = paramName + " = " + funLine;
|
|
funLineEl.classList.remove("funLineEditing");
|
|
document.getElementById("addFunLine").innerText = "Add";
|
|
document.getElementById("funLine").value = "";
|
|
let cancelBtn = document.getElementById("cancelEdit");
|
|
if (cancelBtn) cancelBtn.remove();
|
|
editingFunId = null;
|
|
return;
|
|
}
|
|
|
|
if (funSel.selectedIndex % funSel.options.length < 0 ) return;
|
|
let idPar = "fn" + funSel.value;
|
|
document.getElementById(idPar).disabled = true;
|
|
|
|
let funBlock = document.getElementById("funBlock");
|
|
// Container for the function line and associated buttons
|
|
let singleFun = document.createElement("div");
|
|
singleFun.className = "constraint-line";
|
|
// Add a functions line, keep the parameters as is for now, change for fun+i later
|
|
let singleFunTxt = document.createElement("span");
|
|
singleFunTxt.className = "funLine";
|
|
singleFunTxt.id = "fln" + idPar;
|
|
singleFunTxt.innerText = funSel.value + " = " + funLine;
|
|
singleFun.appendChild(singleFunTxt);
|
|
let lineActions = document.createElement("span");
|
|
lineActions.className = "constraint-line-actions";
|
|
|
|
// Inline SVGs keep these controls independent of external icon fonts.
|
|
let delBtn = document.createElement("button");
|
|
delBtn.type = "button";
|
|
delBtn.className = "constraint-icon-button delBtn";
|
|
delBtn.id = "del" + idPar;
|
|
delBtn.title = "Delete constraint";
|
|
delBtn.setAttribute("aria-label", "Delete constraint");
|
|
delBtn.innerHTML = `
|
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
<path d="M4 7h16"></path>
|
|
<path d="M9 7V4h6v3"></path>
|
|
<path d="M7 7l1 13h8l1-13"></path>
|
|
<path d="M10 11v5"></path>
|
|
<path d="M14 11v5"></path>
|
|
</svg>`;
|
|
delBtn.onclick = function() {
|
|
// Get id for parameter select
|
|
let selID = this.id.substring(3);
|
|
document.getElementById(selID).disabled = false;
|
|
// Delete all elements related to this line
|
|
singleFun.remove();
|
|
};
|
|
// Add edit button
|
|
let edtBtn = document.createElement("button");
|
|
edtBtn.type = "button";
|
|
edtBtn.className = "constraint-icon-button edtBtn";
|
|
edtBtn.id = "edt" + idPar;
|
|
edtBtn.title = "Edit constraint";
|
|
edtBtn.setAttribute("aria-label", "Edit constraint");
|
|
edtBtn.innerHTML = `
|
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
<path d="M4 20l1-4L16.5 4.5a2.1 2.1 0 0 1 3 3L8 19z"></path>
|
|
<path d="M14.5 6.5l3 3"></path>
|
|
</svg>`;
|
|
edtBtn.onclick= function() {
|
|
let selID = this.id.substring(3);
|
|
let funLineEl = document.getElementById("fln" + selID);
|
|
let funLn = funLineEl.innerText.split("=")[1].trim();
|
|
editingFunId = "fln" + selID;
|
|
document.getElementById(selID).selected = true;
|
|
document.getElementById("funLine").value = funLn;
|
|
document.getElementById("funLine").focus();
|
|
document.getElementById("addFunLine").innerText = "Save";
|
|
funLineEl.classList.add("funLineEditing");
|
|
let cancelBtn = document.getElementById("cancelEdit");
|
|
if (!cancelBtn) {
|
|
cancelBtn = document.createElement("button");
|
|
cancelBtn.type = "button";
|
|
cancelBtn.id = "cancelEdit";
|
|
cancelBtn.innerText = "Cancel";
|
|
cancelBtn.onclick = function() {
|
|
let el = document.getElementById(editingFunId);
|
|
if (el) el.classList.remove("funLineEditing");
|
|
document.getElementById("funLine").value = "";
|
|
document.getElementById("addFunLine").innerText = "Add";
|
|
this.remove();
|
|
editingFunId = null;
|
|
};
|
|
document.getElementById("addFunLine").parentNode.appendChild(cancelBtn);
|
|
}
|
|
};
|
|
lineActions.appendChild(edtBtn);
|
|
lineActions.appendChild(delBtn);
|
|
singleFun.appendChild(lineActions);
|
|
funBlock.appendChild(singleFun);
|
|
|
|
// Move to next parameter
|
|
// If next element is already disabled use empty
|
|
funSel.selectedIndex = 1+ funSel.selectedIndex % funSel.options.length;
|
|
if (document.getElementById("fn" + funSel.value).disabled) { funSel.value = "";}
|
|
}
|
|
|
|
// Return the built-in default-value key for a GUI parameter name. Component
|
|
// suffixes are numeric (Phi2, Lam2, ...), while SingleHist detector phases use
|
|
// an additional H<N> suffix (PhiH2 or Phi2H2). Keeping this normalization in one
|
|
// place avoids treating detector-specific phases as unknown custom parameters.
|
|
function defaultParameterKey(parName) {
|
|
let name = parName === undefined || parName === null ? "" : String(parName);
|
|
if (/^Phi(?:\d+)?H\d+$/.test(name)) {
|
|
return "Phi";
|
|
}
|
|
return name.replace(/[0-9]/g, '');
|
|
}
|
|
|
|
// Parse the magnetic field printed by dump_header. The exact label differs
|
|
// slightly between supported file formats (Mag., Magn., Magnetic), so normalize
|
|
// only that field and leave the rest of the header available for future guesses.
|
|
function parseRunHeaderMetadata(headerText) {
|
|
let metadata = { fieldG: null, headerText: String(headerText || "") };
|
|
for (let line of metadata.headerText.split(/\r?\n/)) {
|
|
let match = line.match(/Sample\s+(?:Mag(?:n)?\.?|Magnetic)\s+Field\s*:\s*(.*)$/i);
|
|
if (!match) continue;
|
|
|
|
let valueMatch = match[1].match(/[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?/);
|
|
if (!valueMatch) break;
|
|
let value = Number(valueMatch[0]);
|
|
if (!Number.isFinite(value)) break;
|
|
|
|
let unitMatch = match[1].match(/(?:^|\s)(kG|mT|T|G)(?=\s|;|$)/i);
|
|
let unit = unitMatch ? unitMatch[1].toLowerCase() : "g";
|
|
if (unit == "t") value *= 10000.0;
|
|
else if (unit == "mt") value *= 10.0;
|
|
else if (unit == "kg") value *= 1000.0;
|
|
metadata.fieldG = value;
|
|
break;
|
|
}
|
|
return metadata;
|
|
}
|
|
|
|
function guessMuonFrequencyMHz(metadata) {
|
|
if (!metadata || !Number.isFinite(Number(metadata.fieldG))) return null;
|
|
return Math.abs(Number(metadata.fieldG)) * muonGammaBarMHzPerGauss;
|
|
}
|
|
|
|
function formatInitialParameterGuess(value) {
|
|
if (!Number.isFinite(Number(value))) return "";
|
|
return Number(Number(value).toPrecision(9)).toString();
|
|
}
|
|
|
|
function setConfiguredInitialParameterGuess(enabled, persist) {
|
|
let value = Boolean(enabled);
|
|
let input = typeof document !== "undefined"
|
|
? document.getElementById("guessInitialParameters") : null;
|
|
if (input) input.checked = value;
|
|
if (persist && typeof window !== "undefined" && window.localStorage) {
|
|
try {
|
|
window.localStorage.setItem(guessInitialParametersStorageKey, value ? "1" : "0");
|
|
} catch (error) {
|
|
console.log("Could not persist initial-parameter guessing preference: " + error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function initializeInitialParameterGuessPreference() {
|
|
let enabled = true;
|
|
if (typeof window !== "undefined" && window.localStorage) {
|
|
try {
|
|
let stored = window.localStorage.getItem(guessInitialParametersStorageKey);
|
|
if (stored === "0") enabled = false;
|
|
else if (stored === "1") enabled = true;
|
|
} catch (error) {
|
|
console.log("Could not read initial-parameter guessing preference: " + error.message);
|
|
}
|
|
}
|
|
setConfiguredInitialParameterGuess(enabled, false);
|
|
}
|
|
|
|
// Prompt-peak t0 preference. Enabled by default so eligible bulk data gets t0
|
|
// from the histogram peak before a local fit; users can opt out. LEM and HAL are
|
|
// never affected (see shouldEstimateT0FromPromptPeak in the Electron adapter).
|
|
function setConfiguredT0FromPromptPeak(enabled, persist) {
|
|
let value = Boolean(enabled);
|
|
let input = typeof document !== "undefined"
|
|
? document.getElementById("estimateT0FromPromptPeak") : null;
|
|
if (input) input.checked = value;
|
|
if (persist && typeof window !== "undefined" && window.localStorage) {
|
|
try {
|
|
window.localStorage.setItem(estimateT0FromPromptPeakStorageKey, value ? "1" : "0");
|
|
} catch (error) {
|
|
console.log("Could not persist prompt-peak t0 preference: " + error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function getConfiguredT0FromPromptPeak() {
|
|
if (typeof window !== "undefined" && window.localStorage) {
|
|
try {
|
|
let stored = window.localStorage.getItem(estimateT0FromPromptPeakStorageKey);
|
|
if (stored === "0") return false;
|
|
if (stored === "1") return true;
|
|
} catch (error) {
|
|
console.log("Could not read prompt-peak t0 preference: " + error.message);
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function initializeT0FromPromptPeak() {
|
|
setConfiguredT0FromPromptPeak(getConfiguredT0FromPromptPeak(), false);
|
|
}
|
|
|
|
function frequencyGuessTargets() {
|
|
let table = typeof document !== "undefined" ? document.getElementById("Params") : null;
|
|
if (!table || !table.querySelectorAll) return [];
|
|
|
|
let targets = [];
|
|
for (let row of table.querySelectorAll("tr[data-plot-parameter]")) {
|
|
if (defaultParameterKey(row.dataset.plotParameter) != "Frq") continue;
|
|
let parameterName = row.id && row.id.startsWith("row") ? row.id.substring(3) : "";
|
|
let input = parameterName ? document.getElementById("val" + parameterName) : null;
|
|
if (!parameterName || !input) continue;
|
|
targets.push({ parameterName: parameterName, originalValue: input.value });
|
|
}
|
|
return targets;
|
|
}
|
|
|
|
// When a FUNCTIONS constraint expresses the Larmor frequency as a field
|
|
// parameter times gamma_mu (e.g. `Frq = gamma_mu * Pfield`), the frequency is
|
|
// derived and the free variable is the field. Invert the relation so the field
|
|
// parameter is initialized from the header field instead of guessing Frq.
|
|
function parseFrequencyReverseExpression(expr) {
|
|
if (!expr) return null;
|
|
let fwd = expr.match(/^\s*gamma_mu\s*\*\s*([A-Za-z]\w*)\s*$/i);
|
|
if (fwd) return fwd[1];
|
|
let rev = expr.match(/^\s*([A-Za-z]\w*)\s*\*\s*gamma_mu\s*$/i);
|
|
if (rev) return rev[1];
|
|
return null;
|
|
}
|
|
|
|
function frequencyReverseTargets() {
|
|
let reverse = [];
|
|
if (typeof document === "undefined" || !document.getElementsByClassName) return reverse;
|
|
for (let el of document.getElementsByClassName("funLine")) {
|
|
let line = el.innerText;
|
|
let eq = line.indexOf("=");
|
|
if (eq < 0) continue;
|
|
let lhs = line.slice(0, eq).trim();
|
|
if (defaultParameterKey(lhs) != "Frq") continue;
|
|
let fieldParam = parseFrequencyReverseExpression(line.slice(eq + 1).trim());
|
|
if (!fieldParam) continue;
|
|
let valueInput = document.getElementById("val" + fieldParam);
|
|
if (!valueInput) continue;
|
|
reverse.push({ parameterName: fieldParam, originalValue: valueInput.value });
|
|
}
|
|
return reverse;
|
|
}
|
|
|
|
function applyFieldLinkedFrequencyGuess(metadata, reverse) {
|
|
let fieldG = metadata ? Number(metadata.fieldG) : NaN;
|
|
if (!Number.isFinite(fieldG)) return false;
|
|
let changed = false;
|
|
let magnitude = Math.abs(fieldG);
|
|
for (let target of reverse || []) {
|
|
let valueInput = document.getElementById("val" + target.parameterName);
|
|
if (!valueInput || valueInput.value !== target.originalValue) continue;
|
|
let valueText = formatInitialParameterGuess(magnitude);
|
|
if (!valueText) continue;
|
|
valueInput.value = valueText;
|
|
All["val" + target.parameterName] = valueText;
|
|
// Keep the existing 1% step convention. At exactly zero field retain the
|
|
// existing non-zero step so the field does not accidentally become fixed.
|
|
if (magnitude > 0) {
|
|
let stepText = formatInitialParameterGuess(magnitude * 0.01);
|
|
let stepInput = document.getElementById("err" + target.parameterName);
|
|
if (stepInput && stepText) {
|
|
stepInput.value = stepText;
|
|
All["err" + target.parameterName] = stepText;
|
|
}
|
|
}
|
|
changed = true;
|
|
}
|
|
return changed;
|
|
}
|
|
|
|
function applyFrequencyGuess(metadata, targets) {
|
|
let frequency = guessMuonFrequencyMHz(metadata);
|
|
if (!Number.isFinite(frequency)) return false;
|
|
let valueText = formatInitialParameterGuess(frequency);
|
|
if (!valueText) return false;
|
|
|
|
for (let target of targets || []) {
|
|
let valueInput = document.getElementById("val" + target.parameterName);
|
|
if (!valueInput || valueInput.value !== target.originalValue) continue;
|
|
valueInput.value = valueText;
|
|
All["val" + target.parameterName] = valueText;
|
|
|
|
// Keep the existing 1% step convention. At exactly zero field retain the
|
|
// existing non-zero step so Frq does not accidentally become fixed.
|
|
if (frequency > 0) {
|
|
let stepText = formatInitialParameterGuess(frequency * 0.01);
|
|
let stepInput = document.getElementById("err" + target.parameterName);
|
|
if (stepInput && stepText) {
|
|
stepInput.value = stepText;
|
|
All["err" + target.parameterName] = stepText;
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function applyHeaderBasedInitialGuess(metadata, targets) {
|
|
let fieldG = metadata ? Number(metadata.fieldG) : NaN;
|
|
let modelChanged = false;
|
|
|
|
// The default oscillating model is useful for transverse fields, but below
|
|
// 1 G its frequency is effectively zero and a plain exponential is the more
|
|
// useful starting point. Only an automatic single-component default may be
|
|
// changed here; explicit model choices remain authoritative.
|
|
if (automaticInitialFitModel && Number.isFinite(fieldG)) {
|
|
let components = getFitComponentValues();
|
|
let currentModel = components.length == 1 ? components[0] : "";
|
|
let automaticModels = ["Exponential", "ExponentialCos"];
|
|
let desiredModel = Math.abs(fieldG) < zeroFieldThresholdGauss
|
|
? "Exponential" : "ExponentialCos";
|
|
|
|
if (automaticModels.includes(currentModel) && currentModel != desiredModel) {
|
|
let modelSelect = document.getElementById("fitFunc1");
|
|
if (modelSelect) {
|
|
modelSelect.value = desiredModel;
|
|
All.fitFunc1 = desiredModel;
|
|
clearTabs(false);
|
|
targets = frequencyGuessTargets();
|
|
modelChanged = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Once a constraint expresses Frq as gamma_mu times a field parameter, that
|
|
// field parameter is the free variable: initialize it from the header field
|
|
// instead of guessing Frq directly.
|
|
let reverse = frequencyReverseTargets();
|
|
if (reverse.length > 0) {
|
|
return applyFieldLinkedFrequencyGuess(metadata, reverse) || modelChanged;
|
|
}
|
|
|
|
return applyFrequencyGuess(metadata, targets) || modelChanged;
|
|
}
|
|
|
|
function dumpHeaderRequestFromRunDirective(runLine) {
|
|
let fields = String(runLine || "").trim().split(/\s+/);
|
|
if (fields.length < 5 || fields[0] != "RUN") return null;
|
|
|
|
let formatKey = fields[4].toUpperCase();
|
|
let formats = {
|
|
"MUSR-ROOT": { dumpFormat: "MusrRoot", extension: ".root" },
|
|
"PSI-BIN": { dumpFormat: "PSI-BIN", extension: ".bin" },
|
|
"PSI-MDU": { dumpFormat: "PSI-MDU", extension: ".mdu" },
|
|
"MUD": { dumpFormat: "MUD", extension: ".msr" },
|
|
"NEXUS": { dumpFormat: "NeXus", extension: ".nxs" }
|
|
};
|
|
let info = formats[formatKey];
|
|
if (!info) return null;
|
|
|
|
let filePath = fields[1];
|
|
let platform = window.MusRFlowPlatform;
|
|
if (platform && typeof platform.resolveDataFile === 'function') {
|
|
let localPath = platform.resolveDataFile(filePath);
|
|
if (localPath) return { filePath: localPath, fileFormat: info.dumpFormat };
|
|
}
|
|
if (info.extension && !filePath.toLowerCase().endsWith(info.extension)) {
|
|
filePath += info.extension;
|
|
}
|
|
return { filePath: filePath, fileFormat: info.dumpFormat };
|
|
}
|
|
|
|
function updateInitialParameterGuessFirstRun(firstRun) {
|
|
let run = firstRun === undefined || firstRun === null ? "" : String(firstRun);
|
|
if (!run) return false;
|
|
|
|
let state = initialParameterGuessState;
|
|
if (!state.firstRun) {
|
|
state.firstRun = run;
|
|
return false;
|
|
}
|
|
if (state.firstRun == run) return false;
|
|
|
|
state.firstRun = run;
|
|
state.generation++;
|
|
state.metadataKey = "";
|
|
state.metadata = null;
|
|
return true;
|
|
}
|
|
|
|
// Runs are edited outside the parameter tab. Rebuild an existing parameter
|
|
// table after a committed valid change so appended runs can inherit the
|
|
// preceding run immediately. A changed first run is also a new initialization
|
|
// context, therefore discard the old header and allow one fresh guess.
|
|
function handleRunSelectionChange(runNumbers) {
|
|
let runs = arrayRunNumbers(runNumbers || "");
|
|
// The chips mirror the last committed selection, so capture it BEFORE the
|
|
// re-render below clears it. Falls back to the committed snapshot.
|
|
let previousSelection = collectSeriesChipRuns();
|
|
if (previousSelection.length === 0 && Array.isArray(window.MusrfitSeriesLastSelection)) {
|
|
previousSelection = window.MusrfitSeriesLastSelection.slice();
|
|
}
|
|
installSeriesGUIEditCapture();
|
|
updateSeriesActionVisibility();
|
|
if (!runs.length) {
|
|
window.MusrfitSeriesLastSelection = [];
|
|
return;
|
|
}
|
|
|
|
updateInitialParameterGuessFirstRun(runs[0]);
|
|
|
|
let table = typeof document !== "undefined" ? document.getElementById("Params") : null;
|
|
if (table && table.querySelector && table.querySelector("tr[data-plot-parameter]")) {
|
|
cfgParams();
|
|
}
|
|
|
|
// Committing a run selection rebuilds RUN blocks for newly selected data
|
|
// sets. Only those (plus the previous pair boundary on a high-end append)
|
|
// need refitting; unchanged data sets keep the chip state they had.
|
|
markSeriesRunSelectionEdited(runs, previousSelection);
|
|
window.MusrfitSeriesLastSelection = runs.slice();
|
|
}
|
|
|
|
// The per-run series action controls live in the Runs tab and only apply to the
|
|
// independent-series route (≥2 data sets with no shared parameters). Show or
|
|
// hide the row and (re)render the chips each time the run selection or the
|
|
// Shared checkboxes change so the chips always mirror the current set of runs.
|
|
// Rendering preserves explicit choices for data sets whose full identity did
|
|
// not change.
|
|
function updateSeriesActionVisibility() {
|
|
if (typeof document === "undefined") return;
|
|
installSeriesGUIEditCapture();
|
|
let row = document.getElementById("seriesActionsRow");
|
|
if (!row) return;
|
|
let input = document.getElementById("runNumbers");
|
|
let dataSets = input && input.value
|
|
? parseRunSelection(input.value) : parseRunSelection(All.runNumbers || "");
|
|
let multiRun = dataSets.length > 1;
|
|
let anyShared = false;
|
|
let sharedFlags = collectSharedParameterControls();
|
|
for (let key in sharedFlags) {
|
|
if (/^sh/.test(key) && sharedFlags[key] === true) {
|
|
anyShared = true;
|
|
break;
|
|
}
|
|
}
|
|
let seriesEligible = multiRun && !anyShared;
|
|
row.hidden = !seriesEligible;
|
|
if (seriesEligible) {
|
|
renderSeriesActionChips(dataSets);
|
|
}
|
|
}
|
|
|
|
// Render one clickable chip per data set. Each chip's <select>-style state
|
|
// cycles reuse → refit → skip → reuse. The action is stored/read back purely
|
|
// from the DOM by collectSeriesActionOverrides(). The "All" selector next to
|
|
// the chips sets every chip to one action at once.
|
|
function renderSeriesActionChips(dataSets) {
|
|
if (typeof document === "undefined") return;
|
|
let container = document.getElementById("seriesActionChips");
|
|
if (!container) return;
|
|
|
|
// Rebuilding is triggered by several unrelated GUI changes. Preserve the
|
|
// user's explicit action by the full logical data-set identity, including
|
|
// ADDRUN members; a changed group must not inherit an action accidentally.
|
|
let previousActions = {};
|
|
if (typeof container.querySelectorAll === "function") {
|
|
for (let previousChip of container.querySelectorAll(".series-action-chip")) {
|
|
let key = previousChip.dataset.seriesKey || previousChip.dataset.run || "";
|
|
let action = previousChip.dataset.action;
|
|
if (key && (action == "reuse" || action == "refit" || action == "skip")) {
|
|
previousActions[key] = action;
|
|
}
|
|
}
|
|
}
|
|
container.innerHTML = "";
|
|
let chipLabel = {};
|
|
for (let dataSet of (dataSets || [])) {
|
|
let run = normalizeSeriesDataSet(dataSet);
|
|
if (!run) continue;
|
|
let text = seriesDataSetText(run);
|
|
let action = previousActions[text] || "reuse";
|
|
let chip = document.createElement("button");
|
|
chip.type = "button";
|
|
chip.className = "series-action-chip";
|
|
chip.dataset.run = String(run.main);
|
|
chip.dataset.seriesKey = text;
|
|
chip.dataset.action = action;
|
|
chip.title = text + " — series action. Click to cycle: reuse → refit → skip";
|
|
chip.textContent = text + " · " + action;
|
|
chipLabel[text] = text;
|
|
chip.onclick = function() {
|
|
let cycle = { reuse: "refit", refit: "skip", skip: "reuse" };
|
|
let next = cycle[this.dataset.action] || "reuse";
|
|
this.dataset.action = next;
|
|
this.textContent = (chipLabel[this.dataset.seriesKey] || "")
|
|
+ " · " + next;
|
|
};
|
|
container.appendChild(chip);
|
|
}
|
|
|
|
let bulk = document.getElementById("seriesActionAll");
|
|
if (bulk) {
|
|
bulk.value = "";
|
|
bulk.onchange = function() {
|
|
let target = this.value;
|
|
for (let chip of container.querySelectorAll(".series-action-chip")) {
|
|
if (target == "reuse" || target == "refit" || target == "skip") {
|
|
chip.dataset.action = target;
|
|
chip.textContent = (chipLabel[chip.dataset.seriesKey] || "")
|
|
+ " · " + target;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
}
|
|
|
|
// Read every visible chip back as an explicit user choice. Keeping "reuse" in
|
|
// the map matters for recent converged runs: automatic classification would
|
|
// conservatively refit them, while the user's choice should accept the result.
|
|
function collectSeriesActionOverrides() {
|
|
let overrides = {};
|
|
if (typeof document === "undefined") return overrides;
|
|
let container = document.getElementById("seriesActionChips");
|
|
if (!container || !container.querySelectorAll) return overrides;
|
|
for (let chip of container.querySelectorAll(".series-action-chip")) {
|
|
let run = Number(chip.dataset.run || 0);
|
|
let action = chip.dataset.action;
|
|
if (run > 0 && (action == "reuse" || action == "refit" || action == "skip")) {
|
|
overrides[run] = action;
|
|
}
|
|
}
|
|
return overrides;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Series fit edit capture
|
|
// ---------------------------------------------------------------------------
|
|
//
|
|
// Independent-series reuse decides purely from identity, convergence, and data
|
|
// maturity on disk. A user edit in the live GUI (a parameter value, the range,
|
|
// the theory, t0/background overrides, or a new run selection) is invisible to
|
|
// that decision, so an edited run would silently be "reused" with stale files.
|
|
// These helpers mark edited data sets and force the next plan to rebuild them
|
|
// from the GUI. The marker clears once a refit successfully rebuilds the run.
|
|
|
|
function setSeriesActionChipAction(run, action) {
|
|
if (typeof document === "undefined") return;
|
|
if (action != "reuse" && action != "refit" && action != "skip") return;
|
|
let container = document.getElementById("seriesActionChips");
|
|
if (!container || typeof container.querySelectorAll !== "function") return;
|
|
let wanted = Number(run);
|
|
for (let chip of container.querySelectorAll(".series-action-chip")) {
|
|
if (!chip || !chip.dataset) continue;
|
|
if (Number(chip.dataset.run) === wanted) {
|
|
chip.dataset.action = action;
|
|
chip.textContent = (chip.dataset.seriesKey || String(wanted)) + " · " + action;
|
|
}
|
|
}
|
|
}
|
|
|
|
function markSeriesRunParametersEdited(run) {
|
|
let number = Number(run || 0);
|
|
if (!Number.isInteger(number) || number <= 0) return;
|
|
if (!window.MusrfitSeriesEditedRuns) window.MusrfitSeriesEditedRuns = {};
|
|
window.MusrfitSeriesEditedRuns[number] = true;
|
|
setSeriesActionChipAction(number, "refit");
|
|
}
|
|
|
|
function markAllCurrentSeriesRunsEdited() {
|
|
// Read the currently selected run numbers so every edited data set is forced
|
|
// to rebuild on the next series plan.
|
|
let source = "";
|
|
if (typeof document !== "undefined" && document.getElementById) {
|
|
let input = document.getElementById("runNumbers");
|
|
if (input && input.value) source = input.value;
|
|
}
|
|
if (source === "") source = All.runNumbers || "";
|
|
let runs = [];
|
|
for (let dataSet of parseRunSelection(source)) runs.push(dataSet.main);
|
|
for (let run of Array.from(new Set(runs))) markSeriesRunParametersEdited(run);
|
|
}
|
|
|
|
// The chip row mirrors the last committed selection: each chip carries its data
|
|
// set's main run in dataset.run and chips are only re-rendered when the run
|
|
// selection (or shared-parameter layout) changes. Reading them back gives the
|
|
// previous selection for the run-list diff without a dedicated undo store.
|
|
function collectSeriesChipRuns() {
|
|
let runs = [];
|
|
if (typeof document === "undefined" || !document.getElementById) return runs;
|
|
let container = document.getElementById("seriesActionChips");
|
|
if (!container || typeof container.querySelectorAll !== "function") return runs;
|
|
for (let chip of container.querySelectorAll(".series-action-chip")) {
|
|
if (!chip || !chip.dataset) continue;
|
|
let run = Number(chip.dataset.run || 0);
|
|
if (Number.isInteger(run) && run > 0) runs.push(run);
|
|
}
|
|
return runs;
|
|
}
|
|
|
|
// A run-selection change only rebuilds RUN blocks for data sets that entered
|
|
// the selection; unchanged data sets keep whatever chip action they had. The
|
|
// previous selection is diffed against the new one:
|
|
// - runs that left the selection lose any edit marker (their chips vanish),
|
|
// - runs added to the selection are new and must refit,
|
|
// - on a high-end append (e.g. 2759-2760 -> 2759-2761) the largest run that
|
|
// was already present becomes the new pair boundary and conservatively
|
|
// refits too, so at most the appended tail plus that boundary flip.
|
|
// Any other GUI edit (parameters, ranges, t0/Bg) still marks every run.
|
|
function markSeriesRunSelectionEdited(newRuns, previousRuns) {
|
|
let wanted = new Set((Array.isArray(newRuns) ? newRuns : []).map(Number));
|
|
let previous = (Array.isArray(previousRuns) ? previousRuns : [])
|
|
.map(Number)
|
|
.filter(function(run) { return Number.isInteger(run) && run > 0; });
|
|
previous = Array.from(new Set(previous));
|
|
|
|
if (previous.length === 0) {
|
|
// No reference selection to diff against: every data set is new.
|
|
for (let run of wanted) markSeriesRunParametersEdited(run);
|
|
return;
|
|
}
|
|
|
|
let previousSet = new Set(previous);
|
|
for (let oldRun of previous) {
|
|
if (!wanted.has(oldRun)) clearSeriesRunParametersEdited(oldRun);
|
|
}
|
|
|
|
let appended = [];
|
|
let maxNew = -Infinity;
|
|
for (let run of newRuns) {
|
|
let number = Number(run);
|
|
if (!Number.isInteger(number) || number <= 0) continue;
|
|
maxNew = Math.max(maxNew, number);
|
|
if (!previousSet.has(number)) {
|
|
markSeriesRunParametersEdited(number);
|
|
appended.push(number);
|
|
}
|
|
}
|
|
|
|
if (appended.length > 0 && appended.includes(maxNew)) {
|
|
let remaining = previous.filter(function(run) { return wanted.has(run); });
|
|
if (remaining.length > 0) {
|
|
markSeriesRunParametersEdited(Math.max.apply(null, remaining));
|
|
}
|
|
}
|
|
}
|
|
|
|
function clearSeriesRunParametersEdited(run) {
|
|
let number = Number(run || 0);
|
|
if (!Number.isInteger(number) || number <= 0) return;
|
|
if (window.MusrfitSeriesEditedRuns) {
|
|
delete window.MusrfitSeriesEditedRuns[number];
|
|
}
|
|
// A refit rebuilt this run from the live GUI, so the marker is gone and the
|
|
// run's chip returns to the reusable default.
|
|
setSeriesActionChipAction(number, "reuse");
|
|
}
|
|
|
|
function collectSeriesGUIEditedRuns() {
|
|
let edited = {};
|
|
for (let key of Object.keys(window.MusrfitSeriesEditedRuns || {})) {
|
|
let run = Number(key);
|
|
if (Number.isInteger(run) && run > 0) edited[run] = true;
|
|
}
|
|
return edited;
|
|
}
|
|
|
|
// One shared installer for all three editing surfaces. Each container is
|
|
// guarded so repeated calls (cfgParams/cfgt0Bg rerun constantly) are idempotent.
|
|
function installSeriesGUIEditCapture() {
|
|
if (typeof document === "undefined" || !document.getElementById) return;
|
|
let containers = [
|
|
["Params", handleSeriesParameterEditEvent, true],
|
|
["Runs", handleSeriesRunsTabEditEvent, false],
|
|
["t0Bg", handleSeriesT0BgEditEvent, false]
|
|
];
|
|
for (let entry of containers) {
|
|
let element = document.getElementById(entry[0]);
|
|
if (!element || typeof element.setAttribute !== "function"
|
|
|| typeof element.addEventListener !== "function") continue;
|
|
if (element.getAttribute("data-series-edit-capture")) continue;
|
|
element.setAttribute("data-series-edit-capture", "1");
|
|
element.addEventListener("input", entry[1]);
|
|
if (!entry[2]) element.addEventListener("change", entry[1]);
|
|
}
|
|
}
|
|
|
|
function handleSeriesParameterEditEvent(event) {
|
|
if (suppressSeriesGUIEditCapture) return;
|
|
let target = event && event.target;
|
|
if (!target || typeof target.closest !== "function" || target.tagName !== "INPUT") return;
|
|
if (!target.classList || !target.classList.contains("parameter-value-input")) return;
|
|
let row = target.closest("tr");
|
|
if (!row || typeof row.getAttribute !== "function") return;
|
|
if (row.getAttribute("data-shared") === "1") {
|
|
// The single shared row feeds every data set.
|
|
markAllCurrentSeriesRunsEdited();
|
|
} else if (row.getAttribute("data-run")) {
|
|
markSeriesRunParametersEdited(Number(row.getAttribute("data-run")));
|
|
}
|
|
}
|
|
|
|
function handleSeriesRunsTabEditEvent(event) {
|
|
if (suppressSeriesGUIEditCapture) return;
|
|
let target = event && event.target;
|
|
if (!target || typeof target.id !== "string") return;
|
|
let id = target.id;
|
|
// Run selection is handled by its own committed-change path; the series
|
|
// action controls only choose chip states. Plot/FFT/RRF view controls do not
|
|
// affect the fitted result and are deliberately left out.
|
|
if (id == "runNumbers" || id == "seriesActionAll") return;
|
|
let fitAffecting = {
|
|
Tis: 1, Tfs: 1, BINS: 1, selYear: 1, instrName: 1,
|
|
minType: 1, errEst: 1, minStrategy: 1, fitObjective: 1, saveMinuit: 1
|
|
};
|
|
if (!(id in fitAffecting)) return;
|
|
markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function handleSeriesT0BgEditEvent(event) {
|
|
if (suppressSeriesGUIEditCapture) return;
|
|
markAllCurrentSeriesRunsEdited();
|
|
}
|
|
|
|
function logInitialParameterGuessHeader(headerRequest, metadata, cached) {
|
|
console.log("Initial parameter guess header" + (cached ? " (cached)" : "") + ":", {
|
|
file: headerRequest ? headerRequest.filePath : "",
|
|
format: headerRequest ? headerRequest.fileFormat : "",
|
|
fieldG: metadata ? metadata.fieldG : null,
|
|
header: metadata ? metadata.headerText : ""
|
|
});
|
|
}
|
|
|
|
function scheduleInitialParameterGuess() {
|
|
let state = initialParameterGuessState;
|
|
let runs = arrayRunNumbers(All.runNumbers || "");
|
|
if (!runs.length) return Promise.resolve(false);
|
|
|
|
// Catch programmatic run changes as well as changes committed in the Runs
|
|
// input. This must happen before the one-shot generation check.
|
|
updateInitialParameterGuessFirstRun(runs[0]);
|
|
if (state.appliedGeneration == state.generation) return Promise.resolve(false);
|
|
|
|
let targets = frequencyGuessTargets();
|
|
// No parameter rows means the table has not actually been populated yet.
|
|
let table = typeof document !== "undefined" ? document.getElementById("Params") : null;
|
|
if (!table || !table.querySelector || !table.querySelector("tr[data-plot-parameter]")) {
|
|
return Promise.resolve(false);
|
|
}
|
|
|
|
// Once this parameter-table generation exists, guessing is a one-shot
|
|
// initialization. Enabling the preference later must not modify user values.
|
|
state.appliedGeneration = state.generation;
|
|
let components = getFitComponentValues();
|
|
let canSelectAutomaticModel = automaticInitialFitModel && components.length == 1
|
|
&& ["Exponential", "ExponentialCos"].includes(components[0]);
|
|
let guessInput = typeof document !== "undefined"
|
|
? document.getElementById("guessInitialParameters") : null;
|
|
if ((guessInput ? guessInput.checked : true) === false
|
|
|| (targets.length == 0 && !canSelectAutomaticModel)) {
|
|
return Promise.resolve(false);
|
|
}
|
|
|
|
let headerRequest = null;
|
|
try {
|
|
headerRequest = dumpHeaderRequestFromRunDirective(runFileNameAuto(
|
|
runs[0], All.selYear, All.instrName, All.dataRoot
|
|
));
|
|
} catch (error) {
|
|
console.warn("Initial parameter guess: " + error.message);
|
|
return Promise.resolve(false);
|
|
}
|
|
if (!headerRequest) return Promise.resolve(false);
|
|
let metadataKey = headerRequest.filePath + "|" + headerRequest.fileFormat;
|
|
|
|
let generation = state.generation;
|
|
let originalParameters = JSON.stringify(buildFitParameterSyncSpec({}));
|
|
state.pendingDownloadGuess = null;
|
|
let useMetadata = function(metadata) {
|
|
if (state.generation != generation) return false;
|
|
return applyHeaderBasedInitialGuess(metadata, targets);
|
|
};
|
|
|
|
if (state.metadataKey == metadataKey && state.metadata) {
|
|
logInitialParameterGuessHeader(headerRequest, state.metadata, true);
|
|
return Promise.resolve(useMetadata(state.metadata));
|
|
}
|
|
|
|
if (typeof loadRunHeaderText !== "function") return Promise.resolve(false);
|
|
let consumeHeader = function(result) {
|
|
if (!result || !result.ok) {
|
|
state.pendingDownloadGuess = { generation: generation, parameters: originalParameters };
|
|
if (result && result.error) console.warn("Initial parameter guess: " + result.error);
|
|
return false;
|
|
}
|
|
let metadata = parseRunHeaderMetadata(result.text || "");
|
|
state.metadataKey = metadataKey;
|
|
state.metadata = metadata;
|
|
logInitialParameterGuessHeader(headerRequest, metadata, false);
|
|
return useMetadata(metadata);
|
|
};
|
|
|
|
try {
|
|
let result = loadRunHeaderText(headerRequest.filePath, headerRequest.fileFormat);
|
|
if (result && typeof result.then === "function") {
|
|
return result.then(consumeHeader).catch(function(error) {
|
|
console.warn("Initial parameter guess: " + error.message);
|
|
return false;
|
|
});
|
|
}
|
|
return Promise.resolve(consumeHeader(result));
|
|
} catch (error) {
|
|
console.warn("Initial parameter guess: " + error.message);
|
|
state.pendingDownloadGuess = { generation: generation, parameters: originalParameters };
|
|
return Promise.resolve(false);
|
|
}
|
|
}
|
|
|
|
function parameterPlotNamesInTable() {
|
|
let table = document.getElementById("Params");
|
|
if (!table || !table.querySelectorAll) return [];
|
|
|
|
let names = [];
|
|
for (let row of table.querySelectorAll("tr[data-plot-parameter]")) {
|
|
let name = row.dataset.plotParameter;
|
|
if (name && !names.includes(name)) names.push(name);
|
|
}
|
|
return names;
|
|
}
|
|
|
|
// Build a parameter-data table (the same columnar format musrfit/msr2data
|
|
// emit as `*_par.dat`) directly from the live parameter table. This lets the
|
|
// user plot the current table values even when no fit has produced an on-disk
|
|
// artifact yet (e.g. after restoring a shared configuration or when every run
|
|
// was skipped). One row is emitted per run, with the RUN number as the x-axis
|
|
// fallback and one column per (base) parameter carrying that run's value.
|
|
function buildParameterDataFromTable() {
|
|
let table = document.getElementById("Params");
|
|
if (!table || typeof table.querySelector !== "function"
|
|
|| !table.querySelector("tr[data-plot-parameter]")) {
|
|
return null;
|
|
}
|
|
|
|
// Parameter inputs do not update All on every keystroke. Synchronize them
|
|
// here so an inline plot reflects the numbers currently visible in the table
|
|
// rather than the values from its last rebuild.
|
|
prepCFG();
|
|
let runs = arrayRunNumbers(All.runNumbers || "");
|
|
if (!runs.length) return null;
|
|
|
|
let baseParams = parameterPlotNamesInTable();
|
|
if (!baseParams.length) return null;
|
|
|
|
let columns = ["RUN"].concat(baseParams);
|
|
let lines = [columns.join("\t")];
|
|
for (let run of runs) {
|
|
let runSuffix = runSuffixFromFile(run, All.instrName, All.selYear, All.dataRoot);
|
|
let row = [run];
|
|
for (let base of baseParams) {
|
|
let shared = All["sh" + base] === "1";
|
|
let qualified = shared ? base : base + "_" + runSuffix;
|
|
let value = All["val" + qualified];
|
|
let text = (value === undefined || value === null) ? "" : String(value).trim();
|
|
row.push(text);
|
|
}
|
|
lines.push(row.join("\t"));
|
|
}
|
|
return lines.join("\n") + "\n";
|
|
}
|
|
|
|
function updateParameterPlotSelectionUI() {
|
|
if (typeof document === "undefined") return;
|
|
let table = document.getElementById("Params");
|
|
if (!table || !table.querySelectorAll) return;
|
|
|
|
let selected = new Set(selectedParameterPlotNames);
|
|
for (let row of table.querySelectorAll("tr[data-plot-parameter]")) {
|
|
let isSelected = selected.has(row.dataset.plotParameter);
|
|
row.classList.toggle("parameter-row-selected", isSelected);
|
|
row.setAttribute("aria-selected", isSelected ? "true" : "false");
|
|
}
|
|
|
|
let button = document.getElementById("plotSelectedParameters");
|
|
if (!button) return;
|
|
let hasData = Boolean(window.MusrfitJob && window.MusrfitJob.parameterDataPath);
|
|
// A populated parameter table is itself a valid plot source: the fit may
|
|
// not have produced an on-disk _par.dat artifact yet (for example after
|
|
// restoring a shared configuration or when every run was skipped), but the
|
|
// live table values can still be plotted. This lets the user plot whenever
|
|
// the table is built, regardless of whether a fit has just run.
|
|
let tablePopulated = parameterPlotNamesInTable().length > 0;
|
|
let canPlot = hasData || tablePopulated;
|
|
// Keep the action available when fit data exist so a click with no
|
|
// selection can explain what the user needs to do.
|
|
button.disabled = !canPlot;
|
|
button.textContent = "Plot parameters...";
|
|
if (!canPlot) {
|
|
button.title = "Build the parameter table first";
|
|
} else if (selectedParameterPlotNames.length === 0) {
|
|
button.title = "Select one or more parameter names";
|
|
} else {
|
|
button.title = "Plot the selected parameters using one common x axis";
|
|
}
|
|
}
|
|
|
|
function selectParameterForPlot(event, parameterName) {
|
|
let names = parameterPlotNamesInTable();
|
|
if (!names.includes(parameterName)) return;
|
|
|
|
let ctrl = event && (event.ctrlKey || event.metaKey);
|
|
let shift = event && event.shiftKey;
|
|
if (shift && parameterPlotSelectionAnchor && names.includes(parameterPlotSelectionAnchor)) {
|
|
let start = names.indexOf(parameterPlotSelectionAnchor);
|
|
let end = names.indexOf(parameterName);
|
|
let range = names.slice(Math.min(start, end), Math.max(start, end) + 1);
|
|
selectedParameterPlotNames = ctrl
|
|
? Array.from(new Set(selectedParameterPlotNames.concat(range))) : range;
|
|
} else if (ctrl) {
|
|
if (selectedParameterPlotNames.includes(parameterName)) {
|
|
selectedParameterPlotNames = selectedParameterPlotNames.filter(function(name) {
|
|
return name !== parameterName;
|
|
});
|
|
} else {
|
|
selectedParameterPlotNames = selectedParameterPlotNames.concat([parameterName]);
|
|
}
|
|
} else {
|
|
// A second plain click on an already selected parameter deselects it.
|
|
// Plain-clicking a different parameter keeps the familiar single-select
|
|
// behaviour; Ctrl/Cmd and Shift still provide multi-selection.
|
|
selectedParameterPlotNames = selectedParameterPlotNames.includes(parameterName)
|
|
? selectedParameterPlotNames.filter(function(name) {
|
|
return name !== parameterName;
|
|
})
|
|
: [parameterName];
|
|
}
|
|
|
|
parameterPlotSelectionAnchor = parameterName;
|
|
updateParameterPlotSelectionUI();
|
|
}
|
|
|
|
// Determine the parameter-data source used by the "Plot parameters..." action.
|
|
// A real fit prefers the generated on-disk artifact; otherwise the live
|
|
// parameter table provides inline data. Returns null when neither is available.
|
|
function resolveCurrentParameterPlotSource() {
|
|
let job = window.MusrfitJob || {};
|
|
if (job.parameterDataPath) {
|
|
return { source: job.parameterDataPath, resultName: job.resultMSR || job.parameterDataPath };
|
|
}
|
|
if (typeof buildParameterDataFromTable !== "function") return null;
|
|
let inline = buildParameterDataFromTable();
|
|
if (!inline) return null;
|
|
return { source: { kind: "inline", text: inline, label: "Parameter table" }, resultName: "parameter-table" };
|
|
}
|
|
|
|
function openSelectedParameterPlot() {
|
|
if (selectedParameterPlotNames.length === 0) {
|
|
alert("Please select at least one parameter to plot.");
|
|
return;
|
|
}
|
|
if (typeof showMusrfitParameterAxisDialog !== "function") return;
|
|
|
|
let resolved = resolveCurrentParameterPlotSource();
|
|
if (!resolved) {
|
|
alert("The parameter table is not populated. Build the table before plotting.");
|
|
return;
|
|
}
|
|
let resultName = String(resolved.resultName).split(/[?#]/)[0].split(/[\\/]/).pop();
|
|
showMusrfitParameterAxisDialog(
|
|
resolved.source,
|
|
resultName || "",
|
|
selectedParameterPlotNames.slice()
|
|
);
|
|
}
|
|
|
|
// Spreading a shared parameter back into independent per-run copies seeds every
|
|
// copy from the shared row's current values. This makes share -> edit -> unshare
|
|
// predictable: all runs start identically while each remains an independent fit
|
|
// parameter (no global fit). Naming follows the same runSuffixFromFile rule used
|
|
// when the per-run rows are built in cfgParams.
|
|
function seedRunParametersFromShared(baseParName) {
|
|
let seed = {};
|
|
for (let prefix of ["val", "err", "min", "max"]) {
|
|
let input = document.getElementById(prefix + baseParName);
|
|
seed[prefix] = input && input.value !== undefined
|
|
? input.value : (All[prefix + baseParName] ?? "");
|
|
}
|
|
for (let run of arrayRunNumbers(All.runNumbers)) {
|
|
let suffix = runSuffixFromFile(run, All.instrName, All.selYear, All.dataRoot);
|
|
for (let prefix of ["val", "err", "min", "max"]) {
|
|
All[prefix + baseParName + "_" + suffix] = seed[prefix];
|
|
}
|
|
}
|
|
}
|
|
|
|
function cfgParams() {
|
|
/*
|
|
The parameters list can be taken as the non-disabled parameters in funSel
|
|
*/
|
|
// update from GUI
|
|
prepCFG();
|
|
|
|
// Get names of parameters
|
|
let funSel = document.getElementById("funSel");
|
|
// An imported MSR's own parameter order overrides the catalogue order so the
|
|
// table (and anything generated from it) matches the file the user started
|
|
// from. Idempotent: a catalogue order with no imported structure is a no-op.
|
|
if (typeof applyImportedMSRParameterOrder === "function") {
|
|
applyImportedMSRParameterOrder(funSel);
|
|
}
|
|
// Without an imported order the table follows the physical role sequence
|
|
// (asymmetry, damping, frequency, phase, alphas, normalization; custom
|
|
// parameters last) so the parameter rows and the generated FITPARAMETER
|
|
// block present the measurable quantities first.
|
|
if (typeof applyPhysicalParameterOrder === "function") {
|
|
applyPhysicalParameterOrder(funSel);
|
|
}
|
|
// Get theory block
|
|
let theoryBlk = document.getElementById("theoFunBlock").innerHTML.replaceAll("<br>","\n");
|
|
let runs = arrayRunNumbers(All.runNumbers);
|
|
// Parameter counter
|
|
let i = 1;
|
|
// Run counter
|
|
let iRun = 0;
|
|
let previousRunSuffix = "";
|
|
let paramTab = document.getElementById("Params");
|
|
paramTab.innerHTML = "";
|
|
installSeriesGUIEditCapture();
|
|
|
|
// Keep parameter-specific actions with the parameter table rather than in
|
|
// the main Fit/Plot action bar, where "Plot" means spectra.
|
|
let plotToolbar = document.createElement("div");
|
|
plotToolbar.className = "parameter-table-toolbar";
|
|
let plotTitle = document.createElement("strong");
|
|
plotTitle.className = "parameter-table-toolbar-title";
|
|
plotTitle.textContent = "Parameters";
|
|
let plotButton = document.createElement("button");
|
|
plotButton.type = "button";
|
|
plotButton.id = "plotSelectedParameters";
|
|
plotButton.textContent = "Plot parameters...";
|
|
plotButton.onclick = openSelectedParameterPlot;
|
|
plotToolbar.appendChild(plotTitle);
|
|
plotToolbar.appendChild(plotButton);
|
|
paramTab.appendChild(plotToolbar);
|
|
|
|
let paramTable = document.createElement("table");
|
|
let multiRun = runs.length > 1;
|
|
// Keep the parameter table self-contained in ZGUI.css so the GUI does not
|
|
// depend on W3.CSS for borders, hover feedback, header colors, or sizing.
|
|
paramTable.className = "parameter-table";
|
|
if (multiRun) {
|
|
paramTable.className += " parameter-table-multi";
|
|
}
|
|
let headerRow = "<tr class='parameter-table-header'><th>#</th><th>Param</th>";
|
|
if (multiRun) headerRow += "<th>Shared</th>";
|
|
headerRow += "<th>Value</th><th>Error</th><th>Min</th><th>Max</th></tr>";
|
|
paramTable.innerHTML = headerRow;
|
|
|
|
for (let run of runs) {
|
|
let runSuffix = runSuffixFromFile(run, All.instrName, All.selYear, All.dataRoot);
|
|
for (let opt of funSel.options) {
|
|
|
|
if (!opt.disabled) {
|
|
let parName = opt.value;
|
|
let baseParName = parName; // save before _runNumber suffix
|
|
let cparName = defaultParameterKey(parName);
|
|
// If the parameter is shared leave it without _runNumber
|
|
// No need to make map line for template file, the msr2data global option takes care of that.
|
|
let shPar = false;
|
|
if (multiRun) {
|
|
let shEl = document.getElementById("sh" + baseParName);
|
|
if (shEl) {
|
|
shPar = shEl.checked;
|
|
} else {
|
|
// Restore from All when the checkbox hasn't been created yet (first build)
|
|
shPar = All["sh" + baseParName] === "1";
|
|
}
|
|
}
|
|
|
|
// A non-shared fit parameter is always run-qualified, also for one run.
|
|
// This keeps the GUI table, single-run MSR and msr2data global output on
|
|
// exactly the same parameter-name convention.
|
|
if (!shPar) {
|
|
parName += "_" + runSuffix;
|
|
}
|
|
|
|
if (!shPar || (shPar && iRun == 0)) {
|
|
let trPar = paramTable.insertRow(-1);
|
|
trPar.id = "row" + parName;
|
|
let tdParNum = trPar.insertCell(-1);
|
|
tdParNum.innerText = i;
|
|
tdParNum.className = "parameter-label-cell";
|
|
let tdParName = trPar.insertCell(-1);
|
|
tdParName.innerText = parName;
|
|
tdParName.className = "parameter-label-cell parameter-select-cell";
|
|
trPar.dataset.plotParameter = baseParName;
|
|
// Row provenance for series-edit capture: run-specific rows carry
|
|
// their data set, the single shared row marks all data sets.
|
|
if (shPar) {
|
|
trPar.dataset.shared = "1";
|
|
} else {
|
|
trPar.dataset.run = String(run);
|
|
}
|
|
tdParName.tabIndex = 0;
|
|
tdParName.setAttribute("role", "button");
|
|
tdParName.title = "Select " + baseParName + " for plotting";
|
|
let _paramSelectLongPressTimer = null;
|
|
let _paramSelectLongPressTriggered = false;
|
|
function _clearParamSelectLongPress() {
|
|
if (_paramSelectLongPressTimer) {
|
|
clearTimeout(_paramSelectLongPressTimer);
|
|
_paramSelectLongPressTimer = null;
|
|
}
|
|
}
|
|
tdParName.addEventListener("touchstart", function() {
|
|
_paramSelectLongPressTriggered = false;
|
|
_clearParamSelectLongPress();
|
|
_paramSelectLongPressTimer = setTimeout(function() {
|
|
_paramSelectLongPressTriggered = true;
|
|
selectParameterForPlot({ ctrlKey: true, shiftKey: false, preventDefault: function(){}, stopPropagation: function(){} }, baseParName);
|
|
}, 550);
|
|
}, { passive: true });
|
|
tdParName.addEventListener("touchmove", function() {
|
|
_clearParamSelectLongPress();
|
|
}, { passive: true });
|
|
tdParName.addEventListener("touchend", function(event) {
|
|
_clearParamSelectLongPress();
|
|
if (_paramSelectLongPressTriggered) {
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
_paramSelectLongPressTriggered = false;
|
|
}
|
|
});
|
|
tdParName.addEventListener("touchcancel", function() {
|
|
_clearParamSelectLongPress();
|
|
_paramSelectLongPressTriggered = false;
|
|
});
|
|
tdParName.addEventListener("contextmenu", function(event) {
|
|
if (_paramSelectLongPressTriggered) {
|
|
event.preventDefault();
|
|
}
|
|
});
|
|
tdParName.onclick = function(event) {
|
|
if (_paramSelectLongPressTriggered) {
|
|
_paramSelectLongPressTriggered = false;
|
|
return;
|
|
}
|
|
selectParameterForPlot(event, baseParName);
|
|
};
|
|
tdParName.onkeydown = function(event) {
|
|
if (event.key === "Enter" || event.key === " ") {
|
|
event.preventDefault();
|
|
selectParameterForPlot(event, baseParName);
|
|
}
|
|
};
|
|
|
|
if (multiRun && iRun == 0) {
|
|
let tdSh = trPar.insertCell(-1);
|
|
let chk = document.createElement("input");
|
|
chk.type = "checkbox";
|
|
chk.id = "sh" + baseParName;
|
|
chk.checked = shPar;
|
|
chk.onchange = function() {
|
|
All["sh" + baseParName] = this.checked ? "1" : "";
|
|
if (!this.checked) {
|
|
// Unsharing seeds each per-run copy from the shared row's
|
|
// current values (seedRunParametersFromShared reads the live
|
|
// table inputs, so edits on the shared row are honored).
|
|
seedRunParametersFromShared(baseParName);
|
|
}
|
|
cfgParams();
|
|
updateSeriesActionVisibility();
|
|
markAllCurrentSeriesRunsEdited();
|
|
};
|
|
tdSh.appendChild(chk);
|
|
} else if (multiRun) {
|
|
// Per-run copies get an empty cell to keep column alignment
|
|
trPar.insertCell(-1);
|
|
}
|
|
|
|
let tdParVal = trPar.insertCell(-1);
|
|
|
|
// if a parameter already has a value use it, otherwise take defaults
|
|
// this means that if I set parameters in All object, they will be used
|
|
// Custom parameters (not in defVals) get generic defaults 1.0 / 0.01
|
|
if (All["val" + parName] === undefined
|
|
|| sanitizedMSRParameterNumber(All["val" + parName]) === "") {
|
|
// A newly appended run starts from the immediately preceding
|
|
// run's current values. Header guessing is reserved for the
|
|
// initial table and explicit theory changes.
|
|
let previousParName = (!shPar && previousRunSuffix)
|
|
? baseParName + "_" + previousRunSuffix : "";
|
|
if (previousParName && All["val" + previousParName] !== undefined
|
|
&& All["val" + previousParName] !== "") {
|
|
for (let prefix of ["val", "err", "min", "max"]) {
|
|
All[prefix + parName] = All[prefix + previousParName] !== undefined
|
|
? All[prefix + previousParName] : "";
|
|
}
|
|
} 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] = defErr;
|
|
All["min" + parName] = "";
|
|
All["max" + parName] = "";
|
|
}
|
|
}
|
|
|
|
tdParVal.innerHTML = '<input class="parameter-value-input" type="text" id="val' + parName + '" value="' + All["val" + parName] + '"/>';
|
|
let tdParErr = trPar.insertCell(-1);
|
|
let errValue = sanitizedMSRParameterError(
|
|
All["err" + parName], All["val" + parName]
|
|
);
|
|
if (errValue !== All["err" + parName]) All["err" + parName] = errValue;
|
|
tdParErr.innerHTML = '<input class="parameter-value-input" type="text" id="err' + parName + '" value="' + errValue + '"/>';
|
|
let tdParMin = trPar.insertCell(-1);
|
|
let safeMin = sanitizedMSRParameterNumber(All["min" + parName]);
|
|
All["min" + parName] = safeMin;
|
|
tdParMin.innerHTML = '<input class="parameter-value-input" type="text" id="min' + parName + '" value="' + safeMin + '"/>';
|
|
let tdParMax = trPar.insertCell(-1);
|
|
let safeMax = sanitizedMSRParameterNumber(All["max" + parName]);
|
|
All["max" + parName] = safeMax;
|
|
tdParMax.innerHTML = '<input class="parameter-value-input" type="text" id="max' + parName + '" value="' + safeMax + '"/>';
|
|
i++;
|
|
}
|
|
}
|
|
} // params
|
|
previousRunSuffix = runSuffix;
|
|
iRun++;
|
|
} // runs
|
|
paramTab.appendChild(paramTable);
|
|
|
|
let initialGuess = scheduleInitialParameterGuess();
|
|
|
|
// Drop selections that are no longer part of the current theory/parameter table.
|
|
let availablePlotNames = parameterPlotNamesInTable();
|
|
selectedParameterPlotNames = selectedParameterPlotNames.filter(function(name) {
|
|
return availablePlotNames.includes(name);
|
|
});
|
|
if (!availablePlotNames.includes(parameterPlotSelectionAnchor)) parameterPlotSelectionAnchor = "";
|
|
updateParameterPlotSelectionUI();
|
|
return initialGuess;
|
|
}
|
|
|
|
// MSR generation is split into small block builders so tests can verify each
|
|
// section independently of filesystem/process execution.
|
|
function collectFitConfigFromDOM() {
|
|
let funSel = document.getElementById("funSel");
|
|
// A parameter order imported from an MSR file must survive into every
|
|
// regenerated MSR (single fit, series, or template). Replaying it here keeps
|
|
// the DOM select and the generated FITPARAMETER block in the file's order.
|
|
if (typeof applyImportedMSRParameterOrder === "function") {
|
|
applyImportedMSRParameterOrder(funSel);
|
|
}
|
|
// Without an imported order the FITPARAMETER block follows the physical role
|
|
// sequence so msr2data columns are presented with the measurable quantities
|
|
// first (asymmetry, damping, frequency, phase, alphas, normalization).
|
|
if (typeof applyPhysicalParameterOrder === "function") {
|
|
applyPhysicalParameterOrder(funSel);
|
|
}
|
|
let funOptions = [];
|
|
if (funSel) {
|
|
for (let opt of funSel.options) {
|
|
funOptions.push({
|
|
value: opt.value,
|
|
disabled: opt.disabled
|
|
});
|
|
}
|
|
}
|
|
|
|
let funLines = [];
|
|
for (let funLine of document.getElementsByClassName("funLine")) {
|
|
funLines.push(funLine.innerText);
|
|
}
|
|
|
|
let sharedFlags = {};
|
|
for (let e of document.querySelectorAll("input[type='checkbox'][id^='sh']")) {
|
|
sharedFlags[e.id.substring(2)] = e.checked;
|
|
}
|
|
|
|
return {
|
|
all: Object.assign({}, All),
|
|
funOptions: funOptions,
|
|
funLines: funLines,
|
|
sharedFlags: sharedFlags
|
|
};
|
|
}
|
|
|
|
function createMSR() {
|
|
let msrFile = buildMSR(collectFitConfigFromDOM());
|
|
rememberGeneratedMSR(msrFile);
|
|
return msrFile;
|
|
}
|
|
|
|
function buildMSR(config) {
|
|
config = config || {};
|
|
let all = config.all || {};
|
|
let fitType = getFitType(all);
|
|
let runSelection = parseRunSelection(all.runNumbers || "");
|
|
let model = buildModelBlocks(config, fitType);
|
|
let numRuns = runSelection.length;
|
|
let blocks = {
|
|
runNumbers: all.runNumbers,
|
|
parameterBlock: model.parameterBlock,
|
|
theoryBlock: model.theoryBlock,
|
|
functionsBlock: model.functionsBlock,
|
|
globalBlock: buildGlobalBlock(all, fitType),
|
|
runBlock: model.runBlock,
|
|
commandsBlock: buildCommandsBlock(all),
|
|
plotBlock: buildPlotBlock(all, fitType, numRuns),
|
|
fourierBlock: buildFourierBlock(all)
|
|
};
|
|
|
|
let msrFile = renderMSRTemplate(blocks);
|
|
if (runSelection.length === 1 && runSelection[0].add.length > 0) {
|
|
// With one logical data set there is no msr2data expansion step, so ADDRUN
|
|
// can be written directly into the runnable MSR. Multi-data-set templates
|
|
// intentionally stay free of ADDRUN because msr2data copies such lines
|
|
// unchanged into every generated RUN block.
|
|
msrFile = applyAddRunsToMSR(
|
|
msrFile, runSelection, all.selYear, all.instrName, all.dataRoot
|
|
);
|
|
}
|
|
return msrFile;
|
|
}
|
|
|
|
function getFitType(all) {
|
|
if (all.fitAsyType == "SingleHist") return 0;
|
|
return 2;
|
|
}
|
|
|
|
function buildGlobalBlock(all, fitType) {
|
|
let blk = "fittype " + fitType + "\n"
|
|
+ "fit " + all.Tis + " " + all.Tfs + "\n"
|
|
+ "packing " + all.BINS + "\n";
|
|
if (all.globalDataRange && Array.isArray(all.globalDataRange) && all.globalDataRange.length >= 2) {
|
|
blk += "data " + all.globalDataRange.join(" ") + "\n";
|
|
}
|
|
return blk;
|
|
}
|
|
|
|
function buildCommandsBlock(all) {
|
|
all = all || {};
|
|
|
|
// Keep command construction in one place so the compact GUI controls map to
|
|
// a deterministic COMMANDS block. Missing fields retain the historical safe
|
|
// defaults, which also keeps older saved GUI state and tests compatible.
|
|
let commands = [];
|
|
let strategy = all.minStrategy !== undefined ? all.minStrategy.toString() : "";
|
|
if (["0", "1", "2"].includes(strategy)) {
|
|
commands.push("STRATEGY " + strategy);
|
|
}
|
|
|
|
if (all.fitObjective == "MAX_LIKELIHOOD") {
|
|
commands.push("MAX_LIKELIHOOD");
|
|
}
|
|
|
|
let minimizer = ["MINIMIZE", "MIGRAD", "SIMPLEX"].includes(all.minType)
|
|
? all.minType : "MINIMIZE";
|
|
commands.push(minimizer);
|
|
|
|
// HESSE+MINOS is represented as two native musrfit commands rather than a
|
|
// synthetic command. "None" deliberately omits both error calculations.
|
|
let errorMode = all.errEst || "HESSE";
|
|
if (errorMode == "HESSE" || errorMode == "HESSE_MINOS") {
|
|
commands.push("HESSE");
|
|
}
|
|
if (errorMode == "MINOS" || errorMode == "HESSE_MINOS") {
|
|
commands.push("MINOS");
|
|
}
|
|
|
|
// SAVE used to be unconditional. Default it to enabled when the new checkbox
|
|
// is absent so older callers still produce the same COMMANDS block.
|
|
let saveEnabled = all.saveMinuit === undefined
|
|
|| all.saveMinuit === true
|
|
|| all.saveMinuit === "1";
|
|
if (saveEnabled) {
|
|
commands.push("SAVE");
|
|
}
|
|
|
|
return commands.join("\n");
|
|
}
|
|
|
|
function buildFourierBlock(all) {
|
|
all = all || {};
|
|
|
|
// A disabled FFT has no native musrfit representation: musrfit rejects an
|
|
// empty block and `plot none`. Represent "FFT off" by omitting the whole
|
|
// FOURIER section (renderMSRTemplate drops the header for an empty block).
|
|
let plotType = all.fftType !== undefined ? String(all.fftType).trim() : "";
|
|
if (plotType === "none" || plotType === "off") {
|
|
return "";
|
|
}
|
|
|
|
// Build the FOURIER block as native directives rather than concatenating a
|
|
// fixed template. Optional range/phase-correction controls can then disappear
|
|
// cleanly when left at their defaults without producing empty directives.
|
|
let lines = [];
|
|
let dcCorrected = all.fftDCCorrect === true
|
|
|| all.fftDCCorrect === 1
|
|
|| all.fftDCCorrect === "1";
|
|
|
|
lines.push("units " + (all.fftUnits || "Gauss"));
|
|
lines.push("fourier_power " + (all.fftPower || "12"));
|
|
// Emit DC correction explicitly so behavior does not depend on a site-specific
|
|
// musrfit startup-file default.
|
|
lines.push("dc-corrected " + (dcCorrected ? "TRUE" : "FALSE"));
|
|
lines.push("apodization " + (all.fftApod || "STRONG"));
|
|
lines.push("plot " + (all.fftType || "power"));
|
|
|
|
// Phase is intentionally free-form: musrfit accepts numeric phases as well as
|
|
// parameter/reference expressions such as parN, par(...), and parR(...).
|
|
let phase = all.fftPhase !== undefined ? String(all.fftPhase).trim() : "";
|
|
if (phase) {
|
|
lines.push("phase " + phase);
|
|
}
|
|
|
|
let phaseCorrection = all.fftPhaseCorrection || "off";
|
|
if (phaseCorrection == "all") {
|
|
// Native `all` tells musrfit to use the configured Fourier range.
|
|
lines.push("range_for_phase_correction all");
|
|
} else if (phaseCorrection == "custom") {
|
|
let phaseStart = all.fftPhaseCorrectionStart !== undefined
|
|
? String(all.fftPhaseCorrectionStart).trim() : "";
|
|
let phaseEnd = all.fftPhaseCorrectionEnd !== undefined
|
|
? String(all.fftPhaseCorrectionEnd).trim() : "";
|
|
// The directive requires a complete interval. An unfinished GUI pair is
|
|
// left out rather than writing an invalid one-sided MSR command.
|
|
if (phaseStart && phaseEnd) {
|
|
lines.push("range_for_phase_correction " + phaseStart + " " + phaseEnd);
|
|
}
|
|
}
|
|
|
|
let rangeStart = all.fftxi !== undefined ? String(all.fftxi).trim() : "";
|
|
let rangeEnd = all.fftxf !== undefined ? String(all.fftxf).trim() : "";
|
|
// Empty FFT limits mean automatic/default musrview behavior. Emit `range` only
|
|
// when both ends are supplied, mirroring the two-value musrfit syntax.
|
|
if (rangeStart && rangeEnd) {
|
|
lines.push("range " + rangeStart + " " + rangeEnd);
|
|
}
|
|
|
|
return lines.join("\n") + "\n";
|
|
}
|
|
|
|
function getRRFPlotConfig(all) {
|
|
all = all || {};
|
|
|
|
// RRF here is a musrview/PLOT transformation, not an RRF fit type. Keeping
|
|
// this normalization separate prevents the GUI toggle from silently changing
|
|
// the numerical fit from type 0/2 to type 1/3.
|
|
let enabled = all.rrfEnabled === true
|
|
|| all.rrfEnabled === 1
|
|
|| all.rrfEnabled === "1";
|
|
if (!enabled) {
|
|
return { enabled: false, valid: true };
|
|
}
|
|
|
|
let frequencyText = all.rrfFrq !== undefined ? String(all.rrfFrq).trim() : "";
|
|
let packingText = all.rrfPack !== undefined ? String(all.rrfPack).trim() : "";
|
|
let phase = all.rrfPhase !== undefined ? String(all.rrfPhase).trim() : "";
|
|
let units = all.rrfUnits !== undefined ? String(all.rrfUnits).trim() : "G";
|
|
let allowedUnits = ["kHz", "MHz", "Mc/s", "G", "T"];
|
|
let frequency = Number(frequencyText);
|
|
let packing = Number(packingText);
|
|
let frequencyValid = frequencyText !== "" && Number.isFinite(frequency) && frequency > 0;
|
|
let packingValid = packingText !== "" && Number.isInteger(packing) && packing > 0;
|
|
let unitsValid = allowedUnits.includes(units);
|
|
|
|
return {
|
|
enabled: true,
|
|
valid: frequencyValid && packingValid && unitsValid,
|
|
frequency: frequencyText,
|
|
frequencyValid: frequencyValid,
|
|
packing: packingText,
|
|
packingValid: packingValid,
|
|
phase: phase,
|
|
units: units,
|
|
unitsValid: unitsValid
|
|
};
|
|
}
|
|
|
|
function buildRRFPlotLines(all) {
|
|
let rrf = getRRFPlotConfig(all);
|
|
if (!rrf.enabled || !rrf.valid) {
|
|
// Action-time validation reports incomplete opt-in settings to the user.
|
|
// The builder itself stays defensive and never writes a partial RRF block.
|
|
return [];
|
|
}
|
|
|
|
let lines = [
|
|
"rrf_freq " + rrf.frequency + " " + rrf.units,
|
|
"rrf_packing " + rrf.packing
|
|
];
|
|
// rrf_phase is optional in the PLOT block; musrfit/musrview uses zero when
|
|
// it is absent. Preserve advanced `parN` references by passing text through.
|
|
if (rrf.phase) {
|
|
lines.push("rrf_phase " + rrf.phase);
|
|
}
|
|
return lines;
|
|
}
|
|
|
|
function buildPlotBlock(all, fitType, numRuns) {
|
|
let plotBlk = "PLOT " + fitType + "\n";
|
|
|
|
let plotRuns = all && Array.isArray(all.plotRuns) && all.plotRuns.length > 0
|
|
? all.plotRuns.map(String)
|
|
: null;
|
|
|
|
if (!plotRuns) {
|
|
let runs = [];
|
|
for (let i = 1; i <= (numRuns || 1); i++) {
|
|
runs.push(i);
|
|
}
|
|
plotRuns = getExpectedPlotRuns(all, runs);
|
|
}
|
|
plotBlk += "runs " + plotRuns.join(" ") + "\n";
|
|
let hasTimeRange = !((all.Tpfs == 0 && all.Tpis == 0) || all.Tpfs == all.Tpis);
|
|
let hasYRange = !((all.Ypfs == 0 && all.Ypis == 0) || all.Ypfs == all.Ypis);
|
|
if (!hasTimeRange && !hasYRange) {
|
|
plotBlk += "use_fit_ranges\n";
|
|
} else {
|
|
// Native PLOT range syntax is: time-min time-max [y-min y-max]. When the
|
|
// user supplies only a Y range, spell out the fit-time range so the four-
|
|
// value directive remains valid while retaining the GUI's "Auto" meaning.
|
|
let timeStart = hasTimeRange ? all.Tpis : all.Tis;
|
|
let timeEnd = hasTimeRange ? all.Tpfs : all.Tfs;
|
|
plotBlk += "range " + timeStart + " " + timeEnd;
|
|
if (hasYRange) {
|
|
plotBlk += " " + all.Ypis + " " + all.Ypfs;
|
|
}
|
|
plotBlk += "\n";
|
|
}
|
|
if (all.VIEWBINS != 0) plotBlk += "view_packing " + all.VIEWBINS + "\n";
|
|
if (all.plotLogX) {
|
|
plotBlk += "logx\n";
|
|
}
|
|
if (all.plotLogY) {
|
|
plotBlk += "logy\n";
|
|
}
|
|
if (all.fitAsyType == "SingleHist" && all.plotLifetimeCorrection) {
|
|
plotBlk += "lifetimecorrection\n";
|
|
}
|
|
|
|
// RRF display settings belong to PLOT. They are emitted only when the user
|
|
// explicitly enables RRF and supplies its required frequency and packing.
|
|
let rrfLines = buildRRFPlotLines(all);
|
|
if (rrfLines.length > 0) {
|
|
plotBlk += rrfLines.join("\n") + "\n";
|
|
}
|
|
return plotBlk;
|
|
}
|
|
|
|
function replaceAllWords(str, word, replacement) {
|
|
const regex = new RegExp('\\b' + word + '\\b', 'g');
|
|
return str.replace(regex, replacement);
|
|
}
|
|
|
|
function replaceWord(str, word, replacement) {
|
|
const regex = new RegExp('\\b' + word + '\\b');
|
|
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;
|
|
|
|
// RUN block
|
|
let runs = arrayRunNumbers(all.runNumbers);
|
|
let runLine = runFileNameAuto(runs[0], all.selYear, all.instrName, all.dataRoot);
|
|
let hists = all.LRBF.split(",");
|
|
let alphaLine = "alpha ";
|
|
let forwLine = "forward " + hists[0];
|
|
let backLine = "backward " + hists[1];
|
|
let runBlk = "";
|
|
|
|
// 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.
|
|
// For multiple physical runs this still describes only the template RUNs;
|
|
// 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;
|
|
let paramBlk = "";
|
|
// Non shared parameters counter
|
|
//let imap = 0;
|
|
// Functions counter and intial block
|
|
let ifun = 0;
|
|
let funBlock = "";
|
|
for (let funLine of funLines) {
|
|
funBlock += funLine + "\n";
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
for (let opt of funOptions) {
|
|
let parName = opt.value;
|
|
if (opt.disabled) {
|
|
// There is a function here, use it
|
|
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
|
|
let rplcTh = "";
|
|
// Replacement string in funBlock
|
|
let rplcFn = "";
|
|
let parLine = " " + i + " " + parName;
|
|
// If the parameter is shared leave it without _runNumber
|
|
// No need to make map line for template file, the msr2data global option takes care of that.
|
|
let shPar = runs.length > 1 && !!sharedFlags[parName];
|
|
|
|
let singleHistPhase = all.fitAsyType == "SingleHist"
|
|
&& /^Phi(?:\d+)?$/.test(parName)
|
|
&& new RegExp("\\b" + parName + "\\b").test(theoryBlk);
|
|
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 = 1;
|
|
while (occupiedMapNumbers.has(mapNo)) mapNo++;
|
|
occupiedMapNumbers.add(mapNo);
|
|
rplcTh = "map" + mapNo;
|
|
rplcFn = "map" + mapNo;
|
|
singleHistPhaseMaps.push({ baseName: parName, mapNo: mapNo });
|
|
} else {
|
|
rplcTh = i;
|
|
rplcFn = "par"+i;
|
|
}
|
|
if (!shPar) {
|
|
// Non-shared parameters are run-qualified even for a single run.
|
|
let suf = runSuffixFromFile(runs[0], all.instrName, all.selYear, all.dataRoot);
|
|
parLine += "_" + suf;
|
|
}
|
|
let msrParName = parLine.trim().split(/\s+/)[1];
|
|
// Prefer values already shown in the parameter table. These may come from
|
|
// a previous fitted MSR, so regenerating keeps the fit-edit-fit loop intact.
|
|
// Fall back to defVals for built-in params, or 1.0 / 0.01 for custom params
|
|
let defVal = defVals[cparName] ? defVals[cparName].value : 1.0;
|
|
let value = sanitizedMSRParameterValue(
|
|
all["val" + msrParName] ?? all["val" + parName] ?? "", defVal
|
|
);
|
|
let step = sanitizedMSRParameterError(
|
|
all["err" + msrParName] ?? all["err" + parName], value
|
|
);
|
|
if (step === "") step = defVal * 0.01;
|
|
let min = sanitizedMSRParameterNumber(
|
|
all["min" + msrParName] ?? all["min" + parName] ?? ""
|
|
);
|
|
let max = sanitizedMSRParameterNumber(
|
|
all["max" + msrParName] ?? all["max" + parName] ?? ""
|
|
);
|
|
|
|
// Keep the numeric parameter index even when THEORY refers to it through
|
|
// mapN; RUN blocks need the actual fit-parameter number in their map line.
|
|
parameterNumbers[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);
|
|
if (importedComments && importedComments[parName]) {
|
|
for (let text of importedComments[parName]) paramBlk += text + "\n";
|
|
}
|
|
paramBlk += parLine;
|
|
i++;
|
|
}
|
|
}
|
|
for (let text of importedTrailingComments) paramBlk += text + "\n";
|
|
|
|
// Complete runBlk
|
|
if (all.fitAsyType == "Asymmetry" || all.fitAsyType == "AsymmetryGLB") {
|
|
let runLines = [runLine, alphaLine, forwLine, backLine];
|
|
let t0BgLines = buildT0BgRunLines(all, fitType, 0);
|
|
runLines = runLines.concat(t0BgLines);
|
|
runBlk = runLines.join("\n");
|
|
} else if (all.fitAsyType == "SingleHist") {
|
|
// One template RUN block is generated per histogram group. If several
|
|
// physical runs were selected, keep using the first run here: msr2data
|
|
// globalizes this template later instead of duplicating physical runs in
|
|
// the GUI generator itself.
|
|
for (let iHist = 1; iHist < hists.length+1; iHist++) {
|
|
let n0Line = "norm " + n0Maps["No"+iHist];
|
|
let forwLine = "forward " + hists[iHist-1];
|
|
let t0BgLines = buildT0BgRunLines(all, fitType, iHist - 1, n0Maps["NBg"+iHist]);
|
|
let runLines = [runLine, n0Line, forwLine];
|
|
|
|
let mapValues = [];
|
|
if (singleHistPhaseMaps.length > 0) {
|
|
for (let phaseMap of singleHistPhaseMaps) {
|
|
// The first histogram keeps the normal model parameter name; additional
|
|
// detector groups get explicit phase copies selected through RUN maps.
|
|
let phaseName = iHist <= 1 ? phaseMap.baseName
|
|
: phaseMap.baseName + "H" + 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[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(" "));
|
|
}
|
|
|
|
runLines = runLines.concat(t0BgLines);
|
|
runBlk += runLines.join("\n");
|
|
runBlk += "\n";
|
|
}
|
|
}
|
|
|
|
return {
|
|
parameterBlock: paramBlk,
|
|
theoryBlock: theoryBlk,
|
|
functionsBlock: funBlock,
|
|
runBlock: runBlk
|
|
};
|
|
}
|
|
|
|
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 = sanitizedMSRParameterValue(
|
|
all["val" + msrParName] ?? all["val" + parName] ?? "", defVal
|
|
);
|
|
let step = sanitizedMSRParameterError(
|
|
all["err" + msrParName] ?? all["err" + parName], value
|
|
);
|
|
if (step === "") step = defVal * 0.01;
|
|
let min = sanitizedMSRParameterNumber(
|
|
all["min" + msrParName] ?? all["min" + parName] ?? ""
|
|
);
|
|
let max = sanitizedMSRParameterNumber(
|
|
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 = {
|
|
RUN_NUMBERS: blocks.runNumbers,
|
|
PARAMETER_BLOCK: blocks.parameterBlock,
|
|
TEORY_BLOCK: blocks.theoryBlock,
|
|
FUNCTIONS_BLOCK: blocks.functionsBlock
|
|
? "###############################################################\n"
|
|
+ "FUNCTIONS\n"
|
|
+ blocks.functionsBlock
|
|
+ "###############################################################\n"
|
|
: "",
|
|
GLOBAL_BLOCK: blocks.globalBlock,
|
|
RUN_BLOCK: blocks.runBlock,
|
|
COMMANDS_BLOCK: blocks.commandsBlock,
|
|
PLOT_BLOCK: blocks.plotBlock,
|
|
FOURIER_BLOCK: blocks.fourierBlock
|
|
};
|
|
|
|
for (let placeholder in replacements) {
|
|
msrFile = msrFile.replace(placeholder, replacements[placeholder]);
|
|
}
|
|
// A disabled FFT produces an empty FOURIER block. musrfit has no "FFT off"
|
|
// directive and rejects an empty or `plot none` block, so drop the whole
|
|
// FOURIER section rather than emitting an invalid directive.
|
|
if (!blocks.fourierBlock) {
|
|
msrFile = msrFile.replace(/\nFOURIER\n/, "\n");
|
|
}
|
|
return msrFile;
|
|
}
|
|
|
|
// Electron application settings and output-file naming. Web output names are
|
|
// intentionally fixed so deployment configuration never leaks into the GUI.
|
|
function normalizeWorkPath(workPath) {
|
|
let normalized = (workPath || defaultWorkPath).toString().trim();
|
|
return normalized || defaultWorkPath;
|
|
}
|
|
|
|
function setConfiguredWorkPath(workPath, persist) {
|
|
let normalized = normalizeWorkPath(workPath);
|
|
let input = document.getElementById("workPath");
|
|
if (input) {
|
|
input.value = normalized;
|
|
}
|
|
if (persist && !amIWeb()) {
|
|
try {
|
|
window.localStorage.setItem(workPathStorageKey, normalized);
|
|
} catch (error) {
|
|
console.log("Could not persist the work directory: " + error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function initializeWorkPath() {
|
|
let input = document.getElementById("workPath");
|
|
if (!input) return;
|
|
|
|
if (amIWeb()) {
|
|
input.value = defaultWorkPath;
|
|
return;
|
|
}
|
|
|
|
let configuredPath = defaultWorkPath;
|
|
try {
|
|
configuredPath = window.localStorage.getItem(workPathStorageKey) || defaultWorkPath;
|
|
} catch (error) {
|
|
console.log("Could not read the saved work directory: " + error.message);
|
|
}
|
|
setConfiguredWorkPath(configuredPath, false);
|
|
}
|
|
|
|
function normalizeFileSuffix(value, fallback) {
|
|
let suffix = (value || "").toString().trim();
|
|
if (!suffix || /[\\/]/.test(suffix)) return fallback;
|
|
return suffix;
|
|
}
|
|
|
|
function setConfiguredFileSuffix(inputId, storageKey, value, fallback, persist) {
|
|
let suffix = normalizeFileSuffix(value, fallback);
|
|
let input = document.getElementById(inputId);
|
|
if (input) input.value = suffix;
|
|
if (persist && !amIWeb()) {
|
|
try {
|
|
window.localStorage.setItem(storageKey, suffix);
|
|
} catch (error) {
|
|
console.log("Could not persist output-file suffix: " + error.message);
|
|
}
|
|
}
|
|
return suffix;
|
|
}
|
|
|
|
function initializeFileSuffixes() {
|
|
let asymmetry = defaultAsymmetrySuffix;
|
|
let singleHist = defaultSingleHistSuffix;
|
|
if (!amIWeb()) {
|
|
try {
|
|
asymmetry = window.localStorage.getItem(asymmetrySuffixStorageKey) || asymmetry;
|
|
singleHist = window.localStorage.getItem(singleHistSuffixStorageKey) || singleHist;
|
|
} catch (error) {
|
|
console.log("Could not read saved output-file suffixes: " + error.message);
|
|
}
|
|
}
|
|
setConfiguredFileSuffix("asymmetrySuffix", asymmetrySuffixStorageKey,
|
|
asymmetry, defaultAsymmetrySuffix, false);
|
|
setConfiguredFileSuffix("singleHistSuffix", singleHistSuffixStorageKey,
|
|
singleHist, defaultSingleHistSuffix, false);
|
|
}
|
|
|
|
function fitFileSuffix(all, webMode) {
|
|
let singleHist = all && all.fitAsyType == "SingleHist";
|
|
let fallback = singleHist ? defaultSingleHistSuffix : defaultAsymmetrySuffix;
|
|
if (webMode) return fallback;
|
|
|
|
let configured = singleHist ? all.singleHistSuffix : all.asymmetrySuffix;
|
|
return normalizeFileSuffix(configured, fallback);
|
|
}
|
|
|
|
// Data-root configuration and instrument-specific run-file resolution.
|
|
function normalizeDataRoot(dataRoot) {
|
|
let normalized = (dataRoot || defaultDataRoot).toString().trim();
|
|
if (normalized.length > 1) {
|
|
normalized = normalized.replace(/\/+$/, "");
|
|
}
|
|
return normalized || defaultDataRoot;
|
|
}
|
|
|
|
function setConfiguredDataRoot(dataRoot, persist) {
|
|
let normalized = normalizeDataRoot(dataRoot);
|
|
let input = document.getElementById("dataRoot");
|
|
if (input) {
|
|
input.value = normalized;
|
|
}
|
|
|
|
// The standalone setting belongs to this computer and is deliberately not
|
|
// embedded in saved/generated MSR files as application configuration.
|
|
if (persist && !amIWeb()) {
|
|
try {
|
|
window.localStorage.setItem(dataRootStorageKey, normalized);
|
|
} catch (error) {
|
|
console.log("Could not persist the data root: " + error.message);
|
|
}
|
|
}
|
|
updateResolvedDataPathPreview();
|
|
}
|
|
|
|
function initializeDataRoot() {
|
|
let input = document.getElementById("dataRoot");
|
|
let browseButton = document.getElementById("dataRootBrowse");
|
|
let modeText = document.getElementById("dataRootModeText");
|
|
if (!input) {
|
|
return;
|
|
}
|
|
|
|
if (amIWeb()) {
|
|
input.readOnly = true;
|
|
if (browseButton) {
|
|
browseButton.style.display = "none";
|
|
}
|
|
if (modeText) {
|
|
modeText.textContent = "Managed by web server";
|
|
}
|
|
setConfiguredDataRoot(defaultDataRoot, false);
|
|
if (typeof loadWebDataRoot === "function") {
|
|
loadWebDataRoot();
|
|
}
|
|
return;
|
|
}
|
|
|
|
let configuredRoot = defaultDataRoot;
|
|
try {
|
|
configuredRoot = window.localStorage.getItem(dataRootStorageKey) || defaultDataRoot;
|
|
} catch (error) {
|
|
console.log("Could not read the saved data root: " + error.message);
|
|
}
|
|
input.readOnly = false;
|
|
if (modeText) {
|
|
modeText.textContent = "Saved on this computer";
|
|
}
|
|
setConfiguredDataRoot(configuredRoot, false);
|
|
}
|
|
|
|
// Startup-XML preference and the active RUN-naming source indicator. The XML
|
|
// file selected here is used by the Electron adapter to enable portable RUN
|
|
// naming through setPortableRunNaming(); the web deployment obtains its startup
|
|
// XML from the server and never lets the browser set this.
|
|
function setConfiguredStartupXml(filePath, persist) {
|
|
let input = document.getElementById("startupXml");
|
|
if (input) {
|
|
input.value = filePath || "";
|
|
}
|
|
if (persist && !amIWeb()) {
|
|
try {
|
|
if (filePath) {
|
|
window.localStorage.setItem(startupXmlStorageKey, filePath);
|
|
} else {
|
|
window.localStorage.removeItem(startupXmlStorageKey);
|
|
}
|
|
} catch (error) {
|
|
console.log("Could not persist the startup XML path: " + error.message);
|
|
}
|
|
}
|
|
updateStartupNamingSourceIndicator();
|
|
}
|
|
|
|
function getConfiguredStartupXml() {
|
|
try {
|
|
return window.localStorage.getItem(startupXmlStorageKey) || "";
|
|
} catch (error) {
|
|
console.log("Could not read the saved startup XML path: " + error.message);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function initializeStartupXml() {
|
|
let configured = "";
|
|
if (!amIWeb()) {
|
|
configured = getConfiguredStartupXml();
|
|
}
|
|
let input = document.getElementById("startupXml");
|
|
if (input) {
|
|
input.value = configured;
|
|
}
|
|
updateStartupNamingSourceIndicator();
|
|
}
|
|
|
|
// Local musrfit-tool directory preference. An empty value means auto-detect
|
|
// from the usual installation locations; the web build has no local commands
|
|
// and never exposes this field.
|
|
function normalizeBinDir(binDir) {
|
|
return (binDir || "").toString().trim();
|
|
}
|
|
|
|
function setConfiguredBinDir(binDir, persist) {
|
|
let normalized = normalizeBinDir(binDir);
|
|
let input = document.getElementById("binDir");
|
|
if (input) {
|
|
input.value = normalized;
|
|
}
|
|
if (persist && !amIWeb() && window.localStorage) {
|
|
try {
|
|
if (normalized === "") {
|
|
window.localStorage.removeItem(binDirStorageKey);
|
|
} else {
|
|
window.localStorage.setItem(binDirStorageKey, normalized);
|
|
}
|
|
} catch (error) {
|
|
console.log("Could not persist the musrfit binaries directory: " + error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function getConfiguredBinDir() {
|
|
try {
|
|
if (!window.localStorage) return "";
|
|
return normalizeBinDir(window.localStorage.getItem(binDirStorageKey));
|
|
} catch (error) {
|
|
console.log("Could not read the saved musrfit binaries directory: " + error.message);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function initializeBinDir() {
|
|
let input = document.getElementById("binDir");
|
|
if (!input) return;
|
|
if (amIWeb()) {
|
|
input.value = "";
|
|
input.readOnly = true;
|
|
return;
|
|
}
|
|
input.value = getConfiguredBinDir();
|
|
}
|
|
|
|
// Local musrfit OpenMP thread preference. A blank or non-positive value means
|
|
// "auto" (return 0) so runMSRFileLocal omits `-u` and musrfit uses all cores.
|
|
// The web build never runs musrfit locally, so this field is desktop-only.
|
|
function normalizeMusrfitThreads(value) {
|
|
let parsed = parseInt((value === undefined || value === null) ? "" : value.toString().trim(), 10);
|
|
if (isNaN(parsed) || parsed < 1) return 0;
|
|
return parsed;
|
|
}
|
|
|
|
function setConfiguredMusrfitThreads(value, persist) {
|
|
let normalized = normalizeMusrfitThreads(value);
|
|
let input = document.getElementById("musrfitThreads");
|
|
if (input) {
|
|
input.value = normalized > 0 ? String(normalized) : "";
|
|
}
|
|
if (persist && !amIWeb() && window.localStorage) {
|
|
try {
|
|
if (normalized > 0) {
|
|
window.localStorage.setItem(musrfitThreadsStorageKey, String(normalized));
|
|
} else {
|
|
window.localStorage.removeItem(musrfitThreadsStorageKey);
|
|
}
|
|
} catch (error) {
|
|
console.log("Could not persist the musrfit thread count: " + error.message);
|
|
}
|
|
}
|
|
}
|
|
|
|
function getConfiguredMusrfitThreads() {
|
|
try {
|
|
if (!window.localStorage) return 0;
|
|
return normalizeMusrfitThreads(window.localStorage.getItem(musrfitThreadsStorageKey));
|
|
} catch (error) {
|
|
console.log("Could not read the saved musrfit thread count: " + error.message);
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
function initializeMusrfitThreads() {
|
|
let input = document.getElementById("musrfitThreads");
|
|
if (!input) return;
|
|
if (amIWeb()) {
|
|
input.value = "";
|
|
input.readOnly = true;
|
|
return;
|
|
}
|
|
let threads = getConfiguredMusrfitThreads();
|
|
input.value = threads > 0 ? String(threads) : "";
|
|
}
|
|
|
|
// Reflect whether portable names come from a musrfit_startup.xml or from the
|
|
// explicit absolute-path fallback. Depends on the platform having called
|
|
// setPortableRunNaming() with a validated startup object.
|
|
function updateStartupNamingSourceIndicator() {
|
|
let indicator = document.getElementById("startupNamingStatus");
|
|
if (!indicator) {
|
|
return;
|
|
}
|
|
let active = portableRunNamingEnabled && portableRunNamingStartup;
|
|
indicator.textContent = active
|
|
? "Run naming: musrfit startup XML"
|
|
: "Run naming: explicit path";
|
|
}
|
|
|
|
function setRunInputWarning(errorText, labelText) {
|
|
// One compact warning area serves both syntax/action validation and the rarer
|
|
// data-path diagnostic. Keeping those messages in one place avoids adding a
|
|
// second permanent row to the otherwise compact Runs section.
|
|
let warning = document.getElementById("dataPathResolutionWarning");
|
|
let label = document.getElementById("dataPathResolutionLabel");
|
|
let message = document.getElementById("dataPathResolutionMessage");
|
|
if (!warning) {
|
|
return;
|
|
}
|
|
warning.hidden = false;
|
|
if (label) {
|
|
label.textContent = labelText || "Runs";
|
|
}
|
|
if (message) {
|
|
message.textContent = errorText || "Check the run selection.";
|
|
}
|
|
}
|
|
|
|
function clearRunInputWarning() {
|
|
let warning = document.getElementById("dataPathResolutionWarning");
|
|
let message = document.getElementById("dataPathResolutionMessage");
|
|
let runInput = document.getElementById("runNumbers");
|
|
if (warning) {
|
|
warning.hidden = true;
|
|
}
|
|
if (message) {
|
|
message.textContent = "";
|
|
}
|
|
if (runInput && typeof runInput.removeAttribute === "function") {
|
|
runInput.removeAttribute("aria-invalid");
|
|
}
|
|
}
|
|
|
|
function validateRunSelection(actionLabel) {
|
|
// Empty Runs is a valid idle state, but Generate/Fit/Plot need at least one
|
|
// concrete run. Validate only at action time so the user can type ranges
|
|
// naturally without warning banners or modal alerts appearing mid-entry.
|
|
let runInput = document.getElementById("runNumbers");
|
|
let runText = runInput ? runInput.value : (All.runNumbers || "");
|
|
let runs = arrayRunNumbers(runText || "");
|
|
if (runs.length > 0) {
|
|
clearRunInputWarning();
|
|
return 1;
|
|
}
|
|
|
|
let empty = !runText || runText.trim() === "";
|
|
let message = empty
|
|
? "Enter at least one run."
|
|
: "Enter a valid run list, for example 514, 516, 520-525, 520:540:2 or 514+515.";
|
|
setRunInputWarning(message, "Runs");
|
|
if (runInput) {
|
|
if (typeof runInput.setAttribute === "function") {
|
|
runInput.setAttribute("aria-invalid", "true");
|
|
}
|
|
if (typeof runInput.focus === "function") {
|
|
runInput.focus();
|
|
}
|
|
}
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus((actionLabel || "This action") + " requires a valid run selection.", {
|
|
level: "error"
|
|
});
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
function updateResolvedDataPathPreview() {
|
|
let runInput = document.getElementById("runNumbers");
|
|
let yearInput = document.getElementById("selYear");
|
|
let instrumentInput = document.getElementById("instrName");
|
|
let rootInput = document.getElementById("dataRoot");
|
|
if (!runInput || !yearInput || !instrumentInput) {
|
|
return;
|
|
}
|
|
|
|
let instrument = instPars[instrumentInput.value];
|
|
if (instrument) {
|
|
yearInput.min = instrument.minYear;
|
|
}
|
|
|
|
// Successful resolution is intentionally silent. Empty or partially typed
|
|
// run input also stays quiet; only an explicit action invokes syntax/list
|
|
// validation. Once a usable run exists, path-rule errors can be diagnosed.
|
|
let runs = arrayRunNumbers(runInput.value || "");
|
|
if (runs.length === 0 || !yearInput.value || !instrument) {
|
|
clearRunInputWarning();
|
|
return;
|
|
}
|
|
|
|
// The configured minimum year is part of the instrument filename rules. A
|
|
// year before that boundary would produce a plausible-looking but invalid
|
|
// path, so surface that specific problem before MSR generation.
|
|
let yearNumber = Number(yearInput.value);
|
|
if (!Number.isFinite(yearNumber) || yearNumber < Number(instrument.minYear)) {
|
|
setRunInputWarning(instrumentInput.value + " data are supported from " + instrument.minYear + ".", "RUN line");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Construct the same RUN line used later by MSR generation. The result is
|
|
// deliberately not displayed; only an exception needs user attention.
|
|
runFileNameAuto(
|
|
runs[0],
|
|
yearInput.value,
|
|
instrumentInput.value,
|
|
rootInput ? rootInput.value : defaultDataRoot
|
|
);
|
|
clearRunInputWarning();
|
|
} catch (error) {
|
|
setRunInputWarning(
|
|
error && error.message ? error.message : "Could not resolve the data path.",
|
|
"RUN line"
|
|
);
|
|
}
|
|
}
|
|
|
|
// Parse the supported musrfit_startup.xml fields without depending on a DOM
|
|
// parser, so the library runs identically in Electron, the browser, and Node
|
|
// tests. Only <data_path> and <run_name_template inst="..."> are consumed; the
|
|
// rest of the user's startup file is left untouched.
|
|
function parseMusrfitStartupXML(xmlText) {
|
|
let result = { dataPaths: [], templates: {} };
|
|
if (!xmlText) return result;
|
|
// Strip XML comments before matching so prose inside <!-- ... --> cannot be
|
|
// mistaken for a <data_path> or <run_name_template> element.
|
|
let body = String(xmlText).replace(/<!--[\s\S]*?-->/g, "");
|
|
|
|
let dataPathPattern = /<data_path\b[^>]*>([\s\S]*?)<\/data_path\s*>/gi;
|
|
let dataPathMatch;
|
|
while ((dataPathMatch = dataPathPattern.exec(body)) !== null) {
|
|
let value = dataPathMatch[1].replace(/^\s+|\s+$/g, "");
|
|
if (value) result.dataPaths.push(value);
|
|
}
|
|
|
|
let templatePattern = /<run_name_template\b([^>]*)>([\s\S]*?)<\/run_name_template\s*>/gi;
|
|
let templateMatch;
|
|
while ((templateMatch = templatePattern.exec(body)) !== null) {
|
|
let attributes = templateMatch[1];
|
|
let instMatch = /\binst\s*=\s*["']?([A-Za-z0-9_]+)["']?/.exec(attributes);
|
|
let inst = instMatch ? instMatch[1].toLowerCase() : "";
|
|
let value = templateMatch[2].replace(/^\s+|\s+$/g, "");
|
|
if (!inst || !value) continue;
|
|
if (!result.templates[inst]) result.templates[inst] = [];
|
|
result.templates[inst].push(value);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Expand a musrfit run-name template for a given year and run number.
|
|
// %yyyy% -> 4-digit year; %yy% -> 2-digit year; %rrr...% -> run zero-padded to
|
|
// the count of 'r' characters. A bare run number inside a template (no %r%
|
|
// marker) is left verbatim.
|
|
function expandMusrfitRunTemplate(template, year, run) {
|
|
let yearText = String(year);
|
|
let yearShort = yearText.length >= 4 ? yearText.substring(yearText.length - 2) : yearText;
|
|
let runNumber = Number(run);
|
|
let expanded = template.replace(/%yyyy%/g, yearText);
|
|
expanded = expanded.replace(/%yy%/g, yearShort);
|
|
expanded = expanded.replace(/%r+%/gi, function(match) {
|
|
let width = match.replace(/%/g, "").length;
|
|
return Number.isFinite(runNumber) ? String(runNumber).padStart(width, "0") : "";
|
|
});
|
|
return expanded;
|
|
}
|
|
|
|
// Return the lowercase musrfit_startup.xml instrument identifier that
|
|
// corresponds to a GUI instrument name. HAL uses the modern 'hifi' templates.
|
|
function musrfitInstrumentXmlName(guiInstrName) {
|
|
let name = String(guiInstrName || "").toLowerCase();
|
|
if (name === "hal") return "hifi";
|
|
return name;
|
|
}
|
|
|
|
// Expand every run-name template registered for a GUI instrument into candidate
|
|
// paths relative to a data_path. Templates are kept in configured order so that
|
|
// resolution can try them in order. Returns an array of { subPath, file, format }.
|
|
// Best-effort data format for a resolved portable filename. The startup-XML
|
|
// templates carry the same era transitions as the absolute-path generator, so
|
|
// the format follows the resolved path's extension rather than the instrument
|
|
// default: modern ROOT-era files are MUSR-ROOT, HAL's MDU-era files are
|
|
// PSI-MDU, and the classic BIN-era files are PSI-BIN.
|
|
function musrfitPortableFormat(guiInstrName, subPath) {
|
|
let extension = "";
|
|
let name = String(subPath || "");
|
|
let dot = name.lastIndexOf(".");
|
|
if (dot > name.lastIndexOf("/") && dot !== -1) {
|
|
extension = name.substring(dot + 1).toLowerCase();
|
|
}
|
|
let defFormat = instPars[guiInstrName] ? instPars[guiInstrName].defFormat : "";
|
|
if (extension === "root") return "MUSR-ROOT";
|
|
if (extension === "mdu") return "PSI-MDU";
|
|
// HAL's pre-modern era stores PSI-MDU data under a .bin extension; every
|
|
// other instrument's .bin is PSI-BIN.
|
|
if (extension === "bin") {
|
|
let inst = musrfitInstrumentXmlName(guiInstrName);
|
|
if (inst === "hifi" || inst === "hal") return "PSI-MDU";
|
|
return "PSI-BIN";
|
|
}
|
|
return defFormat;
|
|
}
|
|
|
|
function portableMusrfitRunCandidates(run, year, guiInstrName, startup) {
|
|
let candidates = [];
|
|
if (!startup || !startup.templates) return candidates;
|
|
let inst = musrfitInstrumentXmlName(guiInstrName);
|
|
let templates = startup.templates[inst] || [];
|
|
for (let template of templates) {
|
|
let expanded = expandMusrfitRunTemplate(template, year, run);
|
|
if (!expanded) continue;
|
|
let cleaned = expanded.replace(/^\.?\//, "");
|
|
candidates.push({
|
|
subPath: cleaned,
|
|
file: cleaned.replace(/\.[A-Za-z0-9]+$/, ""),
|
|
format: musrfitPortableFormat(guiInstrName, cleaned)
|
|
});
|
|
}
|
|
return candidates;
|
|
}
|
|
|
|
// The portable RUN line respects configured start-up templates only when
|
|
// Portable naming is enabled and a matching template can be resolved against a
|
|
// configured data path. Returns null when no portable candidate is acceptable.
|
|
function portableRunFileName(run, year, instrName, dataRoot) {
|
|
if (!portableRunNamingEnabled) return null;
|
|
if (!portableRunNamingStartup || typeof resolveMusrfitRunFile !== "function") {
|
|
return null;
|
|
}
|
|
let candidates = portableMusrfitRunCandidates(run, year, instrName, portableRunNamingStartup);
|
|
if (!candidates.length) return null;
|
|
|
|
// A run-name template is expressed relative to a startup-XML <data_path>,
|
|
// which is the deployment-authoritative layout. The GUI dataRoot is a
|
|
// different, legacy absolute layout and must not be combined with these
|
|
// templates; without a startup-XML data_path the template cannot be
|
|
// resolved against the right root, so fall back to the explicit path.
|
|
let dataPaths = portableRunNamingStartup.dataPaths || [];
|
|
if (!dataPaths.length) return null;
|
|
|
|
for (let candidate of candidates) {
|
|
for (let dataPath of dataPaths) {
|
|
// The shared generator is synchronous. Accept only an explicit boolean
|
|
// confirmation so a Promise returned by a web adapter cannot be mistaken
|
|
// for a successful filesystem lookup.
|
|
if (resolveMusrfitRunFile(candidate.subPath, dataPath) === true) {
|
|
return {
|
|
subPath: candidate.subPath,
|
|
// Extension-less name used for RUN/ADDRUN directives: musrfit
|
|
// infers the encoding from the trailing format field, so the
|
|
// directive conventionally omits the file extension. Keeping the
|
|
// extension off also lets runSuffixFromFile() extract the run
|
|
// suffix for msr2data run-qualified global parameters.
|
|
file: candidate.file,
|
|
dataPath: dataPath,
|
|
beamLine: instPars[instrName] ? instPars[instrName].beamLine : "PSI",
|
|
format: candidate.format
|
|
};
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function runFileNameAuto(run, year, instrName, dataRoot) {
|
|
/*
|
|
RUNFileNameAuto
|
|
This function returns the runLine for a given run
|
|
input should be
|
|
run - is the run number
|
|
year - is the year
|
|
instrName - is the name of beamline
|
|
dataRoot - is the machine/server data mount point
|
|
*/
|
|
|
|
let runLine = "";
|
|
|
|
let exts = {
|
|
root : "MUSR-ROOT",
|
|
bin : "PSI-BIN",
|
|
mdu : "PSI-MDU",
|
|
msr : "MUD"
|
|
};
|
|
|
|
// if instrName is empty assume manual name
|
|
if (instrName == "") {
|
|
let manualRun = run.toString();
|
|
// Find out the type of manually entered data file.
|
|
let ext = "";
|
|
for (let key of Object.keys(exts)) {
|
|
if (manualRun.includes(key)) {
|
|
ext = key;
|
|
}
|
|
}
|
|
|
|
manualRun = manualRun.replace("." + ext, "");
|
|
runLine = "RUN " + manualRun + " MUE4 PSI " + exts[ext];
|
|
} else {
|
|
let instrument = instPars[instrName];
|
|
if (!instrument) {
|
|
throw new Error("Unsupported instrument: " + instrName);
|
|
}
|
|
|
|
// Opt-in portable naming: when configured against a valid musrfit_startup
|
|
// XML and a matching template resolves for this run, emit the sub-path
|
|
// relative to a data_path instead of an absolute machine-specific path.
|
|
if (portableRunNamingEnabled) {
|
|
let portable = portableRunFileName(run, year, instrName, dataRoot);
|
|
if (portable) {
|
|
runLine = ["RUN", portable.file, portable.beamLine, "PSI", portable.format].join(" ");
|
|
return runLine;
|
|
}
|
|
}
|
|
|
|
// Downloaded files keep their exact server names and resolve through
|
|
// per-process search paths, including read-only data mount fallbacks.
|
|
let platform = window.MusRFlowPlatform;
|
|
if (platform && typeof platform.resolveRunData === 'function') {
|
|
let local = platform.resolveRunData(run, year, instrName);
|
|
if (local) {
|
|
return ['RUN', local.runName, instrument.beamLine, 'PSI', local.format].join(' ');
|
|
}
|
|
}
|
|
|
|
let yearText = year.toString();
|
|
let yearNumber = Number(yearText);
|
|
let runNumber = Number(run);
|
|
let runTmp = runNumber.toString().padStart(4, "0");
|
|
let runFileName = "";
|
|
let dataFormat = instrument.defFormat;
|
|
|
|
// These transitions mirror RUNFileNameAuto in the current MSR.pm CGI
|
|
// implementation. Keep the format local so calls for different years do
|
|
// not mutate shared instrument metadata.
|
|
if (instrName == "LEM") {
|
|
runFileName = "lem" + yearText.substring(2) + "_his_" + runTmp;
|
|
} else if (instrName == "GPS") {
|
|
if (yearNumber >= 2023) {
|
|
runFileName = "deltatbc_tdc_gps_" + yearText + "_" + runTmp;
|
|
dataFormat = "MUSR-ROOT";
|
|
} else if (yearNumber >= 2008) {
|
|
runFileName = "deltat_tdc_gps_" + runTmp;
|
|
} else {
|
|
runFileName = "deltat_pta_gps_" + runTmp;
|
|
}
|
|
} else if (instrName == "LTF") {
|
|
if (yearNumber >= 2009) {
|
|
runFileName = "deltat_tdc_ltf_" + runTmp;
|
|
} else {
|
|
runFileName = "deltat_pta_ltf_" + runTmp;
|
|
}
|
|
} else if (instrName == "Dolly") {
|
|
if (yearNumber >= 2023) {
|
|
runFileName = "deltat_tdc_dolly_" + yearText + "_" + runTmp;
|
|
dataFormat = "MUSR-ROOT";
|
|
} else if (yearNumber >= 2008) {
|
|
runFileName = "deltat_tdc_dolly_" + runTmp;
|
|
} else {
|
|
runFileName = "deltat_pta_dolly_" + runTmp;
|
|
}
|
|
} else if (instrName == "VMS") {
|
|
runFileName = "deltat_tdc_vms_" + yearText + "_" + runTmp;
|
|
} else if (instrName == "GPD") {
|
|
if (yearNumber >= 2023) {
|
|
runFileName = "deltatbc_tdc_gpd_" + yearText + "_" + runTmp;
|
|
dataFormat = "MUSR-ROOT";
|
|
} else if (yearNumber >= 2008) {
|
|
runFileName = "deltat_tdc_gpd_" + runTmp;
|
|
} else {
|
|
runFileName = "deltat_pta_gpd_" + runTmp;
|
|
}
|
|
} else if (instrName == "HAL") {
|
|
if (yearNumber >= 2023) {
|
|
runFileName = "deltat_tdc_hifi_" + yearText + "_" + runTmp;
|
|
dataFormat = "MUSR-ROOT";
|
|
} else {
|
|
runFileName = "tdc_hifi_" + yearText + "_" + runNumber.toString().padStart(5, "0");
|
|
}
|
|
} else if (instrName == "FLAME") {
|
|
if (yearNumber < 2026) {
|
|
runFileName = "deltat_tdc_flame_" + yearText + "_" + runTmp;
|
|
} else {
|
|
runFileName = "flame" + yearText.substring(2) + "_his_" + runNumber.toString().padStart(5, "0");
|
|
}
|
|
}
|
|
|
|
let normalizedRoot = normalizeDataRoot(dataRoot);
|
|
let pathSeparator = normalizedRoot == "/" ? "" : "/";
|
|
let dataDirectory = normalizedRoot + pathSeparator + instrument.dataFolder + "/his/" + yearText;
|
|
let fullRunPath = dataDirectory + "/" + runFileName;
|
|
runLine = ["RUN", fullRunPath, instrument.beamLine, "PSI", dataFormat].join(" ");
|
|
}
|
|
return runLine;
|
|
}
|
|
|
|
function runFileTokenFromDirective(line) {
|
|
// RUN and ADDRUN share the same token layout. Matching by the data-file token
|
|
// is robust against spacing changes introduced by msr2data.
|
|
let fields = String(line || "").trim().split(/\s+/);
|
|
return fields.length > 1 ? fields[1] : "";
|
|
}
|
|
|
|
function buildAddRunSpec(runSelection, year, instrName, dataRoot) {
|
|
// Build an explicit, already-resolved specification that can be used locally
|
|
// and sent to the web CGI. The server then does not need a second copy of the
|
|
// instrument/year filename rules merely to insert ADDRUN after msr2data.
|
|
let spec = [];
|
|
for (let dataSet of (runSelection || [])) {
|
|
if (!dataSet || !Array.isArray(dataSet.add) || dataSet.add.length === 0) {
|
|
continue;
|
|
}
|
|
|
|
let mainLine = runFileNameAuto(dataSet.main, year, instrName, dataRoot);
|
|
let mainFile = runFileTokenFromDirective(mainLine);
|
|
let addLines = dataSet.add.map(function(run) {
|
|
// This mirrors the legacy MSR.pm behavior: ADD + RUN ... = ADDRUN ... .
|
|
return "ADD" + runFileNameAuto(run, year, instrName, dataRoot);
|
|
});
|
|
spec.push({
|
|
main: dataSet.main,
|
|
mainFile: mainFile,
|
|
addLines: addLines
|
|
});
|
|
}
|
|
return spec;
|
|
}
|
|
|
|
function applyAddRunsToMSR(msrText, runSelection, year, instrName, dataRoot) {
|
|
if (!msrText || typeof msrText !== "string") {
|
|
return msrText;
|
|
}
|
|
|
|
let spec = buildAddRunSpec(runSelection, year, instrName, dataRoot);
|
|
if (spec.length === 0) {
|
|
return msrText;
|
|
}
|
|
|
|
let byMainFile = Object.create(null);
|
|
for (let entry of spec) {
|
|
byMainFile[entry.mainFile] = entry.addLines;
|
|
}
|
|
|
|
let lines = msrText.split(/\r?\n/);
|
|
let output = [];
|
|
let replaceExistingAddRuns = false;
|
|
|
|
for (let line of lines) {
|
|
if (/^\s*RUN\b/.test(line)) {
|
|
let mainFile = runFileTokenFromDirective(line);
|
|
let addLines = byMainFile[mainFile] || null;
|
|
output.push(line);
|
|
if (addLines) {
|
|
// Insert immediately after RUN, as required by musrfit. If this helper
|
|
// is called twice, replace the generated ADDRUN lines rather than
|
|
// accumulating duplicates. This also handles every histogram RUN in
|
|
// a SingleHist global file because those blocks share the main file.
|
|
for (let addLine of addLines) {
|
|
output.push(addLine);
|
|
}
|
|
replaceExistingAddRuns = true;
|
|
} else {
|
|
replaceExistingAddRuns = false;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (replaceExistingAddRuns && /^\s*ADDRUN\b/.test(line)) {
|
|
continue;
|
|
}
|
|
replaceExistingAddRuns = false;
|
|
output.push(line);
|
|
}
|
|
|
|
return output.join("\n");
|
|
}
|
|
|
|
function missingAddRunTargets(msrText, addRunSpec) {
|
|
// A path-rule mismatch must fail closed. Otherwise a requested summed data set
|
|
// could look like a successful fit while silently using only its main run.
|
|
let runFiles = Object.create(null);
|
|
for (let line of String(msrText || "").split(/\r?\n/)) {
|
|
if (/^\s*RUN\b/.test(line)) {
|
|
runFiles[runFileTokenFromDirective(line)] = true;
|
|
}
|
|
}
|
|
return (addRunSpec || []).filter(function(entry) {
|
|
return !runFiles[entry.mainFile];
|
|
});
|
|
}
|
|
|
|
function runSuffixFromFile(run, instrName, year, dataRoot) {
|
|
// Return the run number string as it appears in the file name,
|
|
// so parameter suffixes match what msr2data expects.
|
|
if (!instrName) {
|
|
return run.toString();
|
|
}
|
|
let runLine = runFileNameAuto(run, year, instrName, dataRoot);
|
|
let parts = runLine.split(/\s+/);
|
|
if (parts.length < 2) {
|
|
return run.toString();
|
|
}
|
|
let fileName = parts[1].replace(/\.(root|bin|mdu)$/i, '');
|
|
let match = fileName.match(/_(\d+)$/);
|
|
if (match) {
|
|
return match[1];
|
|
}
|
|
return run.toString();
|
|
}
|
|
|
|
// Plot/FFT/RRF controls and validation.
|
|
function updateFFTOptionsIndicator() {
|
|
let disclosure = document.getElementById("fftOptionsDisclosure");
|
|
if (!disclosure) {
|
|
return;
|
|
}
|
|
|
|
// FFT is now a single collapsed disclosure, so the marker covers every FFT
|
|
// setting rather than only the former secondary Options popup.
|
|
let type = document.getElementById("fftType");
|
|
let apod = document.getElementById("fftApod");
|
|
let phase = document.getElementById("fftPhase");
|
|
let dcCorrect = document.getElementById("fftDCCorrect");
|
|
let rangeStart = document.getElementById("fftxi");
|
|
let rangeEnd = document.getElementById("fftxf");
|
|
let units = document.getElementById("fftUnits");
|
|
let power = document.getElementById("fftPower");
|
|
let phaseCorrection = document.getElementById("fftPhaseCorrection");
|
|
|
|
let hasCustomType = Boolean(type && type.value !== "power");
|
|
let hasCustomApod = Boolean(apod && apod.value !== "STRONG");
|
|
let hasCustomPhase = Boolean(phase && phase.value.trim() !== "8.5");
|
|
let hasDCCorrect = Boolean(dcCorrect && dcCorrect.checked);
|
|
let hasCustomRange = Boolean(
|
|
(rangeStart && rangeStart.value.trim()) || (rangeEnd && rangeEnd.value.trim())
|
|
);
|
|
let hasCustomUnits = Boolean(units && units.value !== "Gauss");
|
|
let powerValue = power ? power.value.trim() : "12";
|
|
let hasCustomPower = powerValue !== "12";
|
|
let hasPhaseCorrection = Boolean(
|
|
phaseCorrection && phaseCorrection.value && phaseCorrection.value !== "off"
|
|
);
|
|
|
|
disclosure.classList.toggle(
|
|
"has-overrides",
|
|
hasCustomType || hasCustomApod || hasCustomPhase || hasDCCorrect ||
|
|
hasCustomRange || hasCustomUnits || hasCustomPower || hasPhaseCorrection
|
|
);
|
|
}
|
|
|
|
function updateFFTPhaseCorrectionVisibility() {
|
|
let mode = document.getElementById("fftPhaseCorrection");
|
|
let customRange = document.getElementById("fftPhaseCorrectionRange");
|
|
if (customRange) {
|
|
// A custom phase-correction interval is meaningful only in Custom mode.
|
|
// Preserve typed values while hidden so switching modes never loses work.
|
|
customRange.hidden = !mode || mode.value !== "custom";
|
|
}
|
|
updateFFTOptionsIndicator();
|
|
}
|
|
|
|
function updateRRFVisibility() {
|
|
let enabled = document.getElementById("rrfEnabled");
|
|
let settings = document.getElementById("rrfSettings");
|
|
let disclosure = document.getElementById("rrfOptionsDisclosure");
|
|
|
|
// The RRF values stay visible whenever the RRF disclosure is open. Enable
|
|
// controls only whether directives are emitted into the PLOT block.
|
|
if (settings) {
|
|
settings.hidden = false;
|
|
}
|
|
if (disclosure && disclosure.classList) {
|
|
disclosure.classList.toggle("has-overrides", Boolean(enabled && enabled.checked));
|
|
}
|
|
|
|
if (!enabled || !enabled.checked) {
|
|
// Remove stale validation styling when the feature is disabled because its
|
|
// inputs are no longer required for MSR generation.
|
|
for (let id of ["rrfFrq", "rrfPack"]) {
|
|
let field = document.getElementById(id);
|
|
if (field && typeof field.removeAttribute === "function") {
|
|
field.removeAttribute("aria-invalid");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function validateRRFSettings(actionLabel, all) {
|
|
// Only GUI-owned generation is validated here. Editor-owned MSRs remain the
|
|
// source of truth and may contain RRF syntax that is intentionally not mirrored
|
|
// by the current controls.
|
|
let config = all || {};
|
|
if (!all && typeof document !== "undefined") {
|
|
let enabled = document.getElementById("rrfEnabled");
|
|
config = {
|
|
rrfEnabled: enabled && enabled.checked ? "1" : "",
|
|
rrfFrq: document.getElementById("rrfFrq") ? document.getElementById("rrfFrq").value : "",
|
|
rrfUnits: document.getElementById("rrfUnits") ? document.getElementById("rrfUnits").value : "G",
|
|
rrfPack: document.getElementById("rrfPack") ? document.getElementById("rrfPack").value : "",
|
|
rrfPhase: document.getElementById("rrfPhase") ? document.getElementById("rrfPhase").value : ""
|
|
};
|
|
}
|
|
|
|
let rrf = getRRFPlotConfig(config);
|
|
if (!rrf.enabled) {
|
|
return 1;
|
|
}
|
|
|
|
let frequencyInput = typeof document !== "undefined" ? document.getElementById("rrfFrq") : null;
|
|
let packingInput = typeof document !== "undefined" ? document.getElementById("rrfPack") : null;
|
|
if (frequencyInput && typeof frequencyInput.setAttribute === "function") {
|
|
rrf.frequencyValid
|
|
? frequencyInput.removeAttribute("aria-invalid")
|
|
: frequencyInput.setAttribute("aria-invalid", "true");
|
|
}
|
|
if (packingInput && typeof packingInput.setAttribute === "function") {
|
|
rrf.packingValid
|
|
? packingInput.removeAttribute("aria-invalid")
|
|
: packingInput.setAttribute("aria-invalid", "true");
|
|
}
|
|
|
|
if (rrf.valid) {
|
|
return 1;
|
|
}
|
|
|
|
let message = "RRF requires a positive frequency and a positive integer packing value.";
|
|
if (!rrf.unitsValid) {
|
|
message = "RRF uses an unsupported frequency unit.";
|
|
}
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Check the RRF settings before continuing.", {
|
|
level: "error",
|
|
details: (actionLabel || "This action") + ": " + message
|
|
});
|
|
}
|
|
let firstInvalid = !rrf.frequencyValid ? frequencyInput : packingInput;
|
|
if (firstInvalid && typeof firstInvalid.focus === "function") {
|
|
firstInvalid.focus();
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
function closeViewSettingsPanel() {
|
|
// Collapse the shared inline panel and clear the selected state from all
|
|
// three view-setting buttons without changing any stored option values.
|
|
if (typeof document === "undefined") {
|
|
return;
|
|
}
|
|
|
|
let sharedPanel = document.getElementById("viewSettingsPanel");
|
|
let entries = [
|
|
["plotOptionsDisclosure", "plotOptionsPanel"],
|
|
["fftOptionsDisclosure", "fftOptionsPanel"],
|
|
["rrfOptionsDisclosure", "rrfOptionsPanel"]
|
|
];
|
|
|
|
for (let entry of entries) {
|
|
let button = document.getElementById(entry[0]);
|
|
let panel = document.getElementById(entry[1]);
|
|
if (button && typeof button.setAttribute === "function") {
|
|
button.setAttribute("aria-expanded", "false");
|
|
}
|
|
if (panel) {
|
|
panel.hidden = true;
|
|
}
|
|
}
|
|
if (sharedPanel) {
|
|
sharedPanel.hidden = true;
|
|
}
|
|
}
|
|
|
|
function toggleViewSettingsPanel(kind) {
|
|
// Plot, FFT and RRF reuse one full-width panel. Opening another group simply
|
|
// swaps its contents; clicking the active button a second time collapses it.
|
|
if (typeof document === "undefined") {
|
|
return;
|
|
}
|
|
|
|
let targets = {
|
|
plot: ["plotOptionsDisclosure", "plotOptionsPanel"],
|
|
fft: ["fftOptionsDisclosure", "fftOptionsPanel"],
|
|
rrf: ["rrfOptionsDisclosure", "rrfOptionsPanel"]
|
|
};
|
|
let target = targets[kind];
|
|
if (!target) {
|
|
return;
|
|
}
|
|
|
|
let button = document.getElementById(target[0]);
|
|
let panel = document.getElementById(target[1]);
|
|
let sharedPanel = document.getElementById("viewSettingsPanel");
|
|
if (!button || !panel || !sharedPanel) {
|
|
return;
|
|
}
|
|
|
|
let wasOpen = button.getAttribute && button.getAttribute("aria-expanded") === "true";
|
|
closeViewSettingsPanel();
|
|
if (wasOpen) {
|
|
return;
|
|
}
|
|
|
|
button.setAttribute("aria-expanded", "true");
|
|
panel.hidden = false;
|
|
sharedPanel.hidden = false;
|
|
}
|
|
|
|
function configureViewSettingsDisclosures() {
|
|
// Close the inline settings area when the user clicks elsewhere. Clicks on
|
|
// one of the selectors or inside the shared panel are handled normally.
|
|
if (typeof document === "undefined"
|
|
|| typeof document.addEventListener !== "function"
|
|
|| document._musrfitViewDismissHandler) {
|
|
return;
|
|
}
|
|
|
|
document._musrfitViewDismissHandler = function(event) {
|
|
let sharedPanel = document.getElementById("viewSettingsPanel");
|
|
if (sharedPanel && typeof sharedPanel.contains === "function" && sharedPanel.contains(event.target)) {
|
|
return;
|
|
}
|
|
|
|
for (let id of ["plotOptionsDisclosure", "fftOptionsDisclosure", "rrfOptionsDisclosure"]) {
|
|
let button = document.getElementById(id);
|
|
if (button && typeof button.contains === "function" && button.contains(event.target)) {
|
|
return;
|
|
}
|
|
}
|
|
closeViewSettingsPanel();
|
|
};
|
|
document.addEventListener("click", document._musrfitViewDismissHandler);
|
|
}
|
|
|
|
function cfgFFTRRF() {
|
|
// Refresh conditional controls and disclosure markers after startup or
|
|
// programmatic updates. RRF remains opt-in.
|
|
updateFFTPhaseCorrectionVisibility();
|
|
updateRRFVisibility();
|
|
configureViewSettingsDisclosures();
|
|
}
|
|
|
|
|
|
// Prepare the runnable MSR. Multi-run jobs deliberately follow the proven CGI
|
|
// sequence: write template -> msr2data global; single-run jobs write the
|
|
// runnable document once after applying the GUI parameters in memory.
|
|
async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) {
|
|
let msr2data = "/usr/local/bin/msr2data";
|
|
let webOrApp = amIWeb();
|
|
let runM2D = false;
|
|
|
|
// Ensure the server-owned root is known before web generation. The health
|
|
// probe is cached, so this normally reuses the startup response but still
|
|
// waits for it when the user clicks Fit immediately after loading the page.
|
|
if (webOrApp && typeof loadWebDataRoot === "function") {
|
|
let dataRootLoaded = await loadWebDataRoot();
|
|
if (!dataRootLoaded) {
|
|
let message = "Could not read the muSR data root from the web server.";
|
|
alert(message);
|
|
setFitStatus("Could not read the web data location.", {
|
|
level: "error",
|
|
details: message
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
}
|
|
|
|
// Update configuration from GUI before reading All.* values. File naming
|
|
// below uses local variables so createMSR()/prepCFG() cannot later overwrite
|
|
// a generated web job path from the visible DOM defaults.
|
|
prepCFG();
|
|
|
|
let runSelection = parseRunSelection(All.runNumbers);
|
|
let runs = runSelection.map(function(dataSet) { return dataSet.main; });
|
|
if (runs.length === 0) {
|
|
// Keep this guard even though the normal Fit/Plot buttons validate first:
|
|
// preparation is also called by tests and alternate entry points.
|
|
setRunInputWarning("Enter at least one valid run before " + actionLabel.toLowerCase() + ".", "Runs");
|
|
setFitStatus(actionLabel + " requires a valid run selection.", { level: "error" });
|
|
return({ ok: 0 });
|
|
}
|
|
|
|
if (webOrApp && typeof resolveWebPortableRunSelection === "function") {
|
|
// Prime the web resolver before createMSR() enters the synchronous shared
|
|
// naming path. Unresolved runs retain the explicit-path fallback and are
|
|
// subsequently reported through the normal missing-data handling.
|
|
await resolveWebPortableRunSelection(runSelection, All);
|
|
}
|
|
|
|
let platform = window.MusRFlowPlatform;
|
|
if (!webOrApp && platform && typeof platform.ensureRunData === 'function'
|
|
&& !isMSREditorSourceAuthoritative('current')
|
|
&& !isMSREditorSourceAuthoritative('template')) {
|
|
let data = await platform.ensureRunData({ all: All, runSelection: runSelection, action: actionLabel });
|
|
if (!data.ok) return data;
|
|
}
|
|
|
|
let fileNameSuffix = fitFileSuffix(All, webOrApp);
|
|
let workPath = All.workPath && All.workPath !== "" ? All.workPath : defaultWorkPath;
|
|
|
|
// Only for Node.js
|
|
if (!webOrApp) {
|
|
if (!fileExists(msr2data)) {
|
|
// if not found, try in PATH and hope for the best
|
|
msr2data = "msr2data";
|
|
}
|
|
let directoryCheck = checkDir(workPath);
|
|
if (!directoryCheck.ok) {
|
|
return({
|
|
ok: 0,
|
|
reason: "work-directory-unavailable",
|
|
message: directoryCheck.message
|
|
});
|
|
}
|
|
} else {
|
|
// A stable folder keeps Fit, Plot, links, and editor files in one web job.
|
|
// Selecting a different first run starts a new job and therefore a new folder.
|
|
if (window.MusrfitWebJob.firstRun !== runs[0].toString()) {
|
|
let randomPart = (Math.random() + 1).toString(36).substring(7);
|
|
window.MusrfitWebJob.firstRun = runs[0].toString();
|
|
window.MusrfitWebJob.workPath = "/tmp/" + randomPart;
|
|
}
|
|
workPath = window.MusrfitWebJob.workPath;
|
|
}
|
|
|
|
All.fileNameSuffix = fileNameSuffix;
|
|
All.workPath = workPath;
|
|
|
|
// msr2data requires the `_tmpl` input name; the runnable file gets the
|
|
// fit-type suffix selected above.
|
|
let needsGlobalMSR = runs.length > 1
|
|
&& (All.fitAsyType == "AsymmetryGLB" || All.fitAsyType == "SingleHist");
|
|
let finalMSR = needsGlobalMSR
|
|
? runs[0] + "+global" + fileNameSuffix + ".msr"
|
|
: runs[0] + fileNameSuffix + ".msr";
|
|
let finalPath = workPath + "/" + finalMSR;
|
|
|
|
// The runnable/global document is authoritative only while it is the
|
|
// selected editor document. A selected template has its own independent
|
|
// lock state, so check both. A manually edited runnable/global MSR is then
|
|
// used verbatim; keep any template document beside it, since editing the
|
|
// global file must not erase template work.
|
|
if (window.MSREditor.activeSource == "current"
|
|
&& isMSREditorSourceAuthoritative("current")) {
|
|
let editorMSR = getCurrentEditorText();
|
|
if (!editorMSR || editorMSR.trim() === "") {
|
|
setFitStatus("The active editor is empty.", {
|
|
level: "error",
|
|
details: "Editor source is active, but the editor is empty."
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
if (!await writeAsciiFile(finalPath, editorMSR)) {
|
|
return({ ok: 0 });
|
|
}
|
|
|
|
window.MSREditor.currentContent = editorMSR;
|
|
window.MSREditor.currentPath = finalPath;
|
|
window.MSREditor.activeSource = "current";
|
|
setMSREditorDirty(false, "current");
|
|
markMSREditorAsEditorOwned(editorMSR, "current");
|
|
loadMSRIntoEditor(editorMSR, finalPath, true, { editorOwned: true, syncGUI: false });
|
|
updateJobStatus({
|
|
templatePath: window.MSREditor.hasTemplateTab ? window.MSREditor.templatePath : "",
|
|
resultMSR: finalPath
|
|
});
|
|
setFitStatus(actionLabel + " will use the editor MSR.", {
|
|
level: "info",
|
|
details: actionLabel + " will use the editor MSR: " + finalPath
|
|
});
|
|
|
|
return({
|
|
ok: 1,
|
|
finalPath: finalPath,
|
|
options: {
|
|
useM2D: 0,
|
|
runs: runs.join(" "),
|
|
templateName: "",
|
|
baseRun: runs[0],
|
|
fftv: "n",
|
|
// Editor-owned MSRs are authoritative. Never inject GUI ADDRUN
|
|
// selections into a document the user chose to control manually.
|
|
addRunSpec: "",
|
|
editorSource: 1
|
|
}
|
|
});
|
|
}
|
|
|
|
let templateEditorSource = needsGlobalMSR && isMSREditorSourceAuthoritative("template");
|
|
let parameterSyncSpec = templateEditorSource ? { parameters: [] } : buildFitParameterSyncSpec(All);
|
|
if (templateEditorSource && window.MSREditor.activeSource == "template") {
|
|
// Capture the live editor before preparing files. The cached copy may be one
|
|
// keystroke behind if the user starts Fit/Plot without switching tabs first.
|
|
window.MSREditor.templateContent = getCurrentEditorText();
|
|
}
|
|
|
|
if (templateEditorSource && isMSREditorSourceAuthoritative("current")
|
|
&& window.MSREditor.activeSource == "template" && typeof confirm === "function") {
|
|
// Both documents contain manual work. Regenerating the global file from the
|
|
// edited template would replace the global edits, so require explicit consent.
|
|
let replaceGlobal = confirm("Global MSR also contains manual edits. Regenerate it from the edited template and replace those global edits?");
|
|
if (!replaceGlobal) {
|
|
setFitStatus(actionLabel + " cancelled; Global edits were kept.", {
|
|
level: "warning",
|
|
details: actionLabel + " cancelled; manual global MSR edits were kept."
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
}
|
|
|
|
// GUI-specific validation applies only when the GUI is producing the
|
|
// template/current MSR. An editor-owned template is already the complete
|
|
// source of truth and must not be blocked by unrelated GUI RRF controls.
|
|
if (!templateEditorSource) {
|
|
if (!validateRRFSettings(actionLabel, All)) {
|
|
return({ ok: 0 });
|
|
}
|
|
let t0BgValidation = validateT0BgOverrides(All, runs);
|
|
if (!t0BgValidation.ok) {
|
|
alert(t0BgValidation.message);
|
|
setFitStatus("Check the t₀/background overrides.", {
|
|
level: "error",
|
|
details: t0BgValidation.message
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
}
|
|
|
|
// Global fitting always starts from a template. Use the cached editor-owned
|
|
// template verbatim when locked; otherwise generate a fresh one from the GUI.
|
|
let templateMSR = templateEditorSource ? window.MSREditor.templateContent : createMSR();
|
|
if (!templateMSR || templateMSR.trim() === "") {
|
|
setFitStatus("The active template editor is empty.", {
|
|
level: "error",
|
|
details: "Template source is active, but the template editor is empty."
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
let templateName = runs[0] + "_tmpl.msr";
|
|
let templatePath = workPath + "/" + templateName;
|
|
// The runnable MSR is written exactly once, below, after the GUI parameter
|
|
// table has been applied in memory. Only a global/msr2data fit needs the
|
|
// separate template file on the server.
|
|
let preparedContent = templateMSR;
|
|
if (needsGlobalMSR) {
|
|
if (!await writeAsciiFile(templatePath, templateMSR)) {
|
|
return({ ok: 0 });
|
|
}
|
|
} else {
|
|
templatePath = "";
|
|
}
|
|
|
|
// Multiple logical data sets use a template-first workflow. This applies to
|
|
// Asymmetry and SingleHist alike: msr2data expands the template to each main
|
|
// run, while ADDRUN decoration is intentionally deferred until afterwards.
|
|
if (needsGlobalMSR) {
|
|
runM2D = true;
|
|
if (!webOrApp) {
|
|
let runList = runs.join(" ");
|
|
let msr2dataGlobal = workPath + "/" + runs[0] + "+global_tmpl.msr";
|
|
if (fileExists(msr2dataGlobal) && typeof deleteAsciiFile === "function") {
|
|
if (!deleteAsciiFile(msr2dataGlobal)) {
|
|
setFitStatus("Could not prepare the global MSR.", {
|
|
level: "error",
|
|
details: "Failed to remove stale global MSR before running msr2data: " + msr2dataGlobal
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
}
|
|
|
|
let addRunSpec = !templateEditorSource
|
|
? buildAddRunSpec(runSelection, All.selYear, All.instrName, All.dataRoot) : [];
|
|
let cmdM2D = msr2data + " \"[" + runList + "]\" _tmpl msr-" + runs[0] + " global";
|
|
if (typeof appendJobLog === "function") {
|
|
let workDirectory = workPath;
|
|
if (typeof displayCommand === "function") {
|
|
workDirectory = displayCommand(workPath, []);
|
|
}
|
|
appendJobLog("$ cd " + workDirectory + " && " + cmdM2D);
|
|
}
|
|
let m2dRes = executeCapture(cmdM2D, workPath);
|
|
if (m2dRes.stdout && m2dRes.stdout.trim() !== "") {
|
|
appendJobLog("msr2data output:\n" + m2dRes.stdout.trim());
|
|
}
|
|
setFitStatus("msr2data finished with exit code " + m2dRes.code + ".", {
|
|
level: m2dRes.code === 0 ? "info" : "warning"
|
|
});
|
|
if (m2dRes.stderr && m2dRes.stderr.trim() !== "") {
|
|
setFitStatus("msr2data reported diagnostics.", {
|
|
level: "warning",
|
|
details: "msr2data stderr:\n" + m2dRes.stderr.trim()
|
|
});
|
|
}
|
|
let generatedGlobalContent = fileExists(msr2dataGlobal) ? await readAsciiFile(msr2dataGlobal) : "";
|
|
if (isValidGeneratedGlobalMSR(generatedGlobalContent)) {
|
|
// Normalize immediately after msr2data so the Plot button opens the same
|
|
// multi-run view that Fit would eventually show after musrfit.
|
|
let normalizedGlobalContent = normalizeMSRPlotRuns(generatedGlobalContent, All, runs);
|
|
if (!templateEditorSource) {
|
|
// GUI overrides are safe only for GUI-generated templates. An edited
|
|
// template must flow through msr2data without hidden GUI mutations.
|
|
normalizedGlobalContent = applyT0BgOverridesToMSR(normalizedGlobalContent, All, runs);
|
|
// msr2data copies template ADDRUN lines unchanged, so multi-data-set
|
|
// templates deliberately contain none. Insert the correct additions
|
|
// only after expansion and before musrfit/musrview see the global file.
|
|
let missingTargets = missingAddRunTargets(normalizedGlobalContent, addRunSpec);
|
|
if (missingTargets.length > 0) {
|
|
setFitStatus("Not all ADDRUN data sets could be matched.", {
|
|
level: "error",
|
|
details: "Could not match all ADDRUN data sets in msr2data output. Fit/plot cancelled."
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
normalizedGlobalContent = applyAddRunsToMSR(
|
|
normalizedGlobalContent, runSelection, All.selYear, All.instrName, All.dataRoot
|
|
);
|
|
}
|
|
preparedContent = normalizedGlobalContent;
|
|
if (msr2dataGlobal !== finalPath && typeof deleteAsciiFile === "function"
|
|
&& fileExists(msr2dataGlobal) && !deleteAsciiFile(msr2dataGlobal)) {
|
|
setFitStatus("Temporary msr2data file was not removed.", {
|
|
level: "warning",
|
|
details: "Could not remove temporary msr2data file: " + msr2dataGlobal
|
|
});
|
|
}
|
|
if (m2dRes.code !== 0) {
|
|
setFitStatus("Global MSR prepared with warnings.", {
|
|
level: "warning",
|
|
details: "msr2data returned code " + m2dRes.code + " but produced a valid global MSR."
|
|
});
|
|
}
|
|
} else {
|
|
// Do not silently fit the template for a requested global fit. That would
|
|
// look successful while using the wrong model/file.
|
|
setFitStatus("msr2data did not produce a valid global MSR.", {
|
|
level: "error",
|
|
details: "msr2data did not produce a valid global MSR. Fit/plot cancelled."
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
}
|
|
}
|
|
|
|
// Apply the current GUI parameter table in memory, then write the runnable
|
|
// MSR once. The web CGI applies the same spec immediately before musrfit, so
|
|
// no read-back synchronization pass is required.
|
|
if (!templateEditorSource && parameterSyncSpec.parameters.length > 0) {
|
|
preparedContent = applyFitParameterSpecToMSR(preparedContent, parameterSyncSpec);
|
|
}
|
|
if (!await writeAsciiFile(finalPath, preparedContent)) {
|
|
setFitStatus("Could not write the prepared MSR.", {
|
|
level: "error",
|
|
details: "Failed to write prepared MSR file: " + finalPath
|
|
});
|
|
return({ ok: 0 });
|
|
}
|
|
|
|
// Keep the editor model aligned with the files written for this action.
|
|
// Single-run fits expose only the runnable MSR. Global fits also expose the
|
|
// template used by msr2data so expert users can inspect the expansion input.
|
|
let finalContent = preparedContent;
|
|
updateJobStatus({
|
|
templatePath: templatePath,
|
|
resultMSR: finalPath
|
|
});
|
|
if (runM2D) {
|
|
window.MSREditor.templateContent = templateMSR;
|
|
window.MSREditor.templatePath = templatePath;
|
|
window.MSREditor.currentContent = finalContent;
|
|
window.MSREditor.globalContent = finalContent;
|
|
window.MSREditor.hasTemplateTab = true;
|
|
|
|
if (templateEditorSource) {
|
|
// Saving/preparing an editor-owned template does not surrender its lock.
|
|
acceptMSRTextAsKnown(templateMSR, "template");
|
|
setMSREditorDirty(false, "template");
|
|
} else {
|
|
rememberGeneratedMSR(templateMSR, "template");
|
|
markMSREditorAsGUIOwned(templateMSR, "template");
|
|
setMSREditorDirty(false, "template");
|
|
}
|
|
|
|
// The runnable/global file has just been regenerated from this template.
|
|
// It is therefore current and GUI/generated until the user edits it.
|
|
let currentState = getMSRDocumentState("current");
|
|
currentState.sourceOfTruth = "gui";
|
|
currentState.locked = false;
|
|
currentState.dirty = false;
|
|
currentState.lastGeneratedHash = hashMSRText(finalContent);
|
|
currentState.lastAcceptedHash = hashMSRText(finalContent);
|
|
currentState.stale = false;
|
|
} else {
|
|
window.MSREditor.templateContent = "";
|
|
window.MSREditor.templatePath = "";
|
|
window.MSREditor.currentContent = finalContent;
|
|
window.MSREditor.globalContent = "";
|
|
window.MSREditor.hasTemplateTab = false;
|
|
|
|
// Single-run mode has no template/global relationship, so reset the unused
|
|
// template state and treat the runnable file as the generated GUI document.
|
|
window.MSREditor.documents.template = {
|
|
sourceOfTruth: "gui", locked: false, dirty: false,
|
|
lastGeneratedHash: "", lastAcceptedHash: "", stale: false
|
|
};
|
|
let currentState = getMSRDocumentState("current");
|
|
currentState.sourceOfTruth = "gui";
|
|
currentState.locked = false;
|
|
currentState.dirty = false;
|
|
currentState.lastGeneratedHash = hashMSRText(finalContent);
|
|
currentState.lastAcceptedHash = hashMSRText(finalContent);
|
|
currentState.stale = false;
|
|
}
|
|
window.MSREditor.activeSource = "current";
|
|
syncMSREditorLegacyState();
|
|
|
|
window.MSREditor.currentPath = finalPath;
|
|
loadMSRIntoEditor(finalContent, finalPath, true, { guiOwned: true });
|
|
|
|
setFitStatus("Template written.", {
|
|
level: "info",
|
|
details: templatePath ? "Template written: " + templatePath
|
|
: "MSR prepared: " + finalPath
|
|
});
|
|
if (runM2D) {
|
|
setFitStatus("Global MSR prepared.", {
|
|
level: "success",
|
|
details: "Global file prepared with msr2data: " + finalPath
|
|
});
|
|
} else {
|
|
setFitStatus(actionLabel + " MSR prepared.", {
|
|
level: "success",
|
|
details: actionLabel + " file prepared: " + finalPath
|
|
});
|
|
}
|
|
|
|
return({
|
|
ok: 1,
|
|
finalPath: finalPath,
|
|
options: {
|
|
useM2D: runM2D ? 1 : 0,
|
|
runs: runs.join(" "),
|
|
templateName: templateName,
|
|
baseRun: runs[0],
|
|
fftv: "n",
|
|
// The web CGI needs the resolved ADDRUN directives only after msr2data has
|
|
// expanded a multi-data-set template. Single-data-set MSRs already contain
|
|
// their ADDRUN lines, so sending the spec again is harmlessly unnecessary.
|
|
addRunSpec: (!templateEditorSource && runM2D)
|
|
? JSON.stringify(buildAddRunSpec(runSelection, All.selYear, All.instrName, All.dataRoot))
|
|
: "",
|
|
fitParameterSpec: (!templateEditorSource && parameterSyncSpec.parameters.length > 0)
|
|
? JSON.stringify(parameterSyncSpec) : "",
|
|
// Preserve how the global file was produced so runners can keep template
|
|
// ownership separate from the returned runnable/global MSR.
|
|
templateEditorSource: templateEditorSource ? 1 : 0
|
|
}
|
|
});
|
|
}
|
|
|
|
function seriesFitFailureMessage(reason, result = {}) {
|
|
let messages = {
|
|
"file-access-unavailable": "Could not inspect the existing series files.",
|
|
"web-series-inventory-failed": "Could not inspect the web series files.",
|
|
"web-series-inventory-incomplete": "The web series inventory was incomplete.",
|
|
"web-series-inventory-invalid": "The web series inventory was invalid.",
|
|
"reusable-reference-not-found": "No reusable series reference was found.",
|
|
"skipped-missing-msr": "A run is set to skip but has no MSR file on disk "
|
|
+ "(it may have been deleted; change that run to refit, or remove it from the fit)",
|
|
"series-bootstrap-first-run-blocked": "The first selected run has no complete data set.",
|
|
"series-bootstrap-template-invalid": "The first-run template could not be generated safely.",
|
|
"series-bootstrap-result-not-readable": "The fitted first-run MSR could not be read.",
|
|
"series-bootstrap-reference-invalid": "The fitted first run could not be validated as a series reference.",
|
|
"series-bootstrap-reference-not-reusable": "The fitted first run is not yet a mature series reference.",
|
|
"reference-msr-not-readable": "The reference MSR could not be read.",
|
|
"reference-msr-not-converged": "The reference MSR has not converged.",
|
|
"reference-fit-parameters-not-found": "The reference MSR has no fit parameters.",
|
|
"candidate-validation-failed": "One or more series MSRs could not be prepared safely.",
|
|
"series-runner-unavailable": "The independent series runner is unavailable.",
|
|
"series-candidate-staging-failed": "A series MSR could not be staged safely.",
|
|
"series-candidate-stage-uncertain": "The staged series MSR could not be verified.",
|
|
"series-candidate-run-failed": "An independent run fit failed.",
|
|
"series-candidate-run-failed-retained": "An independent run fit failed; its MSR was kept.",
|
|
"series-candidate-result-invalid": "A fitted series MSR did not pass validation.",
|
|
"series-candidate-result-invalid-retained": "A fitted series MSR did not pass validation and was kept.",
|
|
"series-candidate-retention-failed": "The failed series MSR could not be retained safely.",
|
|
"series-candidate-rollback-failed": "A failed series MSR could not be restored safely.",
|
|
"series-candidate-commit-uncertain": "The fitted series MSR could not be finalized safely."
|
|
};
|
|
let message = messages[reason] || "The independent series fit could not continue.";
|
|
let failedRun = result.failed && result.failed.run;
|
|
if (failedRun) message += " Run " + failedRun + ".";
|
|
return message;
|
|
}
|
|
|
|
function seriesSequenceFailureDetails(sequence) {
|
|
let failed = sequence && sequence.failed ? sequence.failed : {};
|
|
let details = [];
|
|
let runResult = failed.runResult || {};
|
|
if (runResult.reason) details.push("Validation: " + runResult.reason);
|
|
if (runResult.error) details.push("Runner: " + runResult.error);
|
|
let finalization = failed.commit || failed.finalization || failed.recovery;
|
|
if (finalization && Array.isArray(finalization.errors)) {
|
|
for (let error of finalization.errors) {
|
|
if (error && error.message) details.push("Finalization: " + error.message);
|
|
}
|
|
}
|
|
if (failed.retained && failed.targetPath) {
|
|
details.push("Output kept: " + failed.targetPath);
|
|
}
|
|
return details.join("\n");
|
|
}
|
|
|
|
async function synchronizeLastSeriesResult(sequence) {
|
|
if (!sequence || !Array.isArray(sequence.completed)
|
|
|| sequence.completed.length === 0) return;
|
|
let completed = sequence.completed[sequence.completed.length - 1];
|
|
let runResult = completed.runResult || {};
|
|
let resultPath = runResult.targetPath || completed.targetPath;
|
|
updateJobStatus({
|
|
resultMSR: resultPath,
|
|
logPath: runResult.logPath || ""
|
|
});
|
|
let fittedMSR = await readAsciiFile(resultPath);
|
|
if (!fittedMSR || typeof fittedMSR !== "string") return;
|
|
|
|
updateFitStatisticFromMSR(fittedMSR);
|
|
if (typeof loadMSRIntoEditor === "function") {
|
|
// Keep the selected run series intact while exposing the most recent
|
|
// fitted document and values. Full settings synchronization would replace
|
|
// the run list with this one candidate.
|
|
loadMSRIntoEditor(fittedMSR, resultPath, true, {
|
|
guiOwned: true,
|
|
syncGUI: false
|
|
});
|
|
}
|
|
if (typeof syncParametersFromMSR === "function") {
|
|
syncParametersFromMSR(fittedMSR);
|
|
}
|
|
}
|
|
|
|
function seriesDataSetText(dataSet) {
|
|
let normalized = normalizeSeriesDataSet(dataSet);
|
|
return normalized ? [normalized.main].concat(normalized.add).join("+") : "";
|
|
}
|
|
|
|
// Describe the fitted per-run files that may be collected after an independent
|
|
// series completes. This is deliberately separate from candidate preparation:
|
|
// collection never changes, refits, or reclassifies an individual result.
|
|
function buildIndependentSeriesArtifactSpec(plan, config = {}) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-series-artifact-plan",
|
|
workPath: String(config.workPath || ""),
|
|
fileNameSuffix: String(config.fileNameSuffix || ""),
|
|
runs: [],
|
|
msrPaths: [],
|
|
fftv: config.fftv == "y" ? "y" : "n"
|
|
};
|
|
if (!plan || plan.ok !== true || plan.mode != "series"
|
|
|| !Array.isArray(plan.entries) || plan.entries.length < 2
|
|
|| result.workPath === "" || result.fileNameSuffix === "") {
|
|
return result;
|
|
}
|
|
|
|
for (let entry of plan.entries) {
|
|
// A deliberate skip means "leave this run out", not "reuse its current
|
|
// file". Reusable skips are converged fits and remain valid inputs to
|
|
// msr2data; user-requested skips must not leak into the aggregate table.
|
|
if (entry && entry.action == "skip" && entry.reusable !== true) {
|
|
continue;
|
|
}
|
|
if (!entry || entry.action == "blocked" || !entry.dataSet
|
|
|| !Number.isInteger(entry.dataSet.main) || entry.dataSet.main <= 0
|
|
|| typeof entry.msrPath !== "string" || entry.msrPath === "") {
|
|
result.reason = "incomplete-series-artifact-plan";
|
|
return result;
|
|
}
|
|
result.runs.push(entry.dataSet.main.toString());
|
|
result.msrPaths.push(entry.msrPath);
|
|
}
|
|
if (result.runs.length < 2) {
|
|
result.reason = "insufficient-series-artifact-runs";
|
|
return result;
|
|
}
|
|
if (new Set(result.runs).size !== result.runs.length) {
|
|
result.reason = "duplicate-series-artifact-run";
|
|
return result;
|
|
}
|
|
result.baseRun = result.runs[0];
|
|
result.ok = true;
|
|
result.reason = "series-artifact-plan-ready";
|
|
return result;
|
|
}
|
|
|
|
// Normalize the platform-neutral part of a completed-series collection. Local
|
|
// filesystem confinement and web URL/job checks remain adapter responsibilities,
|
|
// but artifact names and the data exchanged with the CGI must be identical.
|
|
function prepareIndependentSeriesCollection(spec) {
|
|
let invalid = function(reason) {
|
|
return {
|
|
ok: false,
|
|
reason: reason || "invalid-series-artifact-spec",
|
|
workPath: "",
|
|
fileNameSuffix: "",
|
|
runs: [],
|
|
msrPaths: [],
|
|
fftv: "n",
|
|
baseRun: "",
|
|
combinedName: "",
|
|
parameterName: "",
|
|
logName: ""
|
|
};
|
|
};
|
|
if (!spec || spec.ok !== true || !Array.isArray(spec.runs)
|
|
|| spec.runs.length < 2 || !Array.isArray(spec.msrPaths)
|
|
|| spec.msrPaths.length !== spec.runs.length
|
|
|| typeof spec.workPath !== "string" || spec.workPath === ""
|
|
|| !/^_[A-Za-z0-9._+\-]+$/.test(spec.fileNameSuffix || "")) {
|
|
return invalid("invalid-series-artifact-spec");
|
|
}
|
|
let runs = spec.runs.map(function(run) { return String(run); });
|
|
if (runs.some(function(run) { return !/^\d+$/.test(run) || Number(run) <= 0; })
|
|
|| new Set(runs).size !== runs.length
|
|
|| spec.msrPaths.some(function(path) {
|
|
return typeof path !== "string" || path === "";
|
|
})) {
|
|
return invalid("series-artifact-source-invalid");
|
|
}
|
|
let baseRun = runs[0];
|
|
let suffix = spec.fileNameSuffix;
|
|
return {
|
|
ok: true,
|
|
reason: "series-collection-request-ready",
|
|
workPath: spec.workPath,
|
|
fileNameSuffix: suffix,
|
|
runs: runs,
|
|
msrPaths: spec.msrPaths.slice(),
|
|
fftv: spec.fftv == "y" ? "y" : "n",
|
|
baseRun: baseRun,
|
|
combinedName: baseRun + "+series" + suffix + ".msr",
|
|
parameterName: baseRun + "+series" + suffix + "_par.dat",
|
|
logName: baseRun + "+series" + suffix + ".out"
|
|
};
|
|
}
|
|
|
|
function buildIndependentSeriesCollectionRequest(spec, combinedMSR) {
|
|
let prepared = prepareIndependentSeriesCollection(spec);
|
|
if (!prepared.ok) return prepared;
|
|
return {
|
|
ok: true,
|
|
version: 1,
|
|
runs: prepared.runs.slice(),
|
|
suffix: prepared.fileNameSuffix,
|
|
fftv: prepared.fftv,
|
|
artifacts: {
|
|
combined: prepared.combinedName,
|
|
parameters: prepared.parameterName,
|
|
log: prepared.logName
|
|
},
|
|
combinedMSR: typeof combinedMSR === "string" ? combinedMSR : ""
|
|
};
|
|
}
|
|
|
|
function normalizeIndependentSeriesCollectionResult(value) {
|
|
value = value && typeof value === "object" ? value : {};
|
|
let result = {
|
|
ok: false,
|
|
reason: typeof value.reason === "string" && value.reason
|
|
? value.reason : "series-artifacts-not-produced",
|
|
parameterDataPath: typeof value.parameterDataPath === "string"
|
|
? value.parameterDataPath : "",
|
|
combinedMSRPath: typeof value.combinedMSRPath === "string"
|
|
? value.combinedMSRPath : "",
|
|
logPath: typeof value.logPath === "string" ? value.logPath : "",
|
|
plotPath: typeof value.plotPath === "string" ? value.plotPath : "",
|
|
plotPaths: Array.isArray(value.plotPaths)
|
|
? value.plotPaths.filter(function(path) {
|
|
return typeof path === "string" && path !== "";
|
|
}) : [],
|
|
packagePath: typeof value.packagePath === "string" ? value.packagePath : "",
|
|
templatePath: typeof value.templatePath === "string" ? value.templatePath : "",
|
|
plotStarted: value.plotStarted === true,
|
|
warnings: Array.isArray(value.warnings)
|
|
? value.warnings.filter(function(warning) {
|
|
return typeof warning === "string" && warning !== "";
|
|
}) : []
|
|
};
|
|
result.ok = Boolean(result.parameterDataPath || result.combinedMSRPath);
|
|
if (result.ok && (!value.reason || value.reason == "series-artifacts-not-produced")) {
|
|
result.reason = "series-artifacts-collected";
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async function collectIndependentSeriesArtifacts(plan, config, webMode) {
|
|
let spec = buildIndependentSeriesArtifactSpec(plan, config);
|
|
if (!spec.ok) {
|
|
return { ok: false, reason: spec.reason, warnings: [
|
|
"The completed series could not be prepared for parameter collection."
|
|
] };
|
|
}
|
|
let collector = webMode
|
|
? window.collectIndependentSeriesArtifactsWeb
|
|
: window.collectIndependentSeriesArtifactsLocal;
|
|
if (typeof collector !== "function") {
|
|
return { ok: false, reason: "series-artifact-collector-unavailable", warnings: [
|
|
"Series parameter collection is unavailable."
|
|
] };
|
|
}
|
|
|
|
updateJobStatus({
|
|
state: "Collecting series",
|
|
message: "Collecting fitted-run parameters.",
|
|
messageDetail: "Running msr2data for the merged parameter table and assembling the combined display MSR.",
|
|
noticeLevel: "info"
|
|
});
|
|
appendJobLog("Collecting " + spec.runs.length
|
|
+ " independent fitted runs with msr2data.");
|
|
let artifacts;
|
|
try {
|
|
artifacts = await collector(spec);
|
|
} catch (error) {
|
|
artifacts = {
|
|
ok: false,
|
|
reason: "series-artifact-collection-failed",
|
|
warnings: [error && error.message ? error.message : "Series collection failed."]
|
|
};
|
|
}
|
|
artifacts = normalizeIndependentSeriesCollectionResult(artifacts);
|
|
let status = {};
|
|
if (artifacts.parameterDataPath) status.parameterDataPath = artifacts.parameterDataPath;
|
|
if (artifacts.combinedMSRPath) status.resultMSR = artifacts.combinedMSRPath;
|
|
if (artifacts.logPath) status.logPath = artifacts.logPath;
|
|
if (artifacts.plotPath) status.plotPath = artifacts.plotPath;
|
|
if (artifacts.packagePath) status.packagePath = artifacts.packagePath;
|
|
if (artifacts.templatePath) status.templatePath = artifacts.templatePath;
|
|
if (Object.keys(status).length > 0) updateJobStatus(status);
|
|
for (let warning of (Array.isArray(artifacts.warnings) ? artifacts.warnings : [])) {
|
|
if (warning) appendJobLog("Series post-processing warning: " + warning);
|
|
}
|
|
return artifacts;
|
|
}
|
|
|
|
// When no fitted reference exists, make the first selected data set runnable
|
|
// directly from the current GUI model. This is the series equivalent of the
|
|
// normal single-run template: it never enters msr2data/global preparation.
|
|
function prepareSeriesBootstrapCandidate(plan, config = {}, fitConfig = null) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "invalid-series-plan",
|
|
referenceRun: 0,
|
|
referencePath: "",
|
|
candidates: [],
|
|
excluded: [],
|
|
errors: []
|
|
};
|
|
if (!plan || !plan.ok || plan.mode != "series"
|
|
|| !Array.isArray(plan.entries) || plan.entries.length === 0) {
|
|
return result;
|
|
}
|
|
|
|
let entry = plan.entries[0];
|
|
let pendingActions = new Set(["fit", "retry", "refit"]);
|
|
if (!entry || !pendingActions.has(entry.action)
|
|
|| (Array.isArray(entry.missingDataRuns) && entry.missingDataRuns.length > 0)) {
|
|
// The bootstrap seed is not required to be the first selected run. When
|
|
// an upstream run is skipped or lacks complete data (e.g. the only run
|
|
// needing a fit is a later one whose MSR was deleted), seed from the
|
|
// first pending run that has all its data so the fit can continue.
|
|
entry = null;
|
|
for (let candidate of plan.entries) {
|
|
if (pendingActions.has(candidate.action)
|
|
&& (!Array.isArray(candidate.missingDataRuns)
|
|
|| candidate.missingDataRuns.length === 0)) {
|
|
entry = candidate;
|
|
break;
|
|
}
|
|
}
|
|
if (!entry) {
|
|
result.reason = "series-bootstrap-first-run-blocked";
|
|
return result;
|
|
}
|
|
}
|
|
|
|
let all = Object.assign({}, config.all || {});
|
|
all.runNumbers = seriesDataSetText(entry.dataSet);
|
|
let generatedConfig = fitConfig || collectFitConfigFromDOM();
|
|
generatedConfig = Object.assign({}, generatedConfig, {
|
|
all: all,
|
|
// The route decision has already established that this is independent.
|
|
sharedFlags: {}
|
|
});
|
|
|
|
let templateMSR = "";
|
|
try {
|
|
// buildMSR already emits lifetimecorrection for SingleHist, but reconcile
|
|
// here too so the first-run candidate is never out of step with the GUI.
|
|
templateMSR = applySeriesPlotLifetimeCorrection(buildMSR(generatedConfig), all);
|
|
} catch (error) {
|
|
result.reason = "series-bootstrap-template-invalid";
|
|
result.errors.push({
|
|
run: entry.run,
|
|
reason: error && error.message ? error.message : "template-generation-failed"
|
|
});
|
|
return result;
|
|
}
|
|
let validation = validateSeriesMSRCandidate(templateMSR, entry.dataSet, all);
|
|
if (!validation.ok) {
|
|
result.reason = "series-bootstrap-template-invalid";
|
|
result.errors.push({ run: entry.run, reason: validation.reason });
|
|
return result;
|
|
}
|
|
|
|
result.ok = true;
|
|
result.reason = "series-bootstrap-template-ready";
|
|
result.candidates.push({
|
|
run: entry.run,
|
|
dataSet: normalizeSeriesDataSet(entry.dataSet),
|
|
action: entry.action,
|
|
targetName: entry.msrName,
|
|
targetPath: entry.msrPath,
|
|
expectedTargetText: entry.msrExists ? entry.msrText : "",
|
|
expectedTargetHash: entry.msrExists ? entry.msrHash : "",
|
|
text: templateMSR,
|
|
parameterNamesChanged: 0,
|
|
runBlocks: validation.runBlocks
|
|
});
|
|
return result;
|
|
}
|
|
|
|
async function runSeriesSequenceWithProgress(
|
|
prepared, adapter, runner, workPath, options = {}
|
|
) {
|
|
let positionOffset = Number(options.positionOffset || 0);
|
|
let overallTotal = Number(options.total || prepared.candidates.length);
|
|
return runPreparedSeriesFitSequence(
|
|
prepared,
|
|
adapter,
|
|
async function(receipt, candidate, context) {
|
|
let position = positionOffset + context.position;
|
|
let progress = "Fitting run " + candidate.run + " ("
|
|
+ position + "/" + overallTotal + ")";
|
|
updateJobStatus({
|
|
state: "Running series",
|
|
file: candidate.targetName,
|
|
directory: workPath,
|
|
resultMSR: candidate.targetPath,
|
|
message: progress,
|
|
messageDetail: progress + " as an independent fit.",
|
|
noticeLevel: "info"
|
|
});
|
|
appendJobLog(progress + ".");
|
|
let result = await runner(receipt, candidate, Object.assign({}, context, {
|
|
position: position,
|
|
total: overallTotal
|
|
}));
|
|
appendJobLog(result && result.statusText
|
|
? result.statusText : "Run " + candidate.run + " finished.");
|
|
return result;
|
|
},
|
|
{ transactionId: options.transactionId }
|
|
);
|
|
}
|
|
|
|
async function promoteBootstrapAsSeriesReference(plan, config, bootstrapSequence) {
|
|
let result = {
|
|
ok: false,
|
|
reason: "series-bootstrap-result-not-readable",
|
|
plan: null,
|
|
referenceMSRText: "",
|
|
classification: null
|
|
};
|
|
if (!bootstrapSequence || bootstrapSequence.ok !== true
|
|
|| bootstrapSequence.completed.length !== 1) return result;
|
|
|
|
let completed = bootstrapSequence.completed[0];
|
|
let runResult = completed.runResult || {};
|
|
let resultPath = runResult.targetPath || completed.targetPath;
|
|
let fittedMSR = await readAsciiFile(resultPath);
|
|
if (typeof fittedMSR !== "string" || fittedMSR.trim() === "") return result;
|
|
|
|
// The bootstrapped run is not necessarily the first selected run (upstream
|
|
// runs may be skipped, or the only run needing a fit may be a later one
|
|
// whose MSR was deleted). Match the completed bootstrap candidate back to
|
|
// its plan entry so the reference identity and classification use the run
|
|
// that was actually fitted.
|
|
let bootRun = completed.run
|
|
|| (completed.candidate && completed.candidate.run);
|
|
let bootEntry = bootRun
|
|
? plan.entries.find(function(e) { return e.run === bootRun; }) : null;
|
|
if (!bootEntry) bootEntry = plan.entries[0];
|
|
let firstEntry = bootEntry;
|
|
if (!isValidGeneratedGlobalMSR(fittedMSR)) {
|
|
result.reason = "series-bootstrap-reference-invalid";
|
|
return result;
|
|
}
|
|
|
|
// Maturity controls whether an existing result may be skipped on a later
|
|
// invocation. It must not block a fit that completed and was validated in
|
|
// this operation from serving as the reference for the remaining runs.
|
|
// requiredLaterRuns=0 reuses the normal identity/statistic checks without
|
|
// granting the file permanent maturity; the session flag exists only in
|
|
// this in-memory plan and is recalculated from inventory next time.
|
|
let classification = classifySeriesFitResult({
|
|
expectedDataSet: firstEntry.dataSet,
|
|
expectedInstrument: config.all.instrName || "",
|
|
expectedYear: config.all.selYear || "",
|
|
msrExists: true,
|
|
msrText: fittedMSR,
|
|
availableDataRuns: plan.availableDataRuns,
|
|
requiredLaterRuns: 0
|
|
});
|
|
result.classification = classification;
|
|
if (classification.reusable !== true || classification.action != "skip") {
|
|
result.reason = "series-bootstrap-reference-invalid";
|
|
return result;
|
|
}
|
|
classification = Object.assign({}, classification, {
|
|
state: "converged-current-session",
|
|
action: "skip",
|
|
reusable: true,
|
|
reason: "fitted-in-current-series",
|
|
sessionReference: true
|
|
});
|
|
result.classification = classification;
|
|
|
|
let referenceEntry = Object.assign({}, firstEntry, {
|
|
msrExists: true,
|
|
msrText: fittedMSR,
|
|
msrHash: hashMSRText(fittedMSR),
|
|
state: classification.state,
|
|
action: classification.action,
|
|
reusable: classification.reusable,
|
|
reason: classification.reason,
|
|
classification: classification
|
|
});
|
|
result.ok = true;
|
|
result.reason = "series-bootstrap-reference-ready";
|
|
result.referenceMSRText = fittedMSR;
|
|
result.plan = Object.assign({}, plan, {
|
|
entries: [referenceEntry].concat(
|
|
plan.entries.filter(function(e) { return e !== bootEntry; })
|
|
)
|
|
});
|
|
result.plan.summary = summarizeSeriesFitEntries(result.plan.entries);
|
|
return result;
|
|
}
|
|
|
|
// Execute the independent route selected by currentFitExecution(). Planning is
|
|
// read-only, every candidate is fitted in its own transaction, and a successful
|
|
// prefix remains committed if a later candidate fails.
|
|
async function runIndependentSeriesFit(execution, webMode) {
|
|
if (webMode && typeof loadWebDataRoot === "function") {
|
|
let loaded = await loadWebDataRoot();
|
|
if (!loaded) {
|
|
finishJobStatus(0, 1, "Could not read the muSR data root from the web server.");
|
|
return 0;
|
|
}
|
|
prepCFG();
|
|
}
|
|
|
|
let runSelection = parseRunSelection(All.runNumbers || "");
|
|
let firstRun = runSelection.length > 0 ? runSelection[0].main.toString() : "";
|
|
let workPath = All.workPath && All.workPath !== ""
|
|
? All.workPath : defaultWorkPath;
|
|
if (webMode) {
|
|
if (window.MusrfitWebJob.firstRun !== firstRun) {
|
|
let randomPart = (Math.random() + 1).toString(36).substring(7);
|
|
window.MusrfitWebJob.firstRun = firstRun;
|
|
window.MusrfitWebJob.workPath = "/tmp/" + randomPart;
|
|
}
|
|
workPath = window.MusrfitWebJob.workPath;
|
|
} else {
|
|
let directoryCheck = checkDir(workPath);
|
|
if (!directoryCheck.ok) {
|
|
finishJobStatus(0, 1, directoryCheck.message);
|
|
return 0;
|
|
}
|
|
}
|
|
All.workPath = workPath;
|
|
let fileNameSuffix = fitFileSuffix(All, webMode);
|
|
All.fileNameSuffix = fileNameSuffix;
|
|
let config = {
|
|
all: Object.assign({}, All),
|
|
runSelection: runSelection,
|
|
sharedFlags: collectSharedParameterControls(),
|
|
crossRunCoupling: false,
|
|
webMode: webMode,
|
|
workPath: workPath,
|
|
fileNameSuffix: fileNameSuffix,
|
|
actionOverrides: collectSeriesActionOverrides(),
|
|
guiEditedRuns: collectSeriesGUIEditedRuns()
|
|
};
|
|
|
|
updateJobStatus({
|
|
state: "Inspecting series",
|
|
directory: workPath,
|
|
message: "Checking existing independent fits.",
|
|
messageDetail: "Checking existing MSR files and raw data before fitting.",
|
|
noticeLevel: "info"
|
|
});
|
|
appendJobLog("Independent series route selected for "
|
|
+ execution.dataSetCount + " data sets.");
|
|
|
|
let plan = webMode
|
|
? await inspectSeriesFitPlanWeb(config)
|
|
: await inspectSeriesFitPlan(config);
|
|
if (!plan.ok) {
|
|
let message = seriesFitFailureMessage(plan.reason, plan);
|
|
finishJobStatus(0, 1, message + "\nReason: " + plan.reason);
|
|
return 0;
|
|
}
|
|
|
|
// Inventory decides which entries need raw data. Reused results and explicit
|
|
// skips remain offline; download only missing fit/refit inputs, then inspect
|
|
// again so staging uses the newly available files and exact filenames.
|
|
let platform = window.MusRFlowPlatform;
|
|
let missingEntries = plan.entries.filter(function(entry) {
|
|
return entry.action === 'blocked' && entry.reason === 'required-data-not-found';
|
|
});
|
|
if (!webMode && missingEntries.length && platform && typeof platform.ensureRunData === 'function') {
|
|
let data = await platform.ensureRunData({ all: config.all, action: 'Fit', series: true,
|
|
runSelection: missingEntries.map(function(entry) { return entry.dataSet; }) });
|
|
if (!data.ok) {
|
|
finishJobStatus(0, 1, data.message, data.outcome);
|
|
return 0;
|
|
}
|
|
config.all = Object.assign({}, All);
|
|
plan = await inspectSeriesFitPlan(config);
|
|
if (!plan.ok) {
|
|
finishJobStatus(0, 1, seriesFitFailureMessage(plan.reason, plan));
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
// Snapshot the per-run statistics for the status bar before anything runs.
|
|
// Plan entries already parsed them from the existing MSR files, so reused
|
|
// and skipped runs are visible too; the write-back below refreshes the rows
|
|
// that are actually fitted.
|
|
window.MusrfitJob.seriesStatistic = collectSeriesStatisticRows(plan);
|
|
|
|
let reused = plan.entries.filter(function(entry) {
|
|
return entry.action == "skip" && entry.reusable === true;
|
|
}).length;
|
|
let skipped = plan.entries.filter(function(entry) {
|
|
return entry.action == "skip" && entry.reusable !== true;
|
|
}).length;
|
|
let initiallyBlocked = plan.entries.filter(function(entry) {
|
|
return entry.action == "blocked";
|
|
});
|
|
let pendingTotal = plan.summary.fit + plan.summary.retry + plan.summary.refit;
|
|
if (pendingTotal === 0 && reused === 0 && initiallyBlocked.length === 0) {
|
|
// Explicitly skipped runs are intentionally absent from both fitting and
|
|
// collection. Do not manufacture an aggregate from files the user chose
|
|
// to leave out.
|
|
let message = "No run is scheduled: 0 fitted, 0 reused, " + skipped
|
|
+ " skipped, 0 missing, 0 failed. Set at least one run to reuse or refit.";
|
|
updateJobStatus({
|
|
state: "Complete",
|
|
message: message,
|
|
messageDetail: message,
|
|
noticeLevel: "info",
|
|
finishedAt: jobTimestamp(),
|
|
exitCode: ""
|
|
});
|
|
appendJobLog(message);
|
|
return 1;
|
|
}
|
|
|
|
setMusrfitActionState("fit", "running");
|
|
let sequence;
|
|
if (pendingTotal === 0) {
|
|
// Reusing completed fits does not require the musrfit runner. Continue to
|
|
// the common post-processing path so msr2data refreshes the aggregate.
|
|
sequence = {
|
|
ok: initiallyBlocked.length === 0,
|
|
reason: initiallyBlocked.length > 0
|
|
? "series-no-runnable-candidates" : "series-already-complete",
|
|
completed: [],
|
|
excluded: plan.entries.slice(),
|
|
failed: null
|
|
};
|
|
} else {
|
|
let bootstrapSequence = null;
|
|
let referenceEntry = plan.entries.find(function(entry) {
|
|
return entry.reusable === true && entry.action == "skip" && entry.msrExists === true;
|
|
});
|
|
let adapter = window.MusrfitSeriesTransactionAdapter;
|
|
let runner = webMode
|
|
? window.runSeriesMSRCandidateWeb : window.runSeriesMSRCandidateLocal;
|
|
if (!adapter || typeof runner !== "function") {
|
|
let message = seriesFitFailureMessage("series-runner-unavailable");
|
|
finishJobStatus(0, 1, message);
|
|
return 0;
|
|
}
|
|
|
|
if (!referenceEntry) {
|
|
if (!validateRRFSettings("Fit", config.all)) {
|
|
finishJobStatus(0, 1, "Check the RRF settings before fitting the first run.");
|
|
return 0;
|
|
}
|
|
let t0BgValidation = validateT0BgOverrides(
|
|
config.all, [plan.entries[0].run]
|
|
);
|
|
if (!t0BgValidation.ok) {
|
|
finishJobStatus(0, 1, t0BgValidation.message);
|
|
return 0;
|
|
}
|
|
|
|
updateJobStatus({
|
|
state: "Preparing first run",
|
|
message: "Preparing the first-run template.",
|
|
messageDetail: "No reusable reference exists; generating the first selected run from the GUI.",
|
|
noticeLevel: "info"
|
|
});
|
|
appendJobLog("No reusable reference found; generating run "
|
|
+ plan.entries[0].run + " from the GUI.");
|
|
let bootstrap = prepareSeriesBootstrapCandidate(plan, config);
|
|
if (!bootstrap.ok) {
|
|
let message = seriesFitFailureMessage(bootstrap.reason, bootstrap);
|
|
finishJobStatus(0, 1, message + "\nReason: " + bootstrap.reason);
|
|
return 0;
|
|
}
|
|
bootstrapSequence = await runSeriesSequenceWithProgress(
|
|
bootstrap, adapter, runner, workPath, {
|
|
positionOffset: 0,
|
|
total: pendingTotal,
|
|
transactionId: "series-bootstrap-" + Date.now().toString(36)
|
|
}
|
|
);
|
|
if (!bootstrapSequence.ok) {
|
|
let message = seriesFitFailureMessage(bootstrapSequence.reason, bootstrapSequence);
|
|
let details = seriesSequenceFailureDetails(bootstrapSequence);
|
|
finishJobStatus(0, 1, message + "\nReason: " + bootstrapSequence.reason
|
|
+ (details ? "\n" + details : ""));
|
|
return 0;
|
|
}
|
|
|
|
let promoted = await promoteBootstrapAsSeriesReference(
|
|
plan, config, bootstrapSequence
|
|
);
|
|
if (!promoted.ok) {
|
|
let message = seriesFitFailureMessage(promoted.reason, promoted);
|
|
finishJobStatus(0, 1, message + "\nReason: " + promoted.reason);
|
|
return 0;
|
|
}
|
|
plan = promoted.plan;
|
|
referenceEntry = plan.entries[0];
|
|
config.referenceRun = referenceEntry.run;
|
|
config.referenceMSRText = promoted.referenceMSRText;
|
|
} else {
|
|
config.referenceMSRText = referenceEntry.msrText;
|
|
}
|
|
|
|
let prepared = await prepareSeriesMSRCandidates(plan, config);
|
|
if (!prepared.ok) {
|
|
let message = seriesFitFailureMessage(prepared.reason, prepared);
|
|
finishJobStatus(0, 1, message + "\nReason: " + prepared.reason);
|
|
return 0;
|
|
}
|
|
|
|
let positionOffset = bootstrapSequence ? bootstrapSequence.completed.length : 0;
|
|
sequence = await runSeriesSequenceWithProgress(
|
|
prepared, adapter, runner, workPath, {
|
|
positionOffset: positionOffset,
|
|
total: pendingTotal,
|
|
transactionId: "series-" + Date.now().toString(36)
|
|
}
|
|
);
|
|
if (bootstrapSequence) {
|
|
sequence.completed = bootstrapSequence.completed.concat(sequence.completed);
|
|
}
|
|
}
|
|
|
|
await synchronizeLastSeriesResult(sequence);
|
|
// Re-read the freshly built MSRs and refresh the status bar with the whole
|
|
// series spread instead of the last run's single statistic.
|
|
applySeriesFitStatistic(await synchronizeSeriesStatistics(sequence));
|
|
// Runs rebuilt by a successful refit are again represented by a fresh
|
|
// GUI-generated MSR, so their edit marker clears and the next inspection can
|
|
// classify them normally. Runs that were blocked or never ran keep the
|
|
// marker so their pending edits remain visible.
|
|
for (let completed of (Array.isArray(sequence.completed) ? sequence.completed : [])) {
|
|
let run = completed && completed.run;
|
|
if (run) clearSeriesRunParametersEdited(run);
|
|
}
|
|
let fitted = sequence.completed.length;
|
|
let blocked = sequence.excluded.filter(function(entry) {
|
|
return entry.action == "blocked";
|
|
});
|
|
|
|
if (sequence.ok) {
|
|
let artifacts = await collectIndependentSeriesArtifacts(plan, Object.assign({}, config, {
|
|
fftv: execution && execution.fftv ? execution.fftv : "n"
|
|
}), webMode);
|
|
if (artifacts.combinedMSRPath && typeof readAsciiFile === "function") {
|
|
// The parameter table must reflect every run's fitted values, not just
|
|
// the last one. The combined MSR used for the musrview display already
|
|
// contains them, so reuse it instead of parsing per-run files.
|
|
let combinedText = await readAsciiFile(artifacts.combinedMSRPath);
|
|
if (combinedText && typeof combinedText === "string") {
|
|
try {
|
|
syncSeriesParametersToGUI(combinedText);
|
|
} catch (error) {
|
|
artifacts.warnings.push("Could not update the parameter table from "
|
|
+ "the combined series MSR.");
|
|
}
|
|
}
|
|
}
|
|
let summary = fitted + " fitted, " + reused + " reused, " + skipped
|
|
+ " skipped, 0 missing, 0 failed.";
|
|
let message = sequence.reason == "series-already-complete"
|
|
? "No fits were run: " + summary
|
|
: "Independent series fit completed: " + summary;
|
|
if (artifacts.parameterDataPath) message += " Parameter table prepared.";
|
|
if (artifacts.plotStarted || artifacts.plotPath) message += " Combined plot opened.";
|
|
let warnings = Array.isArray(artifacts.warnings)
|
|
? artifacts.warnings.filter(Boolean) : [];
|
|
finishJobStatus(1, 0, message
|
|
+ (warnings.length ? "\nPost-processing warning: " + warnings.join("; ") : ""));
|
|
return 1;
|
|
}
|
|
if (sequence.reason == "series-sequence-completed-with-blocked-runs"
|
|
|| sequence.reason == "series-no-runnable-candidates") {
|
|
let message = "Independent series fit incomplete: " + fitted + " fitted, "
|
|
+ reused + " reused, " + skipped + " skipped, " + blocked.length
|
|
+ " missing, 0 failed.";
|
|
updateJobStatus({
|
|
state: "Incomplete",
|
|
message: message,
|
|
messageDetail: message,
|
|
noticeLevel: "warning",
|
|
finishedAt: jobTimestamp(),
|
|
exitCode: ""
|
|
});
|
|
appendJobLog(message);
|
|
return 0;
|
|
}
|
|
|
|
let failure = seriesFitFailureMessage(sequence.reason, sequence);
|
|
let outcome = "Independent series fit stopped: " + fitted + " fitted, "
|
|
+ reused + " reused, " + skipped + " skipped, " + blocked.length
|
|
+ " missing, " + (sequence.failed ? 1 : 0) + " failed.";
|
|
let code = sequence.failed && sequence.failed.runResult
|
|
&& sequence.failed.runResult.code !== undefined
|
|
? sequence.failed.runResult.code : 1;
|
|
let details = seriesSequenceFailureDetails(sequence);
|
|
finishJobStatus(0, code, failure + "\n" + outcome + "\nReason: " + sequence.reason
|
|
+ (details ? "\n" + details : ""));
|
|
return 0;
|
|
}
|
|
|
|
// Wait for any shell-provided runtime gate to report ready before a Fit/Plot
|
|
// action starts. Returns false (with a status message) when the gate reports a
|
|
// hard failure, so the action aborts instead of spawning a tool that cannot run.
|
|
async function ensureRuntimeGateReady(actionLabel) {
|
|
let gate = window.MusrfitRuntimeGate;
|
|
if (!gate || typeof gate.ready !== "function") return true;
|
|
let ready = true;
|
|
try {
|
|
ready = await gate.ready(actionLabel);
|
|
} catch (error) {
|
|
ready = false;
|
|
}
|
|
if (ready === false) {
|
|
setFitStatus("The " + actionLabel.toLowerCase()
|
|
+ " runtime is not ready. " + (typeof gate.message === "function"
|
|
? gate.message() : ""), { level: "error" });
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
async function startPlot() {
|
|
let webRequest = amIWeb();
|
|
if (window.MusrfitAction.busy || (webRequest && window.MusrfitWebRequestActive)) {
|
|
setFitStatus("A fit or plot action is already running.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (!validateRunSelection("Plot")) {
|
|
return(0);
|
|
}
|
|
if (!confirmOverwriteDirtyEditor("Plot")) {
|
|
setFitStatus("Plot cancelled; editor changes were kept.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (!(await ensureRuntimeGateReady("Plot"))) {
|
|
return(0);
|
|
}
|
|
if (window.MusrfitAction.busy || (webRequest && window.MusrfitWebRequestActive)) {
|
|
setFitStatus("A fit or plot action is already running.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (webRequest) {
|
|
window.MusrfitWebRequestActive = true;
|
|
}
|
|
setMusrfitActionState("plot", "preparing");
|
|
|
|
try {
|
|
beginJobPreparation("Plot");
|
|
let prepared = await prepareMSRRunFiles("Plot");
|
|
if (!prepared.ok) {
|
|
finishJobStatus(0, 1, prepared.message || "Plot file preparation failed.", prepared.outcome);
|
|
return(0);
|
|
}
|
|
prepared.options.plotOnly = 1;
|
|
setMusrfitActionState("plot", "running");
|
|
return await runMSRFile(prepared.finalPath, prepared.options);
|
|
} catch (error) {
|
|
let details = "Plot stopped unexpectedly."
|
|
+ (error && error.message ? "\n" + error.message : "");
|
|
finishJobStatus(0, 1, details);
|
|
return(0);
|
|
} finally {
|
|
if (webRequest) {
|
|
window.MusrfitWebRequestActive = false;
|
|
}
|
|
setMusrfitActionState("", "idle");
|
|
}
|
|
}
|
|
|
|
async function startFit() {
|
|
let webRequest = amIWeb();
|
|
if (window.MusrfitAction.busy || (webRequest && window.MusrfitWebRequestActive)) {
|
|
setFitStatus("A fit or plot action is already running.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (!validateRunSelection("Fit")) {
|
|
return(0);
|
|
}
|
|
if (!confirmOverwriteDirtyEditor("Fit")) {
|
|
setFitStatus("Fit cancelled; editor changes were kept.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (!(await ensureRuntimeGateReady("Fit"))) {
|
|
return(0);
|
|
}
|
|
if (window.MusrfitAction.busy || (webRequest && window.MusrfitWebRequestActive)) {
|
|
setFitStatus("A fit or plot action is already running.", { level: "warning" });
|
|
return(0);
|
|
}
|
|
if (webRequest) {
|
|
window.MusrfitWebRequestActive = true;
|
|
}
|
|
setMusrfitActionState("fit", "preparing");
|
|
|
|
try {
|
|
beginJobPreparation("Fit");
|
|
let execution = currentFitExecution();
|
|
if (execution.mode == "series") {
|
|
return await runIndependentSeriesFit(execution, webRequest);
|
|
}
|
|
let prepared = await prepareMSRRunFiles("Fit");
|
|
if (!prepared.ok) {
|
|
finishJobStatus(0, 1, prepared.message || "Fit file preparation failed.", prepared.outcome);
|
|
return(0);
|
|
}
|
|
prepared.options.plotOnly = 0;
|
|
setMusrfitActionState("fit", "running");
|
|
return await runMSRFile(prepared.finalPath, prepared.options);
|
|
} catch (error) {
|
|
let details = "Fit stopped unexpectedly."
|
|
+ (error && error.message ? "\n" + error.message : "");
|
|
finishJobStatus(0, 1, details);
|
|
return(0);
|
|
} finally {
|
|
if (webRequest) {
|
|
window.MusrfitWebRequestActive = false;
|
|
}
|
|
setMusrfitActionState("", "idle");
|
|
}
|
|
}
|
|
|
|
// URL deep links (web query strings on the deployed page and legacy desktop
|
|
// links such as musrflow://.../muSRFlow?action=plot&YEAR=...&BeamLine=...&
|
|
// RunNumbers=...) initialize the same run controls the user edits by hand.
|
|
// They live here in the shared library so both shells can apply them: the web
|
|
// page consumes them from the address bar, and the Electron renderer applies
|
|
// them when the main process forwards a protocol link it received.
|
|
function findWebURLSelectValue(selectElement, requestedValue) {
|
|
// URL values come from links written by people and older CGI pages, so match
|
|
// instrument names case-insensitively while still returning the exact option
|
|
// value used by the current GUI. No arbitrary DOM ids or values are accepted.
|
|
if (!selectElement || requestedValue === undefined || requestedValue === null) {
|
|
return "";
|
|
}
|
|
|
|
let requested = String(requestedValue).trim().toLowerCase();
|
|
if (requested === "") {
|
|
return "";
|
|
}
|
|
|
|
let options = selectElement.options ? Array.from(selectElement.options) : [];
|
|
for (let option of options) {
|
|
if (String(option.value).toLowerCase() === requested) {
|
|
return option.value;
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function applyWebURLParameters(search) {
|
|
// Deep links are deliberately a small whitelist. They initialize the same GUI
|
|
// controls a user would edit manually. The optional plot action is handled only
|
|
// after parameter initialization; server paths and other internal settings are
|
|
// never exposed through URL parameter names.
|
|
let result = {
|
|
applied: {},
|
|
errors: [],
|
|
action: ""
|
|
};
|
|
|
|
if (search === undefined || search === null) {
|
|
search = (typeof window !== "undefined" && window.location
|
|
&& typeof window.location.search === "string")
|
|
? window.location.search : "";
|
|
}
|
|
if (!search) {
|
|
return result;
|
|
}
|
|
|
|
let params = new URLSearchParams(search);
|
|
let instrumentInput = document.getElementById("instrName");
|
|
let yearInput = document.getElementById("selYear");
|
|
let runInput = document.getElementById("runNumbers");
|
|
if (!instrumentInput || !yearInput || !runInput) {
|
|
result.errors.push("Run controls are not available.");
|
|
return result;
|
|
}
|
|
|
|
// Apply the instrument first because it determines the minimum valid year and
|
|
// the default histogram groups used by the rest of the Runs tab.
|
|
if (params.has("BeamLine")) {
|
|
let requestedBeamLine = params.get("BeamLine");
|
|
let instrumentValue = findWebURLSelectValue(instrumentInput, requestedBeamLine);
|
|
if (instrumentValue) {
|
|
instrumentInput.value = instrumentValue;
|
|
result.applied.BeamLine = instrumentValue;
|
|
} else {
|
|
result.errors.push("Unsupported BeamLine: " + requestedBeamLine);
|
|
}
|
|
}
|
|
|
|
if (params.has("YEAR")) {
|
|
let requestedYear = String(params.get("YEAR") || "").trim();
|
|
let yearNumber = Number(requestedYear);
|
|
let currentMax = Number(yearInput.max) || new Date().getFullYear();
|
|
let instrument = (typeof instPars !== "undefined")
|
|
? instPars[instrumentInput.value] : null;
|
|
let minimumYear = instrument && instrument.minYear
|
|
? Number(instrument.minYear) : Number(yearInput.min || 0);
|
|
let validYear = /^\d{4}$/.test(requestedYear)
|
|
&& Number.isInteger(yearNumber)
|
|
&& yearNumber >= minimumYear
|
|
&& yearNumber <= currentMax;
|
|
|
|
if (validYear) {
|
|
yearInput.value = requestedYear;
|
|
result.applied.YEAR = requestedYear;
|
|
} else {
|
|
let rangeText = minimumYear > 0
|
|
? minimumYear + "-" + currentMax : "a supported four-digit year";
|
|
result.errors.push("Invalid YEAR " + requestedYear + " (expected " + rangeText + ").");
|
|
}
|
|
}
|
|
|
|
if (params.has("RunNumbers")) {
|
|
let requestedRuns = String(params.get("RunNumbers") || "").trim();
|
|
let expandedRuns = (typeof arrayRunNumbers === "function")
|
|
? arrayRunNumbers(requestedRuns) : [];
|
|
if (requestedRuns !== "" && expandedRuns.length > 0) {
|
|
// Preserve the compact text exactly as supplied so bookmarked links keep
|
|
// ranges such as 520-525 instead of expanding them into a long list.
|
|
runInput.value = requestedRuns;
|
|
result.applied.RunNumbers = requestedRuns;
|
|
} else {
|
|
result.errors.push("Invalid RunNumbers: " + (requestedRuns || "(empty)"));
|
|
}
|
|
}
|
|
|
|
if (params.has("action")) {
|
|
let requestedAction = String(params.get("action") || "").trim().toLowerCase();
|
|
if (requestedAction === "plot") {
|
|
// Automatic plotting is intentionally allowed only for a fully specified
|
|
// run deep link. YEAR may be omitted and then keeps the GUI's current year.
|
|
if (result.applied.BeamLine && result.applied.RunNumbers) {
|
|
result.action = "plot";
|
|
} else {
|
|
result.errors.push("action=plot requires BeamLine and RunNumbers.");
|
|
}
|
|
} else if (requestedAction !== "") {
|
|
result.errors.push("Unsupported action: " + requestedAction);
|
|
}
|
|
}
|
|
|
|
if (Object.keys(result.applied).length > 0) {
|
|
// Reuse the normal GUI update path so deep-link initialization cannot drift
|
|
// from manual editing behavior. This keeps histogram defaults, RUN-path
|
|
// validation, and the shared All object synchronized without generating MSR.
|
|
if (typeof defaultHistograms === "function") {
|
|
defaultHistograms(1);
|
|
}
|
|
if (typeof updateResolvedDataPathPreview === "function") {
|
|
updateResolvedDataPathPreview();
|
|
}
|
|
if (typeof prepCFG === "function") {
|
|
prepCFG();
|
|
}
|
|
}
|
|
|
|
if (result.errors.length > 0) {
|
|
let message = result.errors.join(" ");
|
|
if (typeof setRunInputWarning === "function") {
|
|
setRunInputWarning(message, "URL parameters");
|
|
}
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Some URL parameters were ignored.", {
|
|
level: "warning",
|
|
details: "URL parameters: " + message
|
|
});
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
async function triggerWebURLAction(result) {
|
|
if (!result || result.action !== "plot") return 0;
|
|
|
|
// Build the parameter table first. cfgParams() returns the pending initial-
|
|
// parameter guess, so a header-based Frq guess is guaranteed to finish before
|
|
// the URL-triggered Plot starts. If guessing is disabled, this resolves at once.
|
|
if (typeof cfgParams === "function") {
|
|
let guess = cfgParams();
|
|
if (guess && typeof guess.then === "function") {
|
|
await guess;
|
|
}
|
|
}
|
|
|
|
if (typeof startPlot !== "function") {
|
|
if (typeof setFitStatus === "function") {
|
|
setFitStatus("Plot is not available for this URL.", {
|
|
level: "error",
|
|
details: "URL action: Plot is not available."
|
|
});
|
|
}
|
|
return 0;
|
|
}
|
|
return await startPlot();
|
|
}
|