nmrlink 0.1.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +167 -0
- package/README.md +77 -41
- package/package.json +2 -1
- package/src/analysis.js +17 -3
- package/src/baseline.js +5 -4
- package/src/browser.js +15 -11
- package/src/controller.js +8 -6
- package/src/device.js +14 -12
- package/src/errors.js +188 -0
- package/src/fft.js +6 -5
- package/src/frequency-record.js +8 -7
- package/src/frequency-sweep.js +3 -2
- package/src/graph-labels.js +88 -0
- package/src/graphs.js +58 -45
- package/src/index.js +2 -0
- package/src/line-decoder.js +7 -6
- package/src/lowpass.js +43 -0
- package/src/protocol.js +7 -6
- package/src/pulse-fit.js +13 -12
- package/src/pulse-record.js +10 -9
- package/src/pulse-sweep.js +10 -9
- package/src/record.js +10 -9
- package/src/relaxation-fit.js +10 -9
- package/src/sample-validation.js +3 -2
- package/src/signed-signal.js +10 -9
- package/src/sweep.js +4 -3
- package/src/t1-record.js +10 -9
- package/src/t1-sweep.js +12 -11
- package/src/t2-record.js +10 -9
- package/src/t2-sweep.js +15 -14
- package/src/timing.js +2 -1
- package/src/web-serial-transport.js +19 -17
package/src/graphs.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { analyzeMeasurement } from "./analysis.js";
|
|
3
|
+
import { resolvePlotLabels, resolveRecordLabels, formatGraphText } from "./graph-labels.js";
|
|
2
4
|
|
|
3
5
|
// Unique SVG clip IDs allow multiple graph views on the same page.
|
|
4
6
|
let nextGraphId = 0;
|
|
5
7
|
const DEFAULT_COLORS = { data1: "#176caa", data2: "#b34e25", fft: "#176caa" };
|
|
6
8
|
|
|
7
9
|
function lineColors(options = {}) {
|
|
8
|
-
if (!options || typeof options !== "object" || Array.isArray(options)) throw
|
|
10
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw createError(TypeError, "INVALID_GRAPH_COLORS");
|
|
9
11
|
const colors = { ...DEFAULT_COLORS, ...options };
|
|
10
12
|
for (const key of Object.keys(colors)) {
|
|
11
|
-
if (!(key in DEFAULT_COLORS) || typeof colors[key] !== "string" || !colors[key].trim()) throw
|
|
13
|
+
if (!(key in DEFAULT_COLORS) || typeof colors[key] !== "string" || !colors[key].trim()) throw createError(TypeError, "INVALID_GRAPH_COLOR");
|
|
12
14
|
}
|
|
13
15
|
return colors;
|
|
14
16
|
}
|
|
@@ -16,7 +18,7 @@ function lineColors(options = {}) {
|
|
|
16
18
|
const escapeAttribute = value => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
17
19
|
|
|
18
20
|
/** Build a responsive SVG. All plotted values come from validated numeric data. */
|
|
19
|
-
function plot(series, { title, xLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null }) {
|
|
21
|
+
function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null, annotation = null, hiddenSeries = [] }) {
|
|
20
22
|
const height = 280;
|
|
21
23
|
const margin = { left: 68, right: 20, top: 20, bottom: 52 };
|
|
22
24
|
const plotWidth = width - margin.left - margin.right;
|
|
@@ -34,6 +36,7 @@ function plot(series, { title, xLabel, xMinimum, xMaximum, nonnegative = false,
|
|
|
34
36
|
const yPosition = value => margin.top + (yMaximum - value) / (yMaximum - yMinimum) * plotHeight;
|
|
35
37
|
const format = value => Math.abs(value) >= 10000 ? value.toExponential(1) : Number(value.toPrecision(4)).toString();
|
|
36
38
|
const elements = [];
|
|
39
|
+
if (annotation) elements.push(`<text x="${margin.left}" y="12" style="font-size:10px">${escapeAttribute(annotation)}</text>`);
|
|
37
40
|
|
|
38
41
|
for (let tick = 0; tick <= 4; tick++) {
|
|
39
42
|
const x = xMinimum + (xMaximum - xMinimum) * tick / 4;
|
|
@@ -51,34 +54,38 @@ function plot(series, { title, xLabel, xMinimum, xMaximum, nonnegative = false,
|
|
|
51
54
|
elements.push(`<g clip-path="url(#${clipId})"><rect x="${left}" y="${margin.top}" width="${right - left}" height="${plotHeight}" fill="#176caa" fill-opacity="0.1"/><path d="M ${left} ${margin.top} V ${margin.top + plotHeight} M ${right} ${margin.top} V ${margin.top + plotHeight}" stroke="#176caa" stroke-dasharray="4 3"/></g>`);
|
|
52
55
|
}
|
|
53
56
|
series.forEach((points, index) => {
|
|
57
|
+
if (hiddenSeries?.[index]) return;
|
|
54
58
|
const coordinates = points.map(([x, y]) => `${xPosition(x).toFixed(2)},${yPosition(y).toFixed(2)}`).join(" ");
|
|
55
59
|
elements.push(`<polyline points="${coordinates}" fill="none" stroke="${escapeAttribute(colors[index])}" stroke-width="1.5" stroke-linejoin="round" clip-path="url(#${clipId})"/>`);
|
|
56
60
|
if (markers && index === 0) for (const [x, y] of points) {
|
|
57
61
|
elements.push(`<circle cx="${xPosition(x)}" cy="${yPosition(y)}" r="3" fill="${escapeAttribute(colors[index])}" clip-path="url(#${clipId})"/>`);
|
|
58
62
|
}
|
|
59
63
|
});
|
|
60
|
-
elements.push(`<text x="${margin.left + plotWidth / 2}" y="${height - 6}" text-anchor="middle">${xLabel}</text>`);
|
|
61
|
-
elements.push(`<text x="16" y="${margin.top + plotHeight / 2}" transform="rotate(-90 16 ${margin.top + plotHeight / 2})" text-anchor="middle"
|
|
62
|
-
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${title}" style="font-family:inherit;font-size:12px;fill:#34454e"><title>${title}</title>${elements.join("")}</svg>`;
|
|
64
|
+
elements.push(`<text x="${margin.left + plotWidth / 2}" y="${height - 6}" text-anchor="middle">${escapeAttribute(xLabel)}</text>`);
|
|
65
|
+
elements.push(`<text x="16" y="${margin.top + plotHeight / 2}" transform="rotate(-90 16 ${margin.top + plotHeight / 2})" text-anchor="middle">${escapeAttribute(yLabel)}</text>`);
|
|
66
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeAttribute(title)}" style="font-family:inherit;font-size:12px;fill:#34454e"><title>${escapeAttribute(title)}</title>${elements.join("")}</svg>`;
|
|
63
67
|
}
|
|
64
68
|
|
|
65
69
|
/** Analyze without modifying record.raw; share the same pipeline in browser/tests. */
|
|
66
|
-
export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {} } = {}) {
|
|
67
|
-
if (!Number.isFinite(width) || width < 160) throw
|
|
68
|
-
if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw
|
|
69
|
-
if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw
|
|
70
|
+
export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {}, locale = "ja", labels = {}, fftSeries = null } = {}) {
|
|
71
|
+
if (!Number.isFinite(width) || width < 160) throw createError(RangeError, "INVALID_PLOT_WIDTH");
|
|
72
|
+
if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw createError(TypeError, "INVALID_SVG_PREFIX");
|
|
73
|
+
if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw createError(RangeError, "INVALID_DISPLAY_LIMITS");
|
|
70
74
|
const palette = lineColors(colors);
|
|
75
|
+
const text = resolveRecordLabels(locale, labels);
|
|
71
76
|
const { data, spectrum, peak } = analysis;
|
|
77
|
+
const annotation = analysis.lowpass ? `LPF ${analysis.lowpass.cutoffHz} Hz (−3 dB), t ≥ ${analysis.lowpass.startMs} ms` : null;
|
|
72
78
|
const endMs = Math.min(displayEndMs, data.length * record.sampleIntervalMs);
|
|
73
79
|
const displayed = data.slice(0, Math.ceil(endMs / record.sampleIntervalMs - 1e-9));
|
|
74
80
|
const channels = [0, 1].map(channel => displayed.map((pair, index) => [index * record.sampleIntervalMs, pair[channel]]));
|
|
75
81
|
const visibleBins = spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz);
|
|
76
82
|
const displayLimit = Math.min(frequencyLimitHz, 500 / record.sampleIntervalMs);
|
|
77
83
|
return {
|
|
78
|
-
fid: plot(channels, {
|
|
79
|
-
fft: plot([visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
|
|
80
|
-
|
|
81
|
-
|
|
84
|
+
fid: plot(channels, { ...text.fid, annotation, xMinimum: 0, xMaximum: endMs, scaleFrom: spectrum.actualStartMs, scaleUntil: spectrum.actualEndExclusiveMs, clipId: `${idPrefix}-fid`, width, selection: [spectrum.actualStartMs, spectrum.actualEndExclusiveMs], colors: [palette.data1, palette.data2] }),
|
|
85
|
+
fft: plot(fftSeries ? fftSeries.map(line => line.spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz).map(bin => [bin.hz / 1000, bin.amplitude])) : [visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
|
|
86
|
+
...text.fft, annotation: fftSeries ? fftSeries.filter(line => !line.hidden).map(line => line.label).join(" / ") : annotation,
|
|
87
|
+
hiddenSeries: fftSeries?.map(line => line.hidden),
|
|
88
|
+
xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: fftSeries ? fftSeries.map(line => line.color) : [palette.fft],
|
|
82
89
|
}),
|
|
83
90
|
peak,
|
|
84
91
|
spectrum,
|
|
@@ -87,10 +94,13 @@ export function createRecordPlots(record, { width = 720, displayEndMs = 10, freq
|
|
|
87
94
|
|
|
88
95
|
/** Browser graph view. Resize redraws the saved analysis, without remeasuring. */
|
|
89
96
|
export class NMRGraphs {
|
|
90
|
-
constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {} }) {
|
|
91
|
-
if (!fid || !fft) throw
|
|
97
|
+
constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {}, locale = "ja", labels = {}, fftSeries = null }) {
|
|
98
|
+
if (!fid || !fft) throw createError(TypeError, "GRAPH_ELEMENTS_REQUIRED");
|
|
92
99
|
Object.assign(this, { fid, fft, peakElement: peak, statusElement: status, displayEndMs, frequencyLimitHz });
|
|
100
|
+
this.fftSeries = fftSeries;
|
|
93
101
|
this.colors = lineColors(colors);
|
|
102
|
+
this.labels = resolveRecordLabels(locale, labels);
|
|
103
|
+
this.locale = locale;
|
|
94
104
|
this.idPrefix = `nmr-${++nextGraphId}`;
|
|
95
105
|
this.widths = new Map();
|
|
96
106
|
this.observer = new ResizeObserver(entries => {
|
|
@@ -120,7 +130,7 @@ export class NMRGraphs {
|
|
|
120
130
|
const style = getComputedStyle(element);
|
|
121
131
|
return Math.max(160, element.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
|
|
122
132
|
};
|
|
123
|
-
const options = { analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors };
|
|
133
|
+
const options = { fftSeries: this.fftSeries, analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors, locale: this.locale, labels: this.labels };
|
|
124
134
|
const fid = createRecordPlots(record, { ...options, width: widthOf(this.fid) });
|
|
125
135
|
const fft = createRecordPlots(record, { ...options, width: widthOf(this.fft) });
|
|
126
136
|
this.fid.innerHTML = fid.fid;
|
|
@@ -133,23 +143,26 @@ export class NMRGraphs {
|
|
|
133
143
|
}
|
|
134
144
|
if (this.peakElement) {
|
|
135
145
|
const peak = analysis.peak;
|
|
136
|
-
const outside = Math.abs(peak.hz) > this.frequencyLimitHz ?
|
|
137
|
-
this.peakElement.textContent = peak.amplitude === 0 ?
|
|
138
|
-
:
|
|
146
|
+
const outside = Math.abs(peak.hz) > this.frequencyLimitHz ? this.labels.peak.outside : "";
|
|
147
|
+
this.peakElement.textContent = peak.amplitude === 0 ? this.labels.peak.none
|
|
148
|
+
: formatGraphText(this.labels.peak.value, { hz: peak.hz.toFixed(1), outside });
|
|
139
149
|
}
|
|
140
150
|
if (this.statusElement) {
|
|
141
151
|
const { spectrum, baseline } = analysis;
|
|
142
|
-
|
|
143
|
-
|
|
152
|
+
this.statusElement.textContent = formatGraphText(this.labels.status, {
|
|
153
|
+
tailPoints: baseline.tailPoints, displayEndMs: this.displayEndMs,
|
|
154
|
+
startMs: spectrum.actualStartMs, endMs: spectrum.actualEndExclusiveMs,
|
|
155
|
+
window: spectrum.window, frequencyLimitKHz: this.frequencyLimitHz / 1000,
|
|
156
|
+
});
|
|
144
157
|
}
|
|
145
158
|
}
|
|
146
159
|
|
|
147
160
|
clear() {
|
|
148
161
|
this.record = null;
|
|
149
162
|
this.analysis = null;
|
|
150
|
-
this.fid.textContent =
|
|
151
|
-
this.fft.textContent =
|
|
152
|
-
if (this.peakElement) this.peakElement.textContent =
|
|
163
|
+
this.fid.textContent = this.labels.fid.empty;
|
|
164
|
+
this.fft.textContent = this.labels.fft.empty;
|
|
165
|
+
if (this.peakElement) this.peakElement.textContent = this.labels.peak.empty;
|
|
153
166
|
if (this.statusElement) this.statusElement.textContent = "";
|
|
154
167
|
}
|
|
155
168
|
|
|
@@ -160,76 +173,76 @@ export class NMRGraphs {
|
|
|
160
173
|
}
|
|
161
174
|
|
|
162
175
|
/** Build the frequency-response curve with the same SVG axes as FID/FFT graphs. */
|
|
163
|
-
export function createFrequencyPlot(points, { width = 720 } = {}) {
|
|
176
|
+
export function createFrequencyPlot(points, { width = 720, locale = "ja", labels = {} } = {}) {
|
|
164
177
|
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) {
|
|
165
|
-
throw
|
|
178
|
+
throw createError(TypeError, "INVALID_FREQUENCY_PLOT");
|
|
166
179
|
}
|
|
167
180
|
const sorted = [...points].sort((a, b) => a.frequencyHz - b.frequencyHz);
|
|
168
181
|
if (!sorted.every(point => Number.isFinite(point.frequencyHz) && Number.isFinite(point.amplitude) && point.amplitude >= 0)) {
|
|
169
|
-
throw
|
|
182
|
+
throw createError(TypeError, "INVALID_FREQUENCY_POINT");
|
|
170
183
|
}
|
|
171
184
|
let min = sorted[0].frequencyHz / 1000;
|
|
172
185
|
let max = sorted.at(-1).frequencyHz / 1000;
|
|
173
186
|
if (min === max) { min -= 0.1; max += 0.1; }
|
|
174
187
|
const svg = plot([sorted.map(point => [point.frequencyHz / 1000, point.amplitude])], {
|
|
175
|
-
|
|
188
|
+
...resolvePlotLabels("frequency", locale, labels), xMinimum: min, xMaximum: max,
|
|
176
189
|
nonnegative: true, scaleUntil: Infinity, clipId: `sweep-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.fft], markers: true, xFormatter: value => Number(value.toFixed(6)).toString(),
|
|
177
190
|
});
|
|
178
191
|
return svg;
|
|
179
192
|
}
|
|
180
193
|
|
|
181
194
|
/** Signed pulse response and optional fitted curve, at a fixed vertical height. */
|
|
182
|
-
export function createPulsePlot(points, { width = 720, fit = null, mode = "signed" } = {}) {
|
|
183
|
-
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw
|
|
184
|
-
if (!["signed", "magnitude"].includes(mode)) throw
|
|
195
|
+
export function createPulsePlot(points, { width = 720, fit = null, mode = "signed", locale = "ja", labels = {} } = {}) {
|
|
196
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_PULSE_PLOT");
|
|
197
|
+
if (!["signed", "magnitude"].includes(mode)) throw createError(TypeError, "INVALID_PULSE_PLOT_MODE");
|
|
185
198
|
const magnitude = mode === "magnitude";
|
|
186
199
|
const sorted = points.map(point => ({ ...point, amplitude: magnitude ? point.magnitude : point.amplitude })).sort((a, b) => a.length - b.length);
|
|
187
|
-
if (!sorted.every(point => Number.isFinite(point.length) && Number.isFinite(point.amplitude))) throw
|
|
200
|
+
if (!sorted.every(point => Number.isFinite(point.length) && Number.isFinite(point.amplitude))) throw createError(TypeError, "INVALID_PULSE_POINT");
|
|
188
201
|
const min = sorted[0].length, max = sorted.at(-1).length;
|
|
189
202
|
const series = [sorted.map(point => [point.length, point.amplitude])];
|
|
190
203
|
if (fit) {
|
|
191
|
-
if (![fit.A, fit.B, fit.p90].every(Number.isFinite) || fit.p90 <= 0) throw
|
|
204
|
+
if (![fit.A, fit.B, fit.p90].every(Number.isFinite) || fit.p90 <= 0) throw createError(TypeError, "INVALID_PULSE_FIT");
|
|
192
205
|
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
193
206
|
const length = min + (max - min) * index / 200;
|
|
194
207
|
const value = Math.sin(Math.PI * length / (2 * fit.p90));
|
|
195
208
|
return [length, fit.A * (magnitude ? Math.abs(value) : value) + fit.B];
|
|
196
209
|
}));
|
|
197
210
|
}
|
|
198
|
-
return plot(series, {
|
|
211
|
+
return plot(series, { ...resolvePlotLabels(magnitude ? "pulseMagnitude" : "pulse", locale, labels), nonnegative: magnitude, xMinimum: 0,
|
|
199
212
|
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, clipId: `pulse-${++nextGraphId}`, width,
|
|
200
213
|
colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
201
214
|
}
|
|
202
215
|
|
|
203
216
|
/** T1 response: preserve signed recovery; magnitude/quadrature are display-only. */
|
|
204
|
-
export function createT1Plot(points, { width = 720, fit = null, mode = "signed" } = {}) {
|
|
205
|
-
if (!["signed", "magnitude", "quadrature"].includes(mode) || !Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw
|
|
217
|
+
export function createT1Plot(points, { width = 720, fit = null, mode = "signed", locale = "ja", labels = {} } = {}) {
|
|
218
|
+
if (!["signed", "magnitude", "quadrature"].includes(mode) || !Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_T1_PLOT");
|
|
206
219
|
const key = mode === "signed" ? "signal" : mode;
|
|
207
220
|
const sorted = [...points].sort((a, b) => a.tau - b.tau);
|
|
208
|
-
if (!sorted.every(point => Number.isFinite(point.tau) && Number.isFinite(point[key]))) throw
|
|
221
|
+
if (!sorted.every(point => Number.isFinite(point.tau) && Number.isFinite(point[key]))) throw createError(TypeError, "INVALID_T1_POINT");
|
|
209
222
|
const min = sorted[0].tau, max = sorted.at(-1).tau;
|
|
210
223
|
const series = [sorted.map(point => [point.tau, point[key]])];
|
|
211
224
|
if (fit && mode === "signed") {
|
|
212
|
-
if (![fit.A, fit.B, fit.T, fit.from, fit.to].every(Number.isFinite) || fit.T <= 0) throw
|
|
225
|
+
if (![fit.A, fit.B, fit.T, fit.from, fit.to].every(Number.isFinite) || fit.T <= 0) throw createError(TypeError, "INVALID_T1_FIT");
|
|
213
226
|
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
214
227
|
const tau = fit.from + (fit.to - fit.from) * index / 200;
|
|
215
228
|
return [tau, fit.A - fit.B * Math.exp(-tau / fit.T)];
|
|
216
229
|
}));
|
|
217
230
|
}
|
|
218
|
-
return plot(series, {
|
|
231
|
+
return plot(series, { ...resolvePlotLabels("t1", locale, labels), xMinimum: 0,
|
|
219
232
|
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, nonnegative: mode === "magnitude",
|
|
220
233
|
clipId: `t1-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
221
234
|
}
|
|
222
235
|
|
|
223
236
|
/** Echo amplitude versus 2*tau; background is fixed at zero. */
|
|
224
|
-
export function createT2Plot(points, {width = 720, fit = null} = {}) {
|
|
225
|
-
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw
|
|
237
|
+
export function createT2Plot(points, {width = 720, fit = null, locale = "ja", labels = {}} = {}) {
|
|
238
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_T2_PLOT");
|
|
226
239
|
const sorted = [...points].sort((a,b)=>a.tau-b.tau);
|
|
227
|
-
if (!sorted.every(p=>Number.isFinite(p.tau)&&p.tau>0&&Number.isFinite(p.signal)&&p.signal>=0)) throw
|
|
240
|
+
if (!sorted.every(p=>Number.isFinite(p.tau)&&p.tau>0&&Number.isFinite(p.signal)&&p.signal>=0)) throw createError(TypeError, "INVALID_T2_POINT");
|
|
228
241
|
const series = [sorted.map(p=>[2*p.tau,p.signal])];
|
|
229
242
|
if (fit) {
|
|
230
|
-
if (![fit.T,fit.A,fit.from,fit.to].every(Number.isFinite) || fit.T<=0) throw
|
|
243
|
+
if (![fit.T,fit.A,fit.from,fit.to].every(Number.isFinite) || fit.T<=0) throw createError(TypeError, "INVALID_T2_FIT");
|
|
231
244
|
series.push(Array.from({length:201},(_,i)=>{const x=fit.from+(fit.to-fit.from)*i/200;return [x,fit.A*Math.exp(-x/fit.T)];}));
|
|
232
245
|
}
|
|
233
|
-
return plot(series,{
|
|
246
|
+
return plot(series,{...resolvePlotLabels("t2", locale, labels),xMinimum:0,xMaximum:Math.max(...sorted.map(p=>2*p.tau)),scaleUntil:Infinity,nonnegative:true,
|
|
234
247
|
clipId:`t2-${++nextGraphId}`,width,colors:[DEFAULT_COLORS.data1,DEFAULT_COLORS.data2],markers:true});
|
|
235
248
|
}
|
package/src/index.js
CHANGED
|
@@ -11,6 +11,7 @@ export {
|
|
|
11
11
|
export { LineDecoder } from "./line-decoder.js";
|
|
12
12
|
export { WebSerialTransport } from "./web-serial-transport.js";
|
|
13
13
|
export { NMRDevice } from "./device.js";
|
|
14
|
+
export { lowpassFilter } from "./lowpass.js";
|
|
14
15
|
export { correctBaseline } from "./baseline.js";
|
|
15
16
|
export { computeSpectrum } from "./fft.js";
|
|
16
17
|
export { analyzeMeasurement } from "./analysis.js";
|
|
@@ -28,3 +29,4 @@ export { measurementDurationMs } from "./timing.js";
|
|
|
28
29
|
export { t2Delays, t2Parameters, t2Window, evaluateT2, runT2Sweep, analyzeT2 } from "./t2-sweep.js";
|
|
29
30
|
export { fitT2 } from "./relaxation-fit.js";
|
|
30
31
|
export { parseT2Measurement, MAX_T2_JSON_BYTES } from "./t2-record.js";
|
|
32
|
+
export { ERROR_CODES } from "./errors.js";
|
package/src/line-decoder.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
/**
|
|
2
3
|
* Assemble ASCII protocol lines from arbitrary serial byte chunks.
|
|
3
4
|
* Keeps only the incomplete line; complete lines are returned to the caller.
|
|
@@ -5,7 +6,7 @@
|
|
|
5
6
|
export class LineDecoder {
|
|
6
7
|
constructor({ maxLineBytes = 65536 } = {}) {
|
|
7
8
|
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
|
|
8
|
-
throw
|
|
9
|
+
throw createError(RangeError, "INVALID_MAX_LINE_BYTES");
|
|
9
10
|
}
|
|
10
11
|
this.maxLineBytes = maxLineBytes;
|
|
11
12
|
this.partial = "";
|
|
@@ -14,17 +15,17 @@ export class LineDecoder {
|
|
|
14
15
|
|
|
15
16
|
push(bytes) {
|
|
16
17
|
if (this.failed) {
|
|
17
|
-
throw
|
|
18
|
+
throw createError(Error, "DECODER_FAILED");
|
|
18
19
|
}
|
|
19
20
|
if (!(bytes instanceof Uint8Array)) {
|
|
20
|
-
throw
|
|
21
|
+
throw createError(TypeError, "INVALID_SERIAL_BYTES");
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
const lines = [];
|
|
24
25
|
for (const byte of bytes) {
|
|
25
26
|
if (byte > 0x7f) {
|
|
26
27
|
this.failed = true;
|
|
27
|
-
throw
|
|
28
|
+
throw createError(Error, "NON_ASCII_RESPONSE");
|
|
28
29
|
}
|
|
29
30
|
if (byte === 0x0a) {
|
|
30
31
|
lines.push(this.partial.replace(/\r$/, ""));
|
|
@@ -33,7 +34,7 @@ export class LineDecoder {
|
|
|
33
34
|
this.partial += String.fromCharCode(byte);
|
|
34
35
|
if (this.partial.length > this.maxLineBytes) {
|
|
35
36
|
this.failed = true;
|
|
36
|
-
throw
|
|
37
|
+
throw createError(Error, "RESPONSE_LINE_TOO_LONG");
|
|
37
38
|
}
|
|
38
39
|
}
|
|
39
40
|
}
|
|
@@ -44,7 +45,7 @@ export class LineDecoder {
|
|
|
44
45
|
finish() {
|
|
45
46
|
if (this.failed || this.partial.length !== 0) {
|
|
46
47
|
this.failed = true;
|
|
47
|
-
throw
|
|
48
|
+
throw createError(Error, "INCOMPLETE_RESPONSE");
|
|
48
49
|
}
|
|
49
50
|
}
|
|
50
51
|
|
package/src/lowpass.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { validateSamples } from './sample-validation.js';
|
|
2
|
+
import { createError } from './errors.js';
|
|
3
|
+
|
|
4
|
+
/** Offline LPF: second-order Butterworth in each direction, with odd reflection.
|
|
5
|
+
* cutoffHz is the FINAL -3.0103 dB frequency after both passes, in Hz.
|
|
6
|
+
* Each channel uses identical coefficients. Input samples are never modified.
|
|
7
|
+
*/
|
|
8
|
+
export function lowpassFilter(data, { sampleIntervalMs, cutoffHz }) {
|
|
9
|
+
validateSamples(data);
|
|
10
|
+
const sampleRate = 1000 / sampleIntervalMs;
|
|
11
|
+
if (!Number.isFinite(sampleRate) || sampleRate <= 0 || !Number.isFinite(cutoffHz) || cutoffHz <= 0 || cutoffHz >= sampleRate / 2 || data.length < 4) {
|
|
12
|
+
throw createError(RangeError, 'INVALID_LOWPASS');
|
|
13
|
+
}
|
|
14
|
+
// Bilinear prewarping compensates for the squared response of two passes.
|
|
15
|
+
const k = Math.tan(Math.PI * cutoffHz / sampleRate) / (Math.SQRT2 - 1) ** 0.25;
|
|
16
|
+
const norm = 1 / (1 + Math.SQRT2 * k + k * k);
|
|
17
|
+
const b0 = k * k * norm, b1 = 2 * b0, b2 = b0;
|
|
18
|
+
const a1 = 2 * (k * k - 1) * norm;
|
|
19
|
+
const a2 = (1 - Math.SQRT2 * k + k * k) * norm;
|
|
20
|
+
const padding = Math.min(data.length - 1, Math.ceil(3 * sampleRate / cutoffHz));
|
|
21
|
+
function pass(values) {
|
|
22
|
+
// Steady-state initialization for the first value avoids a DC startup step.
|
|
23
|
+
let z1 = (1 - b0) * values[0], z2 = (b2 - a2) * values[0];
|
|
24
|
+
return values.map(x => {
|
|
25
|
+
const y = b0 * x + z1;
|
|
26
|
+
z1 = b1 * x - a1 * y + z2;
|
|
27
|
+
z2 = b2 * x - a2 * y;
|
|
28
|
+
if (!Number.isFinite(y)) throw createError(RangeError, 'INVALID_LOWPASS');
|
|
29
|
+
return y;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const channels = [0, 1].map(channel => {
|
|
33
|
+
const values = data.map(pair => pair[channel]);
|
|
34
|
+
const left = Array.from({ length: padding }, (_, i) => 2 * values[0] - values[padding - i]);
|
|
35
|
+
const right = Array.from({ length: padding }, (_, i) => 2 * values.at(-1) - values[values.length - 2 - i]);
|
|
36
|
+
const forward = pass([...left, ...values, ...right]);
|
|
37
|
+
return pass(forward.reverse()).reverse().slice(padding, padding + values.length);
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
data: data.map((_, i) => [channels[0][i], channels[1][i]]),
|
|
41
|
+
cutoffHz, method: 'butterworth-2-forward-backward', paddingSamples: padding,
|
|
42
|
+
};
|
|
43
|
+
}
|
package/src/protocol.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
/** Wire format used by the prototype controller. See docs/PROTOCOL.md. */
|
|
2
3
|
export const SAMPLE_COUNT = 2048;
|
|
3
4
|
export const SAMPLE_INTERVAL_MS = 0.02;
|
|
@@ -36,21 +37,21 @@ const INTEGER_RANGES = {
|
|
|
36
37
|
/** Validate and copy only the supported fields. @param {MeasurementParameters} input */
|
|
37
38
|
export function validateParameters(input) {
|
|
38
39
|
if (input === null || typeof input !== "object" || Array.isArray(input)) {
|
|
39
|
-
throw
|
|
40
|
+
throw createError(TypeError, "INVALID_PARAMETERS");
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
const parameters = {};
|
|
43
44
|
for (const [name, [minimum, maximum]] of Object.entries(INTEGER_RANGES)) {
|
|
44
45
|
const value = input[name];
|
|
45
46
|
if (!Number.isInteger(value) || value < minimum || value > maximum) {
|
|
46
|
-
throw
|
|
47
|
+
throw createError(RangeError, "INVALID_PARAMETER_RANGE", { name, minimum, maximum });
|
|
47
48
|
}
|
|
48
49
|
parameters[name] = value;
|
|
49
50
|
}
|
|
50
51
|
|
|
51
52
|
for (const name of ["phase1Degrees", "phase2Degrees"]) {
|
|
52
53
|
if (![0, 90, 180, 270].includes(input[name])) {
|
|
53
|
-
throw
|
|
54
|
+
throw createError(RangeError, "INVALID_PARAMETER_PHASE", { name });
|
|
54
55
|
}
|
|
55
56
|
parameters[name] = input[name];
|
|
56
57
|
}
|
|
@@ -89,7 +90,7 @@ export function encodeCommand(command) {
|
|
|
89
90
|
read: [0x72, 0x0d, 0x0a],
|
|
90
91
|
};
|
|
91
92
|
if (!Object.hasOwn(commands, command)) {
|
|
92
|
-
throw
|
|
93
|
+
throw createError(RangeError, "UNSUPPORTED_COMMAND", { command });
|
|
93
94
|
}
|
|
94
95
|
return new Uint8Array(commands[command]);
|
|
95
96
|
}
|
|
@@ -97,11 +98,11 @@ export function encodeCommand(command) {
|
|
|
97
98
|
/** Decode one complete channel-pair line. Invalid data is never replaced by zero. */
|
|
98
99
|
export function parseSampleLine(line) {
|
|
99
100
|
if (typeof line !== "string" || !/^-?\d+,-?\d+$/.test(line.trim())) {
|
|
100
|
-
throw
|
|
101
|
+
throw createError(TypeError, "INVALID_SAMPLE_LINE");
|
|
101
102
|
}
|
|
102
103
|
const sample = line.trim().split(",").map(Number);
|
|
103
104
|
if (!sample.every(Number.isSafeInteger)) {
|
|
104
|
-
throw
|
|
105
|
+
throw createError(RangeError, "SAMPLE_OUT_OF_RANGE");
|
|
105
106
|
}
|
|
106
107
|
return sample;
|
|
107
108
|
}
|
package/src/pulse-fit.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
// The original PoC fit is retained as the first choice for well-resolved signed data.
|
|
2
3
|
function signedPulseCandidates(points) {
|
|
3
4
|
const p = [...points].sort((a2, b2) => a2.length - b2.length);
|
|
4
|
-
if (p.length < 5 || new Set(p.map((q) => q.length)).size !== p.length || !p.every((q) => Number.isFinite(q.amplitude) && Number.isFinite(q.length) && q.length > 0)) throw
|
|
5
|
+
if (p.length < 5 || new Set(p.map((q) => q.length)).size !== p.length || !p.every((q) => Number.isFinite(q.amplitude) && Number.isFinite(q.length) && q.length > 0)) throw createError(Error, "INVALID_SIGNED_PULSE_POINTS");
|
|
5
6
|
const scale = Math.max(...p.map((q) => Math.abs(q.amplitude)));
|
|
6
|
-
if (scale < 1e-9) throw
|
|
7
|
+
if (scale < 1e-9) throw createError(Error, "ZERO_SIGNAL");
|
|
7
8
|
const peak = p.findIndex((q, i) => i > 0 && i < p.length - 1 && q.amplitude >= p[i - 1].amplitude && q.amplitude > p[i + 1].amplitude && q.amplitude > 0.35 * scale);
|
|
8
|
-
if (peak < 0) throw
|
|
9
|
-
if (p[0].length >= p[peak].length * 0.65) throw
|
|
9
|
+
if (peak < 0) throw createError(Error, "PULSE_PEAK_NOT_FOUND");
|
|
10
|
+
if (p[0].length >= p[peak].length * 0.65) throw createError(Error, "INSUFFICIENT_SHORT_PULSES");
|
|
10
11
|
let crossing = -1;
|
|
11
12
|
for (let i = peak; i < p.length - 1; i++) if (p[i].amplitude >= 0 && p[i + 1].amplitude < 0) {
|
|
12
13
|
crossing = i;
|
|
13
14
|
break;
|
|
14
15
|
}
|
|
15
|
-
if (crossing < 0) throw
|
|
16
|
+
if (crossing < 0) throw createError(Error, "PULSE_ZERO_CROSSING_NOT_FOUND");
|
|
16
17
|
const a = p[crossing], b = p[crossing + 1], p180 = a.length + (b.length - a.length) * a.amplitude / (a.amplitude - b.amplitude);
|
|
17
18
|
return { p90: p[peak].length, p180, peakIndex: peak, crossingIndex: crossing, points: p, zeroBracket: [a.length, b.length] };
|
|
18
19
|
}
|
|
@@ -34,7 +35,7 @@ function strictPulseFit(points) {
|
|
|
34
35
|
index = i;
|
|
35
36
|
}
|
|
36
37
|
}
|
|
37
|
-
if (index === 0 || index === steps) throw
|
|
38
|
+
if (index === 0 || index === steps) throw createError(Error, "PULSE_FIT_BOUNDARY");
|
|
38
39
|
let l = lower + (upper - lower) * (index - 1) / steps, h = lower + (upper - lower) * (index + 1) / steps;
|
|
39
40
|
for (let i = 0; i < 45; i++) {
|
|
40
41
|
const a2 = l + (h - l) / 3, b2 = h - (h - l) / 3;
|
|
@@ -43,10 +44,10 @@ function strictPulseFit(points) {
|
|
|
43
44
|
}
|
|
44
45
|
best = evaluate((l + h) / 2);
|
|
45
46
|
const mean = p.reduce((s, q) => s + q.amplitude, 0) / p.length, sst = p.reduce((s, q) => s + (q.amplitude - mean) ** 2, 0), r2 = 1 - best.sse / sst, p180 = 2 * best.p90;
|
|
46
|
-
if (!Number.isFinite(r2) || r2 < 0.85) throw
|
|
47
|
-
if (Math.abs(best.B) > 0.2 * best.A) throw
|
|
47
|
+
if (!Number.isFinite(r2) || r2 < 0.85) throw createError(Error, "PULSE_FIT_LOW_R2");
|
|
48
|
+
if (Math.abs(best.B) > 0.2 * best.A) throw createError(Error, "PULSE_BACKGROUND_TOO_LARGE");
|
|
48
49
|
const [a, b] = measured.zeroBracket, margin = Math.max(b - a, 1);
|
|
49
|
-
if (p180 < p[0].length || p180 > p.at(-1).length || p180 < a - margin || p180 > b + margin) throw
|
|
50
|
+
if (p180 < p[0].length || p180 > p.at(-1).length || p180 < a - margin || p180 > b + margin) throw createError(Error, "PULSE_CANDIDATE_MISMATCH");
|
|
50
51
|
return { p90: best.p90, p180, A: best.A, B: best.B, r2, rmse: Math.sqrt(best.sse / p.length), from: p[0].length, to: p.at(-1).length, n: p.length, measured: { p90: measured.p90, p180: measured.p180 }, model: "A*sin(pi*length/(2*p90))+B" };
|
|
51
52
|
}
|
|
52
53
|
/** Least-squares sine estimate even when a peak or zero crossing was not measured. */
|
|
@@ -56,10 +57,10 @@ function fitPulseCalibration(points, { magnitude = false } = {}) {
|
|
|
56
57
|
}
|
|
57
58
|
const p = [...points].sort((a, b) => a.length - b.length);
|
|
58
59
|
if (p.length < 3 || !p.every(q => Number.isFinite(q.length) && q.length > 0 && Number.isFinite(q.amplitude)) || new Set(p.map(q => q.length)).size !== p.length) {
|
|
59
|
-
throw
|
|
60
|
+
throw createError(Error, "INSUFFICIENT_PULSE_FIT_POINTS");
|
|
60
61
|
}
|
|
61
62
|
const scale = Math.max(...p.map(q => Math.abs(q.amplitude)));
|
|
62
|
-
if (scale < 1e-9) throw
|
|
63
|
+
if (scale < 1e-9) throw createError(Error, "ZERO_PULSE_FIT_SIGNAL");
|
|
63
64
|
const y = p.map(q => q.amplitude / scale), n = p.length, sy = y.reduce((s,v) => s+v,0);
|
|
64
65
|
const mean = sy / n, sst = y.reduce((s,v) => s+(v-mean)**2,0);
|
|
65
66
|
function solve(logLength) {
|
|
@@ -76,7 +77,7 @@ function fitPulseCalibration(points, { magnitude = false } = {}) {
|
|
|
76
77
|
const lo = Math.log(step/2), hi = Math.log(p.at(-1).length*10), steps = 4000;
|
|
77
78
|
let best = {sse:Infinity}, index = 0;
|
|
78
79
|
for (let i=0;i<=steps;i++) { const value=solve(lo+(hi-lo)*i/steps); if(value.sse<best.sse){best=value;index=i;} }
|
|
79
|
-
if (!Number.isFinite(best.sse)) throw
|
|
80
|
+
if (!Number.isFinite(best.sse)) throw createError(Error, "PULSE_FIT_FAILED");
|
|
80
81
|
let l=lo+(hi-lo)*Math.max(0,index-1)/steps, h=lo+(hi-lo)*Math.min(steps,index+1)/steps;
|
|
81
82
|
for(let i=0;i<45;i++){const a=l+(h-l)/3,b=h-(h-l)/3;if(solve(a).sse<solve(b).sse)h=b;else l=a;}
|
|
82
83
|
best=solve((l+h)/2);
|
package/src/pulse-record.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { parseMeasurement } from "./record.js";
|
|
2
3
|
import { pulseSteps, evaluatePulse, analyzePulseCalibration } from "./pulse-sweep.js";
|
|
3
4
|
import { validateParameters } from "./protocol.js";
|
|
@@ -7,21 +8,21 @@ export const MAX_PULSE_JSON_BYTES = 32 * 1024 * 1024;
|
|
|
7
8
|
/** Restore raw records and recompute all derived values before replacing a UI's results. */
|
|
8
9
|
export function parsePulseCalibration(text) {
|
|
9
10
|
if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_PULSE_JSON_BYTES) {
|
|
10
|
-
throw
|
|
11
|
+
throw createError(TypeError, "ARCHIVE_TOO_LARGE");
|
|
11
12
|
}
|
|
12
13
|
let value;
|
|
13
14
|
try { value = JSON.parse(text.replace(/^\uFEFF/, "")); }
|
|
14
|
-
catch { throw
|
|
15
|
+
catch (cause) { throw createError(TypeError, "INVALID_JSON", {}, { cause }); }
|
|
15
16
|
if (value?.kind !== "pulse-calibration" || !Array.isArray(value.points) || !value.points.length || value.points.length > 201) {
|
|
16
|
-
throw
|
|
17
|
+
throw createError(TypeError, "INVALID_PULSE_ARCHIVE");
|
|
17
18
|
}
|
|
18
19
|
const saved = value.settings;
|
|
19
|
-
if (!saved) throw
|
|
20
|
+
if (!saved) throw createError(TypeError, "MISSING_SWEEP_SETTINGS");
|
|
20
21
|
const lengths = pulseSteps(saved.startCycles, saved.endCycles, saved.stepCycles);
|
|
21
22
|
const parameters = validateParameters(saved.parameters);
|
|
22
23
|
const a = saved.analysis;
|
|
23
24
|
if (!a || ![a.startMs, a.endMs, a.tailPoints, a.minHz, a.maxHz].every(Number.isFinite) || !["hann", "rect"].includes(a.window)) {
|
|
24
|
-
throw
|
|
25
|
+
throw createError(TypeError, "INVALID_ANALYSIS_OPTIONS");
|
|
25
26
|
}
|
|
26
27
|
const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, window: a.window, minHz: a.minHz, maxHz: a.maxHz };
|
|
27
28
|
const points = value.points.map((point, index) => {
|
|
@@ -29,21 +30,21 @@ export function parsePulseCalibration(text) {
|
|
|
29
30
|
if (!record.parameters || record.source !== value.source || record.mode !== "single" ||
|
|
30
31
|
point.length !== lengths[index] || record.parameters.pulse1Cycles !== lengths[index] ||
|
|
31
32
|
Object.keys(parameters).some(key => key !== "pulse1Cycles" && parameters[key] !== record.parameters[key])) {
|
|
32
|
-
throw
|
|
33
|
+
throw createError(TypeError, "SWEEP_RECORD_MISMATCH");
|
|
33
34
|
}
|
|
34
35
|
return evaluatePulse(record, analysis);
|
|
35
36
|
});
|
|
36
37
|
const referenceIndex = value.calibration?.reference?.referenceIndex ?? null;
|
|
37
38
|
const phaseDegrees = value.calibration?.reference?.phaseDegrees ?? 0;
|
|
38
|
-
if (referenceIndex !== null && (!Number.isInteger(referenceIndex) || referenceIndex < 0 || referenceIndex >= points.length)) throw
|
|
39
|
-
if (!Number.isFinite(phaseDegrees)) throw
|
|
39
|
+
if (referenceIndex !== null && (!Number.isInteger(referenceIndex) || referenceIndex < 0 || referenceIndex >= points.length)) throw createError(TypeError, "INVALID_REFERENCE_INDEX");
|
|
40
|
+
if (!Number.isFinite(phaseDegrees)) throw createError(TypeError, "INVALID_PHASE");
|
|
40
41
|
let calibration = null;
|
|
41
42
|
try { calibration = analyzePulseCalibration(points.map(point => point.record), { analysis, referenceIndex, phaseDegrees }); }
|
|
42
43
|
catch (error) {
|
|
43
44
|
// A valid zero-signal scan is still useful for inspecting raw waveforms.
|
|
44
45
|
if (error.code !== "NO_REFERENCE_SIGNAL") throw error;
|
|
45
46
|
}
|
|
46
|
-
if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw
|
|
47
|
+
if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw createError(TypeError, "INVALID_SWEEP_TIME");
|
|
47
48
|
return { source: value.source, acquiredAt: value.acquiredAt,
|
|
48
49
|
settings: { startCycles: saved.startCycles, endCycles: saved.endCycles, stepCycles: saved.stepCycles, lengths, parameters, analysis },
|
|
49
50
|
points, calibration, referenceIndex, phaseDegrees };
|
package/src/pulse-sweep.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createWarning, warningFromError } from "./errors.js";
|
|
1
2
|
import { integerSteps, runSingleSweep } from "./sweep.js";
|
|
2
3
|
import { evaluateFrequency } from "./frequency-sweep.js";
|
|
3
4
|
import { analyzeSignedRecords } from "./signed-signal.js";
|
|
@@ -26,15 +27,15 @@ export function analyzePulseCalibration(records, options = {}) {
|
|
|
26
27
|
const { points, reference } = result;
|
|
27
28
|
const coherence = reference.coherence;
|
|
28
29
|
let measured = null, fit = null;
|
|
29
|
-
const
|
|
30
|
-
if (coherence < 0.85)
|
|
31
|
-
try { measured = signedPulseCandidates(points); } catch (error) {
|
|
32
|
-
try { fit = fitPulseCalibration(points); } catch (error) {
|
|
30
|
+
const warningDetails = [];
|
|
31
|
+
if (coherence < 0.85) warningDetails.push(createWarning("PHASE_INCOHERENT"));
|
|
32
|
+
try { measured = signedPulseCandidates(points); } catch (error) { warningDetails.push(warningFromError(error)); }
|
|
33
|
+
try { fit = fitPulseCalibration(points); } catch (error) { warningDetails.push(warningFromError(error)); }
|
|
33
34
|
let magnitudeFit = null;
|
|
34
35
|
try { magnitudeFit = fitPulseCalibration(points.map(point => ({length:point.length,amplitude:point.magnitude})), {magnitude:true}); }
|
|
35
|
-
catch (error) {
|
|
36
|
-
if (fit && (fit.p180 > Math.max(...points.map(point => point.length)) || fit.p90 < Math.min(...points.map(point => point.length))))
|
|
37
|
-
if (fit && fit.r2 < 0.85)
|
|
38
|
-
if (magnitudeFit && magnitudeFit.r2 < 0.85)
|
|
39
|
-
return { ...result, measured, fit, magnitudeFit, warnings };
|
|
36
|
+
catch (error) { warningDetails.push(warningFromError(error)); }
|
|
37
|
+
if (fit && (fit.p180 > Math.max(...points.map(point => point.length)) || fit.p90 < Math.min(...points.map(point => point.length)))) warningDetails.push(createWarning("PULSE_FIT_EXTRAPOLATED"));
|
|
38
|
+
if (fit && fit.r2 < 0.85) warningDetails.push(createWarning("PULSE_FIT_LOW_AGREEMENT"));
|
|
39
|
+
if (magnitudeFit && magnitudeFit.r2 < 0.85) warningDetails.push(createWarning("MAGNITUDE_FIT_LOW_AGREEMENT"));
|
|
40
|
+
return { ...result, measured, fit, magnitudeFit, warnings: warningDetails.map(warning => warning.message), warningDetails };
|
|
40
41
|
}
|