Add prompt-peak t0 estimation preference for non-LEM data

The Electron Preferences dialog gains an "Estimate t0 from the prompt
peak (non-LEM data)" option (on by default). For local fits of non-LEM
instruments, muSRFlow now runs 'musrt0 --getT0FromPromptPeak' before
'musrfit' to write explicit t0 lines from the histogram peak into the
generated MSR; the step is skipped automatically for LEM data and when
the preference is disabled. The preference is stored locally and wired
through save/open/cancel. Documentation and CHANGELOG updated; new
electron tests cover the gating behavior, and existing tests adjusted
to work with the added pre-step.
This commit is contained in:
salman committed 2026-10-10 17:29:00 +02:00
1 parent 184c5b9eb1
commit f9d19bc57a
7 files changed
+305 -7

No files matched your search

+6
View File
@@ -50,6 +50,12 @@ release path documented in [`TODO.md`](TODO.md).
ignored by the web edition (fits run on the server). This mirrors the
thread-count preference in musredit and is useful on shared workstations.
- The Electron **Preferences** dialog now includes an **Estimate t0 from the
prompt peak (non-LEM data)** option (on by default). For local fits of
non-LEM instruments, muSRFlow runs `musrt0 --getT0FromPromptPeak` before
`musrfit` to write explicit `t0` lines from the histogram peak into the
generated MSR; the step is skipped automatically for LEM data.
## 1.0.0-rc.4 (2026-09-23)
### Parameter ordering
+7
View File
@@ -43,6 +43,13 @@ Initial parameters
sensible starting values (for example an approximate frequency or
asymmetry) instead of generic defaults.
**Estimate t0 from the prompt peak (non-LEM data)** (on by default): before a
local fit, muSRFlow runs ``musrt0 --getT0FromPromptPeak`` to write explicit
``t0`` lines into the generated MSR. This forces musrfit to use the
histogram peak as the time-zero for instruments whose data-file header t0 is
unreliable; the step is skipped automatically for LEM data. Uncheck it to
preserve the MSR as generated.
Output file suffixes
The suffixes appended to generated artifacts: **Asymmetry** (default
``_asy``) and **Single histogram** (default ``_singleHist``). Change
+6 -1
View File
@@ -25,7 +25,7 @@
<script src="muSRFitlib.js"></script>
<title>muSRFlow</title>
</head>
<body onload="adjustComps();defaultHistograms(1);updateTheoryBlock();updatePlotOptionVisibility();cfgFFTRRF();initializeDataRoot();initializeWorkPath();initializeFileSuffixes();initializeInitialParameterGuessPreference();initializeStartupXml();initializeBinDir();initializeMusrfitThreads();if (amIWeb() && typeof initializeWebURLParameters === 'function') initializeWebURLParameters();">
<body onload="adjustComps();defaultHistograms(1);updateTheoryBlock();updatePlotOptionVisibility();cfgFFTRRF();initializeDataRoot();initializeWorkPath();initializeFileSuffixes();initializeInitialParameterGuessPreference();initializeT0FromPromptPeak();initializeStartupXml();initializeBinDir();initializeMusrfitThreads();if (amIWeb() && typeof initializeWebURLParameters === 'function') initializeWebURLParameters();">
<main class="app-shell" id="appShell" aria-busy="false">
<div class="app-card">
<div class="tab">
@@ -776,6 +776,11 @@ pairs of a multi-run (global) fit.">
<input type="checkbox" id="guessInitialParameters" checked>
<span>Guess initial parameters from first-run header</span>
</label>
<label class="preferences-check-row" for="estimateT0FromPromptPeak">
<input type="checkbox" id="estimateT0FromPromptPeak" checked>
<span>Estimate t0 from the prompt peak (non-LEM data)</span>
</label>
<span class="preferences-hint" id="estimateT0FromPromptPeakHint">Before a local fit, run <code>musrt0 --getT0FromPromptPeak</code> so t0 is written from the histogram peak. Applies to every instrument except LEM, whose data file already carries a reliable t0.</span>
<div class="preferences-section-title">Output file suffixes</div>
<div class="settings-grid settings-grid-2 preferences-suffix-grid">
<label class="settings-field" for="asymmetrySuffix">
+66 -6
View File
@@ -758,6 +758,7 @@ function openElectronPreferences() {
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
preferences.dataset.originalWorkPath = workPath ? workPath.value : ".";
preferences.dataset.originalDataRoot = dataRoot ? dataRoot.value : "";
preferences.dataset.originalStartupXml = startupXml ? startupXml.value : "";
@@ -766,6 +767,7 @@ function openElectronPreferences() {
preferences.dataset.originalAsymmetrySuffix = asymmetrySuffix ? asymmetrySuffix.value : "_asy";
preferences.dataset.originalSingleHistSuffix = singleHistSuffix ? singleHistSuffix.value : "_singleHist";
preferences.dataset.originalGuessInitialParameters = guessInitialParameters && guessInitialParameters.checked ? "1" : "0";
preferences.dataset.originalEstimateT0FromPromptPeak = estimateT0FromPromptPeak && estimateT0FromPromptPeak.checked ? "1" : "0";
if (!preferences.dataset.cancelHandlerInstalled) {
preferences.addEventListener("cancel", function(event) {
event.preventDefault();
@@ -796,6 +798,7 @@ function saveElectronPreferences() {
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
if (typeof setConfiguredWorkPath === "function" && workPath) {
setConfiguredWorkPath(workPath.value, true);
}
@@ -817,6 +820,9 @@ function saveElectronPreferences() {
if (typeof setConfiguredInitialParameterGuess === "function" && guessInitialParameters) {
setConfiguredInitialParameterGuess(guessInitialParameters.checked, true);
}
if (typeof setConfiguredT0FromPromptPeak === "function" && estimateT0FromPromptPeak) {
setConfiguredT0FromPromptPeak(estimateT0FromPromptPeak.checked, true);
}
if (typeof setConfiguredFileSuffix === "function") {
if (asymmetrySuffix) {
setConfiguredFileSuffix("asymmetrySuffix", asymmetrySuffixStorageKey,
@@ -841,6 +847,7 @@ function cancelElectronPreferences() {
let asymmetrySuffix = document.getElementById("asymmetrySuffix");
let singleHistSuffix = document.getElementById("singleHistSuffix");
let guessInitialParameters = document.getElementById("guessInitialParameters");
let estimateT0FromPromptPeak = document.getElementById("estimateT0FromPromptPeak");
if (workPath) workPath.value = preferences.dataset.originalWorkPath || ".";
if (dataRoot) dataRoot.value = preferences.dataset.originalDataRoot || "";
if (startupXml) startupXml.value = preferences.dataset.originalStartupXml || "";
@@ -851,6 +858,9 @@ function cancelElectronPreferences() {
if (guessInitialParameters) {
guessInitialParameters.checked = preferences.dataset.originalGuessInitialParameters !== "0";
}
if (estimateT0FromPromptPeak) {
estimateT0FromPromptPeak.checked = preferences.dataset.originalEstimateT0FromPromptPeak !== "0";
}
if (typeof updateResolvedDataPathPreview === "function") updateResolvedDataPathPreview();
if (typeof updateStartupNamingSourceIndicator === "function") updateStartupNamingSourceIndicator();
closeElectronPreferences();
@@ -1677,12 +1687,39 @@ async function runMSRFileLocal(fullPath, options = {}) {
return 1;
}
// The first phase performs the fit. Whether it succeeds or fails, we still
// open musrview on the resulting MSR so users can inspect why a fit did not
// converge. Parameter export and GUI synchronization only apply to a
// successful fit, whose MSR contains the fitted values.
let fitResult = await runLocalProcess("musrfit", musrfit, musrfitArgs, fitDir, logFile);
window.MusrfitRunner.fitActive = false;
// The first phase performs the fit. Whether it succeeds or fails, we still
// open musrview on the resulting MSR so users can inspect why a fit did not
// converge. Parameter export and GUI synchronization only apply to a
// successful fit, whose MSR contains the fitted values.
// For instruments whose data-file header t0 is unreliable (everything except
// LEM), force t0 to the prompt peak before fitting. musrt0 writes explicit
// `t0` lines into the generated MSR, which musrfit then always honors. This is
// a best-effort pre-step: if musrt0 fails, musrfit still runs and reports the
// real problem.
let instrumentNameForT0 = (typeof activeInstrumentName === "function")
? activeInstrumentName() : ((typeof All !== "undefined" && All && All.instrName) ? All.instrName : "");
if (typeof shouldEstimateT0FromPromptPeak === "function" && shouldEstimateT0FromPromptPeak(instrumentNameForT0)) {
let musrt0 = resolveLocalCommand("musrt0");
if (typeof appendJobLog === "function") {
appendJobLog("Estimating t0 from the prompt peak for non-LEM data.");
}
try {
let t0Result = await runLocalProcess("musrt0", musrt0, [fitName, "-g"], fitDir, logFile, {
reportStatus: false
});
if (t0Result && t0Result.ok !== 1 && typeof appendJobLog === "function") {
appendJobLog("musrt0 prompt-peak estimation did not complete; continuing with the MSR as-is.");
}
} catch (err) {
if (typeof appendJobLog === "function") {
appendJobLog("musrt0 prompt-peak estimation failed: " + (err ? err.message : err) + "; continuing with the MSR as-is.");
}
}
}
let fitResult = await runLocalProcess("musrfit", musrfit, musrfitArgs, fitDir, logFile);
if (window.MusrfitRunner) window.MusrfitRunner.fitActive = false;
// A missing input is not a failed minimization and there is no useful result
// for musrview to inspect. The process runner has already reported the path.
if (fitResult.outcome == "missing-data") {
@@ -1934,3 +1971,26 @@ function firstLoad() {
// Load the local startup XML after the Preferences field is initialized.
loadLocalPortableRunNaming();
}
function activeInstrumentName() {
let element = document.getElementById("instrName");
if (element && typeof element.value === "string") {
return element.value.trim();
}
if (typeof All !== "undefined" && All && All.instrName) {
return String(All.instrName).trim();
}
return "";
}
function shouldEstimateT0FromPromptPeak(instrumentName) {
if (typeof getConfiguredT0FromPromptPeak === "function" && !getConfiguredT0FromPromptPeak()) {
return false;
}
let name = String(instrumentName || "").toUpperCase();
if (name === "LEM") {
return false;
}
return true;
}
+38
View File
@@ -27,6 +27,10 @@ var binDirStorageKey = "musrflow.binDir";
// "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 is unreliable (everything except LEM). 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;
@@ -8884,6 +8888,40 @@ function initializeInitialParameterGuessPreference() {
setConfiguredInitialParameterGuess(enabled, false);
}
// Prompt-peak t0 preference. Enabled by default so non-LEM data gets t0 from
// the histogram peak before a local fit; users can opt out, and LEM data is
// 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 [];
+12
View File
@@ -68,6 +68,14 @@ const sandbox = {
window: {
MSREditor: {},
electronIpcRenderer: { on: function() {}, send: function() {} },
localStorage: (function() {
const store = {};
return {
getItem: function(k){ return Object.prototype.hasOwnProperty.call(store,k)?store[k]:null; },
setItem: function(k,v){ store[k]=String(v); },
removeItem: function(k){ delete store[k]; }
};
})(),
nodeChildProcess: fakeChildProcess,
nodeFs: fakeFs,
nodePath: path
@@ -86,6 +94,10 @@ vm.runInNewContext(
{ filename: "muSRFitelec.js" }
);
if (sandbox.setConfiguredT0FromPromptPeak) {
sandbox.setConfiguredT0FromPromptPeak(false, true);
}
sandbox.appendJobLog = function() {
};
sandbox.updateJobStatus = function() {
+170
View File
@@ -0,0 +1,170 @@
// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
// Regression coverage for the prompt-peak t0 preference. When enabled and the
// instrument is non-LEM, runMSRFileLocal() runs musrt0 --getT0FromPromptPeak
// before musrfit so explicit t0 lines are written into the MSR. When the
// instrument is LEM, or the preference is disabled, musrt0 must not run.
const assert = require("assert");
const events = require("events");
const fs = require("fs");
const path = require("path");
const vm = require("vm");
const repoRoot = path.resolve(__dirname, "..");
const missingOutput = [
"PRunDataHandler::FileExistsCheck(): **ERROR** Couldn't find "
+ "'/mnt/fake/gps/his/2026/gps26_his_0514' in any standard path.",
"musrfit **ERROR** Couldn't read all data files, will quit ..."
].join("\n");
const missingOutputMusrfitOnly = [
"musrfit **ERROR** Couldn't read all data files, will quit ..."
].join("\n");
function localStoreFactory() {
const store = {};
return {
getItem: function(key) {
return Object.prototype.hasOwnProperty.call(store, key) ? store[key] : null;
},
setItem: function(key, value) { store[key] = String(value); },
removeItem: function(key) { delete store[key]; }
};
}
function buildSandbox(msrContent, elements) {
const spawnedCommands = [];
const fakeFs = {
appendFileSync: function() {},
existsSync: function() { return false; },
readFileSync: function() { return msrContent; },
writeFileSync: function() {}
};
const fakeChildProcess = {
spawn: function(command, args) {
spawnedCommands.push({ command: command, args: args });
const child = new events.EventEmitter();
child.stdout = new events.EventEmitter();
child.stderr = new events.EventEmitter();
setImmediate(function() {
if (command === "musrt0") {
child.stderr.emit("data", Buffer.from(""));
child.emit("close", 0, null);
} else {
child.stderr.emit("data", Buffer.from(missingOutput));
child.emit("close", 1, null);
}
});
return child;
}
};
const dom = elements || {};
const localStorage = localStoreFactory();
const sandbox = {
alert: function(message) {
throw new Error("Unexpected alert: " + message);
},
console: { log: function() {}, error: console.error, warn: console.warn },
document: {
getElementById: function(id) {
return Object.prototype.hasOwnProperty.call(dom, id) ? dom[id] : null;
}
},
process: { cwd: function() { return repoRoot; }, env: {}, resourcesPath: "" },
require: require,
window: {
All: {},
MSREditor: {},
MusrfitRunner: { fitActive: false },
MusrFlowPlatform: { webMode: false },
localStorage: localStorage,
electronIpcRenderer: { on: function() {}, send: function() {} },
nodeChildProcess: fakeChildProcess,
nodeFs: fakeFs,
nodePath: path
}
};
sandbox.global = sandbox;
return { sandbox: sandbox, spawnedCommands: spawnedCommands, localStorage: localStorage };
}
function loadLibraries(sandbox) {
vm.runInNewContext(
fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"),
sandbox,
{ filename: "muSRFitlib.js" }
);
vm.runInNewContext(
fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8"),
sandbox,
{ filename: "muSRFitelec.js" }
);
}
function runFit(sandbox, msrPath) {
sandbox.appendJobLog = function() {};
sandbox.updateJobStatus = function() {};
sandbox.setFitStatus = function() {};
sandbox.finishJobStatus = function() {};
return sandbox.runMSRFileLocal(msrPath, {});
}
const guiMsr = "# Run Numbers: 514 2453 2454\n# Chisq ...\nFITPARAM ...";
Promise.resolve().then(function() {
// Default preference (on), non-LEM instrument: musrt0 runs before musrfit.
let env = buildSandbox(guiMsr, { instrName: { value: "GPS" } });
loadLibraries(env.sandbox);
assert.strictEqual(env.sandbox.getConfiguredT0FromPromptPeak(), true);
return runFit(env.sandbox, "/tmp/gps-fit.msr").then(function() {
assert.ok(env.spawnedCommands.length >= 2, "expect musrt0 and musrfit");
assert.strictEqual(env.spawnedCommands[0].command, "musrt0");
assert.ok(env.spawnedCommands[0].args.includes("-g"), "musrt0 should receive -g");
assert.strictEqual(env.spawnedCommands[1].command, "musrfit");
return "default-nonlem-runs-musrt0";
});
}).then(function() {
// LEM instrument: musrt0 must not run even if preference is default on.
let env = buildSandbox(guiMsr, { instrName: { value: "LEM" } });
loadLibraries(env.sandbox);
assert.strictEqual(env.sandbox.getConfiguredT0FromPromptPeak(), true);
return runFit(env.sandbox, "/tmp/lem-fit.msr").then(function() {
const musrt0 = env.spawnedCommands.find(function(entry) { return entry.command === "musrt0"; });
const musrfit = env.spawnedCommands.find(function(entry) { return entry.command === "musrfit"; });
assert.strictEqual(musrt0, undefined, "musrt0 must not run for LEM");
assert.ok(musrfit, "musrfit must still run");
return "lem-skips-musrt0";
});
}).then(function() {
// Preference disabled, non-LEM: musrt0 must not run.
let env = buildSandbox(guiMsr, { instrName: { value: "GPS" } });
loadLibraries(env.sandbox);
env.localStorage.setItem("musrflow.estimateT0FromPromptPeak", "0");
assert.strictEqual(env.sandbox.getConfiguredT0FromPromptPeak(), false);
return runFit(env.sandbox, "/tmp/gps-no-t0.msr").then(function() {
const musrt0 = env.spawnedCommands.find(function(entry) { return entry.command === "musrt0"; });
const musrfit = env.spawnedCommands.find(function(entry) { return entry.command === "musrfit"; });
assert.strictEqual(musrt0, undefined, "musrt0 must not run when preference disabled");
assert.ok(musrfit, "musrfit must still run");
return "disabled-skips-musrt0";
});
}).then(function() {
// Preference explicitly enabled via API, instrument empty (treat as non-LEM): musrt0 runs.
let env = buildSandbox(guiMsr, {});
loadLibraries(env.sandbox);
env.sandbox.setConfiguredT0FromPromptPeak(true, true);
assert.strictEqual(env.localStorage.getItem("musrflow.estimateT0FromPromptPeak"), "1");
return runFit(env.sandbox, "/tmp/unknown-fit.msr").then(function() {
const musrt0 = env.spawnedCommands.find(function(entry) { return entry.command === "musrt0"; });
assert.ok(musrt0, "musrt0 should run for unknown instrument when enabled");
return "enabled-unknown-runs-musrt0";
});
}).then(function() {
console.log("Electron prompt-peak t0 preference tests passed");
}).catch(function(error) {
console.error(error);
process.exitCode = 1;
});