Files
muSRFlow/tests/parameter-plot.test.js
T

1184 lines
60 KiB
JavaScript

// Copyright (C) 2026 Zaher Salman
// SPDX-License-Identifier: GPL-3.0-or-later
const assert = require("assert");
const childProcess = require("child_process");
const fs = require("fs");
const os = require("os");
const path = require("path");
const vm = require("vm");
const repoRoot = path.resolve(__dirname, "..");
function loadParameterPlotLibrary() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
const sandbox = {
console: console,
window: {},
document: {},
Promise: Promise,
Set: Set
};
sandbox.global = sandbox;
vm.runInNewContext(code, sandbox, { filename: "muSRFitParameterPlot.js" });
return sandbox;
}
function testParserAndSmartDefaults() {
const lib = loadParameterPlotLibrary();
const dataset = lib.parseMusrfitParameterData([
"% RUN dataT dataB Alpha dAlpha Lambda dLambda",
"514 5 100 0.22 0.01 0.30 0.02",
"515 10 100 0.24 0.01 0.27 0.02",
"",
"# ignored comment"
].join("\n"));
assert.deepStrictEqual(Array.from(dataset.columns),
["RUN", "dataT", "dataB", "Alpha", "dAlpha", "Lambda", "dLambda"]);
assert.strictEqual(dataset.rows.length, 2);
assert.strictEqual(lib.defaultMusrfitParameterXColumn(dataset), 1);
assert.deepStrictEqual(Array.from(lib.musrfitParameterYCandidates(dataset, 1)), [3, 5]);
assert.strictEqual(lib.defaultMusrfitParameterErrorColumn(dataset, 3), 4);
assert.strictEqual(lib.defaultMusrfitParameterErrorColumn(dataset, 5), 6);
assert.strictEqual(lib.musrfitParameterAxisLabel("dataT"), "T (K)");
assert.strictEqual(lib.musrfitParameterAxisLabel("dataSpinRot"), "SR (°)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Asy"), "A₀");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lam"), "λ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Sgm"), "σ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Phi"), "φ (°)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Frq"), "ν (MHz)");
assert.strictEqual(lib.musrfitParameterAxisLabel("custom_parameter"), "custom_parameter");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lam1"), "λ₁ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lam2"), "λ₂ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lam12"), "λ₁₂ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lambda1"), "λ₁ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Sgm2"), "σ₂ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Alpha1"), "α₁");
assert.strictEqual(lib.musrfitParameterAxisLabel("Asy1"), "A₀₁");
assert.strictEqual(lib.musrfitParameterAxisLabel("Bet2"), "β₂");
assert.strictEqual(lib.musrfitParameterAxisLabel("Del1"), "Δ₁");
assert.strictEqual(lib.musrfitParameterAxisLabel("Gam3"), "Γ₃");
assert.strictEqual(lib.musrfitParameterAxisLabel("Phi2"), "φ₂ (°)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Frq2"), "ν₂ (MHz)");
assert.strictEqual(lib.musrfitParameterAxisLabel("Lam"), "λ (μs⁻¹)");
assert.strictEqual(lib.musrfitParameterAxisLabel("custom1"), "custom1");
assert.strictEqual(lib.musrfitParameterAxisLabel("dataT5"), "dataT5");
assert.strictEqual(lib.musrfitParameterAxisLabel("Asy_2274"), "Asy_2274");
const constantTemperature = lib.parseMusrfitParameterData([
"RUN dataT Alpha dAlpha",
"514 5 0.22 0.01",
"515 5 0.24 0.01"
].join("\n"));
assert.strictEqual(lib.defaultMusrfitParameterXColumn(constantTemperature), 0);
const asymmetric = lib.parseMusrfitParameterData([
"RUN dataT dataTErr Asy Asy_PosErr Asy_NegErr Lam Lam_PosErr Lam_NegErr",
"514 5.0 0.1 0.22 0.03 -0.02 0.30 0.04 0.05",
"515 6.0 0.1 0.24 0.02 -0.01 0.27 0.03 0.04"
].join("\n"));
assert.deepStrictEqual(Array.from(lib.musrfitParameterYCandidates(asymmetric, 1)), [3, 6]);
const errors = lib.musrfitParameterErrorColumns(asymmetric, 3);
assert.strictEqual(errors.positive, 4);
assert.strictEqual(errors.negative, 5);
const trace = lib.buildMusrfitParameterTrace(asymmetric, 1, 3, "markers");
assert.strictEqual(trace.name, "A₀");
assert.strictEqual(trace.error_y.symmetric, false);
assert.deepStrictEqual(Array.from(trace.error_y.array), [0.03, 0.02]);
assert.deepStrictEqual(Array.from(trace.error_y.arrayminus), [0.02, 0.01]);
assert.deepStrictEqual(Array.from(trace.error_x.array), [0.1, 0.1]);
assert.strictEqual(trace.error_x.width, 0);
assert.strictEqual(trace.error_y.width, 0);
const cappedTrace = lib.buildMusrfitParameterTrace(asymmetric, 1, 3, "markers", { cap: true });
assert.strictEqual(cappedTrace.error_x.width, 4);
assert.strictEqual(cappedTrace.error_y.width, 4);
// Depending on parameter sharing and the installed msr2data version, error
// labels may omit the separator before PosErr/NegErr. These real export
// forms must remain error columns rather than becoming selectable Y data.
const compactErrors = lib.parseMusrfitParameterData([
"RUN dataE Asy AsyPosErr AsyNegErr Asy_2255 Asy_2255PosErr Asy_2255NegErr",
"2255 2.0 0.20 0.03 0.02 0.21 0.04 0.03",
"2256 4.0 0.22 0.02 0.01 0.23 0.03 0.02"
].join("\n"));
assert.deepStrictEqual(Array.from(lib.musrfitParameterYCandidates(compactErrors, 1)), [2, 5]);
const sharedTrace = lib.buildMusrfitParameterTrace(compactErrors, 1, 2, "markers");
assert.deepStrictEqual(Array.from(sharedTrace.error_y.array), [0.03, 0.02]);
assert.deepStrictEqual(Array.from(sharedTrace.error_y.arrayminus), [0.02, 0.01]);
const runQualifiedTrace = lib.buildMusrfitParameterTrace(compactErrors, 1, 5, "markers");
assert.deepStrictEqual(Array.from(runQualifiedTrace.error_y.array), [0.04, 0.03]);
assert.deepStrictEqual(Array.from(runQualifiedTrace.error_y.arrayminus), [0.03, 0.02]);
}
function testIntegratedParameterTableHook() {
const html = fs.readFileSync(path.join(repoRoot, "index.html"), "utf8");
const web = fs.readFileSync(path.join(repoRoot, "muSRFitweb.js"), "utf8");
const lib = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8");
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
assert.match(html, /muSRFitParameterPlot\.js/);
assert.doesNotMatch(html, /id="resultParameterPlotButton"/);
assert.match(lib, /id = "plotSelectedParameters"/);
assert.match(lib, /selectParameterForPlot/);
assert.match(lib, /showMusrfitParameterAxisDialog\([\s\S]*selectedParameterPlotNames\.slice\(\)/);
assert.match(plot, /function showMusrfitParameterAxisDialog/);
assert.match(plot, /platform\.openPlot\(\{/);
assert.match(plot, /preferredParameters = \[\]/);
assert.match(plot, /preferredXColumn = ""/);
assert.match(plot, /musrfitParameterColumnIndex\(dataset, name\)/);
assert.match(plot, /platform\.createPlotWindow/);
assert.doesNotMatch(plot, /openElectronAuxiliaryWindow|require\("electron"\)|amIWeb\(|fetch\(/);
assert.match(plot, /refreshButton\.textContent = "Refresh"/);
assert.match(plot, /readMusrfitParameterData\(parameterPath\)/);
assert.match(plot, /layoutSelect/);
assert.match(plot, /optionsButton\.textContent = "Plot options"/);
assert.match(plot, /optionsPanel\.hidden = true/);
assert.match(plot, /dataSourceValue\.textContent/);
assert.doesNotMatch(plot, /parameter-plot-panel-caption/);
assert.match(plot, /parameter-plot-grid/);
assert.match(plot, /addButton\.addEventListener/);
assert.match(plot, /musrfitParameterErrorColumns/);
assert.match(plot, /mode: mode \|\| "markers"/);
assert.match(plot, /buildMusrfitParameterTrace\(dataset, xIndex, yIndex, mode, style\)/);
assert.match(plot, /buildMusrfitParameterOverlayTraces\(entries, panel\.xName, panel\.yNames/);
assert.match(plot, /panel\.mode = modeSelect\.value/);
assert.match(plot, /panel\.chart\.on\("plotly_click"/);
assert.doesNotMatch(plot, /plotly\.on\(/);
assert.match(plot, /clearParameterDataSetTraceStyles\(styleRegistry, panel\.dataSetKey\)/);
assert.match(plot, /title\.addEventListener\("pointerdown"/);
assert.match(plot, /picker\.style\.left/);
assert.match(plot, /content\.appendChild\(picker\)/);
assert.match(plot, /Error-bar caps/);
assert.match(plot, /picker\.dataset\.cap = capInput\.checked \? "1" : "0"/);
assert.match(plot, /if \(picker\.dataset\.cap !== undefined\) override\.cap = picker\.dataset\.cap === "1"/);
assert.doesNotMatch(plot, /modeSelect\.addEventListener\("change", redrawVisiblePanels\)/);
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
assert.match(main, /ipcMain\.on\("openParameterPlotWindow"/);
assert.match(main, /ipcMain\.handle\("selectParameterDataFile"/);
assert.strictEqual(fs.existsSync(path.join(repoRoot, "parameter-plot.html")), true);
assert.strictEqual(fs.existsSync(path.join(repoRoot, "parameter-plot-window.js")), true);
assert.doesNotMatch(html, /Open in musrfit plotter/);
assert.doesNotMatch(web, /MusrfitPlotterPath|\/MusrPlot\//);
}
function testPlatformSeparation() {
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
const elec = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8");
const elecAdapter = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlotElec.js"), "utf8");
const web = fs.readFileSync(path.join(repoRoot, "muSRFitweb.js"), "utf8");
const windowScript = fs.readFileSync(path.join(repoRoot, "parameter-plot-window.js"), "utf8");
const windowHtml = fs.readFileSync(path.join(repoRoot, "parameter-plot.html"), "utf8");
assert.doesNotMatch(plot, /require\(|openElectronAuxiliaryWindow|MusrfitStandaloneParameterPlot|amIWeb\(|fetch\(/);
assert.match(plot, /platform\.openPlot\(\{/);
assert.match(plot, /platform\.createPlotWindow/);
assert.match(plot, /platform\.readDataSource/);
assert.match(plot, /platform\.chooseDataSource/);
assert.match(plot, /platform\.loadPlotly/);
assert.match(elec, /MusrfitParameterPlotPlatform\.openPlot/);
assert.match(elec, /openElectronAuxiliaryWindow\("parameterPlot", options\)/);
assert.match(elecAdapter, /window\.electronAPI/);
assert.match(elecAdapter, /process\.plotlyURL/);
assert.match(elecAdapter, /createElement\(["']script["']\)/);
assert.match(elecAdapter, /require\(["']plotly\.js-dist["']\)/);
assert.match(elecAdapter, /readDataSource/);
assert.match(elecAdapter, /selectParameterDataFile/);
assert.match(web, /createWebMusrfitParameterPlotWindow/);
assert.match(web, /MusrfitParameterPlotPlatform\.createPlotWindow/);
assert.match(web, /MusrfitParameterPlotPlatform\.openPlot/);
assert.match(web, /MusrfitParameterPlotPlatform\.readDataSource/);
assert.match(windowScript, /MusrfitParameterPlotPlatform\.createPlotWindow/);
assert.match(windowScript, /showMusrfitParameterPlotWindow/);
assert.match(windowScript, /window\.electronAPI/);
assert.match(windowScript, /ipcRenderer\.on\("parameterPlotData"/);
assert.match(windowHtml, /muSRFitParameterPlotElec\.js/);
assert.doesNotMatch(windowHtml, /MusrfitStandaloneParameterPlot/);
}
function testElectronParameterExport() {
const code = fs.readFileSync(path.join(repoRoot, "muSRFitelec.js"), "utf8");
const root = fs.mkdtempSync(path.join(os.tmpdir(), "musrflow-param-export-"));
try {
const fakeMsr2data = path.join(root, "msr2data");
const fitted = path.join(root, "514_asy.msr");
const template = path.join(root, "514_tmpl.msr");
const log = path.join(root, "514_asy.out");
fs.writeFileSync(fitted, "FITPARAMETER\n1 Alpha 0.22 0.01\n");
fs.writeFileSync(template, "original template\n");
fs.writeFileSync(log, "");
fs.writeFileSync(fakeMsr2data, [
"#!/bin/sh",
"previous=''",
"for arg in \"$@\"; do",
" if [ \"$previous\" = '-o' ]; then printf 'RUN\\tAlpha_\\tAlpha_PosErr\\tAlpha_NegErr\\tmy_parameter\\n514\\t0.22\\t0.01\\t0.01\\t1.5\\n' > \"$arg\"; fi",
" previous=\"$arg\"",
"done",
"exit 0",
""
].join("\n"));
fs.chmodSync(fakeMsr2data, 0o755);
const ipc = { send: function() {}, on: function() {} };
const sandboxProcess = {
env: Object.assign({}, process.env),
resourcesPath: "",
cwd: function() { return root; }
};
const sandbox = {
console: console,
window: {
Plotly: {},
electronIpcRenderer: ipc,
nodeFs: fs,
nodePath: path,
nodeChildProcess: childProcess
},
process: sandboxProcess,
document: { getElementById: function() { return null; } },
alert: function(message) { throw new Error("Unexpected alert: " + message); },
require: require,
appendJobLog: function() {},
updateJobStatus: function() {}
};
sandbox.global = sandbox;
vm.runInNewContext(
fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"),
sandbox,
{ filename: "muSRFitlib.js" }
);
vm.runInNewContext(code, sandbox, { filename: "muSRFitelec.js" });
sandbox.resolveLocalCommand = function(name) {
return name === "msr2data" ? fakeMsr2data : name;
};
const output = sandbox.exportLocalMusrfitParameterData(fitted, {
runs: "514",
baseRun: 514
}, log);
assert.strictEqual(output, path.join(root, "514_asy_par.dat"));
assert.strictEqual(fs.readFileSync(output, "utf8").split(/\r?\n/)[0],
"RUN\tAlpha\tAlpha_PosErr\tAlpha_NegErr\tmy_parameter");
assert.strictEqual(fs.readFileSync(template, "utf8"), "original template\n");
assert.match(fs.readFileSync(log, "utf8"), /msr2data.*514.*_tmpl.*new.*data.*-o.*514_asy_par\.dat/);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
}
function testScanVariableDetection() {
const lib = loadParameterPlotLibrary();
const fieldOnly = lib.parseMusrfitParameterData([
"RUN dataB Asy dAsy",
"514 100 0.22 0.01",
"515 100 0.24 0.01",
"516 200 0.26 0.01",
"517 300 0.28 0.01"
].join("\n"));
const fieldScan = lib.detectMusrfitScanVariable(fieldOnly);
assert.strictEqual(fieldScan.name, "dataB");
assert.strictEqual(fieldScan.column, 1);
assert.strictEqual(fieldScan.confidence, "high");
assert.strictEqual(fieldScan.coverage, 1);
assert.strictEqual(fieldScan.distinct, 3);
assert.strictEqual(fieldScan.varying.length, 1);
const temperatureOnly = lib.parseMusrfitParameterData([
"RUN dataT dataB Asy dAsy",
"514 5 100 0.22 0.01",
"515 10 100 0.24 0.01",
"516 15 100 0.26 0.01"
].join("\n"));
const temperatureScan = lib.detectMusrfitScanVariable(temperatureOnly);
assert.strictEqual(temperatureScan.name, "dataT");
assert.strictEqual(temperatureScan.confidence, "high");
const energyOnly = lib.parseMusrfitParameterData([
"RUN dataE dataT Asy dAsy",
"514 2.0 5 0.22 0.01",
"515 4.0 5 0.24 0.01",
"516 6.0 5 0.26 0.01"
].join("\n"));
assert.strictEqual(lib.detectMusrfitScanVariable(energyOnly).name, "dataE");
const spinRotOnly = lib.parseMusrfitParameterData([
"RUN dataSpinRot dataT Asy dAsy",
"514 90 5 0.22 0.01",
"515 120 5 0.24 0.01",
"516 150 5 0.26 0.01"
].join("\n"));
assert.strictEqual(lib.detectMusrfitScanVariable(spinRotOnly).name, "dataSpinRot");
// Small drift in a secondary variable must not override the real scan.
const drift = lib.parseMusrfitParameterData([
"RUN dataT dataB Asy dAsy",
"514 5 100.00 0.22 0.01",
"515 10 100.10 0.24 0.01",
"516 15 100.20 0.26 0.01",
"517 20 100.30 0.28 0.01"
].join("\n"));
const driftScan = lib.detectMusrfitScanVariable(drift);
assert.strictEqual(driftScan.name, "dataT");
assert.strictEqual(driftScan.confidence, "high");
// Two genuinely varying scan variables must be reported as ambiguous.
const mixed = lib.parseMusrfitParameterData([
"RUN dataT dataB Asy dAsy",
"514 5 100 0.22 0.01",
"515 10 200 0.23 0.01",
"516 15 300 0.24 0.01"
].join("\n"));
const mixedScan = lib.detectMusrfitScanVariable(mixed);
assert.strictEqual(mixedScan.confidence, "ambiguous");
assert.deepStrictEqual(Array.from(mixedScan.varying).sort(), ["dataB", "dataT"]);
// Run-number fallback when no metadata varies.
const constant = lib.parseMusrfitParameterData([
"RUN dataT Asy dAsy",
"514 5 0.22 0.01",
"515 5 0.24 0.01"
].join("\n"));
assert.strictEqual(lib.detectMusrfitScanVariable(constant).name, "RUN");
assert.strictEqual(lib.defaultMusrfitParameterXColumn(constant), 0);
}
function testTfTemplateApplication() {
const lib = loadParameterPlotLibrary();
const templates = lib.MUSRFIT_PARAMETER_PLOT_TEMPLATES;
assert.ok(templates.length >= 1);
const tf = templates.find(function(t) { return t.id === "tf-scan"; });
assert.ok(tf);
assert.strictEqual(tf.layout, "3x1");
assert.strictEqual(tf.panels.length, 3);
const dataset = lib.parseMusrfitParameterData([
"% RUN dataB Asy dAsy Lam dLam Frq dFrq",
"514 100 0.22 0.01 0.30 0.02 12.5 0.1",
"515 200 0.24 0.01 0.27 0.02 12.8 0.1",
"516 300 0.26 0.01 0.24 0.02 13.1 0.1"
].join("\n"));
const names = lib.musrfitParameterTemplatePanelNames(dataset, tf.panels[0].params);
assert.ok(names.indexOf("Asy") >= 0 || names.indexOf("A0") >= 0);
const damping = Array.from(lib.musrfitParameterTemplatePanelNames(dataset, tf.panels[1].params));
assert.deepStrictEqual(damping, ["Lam"]);
const frequency = Array.from(lib.musrfitParameterTemplatePanelNames(dataset, tf.panels[2].params));
assert.deepStrictEqual(frequency, ["Frq"]);
// Unmatched roles are omitted rather than guessed.
const partial = lib.parseMusrfitParameterData([
"% RUN dataB Asy dAsy",
"514 100 0.22 0.01",
"515 200 0.24 0.01"
].join("\n"));
assert.deepStrictEqual(Array.from(lib.musrfitParameterTemplatePanelNames(partial, tf.panels[2].params)), []);
const applied = lib.applyMusrfitParameterTemplate("tf-scan", dataset, "dataB");
assert.strictEqual(applied.layout, "3x1");
assert.strictEqual(applied.sharedX, true);
assert.strictEqual(applied.panels.length, 3);
assert.deepStrictEqual(Array.from(applied.panels[1].yNames), ["Lam"]);
assert.strictEqual(applied.xName, "dataB");
const unknown = lib.applyMusrfitParameterTemplate("does-not-exist", dataset, "");
assert.strictEqual(unknown.panels.length, 0);
}
function testParameterPlotLayoutModes() {
const lib = loadParameterPlotLibrary();
assert.strictEqual(lib.MUSRFIT_PARAMETER_PLOT_LAYOUT_MODES.length, 3);
const modeLabels = Array.from(lib.MUSRFIT_PARAMETER_PLOT_LAYOUT_MODES).map(function(m) {
return m.value + ":" + m.label;
});
assert.deepStrictEqual(modeLabels, ["auto:Auto", "row:Single row", "col:Single column"]);
const layout = lib.musrfitParameterLayoutFromMode;
// Auto keeps up to three parameters in a single column.
assert.strictEqual(layout("auto", 1), "1x1");
assert.strictEqual(layout("auto", 2), "2x1");
assert.strictEqual(layout("auto", 3), "3x1");
// Beyond three it grows toward a near-square grid.
assert.strictEqual(layout("auto", 4), "2x2");
assert.strictEqual(layout("auto", 5), "2x3");
assert.strictEqual(layout("auto", 6), "2x3");
assert.strictEqual(layout("auto", 7), "3x3");
assert.strictEqual(layout("auto", 8), "3x3");
assert.strictEqual(layout("auto", 9), "3x3");
assert.strictEqual(layout("auto", 10), "3x4");
assert.strictEqual(layout("auto", 16), "4x4");
// Explicit modes force the arrangement regardless of count.
assert.strictEqual(layout("row", 1), "1x1");
assert.strictEqual(layout("row", 4), "1x4");
assert.strictEqual(layout("col", 1), "1x1");
assert.strictEqual(layout("col", 4), "4x1");
// Degenerate inputs collapse to a single panel.
assert.strictEqual(layout("auto", 0), "1x1");
assert.strictEqual(layout("auto", undefined), "1x1");
assert.strictEqual(layout("auto", -3), "1x1");
assert.strictEqual(layout("unknown", 5), "2x3");
}
function testParameterPlotLayoutPersistence() {
const lib = loadParameterPlotLibrary();
const storage = {};
lib.window.localStorage = {
getItem: function(key) { return Object.prototype.hasOwnProperty.call(storage, key) ? storage[key] : null; },
setItem: function(key, value) { storage[key] = String(value); },
removeItem: function(key) { delete storage[key]; }
};
// No stored choice yet defaults to Auto.
assert.strictEqual(lib.rememberedParameterPlotLayoutMode(), "auto");
lib.rememberParameterPlotLayoutMode("col");
assert.strictEqual(lib.rememberedParameterPlotLayoutMode(), "col");
assert.strictEqual(storage[lib.parameterPlotLayoutStorageKey], "col");
// Invalid modes are rejected and the previous choice remains.
lib.rememberParameterPlotLayoutMode("grid");
assert.strictEqual(lib.rememberedParameterPlotLayoutMode(), "col");
// Unavailable storage degrades to Auto without throwing.
const storageLess = loadParameterPlotLibrary();
storageLess.window.localStorage = null;
assert.strictEqual(storageLess.rememberedParameterPlotLayoutMode(), "auto");
storageLess.rememberParameterPlotLayoutMode("row");
assert.strictEqual(storageLess.window.localStorage, null);
}
function testDialogAndWindowLayoutPlumbing() {
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
const web = fs.readFileSync(path.join(repoRoot, "muSRFitweb.js"), "utf8");
const windowScript = fs.readFileSync(path.join(repoRoot, "parameter-plot-window.js"), "utf8");
const main = fs.readFileSync(path.join(repoRoot, "main.js"), "utf8");
// The axis dialog offers the three layout modes and seeds the previous choice.
assert.match(plot, /MUSRFIT_PARAMETER_PLOT_LAYOUT_MODES/);
assert.match(plot, /rememberedParameterPlotLayoutMode\(\)/);
assert.match(plot, /rememberParameterPlotLayoutMode\(layoutSelect\.value\)/);
// The chosen mode travels through openPlot to both platforms.
assert.match(plot, /preferredLayoutMode: layoutSelect\.value/);
assert.match(web, /preferredLayoutMode \|\| ""/);
assert.match(web, /options\.preferredTemplate \|\| ""/);
assert.match(windowScript, /preferredLayoutMode \|\| ""/);
// The window resolves the mode into a concrete grid that shades the layout select.
assert.match(plot, /musrfitParameterLayoutFromMode\(preferredLayoutMode, count\)/);
assert.match(plot, /layoutSelect\.value = layoutValue/);
assert.match(plot, /preferredLayoutMode = ""/);
// Electron forwards the whole option object through the IPC channel.
assert.match(main, /openParameterPlotWindow/);
}
function testInlineParameterSource() {
const lib = loadParameterPlotLibrary();
// A bare path string normalizes into a "path" source with a display label.
const pathSource = lib.normalizeParameterSource("/work/514+series_asy_par.dat");
assert.strictEqual(pathSource.kind, "path");
assert.strictEqual(pathSource.path, "/work/514+series_asy_par.dat");
assert.strictEqual(pathSource.label, "514+series_asy_par.dat");
// An already-structured inline source is passed through unchanged.
const inline = { kind: "inline", text: "RUN\tAlpha\n514\t0.22\n", label: "Parameter table" };
assert.strictEqual(lib.normalizeParameterSource(inline), inline);
// readMusrfitParameterData for an inline source must resolve to its text
// without touching any file system.
let seen = null;
lib.window.MusrfitParameterPlotPlatform = {
readDataSource: async function(source) { seen = source; return String(source.text || ""); }
};
return lib.readMusrfitParameterData(inline).then(function(contents) {
assert.strictEqual(contents, "RUN\tAlpha\n514\t0.22\n");
assert.strictEqual(seen.kind, "inline");
return lib.readMusrfitParameterData("/work/fit_par.dat").then(function() {
assert.strictEqual(seen.kind, "path");
});
});
}
function testTraceStyleAndOverlayFoundation() {
const lib = loadParameterPlotLibrary();
// Palettes: the default first color, index wrap-around, and fallback for
// unknown palette ids all resolve to classic Plotly blue.
assert.strictEqual(lib.musrfitParameterPaletteColor("default", 0), "#1f77b4");
assert.strictEqual(lib.musrfitParameterPaletteColor("default", 10), "#1f77b4");
assert.strictEqual(lib.musrfitParameterPaletteColor("bogus", 0), "#1f77b4");
assert.strictEqual(lib.musrfitParameterPaletteColor("pastel", 2), "#98df8a");
// A trace built without a style keeps the original (style-less) shape.
const dataset = lib.parseMusrfitParameterData([
"% RUN dataT Alpha dAlpha Lambda dLambda",
"514 5 0.30 0.01 1.1 0.02",
"515 10 0.29 0.01 1.0 0.02"
].join("\n"));
const plain = lib.buildMusrfitParameterTrace(dataset, 1, 2, "markers");
assert.strictEqual(plain.type, "scatter");
assert.strictEqual(plain.mode, "markers");
assert.strictEqual(plain.name, "α");
assert.strictEqual(plain.marker, undefined);
assert.strictEqual(plain.line, undefined);
assert.ok(plain.error_y && plain.error_y.array && plain.error_y.array.length);
// Error bars default to plain vertical lines (cap width zero); the cap is
// an explicit opt-in so traces stay uncapped unless the style asks for it.
assert.strictEqual(plain.error_y.width, 0);
const capped = lib.buildMusrfitParameterTrace(dataset, 1, 2, "markers", { cap: true });
assert.strictEqual(capped.error_y.width, 4);
// Marker styling is injected for marker and lines+markers modes.
const styledMarkers = lib.buildMusrfitParameterTrace(dataset, 1, 2, "markers",
{ color: "#2ca02c", symbol: "star", size: 12 });
assert.strictEqual(styledMarkers.marker.size, 12);
assert.strictEqual(styledMarkers.marker.color, "#2ca02c");
assert.strictEqual(styledMarkers.marker.symbol, "star");
assert.strictEqual(styledMarkers.line, undefined);
// Transparency appears only when below one, so default traces stay opaque.
const styledBoth = lib.buildMusrfitParameterTrace(dataset, 1, 2, "lines+markers",
{ color: "#2ca02c", symbol: "square", opacity: 0.5 });
assert.strictEqual(styledBoth.marker.size, 8);
assert.strictEqual(styledBoth.marker.color, "#2ca02c");
assert.strictEqual(styledBoth.marker.symbol, "square");
assert.strictEqual(styledBoth.marker.opacity, 0.5);
assert.strictEqual(styledBoth.line.color, "#2ca02c");
assert.strictEqual(styledBoth.line.opacity, 0.5);
const opaque = lib.buildMusrfitParameterTrace(dataset, 1, 2, "markers", { color: "#2ca02c" });
assert.strictEqual(opaque.marker.opacity, undefined);
// Line-only modes never gain markers.
const styledLines = lib.buildMusrfitParameterTrace(dataset, 1, 2, "lines",
{ color: "#2ca02c", size: 12, symbol: "cross" });
assert.strictEqual(styledLines.marker, undefined);
assert.strictEqual(styledLines.line.color, "#2ca02c");
// Data-set keys distinguish path, uploaded-file, and inline origins.
assert.strictEqual(lib.parameterDataSetKey({ kind: "path", path: "/work/514_par.dat" }),
"path:/work/514_par.dat");
assert.strictEqual(lib.parameterDataSetKey({ kind: "file", file: { name: "a.dat", lastModified: 7, size: 11 } }),
"file:a.dat:7:11");
assert.strictEqual(lib.parameterDataSetKey({ kind: "inline", label: "table", text: "RUN 5\n" }),
"inline:table:6");
// Style resolution: a trace-level override wins, then the data-set level,
// then the caller fallback with default size/opacity.
const dsKey = lib.parameterDataSetKey({ kind: "path", path: "/work/514_par.dat" });
const traceKey = lib.parameterTraceStyleKey(dsKey, "pp1", "Alpha");
const emptyStyles = {};
const fallbackDone = lib.musrfitParameterTraceStyle(emptyStyles, traceKey, dsKey,
{ color: "#ff7f0e" });
assert.strictEqual(fallbackDone.color, "#ff7f0e");
assert.strictEqual(fallbackDone.size, 8);
assert.strictEqual(fallbackDone.opacity, 1);
assert.strictEqual(fallbackDone.cap, false);
emptyStyles[lib.parameterDataSetStyleKey(dsKey)] = { color: "#9467bd", size: 10, cap: true };
const dsStyled = lib.musrfitParameterTraceStyle(emptyStyles, traceKey, dsKey, {});
assert.strictEqual(dsStyled.color, "#9467bd");
assert.strictEqual(dsStyled.size, 10);
assert.strictEqual(dsStyled.cap, true);
emptyStyles[traceKey] = { color: "#d62728", opacity: 0.4, cap: false };
const traceStyled = lib.musrfitParameterTraceStyle(emptyStyles, traceKey, dsKey, {});
assert.strictEqual(traceStyled.color, "#d62728");
assert.strictEqual(traceStyled.opacity, 0.4);
assert.strictEqual(traceStyled.cap, false);
// Overlay builder: two data sets sharing dataT align by column name and
// gain dataset labels in the legend once more than one is present.
const scanA = lib.parseMusrfitParameterData([
"% RUN dataT Alpha dAlpha Lambda dLambda",
"514 5 0.30 0.01 1.1 0.02",
"515 10 0.29 0.01 1.0 0.02"
].join("\n"));
const scanB = lib.parseMusrfitParameterData([
"% RUN dataT Alpha dAlpha Lambda dLambda",
"520 2 0.24 0.01 0.9 0.02",
"521 4 0.22 0.01 0.8 0.02"
].join("\n"));
const keyA = "path:a";
const keyB = "path:b";
const keyC = "path:c";
const build = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyA, label: "Scan A", dataset: scanA },
{ dataSetKey: keyB, label: "Scan B", dataset: scanB }],
"dataT", ["Alpha", "Lambda"], "markers", { paletteId: "default" });
assert.strictEqual(build.traces.length, 4);
assert.strictEqual(build.skipped.length, 0);
assert.strictEqual(build.traces[0].name, "Scan A: α");
assert.strictEqual(build.traces[1].name, "Scan A: λ (μs⁻¹)");
assert.strictEqual(build.traces[2].name, "Scan B: α");
assert.strictEqual(build.traces[3].name, "Scan B: λ (μs⁻¹)");
// Default palette colors alternate per data set, not per trace.
assert.strictEqual(build.traces[0].marker.color, "#1f77b4");
assert.strictEqual(build.traces[1].marker.color, "#1f77b4");
assert.strictEqual(build.traces[2].marker.color, "#d62728");
assert.strictEqual(build.traces[3].marker.color, "#d62728");
// A dataset-level registry style overrides the palette default for its set.
const styles = {};
styles[lib.parameterDataSetStyleKey(keyB)] = { color: "#2ca02c", symbol: "star" };
const styledOverlay = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyA, label: "Scan A", dataset: scanA },
{ dataSetKey: keyB, label: "Scan B", dataset: scanB }],
"dataT", ["Alpha"], "markers", { paletteId: "default", styleRegistry: styles });
assert.strictEqual(styledOverlay.traces[0].marker.color, "#1f77b4");
assert.strictEqual(styledOverlay.traces[1].marker.color, "#2ca02c");
assert.strictEqual(styledOverlay.traces[1].marker.symbol, "star");
// A data set missing the panel X column is skipped with a note.
const detached = lib.parseMusrfitParameterData([
"% RUN dataB Alpha dAlpha",
"600 1.0 0.20 0.01",
"601 1.5 0.19 0.01"
].join("\n"));
const partial = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyA, label: "Scan A", dataset: scanA },
{ dataSetKey: keyC, label: "Detached", dataset: detached }],
"dataT", ["Alpha"], "markers", { paletteId: "default" });
assert.strictEqual(partial.traces.length, 1);
assert.strictEqual(partial.traces[0].name, "Scan A: α");
assert.strictEqual(partial.skipped.length, 1);
assert.strictEqual(partial.skipped[0].label, "Detached");
assert.match(partial.skipped[0].reason, /missing X column dataT/);
// Parameters absent from a data set are skipped per data set, not globally.
const lean = lib.parseMusrfitParameterData([
"% RUN dataT Lambda dLambda",
"600 7 0.50 0.02",
"601 8 0.48 0.02"
].join("\n"));
const leanOverlay = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyA, label: "Scan A", dataset: scanA },
{ dataSetKey: keyC, label: "Lean", dataset: lean }],
"dataT", ["Alpha", "Lambda"], "markers", { paletteId: "default" });
assert.deepStrictEqual(Array.from(leanOverlay.traces, function(t) { return t.name; }),
["Scan A: α", "Scan A: λ (μs⁻¹)", "Lean: λ (μs⁻¹)"]);
assert.strictEqual(leanOverlay.skipped.length, 0);
// Smart legend prefixes: an energy scan is tagged with its constant
// temperature, a temperature scan with its constant energy (LE) or field
// (bulk), and a user rename override replaces the default entirely.
const energyScan = lib.parseMusrfitParameterData([
"% RUN dataE dataT Alpha dAlpha",
"514 5.0 300 0.30 0.01",
"515 7.5 300 0.29 0.01"
].join("\n"));
const temperatureScan = lib.parseMusrfitParameterData([
"% RUN dataT dataE Alpha dAlpha",
"516 10 12.0 0.24 0.01",
"517 20 12.0 0.22 0.01"
].join("\n"));
const bulkScan = lib.parseMusrfitParameterData([
"% RUN dataT dataB Alpha dAlpha",
"518 10 100 0.24 0.01",
"519 20 100 0.22 0.01"
].join("\n"));
// A scan with no fixed coordinate (cold field scan, everything varies).
const fullyVarying = lib.parseMusrfitParameterData([
"% RUN dataT dataB dataE Alpha dAlpha",
"520 10 100 5.0 0.30 0.01",
"521 20 200 7.5 0.29 0.01"
].join("\n"));
assert.strictEqual(lib.musrfitParameterOverlayPrefix(
{ label: "E scan" }, energyScan), "E scan (T = 300 K)");
assert.strictEqual(lib.musrfitParameterOverlayPrefix(
{ label: "T scan" }, temperatureScan), "T scan (E = 12 keV)");
assert.strictEqual(lib.musrfitParameterOverlayPrefix(
{ label: "Bulk" }, bulkScan), "Bulk (B = 100 G)");
assert.strictEqual(lib.musrfitParameterOverlayPrefix(
{ label: "Cold" }, fullyVarying), "Cold");
const keyD = "path:energy";
const keyE = "path:temp";
const smartOverlay = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyD, label: "E scan", dataset: energyScan },
{ dataSetKey: keyE, label: "T scan", dataset: temperatureScan }],
"dataT", ["Alpha"], "markers", { paletteId: "default" });
assert.deepStrictEqual(Array.from(smartOverlay.traces, function(t) { return t.name; }),
["E scan (T = 300 K): α", "T scan (E = 12 keV): α"]);
assert.strictEqual(smartOverlay.traceMeta.length, 2);
assert.strictEqual(smartOverlay.traceMeta[0].name, "Alpha");
assert.strictEqual(smartOverlay.traceMeta[0].defaultName, "E scan (T = 300 K): α");
// A user-renamed legend entry (persisted override) beats the smart default.
const overrides = {};
overrides[lib.musrfitParameterLegendOverrideKey(keyE, "Alpha")] = "My temp scan";
const renamed = lib.buildMusrfitParameterOverlayTraces(
[{ dataSetKey: keyD, label: "E scan", dataset: energyScan },
{ dataSetKey: keyE, label: "T scan", dataset: temperatureScan }],
"dataT", ["Alpha"], "markers", {
paletteId: "default",
legendNameOf: function(dataSetKey, name) {
return overrides[lib.musrfitParameterLegendOverrideKey(dataSetKey, name)] || "";
}
});
assert.deepStrictEqual(Array.from(renamed.traces, function(t) { return t.name; }),
["E scan (T = 300 K): α", "My temp scan"]);
}
function testParameterStyleEditingFoundation() {
const lib = loadParameterPlotLibrary();
const dsKey = "path:/work/scanA_par.dat";
const panel = { dataSetKey: dsKey, stableId: "pp3", source: { label: "Scan A" } };
// Scope keys select either the whole data set or one (data set, panel, name).
assert.strictEqual(lib.parameterStyleScopeKeys(panel, "Alpha", "dataset"),
"data!path:/work/scanA_par.dat");
assert.strictEqual(lib.parameterStyleScopeKeys(panel, "Alpha", "trace"),
"trace!path:/work/scanA_par.dat!pp3!Alpha");
// Prefill: trace scope falls back through trace -> data set -> caller.
let styles = {};
let out = lib.parameterCurrentStyle(styles, panel, "Alpha", "trace",
{ color: "#ff7f0e" });
assert.strictEqual(out.color, "#ff7f0e");
assert.strictEqual(out.size, 8);
assert.strictEqual(out.opacity, 1);
styles[lib.parameterDataSetStyleKey(dsKey)] = { color: "#9467bd", size: 12 };
out = lib.parameterCurrentStyle(styles, panel, "Alpha", "trace", { color: "#ff7f0e" });
assert.strictEqual(out.color, "#9467bd");
assert.strictEqual(out.size, 12);
// Data-set scope never reflects a trace-level override.
styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")] = { color: "#d62728", opacity: 0.4 };
out = lib.parameterCurrentStyle(styles, panel, "Alpha", "trace",
{ color: "#9467bd" });
assert.strictEqual(out.color, "#d62728");
assert.strictEqual(out.opacity, 0.4);
out = lib.parameterCurrentStyle(styles, panel, "Alpha", "dataset",
{ color: "#9467bd" });
assert.strictEqual(out.color, "#9467bd");
assert.strictEqual(out.size, 12);
// Recording keeps only the fields actually edited and never clears others.
lib.recordParameterStyle(styles, lib.parameterStyleScopeKeys(panel, "Alpha", "trace"),
{ color: "#2ca02c" }, false);
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")].color, "#2ca02c");
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")].size, undefined);
lib.recordParameterStyle(styles, lib.parameterStyleScopeKeys(panel, "Alpha", "trace"),
{ symbol: "star" }, false);
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")].color, "#2ca02c");
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")].symbol, "star");
lib.recordParameterStyle(styles, lib.parameterStyleScopeKeys(panel, "Alpha", "trace"),
{}, true);
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")], undefined);
// A data-set-scope edit must unite the whole data set: clearParameterDataSet
// TraceStyles removes exactly that data set's trace overrides (any panel,
// any parameter) while leaving data-set styles and other data sets intact.
styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")] = { color: "#d62728" };
styles["trace!" + dsKey + "!pp9!Lambda"] = { color: "#2ca02c" };
styles[lib.parameterDataSetStyleKey(dsKey)] = { color: "#17becf" };
let siblingKey = dsKey + "?extra";
styles["trace!" + siblingKey + "!pp1!Alpha"] = { color: "#111111" };
styles["trace!path:/scanB!pp1!Alpha"] = { color: "#777777" };
lib.clearParameterDataSetTraceStyles(styles, dsKey);
assert.strictEqual(styles[lib.parameterTraceStyleKey(dsKey, "pp3", "Alpha")], undefined);
assert.strictEqual(styles["trace!" + dsKey + "!pp9!Lambda"], undefined);
assert.strictEqual(styles[lib.parameterDataSetStyleKey(dsKey)].color, "#17becf");
assert.strictEqual(styles["trace!" + siblingKey + "!pp1!Alpha"].color, "#111111");
assert.strictEqual(styles["trace!path:/scanB!pp1!Alpha"].color, "#777777");
// The clicked-series description carries the identity needed by the picker.
const clicked = lib.parameterClickedSeries(panel, "Alpha",
{ clientX: 120, clientY: 340 });
assert.strictEqual(clicked.dataSetKey, dsKey);
assert.strictEqual(clicked.datasetLabel, "Scan A");
assert.strictEqual(clicked.yName, "Alpha");
assert.strictEqual(clicked.clientX, 120);
assert.strictEqual(clicked.clientY, 340);
const noEvent = lib.parameterClickedSeries(panel, "Alpha", null);
assert.strictEqual(noEvent.clientX, 0);
assert.strictEqual(noEvent.clientY, 0);
}
function testDataSetRegistryFoundation() {
const lib = loadParameterPlotLibrary();
let registry = [];
// Registration dedupes by data-set key and assigns stable color indexes.
const sourceA = { kind: "path", path: "/work/scanA_par.dat" };
const sourceB = { kind: "path", path: "/work/scanB_par.dat" };
const entryA = lib.registerParameterDataSet(registry, sourceA, 0);
assert.strictEqual(entryA.key, "path:/work/scanA_par.dat");
assert.strictEqual(entryA.colorIndex, 0);
assert.strictEqual(registry.length, 1);
const againA = lib.registerParameterDataSet(registry, sourceA, 5);
assert.strictEqual(againA, entryA);
assert.strictEqual(registry.length, 1);
const entryB = lib.registerParameterDataSet(registry, sourceB, 1);
assert.strictEqual(entryB.colorIndex, 1);
assert.strictEqual(registry.length, 2);
// Finding preserves identity by key.
assert.strictEqual(lib.findRegisteredDataSet(registry, "path:/work/scanB_par.dat"), entryB);
assert.strictEqual(lib.findRegisteredDataSet(registry, "path:/none"), null);
assert.strictEqual(lib.findRegisteredDataSet([], "path:/none"), null);
// The label falls back to a neutral name when the source has none.
const bare = lib.registerParameterDataSet(registry, { kind: "path", path: "/x/y.dat" }, 9);
assert.strictEqual(bare.label, "y.dat");
const plain = lib.registerParameterDataSet(registry, { kind: "inline", text: "RUN 1\n" }, 9);
assert.strictEqual(plain.label, "Parameter data");
// A panel resolves its primary plus its overlays into overlay entries;
// overlays not present in the registry (e.g. stale clone keys) are skipped.
const scanA = lib.parseMusrfitParameterData([
"% RUN dataT Alpha dAlpha Lambda dLambda",
"514 5 0.30 0.01 1.1 0.02",
"515 10 0.29 0.01 1.0 0.02"
].join("\n"));
entryA.dataset = scanA;
const panel = {
dataSetKey: entryA.key,
source: { kind: "path", path: "/work/scanA_par.dat", label: "Scan A" },
dataset: scanA,
overlays: [entryB.key, "path:/work/never_loaded.dat"]
};
const entries = lib.parameterOverlayEntries(panel, registry);
assert.strictEqual(entries.length, 2);
assert.strictEqual(entries[0].key, entryA.key);
assert.strictEqual(entries[0].dataSetKey, entryA.key);
assert.strictEqual(entries[0].colorIndex, 0);
assert.strictEqual(entries[1].key, entryB.key);
assert.strictEqual(entries[1].dataSetKey, entryB.key);
assert.strictEqual(entries[1].dataset, null);
// A panel without a dataset resolves to no entries.
const emptyPanel = { dataSetKey: "path:/x", source: { label: "x" }, dataset: null, overlays: [] };
assert.strictEqual(lib.parameterOverlayEntries(emptyPanel, registry).length, 0);
// Overlay trace building colors by the stable per-data-set color index.
const scanB = lib.parseMusrfitParameterData([
"% RUN dataT Alpha dAlpha Lambda dLambda",
"520 2 0.24 0.01 0.9 0.02",
"521 4 0.22 0.01 0.8 0.02"
].join("\n"));
entryB.dataset = scanB;
const overlay = lib.buildMusrfitParameterOverlayTraces(
[{ key: entryA.key, label: "Scan A", dataset: scanA, colorIndex: 0 },
{ key: entryB.key, label: "Scan B", dataset: scanB, colorIndex: 4 }],
"dataT", ["Alpha"], "markers", { paletteId: "default" });
assert.strictEqual(overlay.traces[0].name, "Scan A: α");
assert.strictEqual(overlay.traces[1].name, "Scan B: α");
assert.strictEqual(overlay.traces[0].marker.color, "#1f77b4");
assert.strictEqual(overlay.traces[1].marker.color, "#ff7f0e");
// Styles the user records must reach traces whose overlay entries carry only
// a `key` (the exact shape parameterOverlayEntries produces). Looking for
// entry.dataSetKey there silently ignored every user edit.
const styles = {};
styles[lib.parameterDataSetStyleKey(entryB.key)] = { color: "#008837", symbol: "star", size: 14, opacity: 0.6 };
const styled = lib.buildMusrfitParameterOverlayTraces(
[{ key: entryA.key, label: "Scan A", dataset: scanA, colorIndex: 0 },
{ key: entryB.key, label: "Scan B", dataset: scanB, colorIndex: 4 }],
"dataT", ["Alpha"], "markers", {
paletteId: "default",
styleRegistry: styles,
styleKeyOf: function(key, name) {
return lib.parameterTraceStyleKey(key, "pp1", name);
}
});
assert.strictEqual(styled.traces[1].marker.color, "#008837");
assert.strictEqual(styled.traces[1].marker.symbol, "star");
assert.strictEqual(styled.traces[1].marker.size, 14);
assert.strictEqual(styled.traces[1].marker.opacity, 0.6);
assert.strictEqual(styled.traces[0].marker.color, "#1f77b4");
// A single data set keeps per-parameter color cycling (original look).
const solo = lib.buildMusrfitParameterOverlayTraces(
[{ key: entryA.key, label: "Scan A", dataset: scanA, colorIndex: 0 }],
"dataT", ["Alpha", "Lambda"], "markers", { paletteId: "default" });
assert.strictEqual(solo.traces.length, 2);
assert.strictEqual(solo.traces[0].name, "α");
assert.strictEqual(solo.traces[1].name, "λ (μs⁻¹)");
assert.strictEqual(solo.traces[0].marker.color, "#1f77b4");
assert.strictEqual(solo.traces[1].marker.color, "#d62728");
}
function testParameterPlotStatePersistence() {
const lib = loadParameterPlotLibrary();
// Portable source projection preserves key identity for every source kind
// while reducing the object to JSON-safe primitives. A round-trip through
// portable → restore gives back an equivalent source object whose key is
// identical.
const pathSource = { kind: "path", path: "/work/scanA_par.dat", label: "Scan A" };
const pathPortable = lib.portableParameterSource(pathSource);
assert.strictEqual(pathPortable.kind, "path");
assert.strictEqual(pathPortable.path, "/work/scanA_par.dat");
const pathRestored = lib.restorePortableParameterSource(pathPortable);
assert.strictEqual(pathRestored.kind, "path");
assert.strictEqual(pathRestored.path, "/work/scanA_par.dat");
assert.strictEqual(lib.parameterDataSetKey(pathSource), lib.parameterDataSetKey(pathRestored));
const inlineSource = { kind: "inline", label: "table", text: "RUN dataT\n514 5\n" };
const inlinePortable = lib.portableParameterSource(inlineSource);
assert.strictEqual(inlinePortable.text, "RUN dataT\n514 5\n");
const inlineRestored = lib.restorePortableParameterSource(inlinePortable);
assert.strictEqual(lib.parameterDataSetKey(inlineSource), lib.parameterDataSetKey(inlineRestored));
// File source: identity markers survive the round-trip and produce the same
// data-set key, even though the File blob itself is not stored.
const fileSource = { kind: "file", file: { name: "a.dat", lastModified: 7, size: 11 }, label: "a" };
const filePortable = lib.portableParameterSource(fileSource);
assert.strictEqual(filePortable.kind, "file");
assert.strictEqual(filePortable.file.name, "a.dat");
const fileRestored = lib.restorePortableParameterSource(filePortable);
assert.strictEqual(fileRestored.kind, "file");
assert.strictEqual(lib.parameterDataSetKey(fileSource), lib.parameterDataSetKey(fileRestored));
assert.deepStrictEqual(Object.keys(filePortable.file), ["name", "lastModified", "size"]);
// Null / missing sources
assert.strictEqual(lib.portableParameterSource(null), null);
assert.strictEqual(lib.portableParameterSource(undefined), null);
assert.strictEqual(lib.restorePortableParameterSource(null), null);
assert.strictEqual(lib.restorePortableParameterSource({}), null);
// Validation: good snapshots pass, bad ones fail
const goodSnapshot = {
v: 1,
mainSourceKey: "path:/work/514_par.dat",
jobName: "514_par.dat",
windowPaletteId: "bold",
panelSequence: 3,
dataSetColorCounter: 2,
templateId: "",
templatePanels: [],
templateSharedX: false,
layout: "2x2",
activePanelIndex: 0,
panelStates: [{ stableId: "pp1", source: pathPortable, yNames: ["Alpha"], xName: "dataT", xAuto: false, mode: "markers", dataSetKey: "path:/work/514_par.dat", overlays: [], paletteId: "bold", xTitle: "", yTitle: "" }],
registeredDataSets: [{ key: "path:/work/514_par.dat", source: pathPortable, label: "514_par.dat", colorIndex: 0 }],
styleRegistry: { "data!path:/work/514_par.dat": { color: "#d62728", symbol: "star", size: 12, opacity: 0.8, cap: true } }
};
assert.strictEqual(lib.validateParameterPlotState(goodSnapshot), true);
assert.strictEqual(lib.validateParameterPlotState(null), false);
assert.strictEqual(lib.validateParameterPlotState({}), false);
assert.strictEqual(lib.validateParameterPlotState({ v: 99 }), false);
assert.strictEqual(lib.validateParameterPlotState({ v: 1 }), false);
assert.strictEqual(lib.validateParameterPlotState({ v: 1, mainSourceKey: "" }), false);
assert.strictEqual(lib.validateParameterPlotState({ v: 1, mainSourceKey: "k", panelStates: {}, registeredDataSets: [], styleRegistry: null }), false);
// Mock storage: remember → read → round-trip → forget
let mockStore = {};
let mockStorage = {
getItem: function(key) { return mockStore[key] || null; },
setItem: function(key, value) { mockStore[key] = value; }
};
lib.rememberParameterPlotState(mockStorage, goodSnapshot);
let retrieved = lib.readRememberedParameterPlotState(mockStorage, "path:/work/514_par.dat");
assert.strictEqual(retrieved.v, 1);
assert.strictEqual(retrieved.mainSourceKey, "path:/work/514_par.dat");
assert.strictEqual(retrieved.styleRegistry["data!path:/work/514_par.dat"].color, "#d62728");
assert.deepStrictEqual(Object.keys(retrieved.styleRegistry["data!path:/work/514_par.dat"]),
["color", "symbol", "size", "opacity", "cap"]);
assert.strictEqual(retrieved.panelStates[0].yNames[0], "Alpha");
// Wrong key returns null
assert.strictEqual(lib.readRememberedParameterPlotState(mockStorage, "path:/wrong"), null);
// Forget removes the entry
lib.forgetParameterPlotState(mockStorage, "path:/work/514_par.dat");
assert.strictEqual(lib.readRememberedParameterPlotState(mockStorage, "path:/work/514_par.dat"), null);
// Forget with null / missing key is safe
lib.forgetParameterPlotState(mockStorage, null);
lib.forgetParameterPlotState(mockStorage, "");
// Eviction: capping at MAX_REMEMBERED_PARAMETER_PLOT_STATES (8) by insertion order
for (let i = 0; i < 12; i++) {
let snap = Object.assign({}, goodSnapshot, { mainSourceKey: "path:/file" + i });
lib.rememberParameterPlotState(mockStorage, snap);
}
let remaining = 0;
for (let i = 0; i < 12; i++) {
if (lib.readRememberedParameterPlotState(mockStorage, "path:/file" + i)) remaining++;
}
assert.ok(remaining <= 8, "Eviction should cap stored states, got " + remaining);
// Oldest entries were evicted
assert.strictEqual(lib.readRememberedParameterPlotState(mockStorage, "path:/file0"), null);
assert.strictEqual(lib.readRememberedParameterPlotState(mockStorage, "path:/file1"), null);
// Corrupted storage is silently ignored (returns empty)
mockStore["musrflow.parameterPlotStates"] = "not valid JSON {{{";
let corrupted = lib.readRememberedParameterPlotState(mockStorage, "path:/work/514_par.dat");
assert.strictEqual(corrupted, null);
// Invalid snapshot is rejected by rememberParameterPlotState
lib.rememberParameterPlotState(mockStorage, { v: 99, mainSourceKey: "k" });
assert.strictEqual(lib.readRememberedParameterPlotState(mockStorage, "k"), null);
// Plumbing: controller and dialog source assertions
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
const web = fs.readFileSync(path.join(repoRoot, "muSRFitweb.js"), "utf8");
const windowScript = fs.readFileSync(path.join(repoRoot, "parameter-plot-window.js"), "utf8");
assert.ok(/savedState[\s\S]*?applySavedParameterPlotState/.test(plot));
assert.match(plot, /collectParameterPlotStateDescriptor/);
assert.match(plot, /scheduleParameterPlotStateSave/);
assert.match(plot, /saveParameterPlotStateNow/);
assert.match(plot, /forgetParameterPlotState/);
assert.match(plot, /savedState: config/);
assert.match(plot, /readRememberedParameterPlotState\(storage, sourceKey\)/);
assert.match(plot, /readRememberedParameterPlotConfigurations\(storage, sourceKey\)/);
assert.match(plot, /parameterPlotStateParameterSignature/);
assert.match(plot, /parameterPlotConfigurationLabel\(config\)/);
assert.match(web, /options\.savedState/);
assert.match(windowScript, /options\.savedState/);
}
function testRememberedPlotConfigurations() {
const lib = loadParameterPlotLibrary();
function storageFor() {
let mockStore = {};
return {
store: mockStore,
storage: {
getItem: function(key) { return mockStore[key] || null; },
setItem: function(key, value) { mockStore[key] = value; }
}
};
}
function snap(key, yNames, extra) {
let base = {
v: 1,
mainSourceKey: key,
panelStates: [{ stableId: "pp1", source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" }, yNames: yNames.slice(), xName: "dataT", xAuto: false, mode: "markers", dataSetKey: key, overlays: [], paletteId: "bold", xTitle: "", yTitle: "" }],
registeredDataSets: [{ key: key, source: { kind: "path", path: "/work/514_par.dat", label: "514_par.dat" }, label: "514_par.dat", colorIndex: 0 }],
styleRegistry: {}
};
return Object.assign(base, extra || {});
}
function realmSafe(value) { return JSON.parse(JSON.stringify(value)); }
let env = storageFor();
// Two configurations for the same source with different parameter sets are
// both kept.
lib.rememberParameterPlotState(env.storage, snap("path:/runA", ["Alpha"]));
lib.rememberParameterPlotState(env.storage, snap("path:/runA", ["Alpha", "Lam", "Frq"], { layout: "1x3" }));
let list = lib.readRememberedParameterPlotConfigurations(env.storage, "path:/runA").map(realmSafe);
assert.strictEqual(list.length, 2, "Different parameter sets both remembered");
assert.strictEqual(lib.readRememberedParameterPlotState(env.storage, "path:/runA").panelStates[0].yNames[0], "Alpha");
// Newest wins per parameter set: same set with a different layout replaces
// the older entry rather than duplicating it.
lib.rememberParameterPlotState(env.storage, snap("path:/runA", ["Alpha", "Lam", "Frq"], { layout: "1x1" }));
list = lib.readRememberedParameterPlotConfigurations(env.storage, "path:/runA").map(realmSafe);
assert.strictEqual(list.length, 2);
const withNewLayout = realmSafe(lib.readRememberedParameterPlotConfigurations(env.storage, "path:/runA"))
.find(s => s.mainSourceKey === "path:/runA");
assert.deepStrictEqual(withNewLayout, snap("path:/runA", ["Alpha", "Lam", "Frq"], { layout: "1x1" }));
// Parameter-set signatures are order-insensitive: remembering the same set
// in a different order supersedes the earlier configuration.
lib.rememberParameterPlotState(env.storage, snap("path:/runA", ["Lam", "Alpha", "Frq"], { layout: "3x1" }));
list = lib.readRememberedParameterPlotConfigurations(env.storage, "path:/runA").map(realmSafe);
assert.strictEqual(list.length, 2);
// Unknown sources report no configurations.
assert.deepStrictEqual(realmSafe(lib.readRememberedParameterPlotConfigurations(env.storage, "path:/absent")), []);
assert.strictEqual(lib.readRememberedParameterPlotState(env.storage, "path:/absent"), null);
// Per-source cap: filling one source beyond MAX_PARAMETER_PLOT_CONFIGS_PER_SOURCE
// evicts the oldest configuration on that source.
for (let i = 0; i < 12; i++) {
lib.rememberParameterPlotState(env.storage, snap("path:/runB", ["P" + i]));
}
list = lib.readRememberedParameterPlotConfigurations(env.storage, "path:/runB").map(realmSafe);
assert.ok(list.length <= 8, "Per-source cap should apply, got " + list.length);
assert.strictEqual(list[0].panelStates[0].yNames[0], "P11");
assert.strictEqual(list[list.length - 1].panelStates[0].yNames[0], "P4");
// Global cap still bounds the number of distinct sources remembered.
for (let i = 0; i < 12; i++) {
lib.rememberParameterPlotState(env.storage, snap("path:/src" + i, ["Alpha"]));
}
let sourcesKept = new Set(Object.keys(JSON.parse(env.store["musrflow.parameterPlotStates"])));
assert.ok(sourcesKept.size <= 8, "Global source cap should apply, got " + sourcesKept.size);
}
function testAxisScaleSurvivesRefresh() {
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
// A log-scale choice must survive a Refresh. redrawPanel reapplies the
// persisted scale to the fresh layout (plotly.react would otherwise reset
// the axis to linear), the toggle buttons write the choice back to the
// panel and save it, and the saved descriptor carries it.
assert.match(plot, /if \(panel\.xScale === "log"\) layout\.xaxis\.type = "log";/);
assert.match(plot, /if \(panel\.yScale === "log"\) layout\.yaxis\.type = "log";/);
assert.match(plot, /panel\.xScale = next;\s*scheduleParameterPlotStateSave\(\);/);
assert.match(plot, /panel\.yScale = next;\s*scheduleParameterPlotStateSave\(\);/);
assert.match(plot, /xScale: panel\.xScale \|\| "linear"/);
assert.match(plot, /yScale: panel\.yScale \|\| "linear"/);
assert.match(plot, /panel\.xScale = savedPanel\.xScale === "log" \? "log" : "linear";/);
assert.match(plot, /panel\.yScale = savedPanel\.yScale === "log" \? "log" : "linear";/);
// Snapshots carrying the new per-panel scale fields still validate, so a
// window/plot saved with a log axis restores cleanly.
const lib = loadParameterPlotLibrary();
assert.strictEqual(lib.validateParameterPlotState({
v: 1,
mainSourceKey: "path:/work/514_par.dat",
panelStates: [{ stableId: "pp1", xScale: "log", yScale: "linear" }],
registeredDataSets: [],
styleRegistry: {}
}), true);
}
function testParameterToolbarVisibility() {
const plot = fs.readFileSync(path.join(repoRoot, "muSRFitParameterPlot.js"), "utf8");
const css = fs.readFileSync(path.join(repoRoot, "ZGUI.css"), "utf8");
assert.match(plot, /displayModeBar: true/);
assert.match(plot, /addEventListener\("pointerdown"/);
assert.match(plot, /addEventListener\("pointerup"/);
assert.match(plot, /\(movedX \* movedX\) \+ \(movedY \* movedY\) > 64/);
assert.match(plot, /classList\.add\("modebar-open"\)/);
assert.match(plot, /document\.addEventListener\("pointerdown", dismissParameterModeBar, true\)/);
assert.match(plot, /document\.removeEventListener\("pointerdown", dismissParameterModeBar, true\)/);
assert.match(css, /\.js-plotly-plot \.modebar\s*\{[^}]*opacity: 0 !important;[^}]*pointer-events: none !important;/s);
assert.match(css, /\.js-plotly-plot\.modebar-open \.modebar\s*\{[^}]*opacity: 1 !important;[^}]*pointer-events: auto !important;/s);
// Marker styling must remain available after removing the generic click handlers.
assert.match(plot, /panel\.chart\.on\("plotly_click"/);
}
testParameterToolbarVisibility();
testParserAndSmartDefaults();
testScanVariableDetection();
testTfTemplateApplication();
testIntegratedParameterTableHook();
testPlatformSeparation();
testElectronParameterExport();
testInlineParameterSource();
testParameterPlotLayoutModes();
testParameterPlotLayoutPersistence();
testDialogAndWindowLayoutPlumbing();
testTraceStyleAndOverlayFoundation();
testParameterStyleEditingFoundation();
testDataSetRegistryFoundation();
testParameterPlotStatePersistence();
testRememberedPlotConfigurations();
testAxisScaleSurvivesRefresh();
console.log("Parameter plot tests passed");