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/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 new TypeError("colors must be an object.");
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 new TypeError("Expected colors.data1, colors.data2 and colors.fft to be non-empty CSS color strings.");
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("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
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">信号値 [a.u.]</text>`);
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 new RangeError("Plot width must be at least 160 pixels.");
68
- if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw new TypeError("Invalid SVG ID prefix.");
69
- if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw new RangeError("Display limits must be positive finite numbers.");
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, { title: "FID:Data 1とData 2", xLabel: "時間 [ms]", xMinimum: 0, xMaximum: endMs, scaleFrom: spectrum.actualStartMs, scaleUntil: spectrum.actualEndExclusiveMs, clipId: `${idPrefix}-fid`, width, selection: [spectrum.actualStartMs, spectrum.actualEndExclusiveMs], colors: [palette.data1, palette.data2] }),
79
- fft: plot([visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
80
- title: "複素FFTの振幅スペクトル", xLabel: "受信周波数からの差 [kHz]",
81
- xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: [palette.fft],
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 new TypeError("FID and FFT elements are required.");
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
- : `最大ピーク:${peak.hz.toFixed(1)} Hz(受信周波数からの差)${outside}。全周波数から探索・FFTビン値。`;
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
- const interval = `${spectrum.actualStartMs}〜${spectrum.actualEndExclusiveMs} ms`;
143
- this.statusElement.textContent = `末尾${baseline.tailPoints}点の平均で補正。FID表示は0〜${this.displayEndMs} ms、縦軸は${interval}で自動調整(範囲外はクリップ)。薄い青の帯はFFT範囲。FFTは${interval}(終端を含まない)、${spectrum.window}窓。周波数表示は±${this.frequencyLimitHz / 1000} kHz。`;
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 new TypeError("At least one frequency point and a width of 160 or greater are required.");
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 new TypeError("Frequency and nonnegative amplitude must be finite.");
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
- title: "設定周波数とFFTピーク振幅", xLabel: "設定周波数 [kHz]", xMinimum: min, xMaximum: max,
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 new TypeError("Valid pulse points and plot width are required.");
184
- if (!["signed", "magnitude"].includes(mode)) throw new TypeError("Invalid pulse plot mode.");
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 new TypeError("Pulse lengths and signed values must be finite.");
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 new TypeError("Invalid pulse fit.");
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, { title: magnitude ? "パルス周期数と信号の絶対値" : "パルス周期数と符号付き信号", nonnegative: magnitude, xLabel: "第1パルス [周期数]", xMinimum: 0,
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 new TypeError("Invalid T1 plot settings.");
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 new TypeError("T1 points must be finite.");
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 new TypeError("Invalid T1 fit.");
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, { title: "T1・反転回復曲線", xLabel: "待ち時間 τ [ms]", xMinimum: 0,
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 new TypeError("Invalid T2 plot settings.");
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 new TypeError("T2 points must be finite and nonnegative.");
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 new TypeError("Invalid T2 fit.");
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,{title:"T2・エコー減衰曲線",xLabel:"2τ [ms]",xMinimum:0,xMaximum:Math.max(...sorted.map(p=>2*p.tau)),scaleUntil:Infinity,nonnegative:true,
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";
@@ -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 new RangeError("maxLineBytes must be a positive safe integer.");
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 new Error("Decoder failed; reset it only after communication is resynchronized.");
18
+ throw createError(Error, "DECODER_FAILED");
18
19
  }
19
20
  if (!(bytes instanceof Uint8Array)) {
20
- throw new TypeError("Serial input must be a Uint8Array.");
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 new Error("Non-ASCII byte in controller response.");
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 new Error("Controller response line exceeds maxLineBytes.");
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 new Error("Input ended with an invalid or incomplete response.");
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 new TypeError("Measurement parameters must be an object.");
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 new RangeError(`${name} must be an integer from ${minimum} to ${maximum}.`);
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 new RangeError(`${name} must be 0, 90, 180, or 270.`);
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 new RangeError(`Unsupported command: ${command}`);
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 new TypeError("Expected two comma-separated signed integers.");
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 new RangeError("Sample exceeds the safe integer range.");
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 new Error("符号付きの有効な5点以上が必要です。");
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 new Error("信号がゼロです。");
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 new Error("最初の正の山が見つかりません。基準位相・走査範囲を確認してください。");
9
- if (p[0].length >= p[peak].length * 0.65) throw new Error("短いパルスの点が不足しています。");
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 new Error("正から負へのゼロ交差が未測定です。180\xB0の先まで測定してください。");
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 new Error("近似の最適点が探索範囲の端です。");
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 new Error("符号付きモデルとの一致が不十分です(R\xB2 < 0.85)。");
47
- if (Math.abs(best.B) > 0.2 * best.A) throw new Error("背景成分が大きすぎます。基準位相や解析範囲を確認してください。");
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 new Error("推定180\xB0が範囲外またはゼロ交差と不一致です。");
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 new Error("サイン近似には異なる周期数の有限な3点以上が必要です。");
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 new Error("信号がゼロのためサイン近似を求められません。");
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 new Error("サイン近似を計算できませんでした。");
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);
@@ -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 new TypeError("パルス走査JSONは32 MiB以下の文字列を指定してください。");
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 new TypeError("JSONの形式が正しくありません。"); }
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 new TypeError("パルス校正の全データJSONを指定してください(1〜201点)。");
17
+ throw createError(TypeError, "INVALID_PULSE_ARCHIVE");
17
18
  }
18
19
  const saved = value.settings;
19
- if (!saved) throw new TypeError("走査条件がありません。");
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 new TypeError("解析条件が正しくありません。");
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 new TypeError("測定点と走査条件が一致しません。");
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 new TypeError("基準点が不正です。");
39
- if (!Number.isFinite(phaseDegrees)) throw new TypeError("位相補正が不正です。");
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 new TypeError("走査日時が正しくありません。");
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 };
@@ -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 warnings = [];
30
- if (coherence < 0.85) warnings.push("測定点間の位相が共通方向に揃っていません。");
31
- try { measured = signedPulseCandidates(points); } catch (error) { warnings.push(error.message); }
32
- try { fit = fitPulseCalibration(points); } catch (error) { warnings.push(error.message); }
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) { warnings.push(error.message); }
36
- if (fit && (fit.p180 > Math.max(...points.map(point => point.length)) || fit.p90 < Math.min(...points.map(point => point.length)))) warnings.push("近似のパルス長が測定範囲外です。外挿した推定値です。");
37
- if (fit && fit.r2 < 0.85) warnings.push("サイン近似との一致度が低いため、推定値は参考値です。");
38
- if (magnitudeFit && magnitudeFit.r2 < 0.85) warnings.push("絶対値のサイン近似との一致度が低いため、推定値は参考値です。");
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
  }