diff --git a/muSRFitelec.js b/muSRFitelec.js index 04152c0..2c1f7a8 100644 --- a/muSRFitelec.js +++ b/muSRFitelec.js @@ -468,18 +468,39 @@ async function ensureLocalRunData(options) { await initializeLocalRunData(); let all = options.all; let requests = []; + let missingExplicitFiles = []; let seen = new Set(); for (let dataSet of options.runSelection) { for (let run of seriesDataSetPhysicalRuns(dataSet)) { - if (seen.has(run)) continue; - seen.add(run); + let isComponent = run && typeof run === "object"; + let seenKey = isComponent + ? [run.kind, run.year || "", run.instrument || "", activeDataSetMainRun(run) || ""].join("\n") + : String(run); + if (seen.has(seenKey)) continue; + seen.add(seenKey); let dataPath = seriesDataFilePath(run, all); - if (!fileExists(dataPath)) { - requests.push({ instrument: all.instrName, year: Number(all.selYear), run: run }); + if (fileExists(dataPath)) continue; + if (isComponent && run.kind === "file") { + missingExplicitFiles.push(dataPath); + continue; } + let numericRun = isComponent ? activeDataSetMainRun(run) : run; + if (!(numericRun > 0)) continue; + requests.push({ + instrument: isComponent && run.instrument ? run.instrument : all.instrName, + year: Number(isComponent && run.year ? run.year : all.selYear), + run: Number(numericRun) + }); } } - if (!requests.length) return { ok: true }; + if (!requests.length) { + if (missingExplicitFiles.length && !options.series) { + let message = "Missing run data files:\n" + missingExplicitFiles.join("\n"); + appendJobLog(message); + return { ok: false, outcome: "missing-data", message: message }; + } + return { ok: true }; + } let action = options.action.toLowerCase(); let token = 'data-' + Date.now().toString(36) + '-' + (++electronRunJobSeq); @@ -521,8 +542,12 @@ async function ensureLocalRunData(options) { await scheduleInitialParameterGuess(); prepCFG(); } - if (result.missing && result.missing.length) { - let message = result.missing.map(function(file) { return file.message; }).join('\n'); + let missingMessages = (result.missing || []).map(function(file) { return file.message; }); + if (missingExplicitFiles.length) { + missingMessages.push("Missing run data files:\n" + missingExplicitFiles.join("\n")); + } + if (missingMessages.length) { + let message = missingMessages.join("\n"); appendJobLog(message); if (!options.series) return { ok: false, outcome: 'missing-data', message: message }; } diff --git a/muSRFitlib.js b/muSRFitlib.js index a47f542..98864aa 100644 --- a/muSRFitlib.js +++ b/muSRFitlib.js @@ -8320,34 +8320,49 @@ function cfgt0Bg(useStoredValues) { refreshT0BgModeFields(); } -function isMixedRunSourceMode() { - let mode = document.getElementById("runSourceMode"); - return !!(mode && mode.value === "mixed"); +function isMixedRunSourceMode(all) { + if (typeof document !== "undefined") { + let mode = document.getElementById("runSourceMode"); + if (mode) return mode.value === "mixed"; + } + let source = all || (typeof All !== "undefined" ? All : null); + return !!(source && source.runSourceMode === "mixed"); } function setRunSourceMode(mode) { + if (typeof document === "undefined") return; let mixed = mode === "mixed" || mode === true; let modeInput = document.getElementById("runSourceMode"); if (modeInput) modeInput.value = mixed ? "mixed" : "numbers"; + if (typeof document.querySelectorAll !== "function") return; - let numberEls = document.querySelectorAll("[data-run-source='numbers']"); + function sourceElements(kind) { + return document.querySelectorAll("[data-run-source='" + kind + "']"); + } + function descendantInputs(element) { + return element && typeof element.querySelectorAll === "function" + ? element.querySelectorAll("input, select, textarea") + : []; + } + + let numberEls = sourceElements("numbers"); for (let i = 0; i < numberEls.length; i++) { numberEls[i].hidden = mixed; if (numberEls[i].matches && numberEls[i].matches("input,select,textarea")) { numberEls[i].disabled = mixed; } - let controls = numberEls[i].querySelectorAll("input, select, textarea"); + let controls = descendantInputs(numberEls[i]); for (let j = 0; j < controls.length; j++) { controls[j].disabled = mixed; } } - let mixedEls = document.querySelectorAll("[data-run-source='mixed']"); + let mixedEls = sourceElements("mixed"); for (let i = 0; i < mixedEls.length; i++) { mixedEls[i].hidden = !mixed; if (mixedEls[i].matches && mixedEls[i].matches("input,select,textarea")) { mixedEls[i].disabled = !mixed; } - let controls = mixedEls[i].querySelectorAll("input, select, textarea"); + let controls = descendantInputs(mixedEls[i]); for (let j = 0; j < controls.length; j++) { controls[j].disabled = !mixed; } @@ -8403,7 +8418,7 @@ function parseMixedRunComponent(token) { }; } -function parseMixedFiles(mixedFiles) { +function parseMixedFiles(mixedFiles, options) { // Comma-separated logical datasets; '+' adds runs (ADDRUN). No ranges/steps. // Each component is either year/instrument/run or an explicit file/path. if (typeof mixedFiles !== "string") return null; @@ -8420,6 +8435,9 @@ function parseMixedFiles(mixedFiles) { for (let j = 0; j < sumParts.length; j++) { let component = parseMixedRunComponent(sumParts[j]); if (!component) return null; + if (options && options.requireExplicit + && component.kind === "file" + && !/[\\/]/.test(component.fileToken)) return null; components.push(component); } dataSets.push({ main: components[0], add: components.slice(1) }); @@ -8547,28 +8565,31 @@ function handleMixedFilesChange(value) { if (typeof updateResolvedDataPathPreview === "function") updateResolvedDataPathPreview(); } +function sanitizeMSRSuffixToken(value) { + let token = String(value == null ? "" : value).replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, ""); + return token || "run"; +} + function runSuffixForComponent(component, all) { let source = all || (typeof All !== "undefined" ? All : {}); let dataRoot = source.dataRoot || (typeof defaultDataRoot !== "undefined" ? defaultDataRoot : ""); if (component && typeof component === "object") { if (component.kind === "triplet") { - return runSuffixFromFile(component.run, component.instrument, component.year, dataRoot); + return sanitizeMSRSuffixToken(component.year + "_" + component.instrument + "_" + String(component.run).padStart(4, "0")); } let directive = runDirectiveForComponent(component, source); let token = runFileTokenFromDirective(directive); - let fileName = String(token || "").replace(/\.(root|bin|mdu)$/i, ""); - let match = fileName.match(/_(\d+)$/); - if (match) return match[1]; - if (component.run !== undefined && component.run !== null && component.run !== "") { - return String(component.run); + let fileName = String(token || "").split(/[\\/]/).pop().replace(/\.(root|bin|mdu|nxs|msr)$/i, ""); + if (component.run !== undefined && component.run !== null && component.run !== "" && /^\d+$/.test(String(component.run))) { + return sanitizeMSRSuffixToken(fileName || String(component.run)); } - return fileName || String(component.label || ""); + return sanitizeMSRSuffixToken(fileName || String(component.label || "run")); } return runSuffixFromFile(component, source.instrName, source.selYear, dataRoot); } function activeRunSelectionInfo(all) { - if (isMixedRunSourceMode()) { + if (isMixedRunSourceMode(all)) { let dataSets = getActiveMixedDataSets(all); let first = dataSets[0]; return { @@ -9980,7 +10001,12 @@ function buildParameterDataFromTable() { // 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 || ""); + let mixedMode = typeof isMixedRunSourceMode === "function" && isMixedRunSourceMode(); + let runDataSets = mixedMode ? getActiveMixedDataSets(All) : parseRunSelection(All.runNumbers || ""); + let runs = runDataSets.map(function(ds, index) { + if (mixedMode) return activeDataSetMainLabel(ds) || ("ds" + (index + 1)); + return ds.main; + }); if (!runs.length) return null; let baseParams = parameterPlotNamesInTable(); @@ -10122,6 +10148,17 @@ function seedRunParametersFromShared(baseParName) { seed[prefix] = input && input.value !== undefined ? input.value : (All[prefix + baseParName] ?? ""); } + let mixedMode = typeof isMixedRunSourceMode === "function" && isMixedRunSourceMode(); + if (mixedMode) { + let dataSets = typeof getActiveMixedDataSets === "function" ? getActiveMixedDataSets(All) : []; + for (let dataSet of dataSets) { + let suffix = runSuffixForComponent(dataSet.main, All); + for (let prefix of ["val", "err", "min", "max"]) { + All[prefix + baseParName + "_" + suffix] = seed[prefix]; + } + } + return; + } 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"]) { @@ -10777,6 +10814,11 @@ function buildModelBlocks(config, fitType, selectionInfo) { return buildMultiAsymmetryModelBlocks(config, fitType, selectionInfo); } + let dataSets = selectionInfo.dataSets || []; + if (dataSets.length > 1 && selectionInfo.mixed) { + return buildDirectMultiDatasetModelBlocks(config, fitType, selectionInfo); + } + // THEORY block let theoryBlk = all.theoFunBlock; @@ -11255,6 +11297,223 @@ function buildMultiAsymmetryModelBlocks(config, fitType, selectionInfo) { }; } + +function buildDirectMultiDatasetModelBlocks(config, fitType, selectionInfo) { + let all = config.all || {}; + let funOptions = config.funOptions || []; + let funLines = config.funLines || []; + let sharedFlags = config.sharedFlags || {}; + let dataSets = selectionInfo.dataSets || []; + if (dataSets.length < 2) { + return buildModelBlocks(Object.assign({}, config, {}), fitType, selectionInfo); + } + + let isSingleHist = all.fitAsyType == "SingleHist"; + let hists = String(all.LRBF || "").split(","); + let theoryBlk = String(all.theoFunBlock || ""); + let nDataSets = dataSets.length; + + let contexts = dataSets.map(function(dataSet, index) { + return { + index: index, + dataSet: dataSet, + runLine: buildResolvedRunLineForDataSet(dataSet, all), + suffix: runSuffixForComponent(dataSet.main, all), + alphaRef: "", + n0Refs: Object.create(null), + mapValues: [] + }; + }); + + let sharedNumbers = Object.create(null); + let perDatasetNumbers = contexts.map(function() { return Object.create(null); }); + let theoryMapSlotForParam = Object.create(null); + let nextTheoryMapSlot = 1; + 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; + })); + + let paramBlk = ""; + let ifun = 0; + let funBlock = ""; + for (let funLine of funLines) funBlock += funLine + "\n"; + + function ensureTheoryMapSlot(baseName) { + if (!theoryMapSlotForParam[baseName]) { + while (occupiedMapNumbers.has(nextTheoryMapSlot)) nextTheoryMapSlot++; + theoryMapSlotForParam[baseName] = nextTheoryMapSlot; + occupiedMapNumbers.add(nextTheoryMapSlot); + nextTheoryMapSlot++; + } + return theoryMapSlotForParam[baseName]; + } + + function isRunDirectiveParam(parName) { + return parName == "Alpha" || /^(?:No|NBg)\d+$/.test(parName); + } + function needsPerDatasetSlot(parName) { + return !isRunDirectiveParam(parName); + } + + 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 i = 1; + for (let opt of funOptions) { + let parName = opt.value; + if (opt.disabled) { + ifun++; + let functionReference = "fun" + ifun; + funBlock = replaceAllWords(funBlock, parName, functionReference); + if (isRunDirectiveParam(parName)) { + contexts.forEach(function(ctx) { + if (parName == "Alpha") ctx.alphaRef = functionReference; + else ctx.n0Refs[parName] = functionReference; + }); + } else { + let slot = ensureTheoryMapSlot(parName); + theoryBlk = replaceWord(theoryBlk, parName, "map" + slot); + contexts.forEach(function(ctx) { ctx.mapValues[slot - 1] = functionReference; }); + } + continue; + } + + let cparName = defaultParameterKey(parName); + let shPar = !!sharedFlags[parName]; + let singleHistPhase = isSingleHist + && /^Phi(?:\d+)?$/.test(parName) + && new RegExp("\\b" + parName + "\\b").test(theoryBlk); + + if (singleHistPhase) { + let mapNo = 1; + while (occupiedMapNumbers.has(mapNo)) mapNo++; + occupiedMapNumbers.add(mapNo); + theoryBlk = replaceWord(theoryBlk, parName, "map" + mapNo); + funBlock = replaceWord(funBlock, parName, "map" + mapNo); + singleHistPhaseMaps.push({ baseName: parName, mapNo: mapNo }); + } + + let isTheoryParam = !isRunDirectiveParam(parName); + let theorySlot = null; + if (isTheoryParam && !singleHistPhase) { + theorySlot = ensureTheoryMapSlot(parName); + theoryBlk = replaceWord(theoryBlk, parName, "map" + theorySlot); + funBlock = replaceWord(funBlock, parName, "map" + theorySlot); + } + + function emitParam(dsIndex, msrName, lookupName) { + let defVal = defVals[cparName] ? defVals[cparName].value : 1.0; + let val = sanitizedMSRParameterValue(all["val" + lookupName] ?? all["val" + parName] ?? "", defVal); + let step = sanitizedMSRParameterError(all["err" + lookupName] ?? all["err" + parName], val); + if (step === "") step = defVal * 0.01; + let min = sanitizedMSRParameterNumber(all["min" + lookupName] ?? all["min" + parName] ?? ""); + let max = sanitizedMSRParameterNumber(all["max" + lookupName] ?? all["max" + parName] ?? ""); + let parLine = formatFitParameterLine(i, msrName, val, step, min, max); + if (importedComments && importedComments[parName]) { + for (let text of importedComments[parName]) paramBlk += text + "\n"; + importedComments[parName] = null; + } + paramBlk += parLine; + let num = i; + i++; + return num; + } + + if (shPar) { + let msrName = parName; + let num = emitParam(-1, msrName, parName); + sharedNumbers[parName] = num; + if (isTheoryParam) { + let slot = singleHistPhase ? singleHistPhaseMaps[singleHistPhaseMaps.length - 1].mapNo : theorySlot; + contexts.forEach(function(ctx) { ctx.mapValues[slot - 1] = num; }); + } else { + contexts.forEach(function(ctx) { + if (parName == "Alpha") ctx.alphaRef = String(num); + else ctx.n0Refs[parName] = String(num); + }); + } + funBlock = replaceWord(funBlock, parName, "par" + num); + } else { + contexts.forEach(function(ctx, d) { + let msrName = parName + "_" + ctx.suffix; + let num = emitParam(d, msrName, msrName); + perDatasetNumbers[d][parName] = num; + if (isTheoryParam) { + let slot = singleHistPhase ? singleHistPhaseMaps[singleHistPhaseMaps.length - 1].mapNo : theorySlot; + ctx.mapValues[slot - 1] = num; + } else { + if (parName == "Alpha") ctx.alphaRef = String(num); + else ctx.n0Refs[parName] = String(num); + } + }); + if (isTheoryParam) { + let slot = singleHistPhase ? singleHistPhaseMaps[singleHistPhaseMaps.length - 1].mapNo : theorySlot; + funBlock = replaceWord(funBlock, parName, "map" + slot); + } else if (perDatasetNumbers[0][parName]) { + funBlock = replaceWord(funBlock, parName, "par" + perDatasetNumbers[0][parName]); + } + } + } + for (let text of importedTrailingComments) paramBlk += text + "\n"; + + let runBlk = ""; + contexts.forEach(function(ctx, d) { + if (isSingleHist) { + for (let iHist = 1; iHist < hists.length + 1; iHist++) { + let n0Line = "norm " + (ctx.n0Refs["No" + iHist] || "0"); + let forwLine = "forward " + hists[iHist - 1]; + let runLines = [ctx.runLine, n0Line, forwLine]; + if (ctx.mapValues.length > 0) { + let vals = ctx.mapValues.slice(); + for (let mi = 0; mi < vals.length; mi++) if (!vals[mi]) vals[mi] = 0; + runLines.push("map " + vals.join(" ")); + } + runLines = runLines.concat(buildT0BgRunLines(all, fitType, iHist - 1, ctx.n0Refs["NBg" + iHist])); + runBlk += runLines.join("\n") + "\n"; + } + } else { + let alphaLine = "alpha " + (ctx.alphaRef || "1"); + let forwLine = "forward " + hists[0]; + let backLine = "backward " + hists[1]; + let runLines = [ctx.runLine, alphaLine, forwLine, backLine]; + if (ctx.mapValues.length > 0) { + let vals = ctx.mapValues.slice(); + for (let mi = 0; mi < vals.length; mi++) if (!vals[mi]) vals[mi] = 0; + runLines.push("map " + vals.join(" ")); + } + runLines = runLines.concat(buildT0BgRunLines(all, fitType, d)); + runBlk += runLines.join("\n") + "\n"; + } + }); + + return { + parameterBlock: paramBlk, + theoryBlock: theoryBlk, + functionsBlock: funBlock, + runBlock: runBlk + }; +} + function renderMSRTemplate(blocks) { let msrFile = msrTemplate; let replacements = { @@ -12429,7 +12688,7 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { level: "error", details: message }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } } @@ -12453,19 +12712,20 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { mixedMode ? "Mixed files" : "Runs" ); setFitStatus(actionLabel + " requires a valid run selection.", { level: "error" }); - return({ ok: 0 }); + return({ ok: 0, message: actionLabel + " requires a valid run selection." }); } // msr2data global expansion assumes homogeneous numeric runs under one // instrument/year; mixed sources are resolved per component in JS instead. - let needsGlobalMSR = runSelection.length > 1 + let needsGlobalMSR = !mixedMode && runSelection.length > 1 && (All.fitAsyType == "AsymmetryGLB" || All.fitAsyType == "SingleHist"); - if (mixedMode && runSelection.length > 1) { - setFitStatus("Mixed multi-dataset fits/plots are not supported yet.", { + if (mixedMode && runSelection.length > 1 && All.fitAsyType == "SingleHist") { + let message = "Mixed multi-dataset SingleHist fits are not supported yet."; + setFitStatus(message, { level: "error", - details: "Mixed mode currently supports a single dataset (optionally with + ADDRUN). Fit or plot datasets separately." + details: "Use Asymmetry fit type or fit mixed datasets separately for now." }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } let baseRunLabel = mixedMode @@ -12473,7 +12733,7 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { : String(runs[0]); let baseRunToken = String(baseRunLabel).replace(/[^A-Za-z0-9._+\-]+/g, "_").replace(/^_+|_+$/g, "") || "mixed"; - if (!mixedMode && webOrApp && typeof resolveWebPortableRunSelection === "function") { + 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. @@ -12481,7 +12741,7 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { } let platform = window.MusRFlowPlatform; - if (!mixedMode && !webOrApp && platform && typeof platform.ensureRunData === 'function' + if (!webOrApp && platform && typeof platform.ensureRunData === 'function' && !isMSREditorSourceAuthoritative('current') && !isMSREditorSourceAuthoritative('template')) { let data = await platform.ensureRunData({ all: All, runSelection: runSelection, action: actionLabel }); @@ -12535,14 +12795,16 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { && isMSREditorSourceAuthoritative("current")) { let editorMSR = getCurrentEditorText(); if (!editorMSR || editorMSR.trim() === "") { - setFitStatus("The active editor is empty.", { + let message = "The active editor is empty."; + setFitStatus(message, { level: "error", details: "Editor source is active, but the editor is empty." }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } if (!await writeAsciiFile(finalPath, editorMSR)) { - return({ ok: 0 }); + let message = "Could not write editor MSR: " + finalPath; + return({ ok: 0, message: message }); } window.MSREditor.currentContent = editorMSR; @@ -12591,11 +12853,12 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { // 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.", { + let message = actionLabel + " cancelled; Global edits were kept."; + setFitStatus(message, { level: "warning", details: actionLabel + " cancelled; manual global MSR edits were kept." }); - return({ ok: 0 }); + return({ ok: 0, message: message, outcome: "cancelled" }); } } @@ -12606,7 +12869,7 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { // override mapping is not wired for mixed mode yet (minimum running path). if (!templateEditorSource) { if (!validateRRFSettings(actionLabel, All)) { - return({ ok: 0 }); + return({ ok: 0, message: "RRF settings are incomplete or invalid." }); } if (!mixedMode) { let t0BgValidation = validateT0BgOverrides(All, runs); @@ -12616,20 +12879,31 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { level: "error", details: t0BgValidation.message }); - return({ ok: 0 }); + return({ ok: 0, message: t0BgValidation.message || "Check the tâ‚€/background overrides." }); } } } // 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.", { + let templateMSR = ""; + try { + templateMSR = templateEditorSource ? window.MSREditor.templateContent : createMSR(); + } catch (error) { + let message = "Could not generate MSR: " + (error && error.message ? error.message : String(error)); + setFitStatus(message, { level: "error", - details: "Template source is active, but the template editor is empty." + details: error && error.stack ? error.stack : message }); - return({ ok: 0 }); + return({ ok: 0, message: message }); + } + if (!templateMSR || templateMSR.trim() === "") { + let message = "The active template editor is empty."; + setFitStatus(message, { + level: "error", + details: templateEditorSource ? "Template source is active, but the template editor is empty." : "Generated MSR is empty." + }); + return({ ok: 0, message: message }); } let templateName = baseRunToken + "_tmpl.msr"; let templatePath = workPath + "/" + templateName; @@ -12639,7 +12913,9 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { let preparedContent = templateMSR; if (needsGlobalMSR) { if (!await writeAsciiFile(templatePath, templateMSR)) { - return({ ok: 0 }); + let message = "Could not write template MSR: " + templatePath; + setFitStatus(message, { level: "error", details: message }); + return({ ok: 0, message: message }); } } else { templatePath = ""; @@ -12655,11 +12931,12 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { let msr2dataGlobal = workPath + "/" + runs[0] + "+global_tmpl.msr"; if (fileExists(msr2dataGlobal) && typeof deleteAsciiFile === "function") { if (!deleteAsciiFile(msr2dataGlobal)) { - setFitStatus("Could not prepare the global MSR.", { + let message = "Could not prepare the global MSR."; + setFitStatus(message, { level: "error", details: "Failed to remove stale global MSR before running msr2data: " + msr2dataGlobal }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } } @@ -12700,11 +12977,12 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { // 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.", { + let message = "Not all ADDRUN data sets could be matched."; + setFitStatus(message, { level: "error", details: "Could not match all ADDRUN data sets in msr2data output. Fit/plot cancelled." }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } normalizedGlobalContent = applyAddRunsToMSR( normalizedGlobalContent, runSelection, All.selYear, All.instrName, All.dataRoot @@ -12727,11 +13005,12 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { } 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.", { + let message = "msr2data did not produce a valid global MSR."; + setFitStatus(message, { level: "error", details: "msr2data did not produce a valid global MSR. Fit/plot cancelled." }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } } } @@ -12743,11 +13022,12 @@ async function prepareMSRRunFiles(actionLabel, prepareOptions = {}) { preparedContent = applyFitParameterSpecToMSR(preparedContent, parameterSyncSpec); } if (!await writeAsciiFile(finalPath, preparedContent)) { + let message = "Could not write prepared MSR: " + finalPath; setFitStatus("Could not write the prepared MSR.", { level: "error", - details: "Failed to write prepared MSR file: " + finalPath + details: message }); - return({ ok: 0 }); + return({ ok: 0, message: message }); } // Keep the editor model aligned with the files written for this action. @@ -13745,13 +14025,14 @@ async function startFit() { try { beginJobPreparation("Fit"); let execution = currentFitExecution(); - if (isMixedRunSourceMode() && execution.dataSetCount > 1) { - let message = "Mixed multi-dataset fits are not supported yet. Use a single mixed dataset (optionally with + ADDRUN), or fit datasets independently in Run numbers mode."; + if (isMixedRunSourceMode() && execution.dataSetCount > 1 + && All.fitAsyType == "SingleHist") { + let message = "Mixed multi-dataset SingleHist fits are not supported yet. Use Asymmetry fit type or fit mixed datasets separately for now."; setFitStatus("Mixed multi-dataset fit not supported yet.", { level: "error", details: message }); finishJobStatus(0, 1, message); return(0); } - if (execution.mode == "series") { + if (execution.mode == "series" && !isMixedRunSourceMode()) { return await runIndependentSeriesFit(execution, webRequest); } let prepared = await prepareMSRRunFiles("Fit"); @@ -13898,7 +14179,7 @@ function applyWebURLParameters(search) { let expandedRuns = (hasRunNumbers && typeof arrayRunNumbers === "function") ? arrayRunNumbers(requestedValue) : []; let parsedMixed = (typeof parseMixedFiles === "function") - ? parseMixedFiles(requestedValue) : null; + ? parseMixedFiles(requestedValue, { requireExplicit: sourceParam === "RunNumbers" }) : null; if (hasRunNumbers && requestedValue !== "" && expandedRuns.length > 0 && !(Array.isArray(parsedMixed) && parsedMixed.length > 0 && (beamLineMissing || yearMissing))) { diff --git a/muSRFitweb.js b/muSRFitweb.js index ffdb1ff..2a30375 100644 --- a/muSRFitweb.js +++ b/muSRFitweb.js @@ -701,9 +701,35 @@ async function resolveWebPortableRunSelection(runSelection, all) { return result; } - let physicalRuns = Array.from(new Set((runSelection || []).reduce(function(runs, dataSet) { + let physicalRuns = (runSelection || []).reduce(function(runs, dataSet) { return runs.concat(seriesDataSetPhysicalRuns(dataSet)); - }, []))).sort(function(a, b) { return a - b; }); + }, []); + let seenTargets = new Set(); + let resolutionTargets = []; + for (let component of physicalRuns) { + let target = null; + if (component && typeof component === "object") { + if (component.kind === "file") continue; + let run = activeDataSetMainRun(component); + if (!(run > 0)) continue; + target = { + run: Number(run), + year: component.year || all.selYear, + instrument: component.instrument || all.instrName, + key: component.kind + "\n" + component.year + "\n" + component.instrument + "\n" + run + }; + } else if (Number(component) > 0) { + target = { + run: Number(component), + year: all.selYear, + instrument: all.instrName, + key: "number\n" + all.selYear + "\n" + all.instrName + "\n" + component + }; + } + if (!target || seenTargets.has(target.key)) continue; + seenTargets.add(target.key); + resolutionTargets.push(target); + } let configuredPaths = Array.isArray(portableRunNamingStartup.dataPaths) ? portableRunNamingStartup.dataPaths.slice() : []; @@ -717,9 +743,10 @@ async function resolveWebPortableRunSelection(runSelection, all) { })); } - await Promise.all(physicalRuns.map(async function(run) { + await Promise.all(resolutionTargets.map(async function(target) { + let run = target.run; let candidates = portableMusrfitRunCandidates( - run, all.selYear, all.instrName, portableRunNamingStartup + run, target.year, target.instrument, portableRunNamingStartup ); for (let candidate of candidates) { for (let dataPath of configuredPaths) { diff --git a/tests/msr-generation.test.js b/tests/msr-generation.test.js index b165ebe..f0295d9 100644 --- a/tests/msr-generation.test.js +++ b/tests/msr-generation.test.js @@ -4023,8 +4023,61 @@ function testMultiAsymmetryRoundTrip(lib) { assert.doesNotMatch(blocks.runBlock, /undefined/); } +function testMixedMultiDatasetMSRGeneration(lib) { + const all = { + runSourceMode: "mixed", + mixedFiles: "2025/LEM/1014,2024/GPS/0567", + fitAsyType: "AsymmetryGLB", + LRBF: "21 25,23 27", + theoFunBlock: "asymmetry Asy\nsimpleGss Sgm\nTFieldCos Phi Frq", + Tis: "0.1", + Tfs: "5", + BINS: "50", + VIEWBINS: "50", + selYear: "2025", + instrName: "LEM", + dataRoot: "/psi.ch/group/lmu/public/data", + numComps: "1", + valAsy: "0.1", errAsy: "0.01", + valSgm: "0.2", errSgm: "0.02", + valFrq: "1", errFrq: "0.1", + valPhi: "0", errPhi: "0.1" + }; + const msr = lib.buildMSR({ + all: all, + funOptions: [ + { value: "Asy", disabled: false }, + { value: "Sgm", disabled: false }, + { value: "Frq", disabled: false }, + { value: "Phi", disabled: false }, + { value: "Alpha", disabled: false } + ], + funLines: [], + sharedFlags: {} + }); + + assert.strictEqual((msr.match(/^RUN\s/gm) || []).length, 2); + assert.match(msr, /^RUN\s+\S*lem25_his_1014\s/m); + assert.match(msr, /^RUN\s+\S*deltatbc_tdc_gps_2024_0567\s/m); + assert.match(msr, /^runs\s+1\s+2$/m); + assert.match(msr, /^map\s+1\s+3\s+5\s+7$/m); + assert.match(msr, /^map\s+2\s+4\s+6\s+8$/m); + assert.doesNotMatch(msr, /undefined/); + + const libSource = fs.readFileSync(path.join(repoRoot, "muSRFitlib.js"), "utf8"); + assert.doesNotMatch( + libSource, + /Mixed multi-dataset global\/SingleHist fits are not supported yet/ + ); + assert.match( + libSource, + /Mixed multi-dataset SingleHist fits are not supported yet/ + ); +} + const lib = loadLibrary(); testElectronPreferencesAndSuffixControls(lib); +testMixedMultiDatasetMSRGeneration(lib); testInitialFrequencyGuess(lib); testReverseFieldInitialization(lib); testResultArtifactRendering(lib); diff --git a/tests/root-plot-clean.test.js b/tests/root-plot-clean.test.js index 15e6248..51edeea 100644 --- a/tests/root-plot-clean.test.js +++ b/tests/root-plot-clean.test.js @@ -393,9 +393,10 @@ function testDecodeCache() { assert.match(code, /decodeCache\.set\(cacheKey, fileObject\)/); assert.match(code, /if \(jsroot && typeof jsroot\.clone === "function"\)/); // Spectrum renders reuse the window cache; FFT renders never do. - assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, resetVersion, rootViewMode, rootDecodeCache\)/); - assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, fftVersion, rootViewMode\)/); - assert.match(code, /let rootDecodeCache = new Map\(\)/); + assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, resetVersion, rootViewMode, currentDecodeCache\(\)\)/); + assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, version, rootViewMode, rootDecodeCaches\[key\]\)/); + assert.match(code, /renderMusrfitRootPlots\(plotContainer, initialSpecs, renderVersion, rootViewMode, currentDecodeCache\(\)\)/); + assert.match(code, /rootDecodeCaches\[key\] = new Map\(\)/); } function runTests() {