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/device.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createError, normalizeError } from "./errors.js";
1
2
  import { encodeCommand, encodeParameters, validateParameters, parseSampleLine,
2
3
  SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
3
4
  import { measurementDurationMs } from "./timing.js";
@@ -14,7 +15,7 @@ export class NMRDevice {
14
15
  constructor({ transport = new WebSerialTransport(), responseTimeoutMs = 5000,
15
16
  dataTimeoutMs = 30000, measurementMarginMs = 20000 } = {}) {
16
17
  for (const value of [responseTimeoutMs, dataTimeoutMs, measurementMarginMs]) {
17
- if (!Number.isFinite(value) || value <= 0) throw new RangeError("Timeouts must be positive finite numbers.");
18
+ if (!Number.isFinite(value) || value <= 0) throw createError(RangeError, "INVALID_TIMEOUT");
18
19
  }
19
20
  this.transport = transport;
20
21
  this.responseTimeoutMs = responseTimeoutMs;
@@ -35,7 +36,7 @@ export class NMRDevice {
35
36
  set state(value) { this.currentState = value; }
36
37
 
37
38
  async connect() {
38
- if (this.busy || this.state !== "disconnected") throw new Error("Device is already active.");
39
+ if (this.busy || this.state !== "disconnected") throw createError(Error, "DEVICE_ACTIVE");
39
40
  this.busy = true;
40
41
  this.state = "connecting";
41
42
  try {
@@ -43,7 +44,7 @@ export class NMRDevice {
43
44
  this.state = "connected";
44
45
  } catch (error) {
45
46
  this.state = "disconnected";
46
- throw error;
47
+ throw normalizeError(error, "SERIAL_CONNECTION_FAILED");
47
48
  } finally {
48
49
  this.busy = false;
49
50
  }
@@ -51,9 +52,10 @@ export class NMRDevice {
51
52
 
52
53
  /** Disconnecting is not a firmware stop command. */
53
54
  async disconnect() {
54
- if (this.busy) throw new Error("Wait for the current operation; disconnect does not stop a measurement.");
55
+ if (this.busy) throw createError(Error, "DISCONNECT_WHILE_BUSY");
55
56
  this.busy = true;
56
57
  try { await this.transport.disconnect(); }
58
+ catch (error) { throw normalizeError(error, "SERIAL_DISCONNECT_FAILED"); }
57
59
  finally { this.state = "disconnected"; this.busy = false; }
58
60
  }
59
61
 
@@ -65,9 +67,9 @@ export class NMRDevice {
65
67
  async measure(input, { mode = "single" } = {}) {
66
68
  // Invalid local input must not send commands or invalidate a good connection.
67
69
  const parameters = validateParameters(input);
68
- if (!["single", "double"].includes(mode)) throw new RangeError("Mode must be single or double.");
69
- if (this.busy) throw new Error("Another device operation is in progress.");
70
- if (this.state !== "connected") throw new Error("Device is not connected.");
70
+ if (!["single", "double"].includes(mode)) throw createError(RangeError, "INVALID_MODE");
71
+ if (this.busy) throw createError(Error, "DEVICE_BUSY");
72
+ if (this.state !== "connected") throw createError(Error, "DEVICE_NOT_CONNECTED");
71
73
  this.busy = true;
72
74
  this.state = "measuring";
73
75
  try {
@@ -85,7 +87,7 @@ export class NMRDevice {
85
87
  const deadline = performance.now() + this.dataTimeoutMs;
86
88
  for (let index = 0; index < SAMPLE_COUNT; index++) {
87
89
  const remainingMs = deadline - performance.now();
88
- if (remainingMs <= 0) throw new Error(`Sample transfer timed out at ${index}/${SAMPLE_COUNT}.`);
90
+ if (remainingMs <= 0) throw createError(Error, "SAMPLE_TRANSFER_TIMEOUT", { index, sampleCount: SAMPLE_COUNT });
89
91
  const line = await this.transport.readLine(Math.min(remainingMs, this.responseTimeoutMs));
90
92
  raw.push(parseSampleLine(line));
91
93
  }
@@ -104,8 +106,8 @@ export class NMRDevice {
104
106
  // the next operation. Require reconnection rather than retrying commands.
105
107
  this.state = "disconnected";
106
108
  try { await this.transport.disconnect(); }
107
- catch (cleanupError) { throw new AggregateError([error, cleanupError], "Measurement and cleanup failed."); }
108
- throw error;
109
+ catch (cleanupError) { throw createError(AggregateError, "MEASUREMENT_CLEANUP_FAILED", {}, { errors: [error, cleanupError] }); }
110
+ throw normalizeError(error);
109
111
  } finally {
110
112
  this.busy = false;
111
113
  }
@@ -116,7 +118,7 @@ export class NMRDevice {
116
118
  await this.transport.write(encodeCommand("parameters"));
117
119
  await delay(50);
118
120
  const acknowledgement = await this.response(this.responseTimeoutMs);
119
- if (!acknowledgement.includes("CMD_P_OK")) throw new Error("Controller did not accept parameter setup.");
121
+ if (!acknowledgement.includes("CMD_P_OK")) throw createError(Error, "PARAMETER_SETUP_REJECTED");
120
122
  await this.transport.write(encodeParameters(parameters));
121
123
  await delay(50);
122
124
  await this.response(this.responseTimeoutMs);
@@ -125,7 +127,7 @@ export class NMRDevice {
125
127
  async response(timeoutMs) {
126
128
  const line = (await this.transport.readLine(timeoutMs)).trim();
127
129
  if (!line || /error|fail|reject/i.test(line)) {
128
- throw new Error(`Invalid controller acknowledgement: ${line}`);
130
+ throw createError(Error, "INVALID_ACKNOWLEDGEMENT", { line });
129
131
  }
130
132
  return line;
131
133
  }
package/src/errors.js ADDED
@@ -0,0 +1,188 @@
1
+ // Stable codes identify diagnostics; English messages are for humans and may improve over time.
2
+ const messages = Object.freeze({
3
+ "INVALID_JSON": "The file is not valid JSON.",
4
+ "INVALID_RECORD_TEXT": "Measurement JSON must be text.",
5
+ "RECORD_TOO_LARGE": "Measurement JSON must be no larger than 2 MiB.",
6
+ "INVALID_RECORD_FILE": "Choose a measurement JSON file.",
7
+ "INVALID_RECORD": "Expected an NMRLink measurement record.",
8
+ "INVALID_RECORD_KIND": "The measurement source or mode is invalid.",
9
+ "INVALID_ACQUISITION_TIME": "The measurement acquisition date is invalid.",
10
+ "INVALID_RECORD_SAMPLING": "Expected 2048 samples at 0.02 ms intervals.",
11
+ "INVALID_RECORD_CHANNELS": "Each raw sample must contain two finite channel values.",
12
+ "INVALID_RECORD_PARAMETERS": "The saved measurement parameters are invalid.",
13
+ "INVALID_FILENAME_TIME": "The acquisition date used for the filename is invalid.",
14
+ "PNG_IMAGE_LOAD_FAILED": "Could not load the graph image.",
15
+ "PNG_CANVAS_UNAVAILABLE": "Canvas is unavailable for PNG export.",
16
+ "PNG_ENCODING_FAILED": "Could not create the PNG image.",
17
+ "RECORD_REQUIRED": "A measurement record is required.",
18
+ "SVG_REQUIRED": "An SVG graph element is required.",
19
+ "INVALID_PNG_SCALE": "PNG scale must be greater than zero and at most 4.",
20
+ "INVALID_PNG_DIMENSIONS": "PNG dimensions must be positive and within 8192 pixels and 16 megapixels.",
21
+ "INVALID_FFT_RANGE": "FFT range must satisfy 0 <= startMs < endMs <= acquisition duration, with a positive sampleIntervalMs.",
22
+ "INVALID_LOWPASS": "LPF requires finite sampling and cutoff values, 0 < cutoffHz < Nyquist, and at least four samples.",
23
+ "INVALID_WINDOW": "Window must be hann or rect.",
24
+ "INSUFFICIENT_FFT_SAMPLES": "FFT requires at least four selected samples.",
25
+ "INVALID_BASELINE_TAIL": "tailPoints must be an integer from 1 to the sample count.",
26
+ "INVALID_TRUNCATE": "truncate must be boolean.",
27
+ "BASELINE_OVERFLOW": "Baseline calculation overflowed.",
28
+ "BASELINE_CORRECTION_OVERFLOW": "Baseline correction overflowed.",
29
+ "FFT_OVERFLOW": "FFT calculation overflowed.",
30
+ "CONTROLLER_DISPOSED": "Controller is disposed.",
31
+ "CONTROLLER_BUSY": "Controller is disposed or another operation is running.",
32
+ "CONTROLLER_DISPOSE_BUSY": "Wait for the current operation before disposing.",
33
+ "INVALID_TIMEOUT": "Timeouts must be positive finite numbers.",
34
+ "DEVICE_ACTIVE": "Device is already active.",
35
+ "DISCONNECT_WHILE_BUSY": "Wait for the current operation; disconnect does not stop a measurement.",
36
+ "INVALID_MODE": "Mode must be single or double.",
37
+ "DEVICE_BUSY": "Another device operation is in progress.",
38
+ "DEVICE_NOT_CONNECTED": "Device is not connected.",
39
+ "MEASUREMENT_CLEANUP_FAILED": "Measurement and cleanup failed.",
40
+ "PARAMETER_SETUP_REJECTED": "Controller did not accept parameter setup.",
41
+ "SERIAL_ACTIVE": "Serial connection is already active or changing.",
42
+ "WEB_SERIAL_UNAVAILABLE": "Web Serial is unavailable. Use a supported browser and HTTPS or localhost.",
43
+ "SERIAL_CONNECTION_INTERRUPTED": "Connection was interrupted.",
44
+ "SERIAL_INPUT_ENDED": "Serial input ended. Reconnect the device.",
45
+ "SERIAL_BUFFER_OVERFLOW": "Serial response buffer overflow.",
46
+ "INVALID_RESPONSE_TIMEOUT": "Invalid response timeout.",
47
+ "SERIAL_READER_BUSY": "Only one response reader is allowed.",
48
+ "RESPONSE_TIMEOUT": "Controller response timed out. Reconnect the device.",
49
+ "SERIAL_CLEAR_WHILE_READING": "Cannot clear input while awaiting a response.",
50
+ "SERIAL_CLOSED": "Serial connection closed.",
51
+ "SERIAL_CLEANUP_FAILED": "Serial cleanup failed.",
52
+ "INVALID_MAX_LINE_BYTES": "maxLineBytes must be a positive safe integer.",
53
+ "DECODER_FAILED": "Decoder failed; reset it only after communication is resynchronized.",
54
+ "INVALID_SERIAL_BYTES": "Serial input must be a Uint8Array.",
55
+ "NON_ASCII_RESPONSE": "Non-ASCII byte in controller response.",
56
+ "RESPONSE_LINE_TOO_LONG": "Controller response line exceeds maxLineBytes.",
57
+ "INCOMPLETE_RESPONSE": "Input ended with an invalid or incomplete response.",
58
+ "INVALID_PARAMETERS": "Measurement parameters must be an object.",
59
+ "INVALID_SAMPLE_LINE": "Expected two comma-separated signed integers.",
60
+ "SAMPLE_OUT_OF_RANGE": "Sample exceeds the safe integer range.",
61
+ "INVALID_SAMPLES": "Samples must be a non-empty array of channel pairs.",
62
+ "SWEEP_TOO_MANY_POINTS": "A sweep must contain at most 201 points.",
63
+ "INVALID_SEARCH_BAND": "The peak-search lower bound must be less than the upper bound.",
64
+ "NO_FFT_BINS": "No FFT bins are available in the search band.",
65
+ "NO_RECORDS": "At least one measurement record is required.",
66
+ "INVALID_PHASE": "Phase correction must be a finite number.",
67
+ "INCONSISTENT_RECORDS": "Measurement conditions, sample intervals and record sources must match.",
68
+ "INCONSISTENT_FFT_GRID": "FFT frequency grids must match.",
69
+ "NO_REFERENCE_SIGNAL": "No signal is available for a common reference.",
70
+ "INVALID_REFERENCE_INDEX": "The reference point index is invalid.",
71
+ "ZERO_REFERENCE_SIGNAL": "The selected reference point has zero signal.",
72
+ "INVALID_ANALYSIS_OPTIONS": "Analysis options are invalid.",
73
+ "MISSING_SWEEP_SETTINGS": "Sweep settings are missing.",
74
+ "SWEEP_RECORD_MISMATCH": "Measurement points do not match the sweep settings.",
75
+ "INVALID_SWEEP_TIME": "The sweep acquisition date is invalid.",
76
+ "INVALID_FIT_RANGE": "Fit range must have finite bounds with start less than end.",
77
+ "INVALID_FIT_PHASE": "Fit range or phase correction is invalid.",
78
+ "INVALID_FREQUENCY_ARCHIVE": "Expected a full frequency-sweep JSON with 1 to 201 points.",
79
+ "INVALID_PULSE_ARCHIVE": "Expected a full pulse-calibration JSON with 1 to 201 points.",
80
+ "INVALID_T1_ARCHIVE": "Expected a full T1 measurement JSON with 1 to 201 points.",
81
+ "INVALID_T2_ARCHIVE": "Expected a full T2 measurement JSON with 1 to 201 points.",
82
+ "ARCHIVE_TOO_LARGE": "Sweep JSON must be text no larger than 32 MiB.",
83
+ "INVALID_CALIBRATED_PULSES": "Pulse cycles must be integers with 0 < p90Cycles < p180Cycles.",
84
+ "INVALID_TAU": "Tau must be an integer from 1 to 32767 ms.",
85
+ "INVALID_T1_SEQUENCE": "T1 requires 180 degrees at phase 0, then tau, then 90 degrees at phase 0.",
86
+ "INVALID_T2_SEQUENCE": "T2 requires 90 degrees at phase 0, then tau, then 180 degrees at phase 90.",
87
+ "REPETITION_TOO_SHORT": "The repetition interval must exceed tau plus the acquisition duration (40.96 ms).",
88
+ "INVALID_RELAXATION_ANALYSIS": "The FFT window needs at least four samples and a search band within -25 to 25 kHz.",
89
+ "SEARCH_BAND_OUT_OF_RANGE": "The peak-search band must be within -25 to 25 kHz.",
90
+ "INVALID_SIGNED_PULSE_POINTS": "At least five distinct valid signed pulse points are required.",
91
+ "ZERO_SIGNAL": "The signal is zero.",
92
+ "PULSE_PEAK_NOT_FOUND": "The first positive peak was not found. Check phase and sweep range.",
93
+ "INSUFFICIENT_SHORT_PULSES": "More short-pulse measurements are required.",
94
+ "PULSE_ZERO_CROSSING_NOT_FOUND": "A positive-to-negative zero crossing is missing. Measure beyond the 180-degree pulse.",
95
+ "PULSE_FIT_BOUNDARY": "The pulse-fit optimum is at the search boundary.",
96
+ "PULSE_FIT_LOW_R2": "Agreement with the signed model is insufficient (R2 < 0.85).",
97
+ "PULSE_BACKGROUND_TOO_LARGE": "The background is too large. Check phase and analysis range.",
98
+ "PULSE_CANDIDATE_MISMATCH": "The estimated 180-degree pulse is outside the range or inconsistent with the zero crossing.",
99
+ "INSUFFICIENT_PULSE_FIT_POINTS": "Sine fitting requires at least three distinct finite pulse lengths.",
100
+ "ZERO_PULSE_FIT_SIGNAL": "Cannot fit a sine model to zero signal.",
101
+ "PULSE_FIT_FAILED": "Could not compute a sine fit.",
102
+ "INVALID_RELAXATION_SIGNAL": "Relaxation points must contain finite delay and signal values.",
103
+ "INSUFFICIENT_RELAXATION_POINTS": "The fit range needs distinct valid tau points: at least five for T1 or three for T2.",
104
+ "FLAT_RELAXATION_SIGNAL": "The signal is zero or flat.",
105
+ "T1_SIGN_CHANGE_REQUIRED": "T1 fitting needs negative and positive signals. Check delay range and phase reference.",
106
+ "NEGATIVE_ECHO_SIGNAL": "Echo amplitude must be nonnegative.",
107
+ "RELAXATION_FIT_BOUNDARY": "The relaxation-fit optimum is outside the search range.",
108
+ "RELAXATION_FIT_LOW_R2": "Agreement with the exponential model is insufficient (R2 < 0.95).",
109
+ "RELAXATION_RANGE_TOO_SHORT": "The observation range is too short to estimate relaxation.",
110
+ "INVALID_GRAPH_COLORS": "colors must be an object.",
111
+ "INVALID_GRAPH_COLOR": "Expected colors.data1, colors.data2 and colors.fft to be non-empty CSS color strings.",
112
+ "INVALID_PLOT_WIDTH": "Plot width must be at least 160 pixels.",
113
+ "INVALID_SVG_PREFIX": "Invalid SVG ID prefix.",
114
+ "INVALID_DISPLAY_LIMITS": "Display limits must be positive finite numbers.",
115
+ "GRAPH_ELEMENTS_REQUIRED": "FID and FFT elements are required.",
116
+ "INVALID_FREQUENCY_PLOT": "At least one frequency point and a width of 160 or greater are required.",
117
+ "INVALID_FREQUENCY_POINT": "Frequency and nonnegative amplitude must be finite.",
118
+ "INVALID_PULSE_PLOT": "Valid pulse points and plot width are required.",
119
+ "INVALID_PULSE_PLOT_MODE": "Invalid pulse plot mode.",
120
+ "INVALID_PULSE_POINT": "Pulse lengths and signed values must be finite.",
121
+ "INVALID_PULSE_FIT": "Invalid pulse fit.",
122
+ "INVALID_T1_PLOT": "Invalid T1 plot settings.",
123
+ "INVALID_T1_POINT": "T1 points must be finite.",
124
+ "INVALID_T1_FIT": "Invalid T1 fit.",
125
+ "INVALID_T2_PLOT": "Invalid T2 plot settings.",
126
+ "INVALID_T2_POINT": "T2 points must be finite and nonnegative.",
127
+ "INVALID_T2_FIT": "Invalid T2 fit.",
128
+ "INVALID_LOCALE": "locale must be \"ja\" or \"en\".",
129
+ "INVALID_STATUS_LABEL": "labels.status must be a string.",
130
+ "PHASE_INCOHERENT": "Measurement phases are not aligned with a common direction.",
131
+ "T1_PHASE_INCOHERENT": "Measurement phases are not aligned; T1 fitting was skipped.",
132
+ "PULSE_FIT_EXTRAPOLATED": "Estimated pulse lengths are outside the measured range and are extrapolated.",
133
+ "PULSE_FIT_LOW_AGREEMENT": "The sine fit has low agreement; treat the estimate as provisional.",
134
+ "MAGNITUDE_FIT_LOW_AGREEMENT": "The magnitude sine fit has low agreement; treat the estimate as provisional.",
135
+ "T1_INCOMPLETE_RECOVERY": "The maximum delay is less than three times estimated T1; incomplete recovery can make the estimate range-sensitive.",
136
+ "T2_FIT_LOW_AGREEMENT": "The exponential fit has low agreement; treat the estimate as provisional.",
137
+ "T2_SHORT_RANGE": "The measured range is short; estimated T2 may be sensitive to the fit range.",
138
+ "INVALID_SWEEP_RANGE": "Sweep bounds must be integers from 1 to {maximum}, start <= end, with a positive integer step.",
139
+ "INVALID_SAMPLE": "Sample {index} must contain exactly two finite numbers.",
140
+ "SAMPLE_TRANSFER_TIMEOUT": "Sample transfer timed out at {index}/{sampleCount}.",
141
+ "INVALID_ACKNOWLEDGEMENT": "Invalid controller acknowledgement.",
142
+ "INVALID_ECHO_WINDOW": "The echo window at tau={tauMs} ms must contain its center and remain within 0 to 40.96 ms.",
143
+ "FFT_TOO_LARGE": "FFT size exceeds {maximum} points.",
144
+ "INVALID_PARAMETER_RANGE": "{name} must be an integer from {minimum} to {maximum}.",
145
+ "INVALID_PARAMETER_PHASE": "{name} must be 0, 90, 180, or 270.",
146
+ "UNSUPPORTED_COMMAND": "Unsupported command.",
147
+ "INVALID_LABEL_OBJECT": "{name} must be an object.",
148
+ "INVALID_GRAPH_LABEL": "Invalid {name}.{key}; expected a supported string label.",
149
+ "UNKNOWN_LABEL_PLACEHOLDER": "Unknown {name} placeholder: {placeholder}.",
150
+ "UNKNOWN_LABEL_KEY": "Unknown labels.{key}.",
151
+ "SERIAL_CONNECTION_FAILED": "Could not connect to the serial device.",
152
+ "SERIAL_READ_FAILED": "Could not read from the serial device.",
153
+ "SERIAL_WRITE_FAILED": "Could not write to the serial device.",
154
+ "SERIAL_DISCONNECT_FAILED": "Could not disconnect the serial device.",
155
+ "PORT_SELECTION_CANCELLED": "Serial port selection was cancelled.",
156
+ "SERIAL_PERMISSION_DENIED": "Serial port access was denied.",
157
+ "OPERATION_FAILED": "The operation failed. See the cause for details.",
158
+ "ANALYSIS_FAILED": "Analysis failed. See the cause for details."
159
+ });
160
+
161
+ export const ERROR_CODES = Object.freeze(Object.fromEntries(Object.keys(messages).map(code => [code, code])));
162
+
163
+ export function createError(Type, code, details = {}, options = {}) {
164
+ const message = messages[code].replace(/\{(\w+)\}/g, (token, key) => String(details[key] ?? token));
165
+ const error = Type === AggregateError
166
+ ? new AggregateError(options.errors, message, options.cause === undefined ? undefined : { cause: options.cause })
167
+ : new Type(message, options.cause === undefined ? undefined : { cause: options.cause });
168
+ error.code = code;
169
+ error.details = { ...details };
170
+ return error;
171
+ }
172
+
173
+ export function normalizeError(error, fallbackCode = "OPERATION_FAILED") {
174
+ if (error && typeof error.code === "string" && Object.hasOwn(ERROR_CODES, error.code)) return error;
175
+ const code = error?.name === "NotFoundError" ? "PORT_SELECTION_CANCELLED"
176
+ : ["NotAllowedError", "SecurityError"].includes(error?.name) ? "SERIAL_PERMISSION_DENIED" : fallbackCode;
177
+ return createError(Error, code, {}, { cause: error });
178
+ }
179
+
180
+ export function createWarning(code, details = {}) {
181
+ const { message } = createError(Error, code, details);
182
+ return { code, message, details: { ...details } };
183
+ }
184
+
185
+ export function warningFromError(error) {
186
+ const diagnostic = normalizeError(error, "ANALYSIS_FAILED");
187
+ return { code: diagnostic.code, message: diagnostic.message, details: { ...diagnostic.details } };
188
+ }
package/src/fft.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createError } from "./errors.js";
1
2
  import { validateSamples } from "./sample-validation.js";
2
3
 
3
4
  // Bound allocations and bitwise-index operations; normal acquisitions use 2048 points.
@@ -49,17 +50,17 @@ export function computeSpectrum(data, {
49
50
  if (![sampleIntervalMs, startMs, endMs].every(Number.isFinite) ||
50
51
  sampleIntervalMs <= 0 || startMs < 0 || startMs >= endMs ||
51
52
  endMs > data.length * sampleIntervalMs + 1e-9) {
52
- throw new RangeError("FFT range must satisfy 0 <= startMs < endMs <= acquisition duration, with a positive sampleIntervalMs.");
53
+ throw createError(RangeError, "INVALID_FFT_RANGE");
53
54
  }
54
- if (!["hann", "rect"].includes(window)) throw new RangeError("Window must be hann or rect.");
55
+ if (!["hann", "rect"].includes(window)) throw createError(RangeError, "INVALID_WINDOW");
55
56
 
56
57
  // Match the PoC's rounding tolerance at exact sample boundaries.
57
58
  const first = Math.ceil(startMs / sampleIntervalMs - 1e-9);
58
59
  const last = Math.min(data.length, Math.ceil(endMs / sampleIntervalMs - 1e-9));
59
60
  const count = last - first;
60
- if (count < 4) throw new RangeError("FFT requires at least four selected samples.");
61
+ if (count < 4) throw createError(RangeError, "INSUFFICIENT_FFT_SAMPLES");
61
62
  const size = 2 ** Math.ceil(Math.log2(count));
62
- if (size > MAX_FFT_SIZE) throw new RangeError(`FFT size exceeds ${MAX_FFT_SIZE} points.`);
63
+ if (size > MAX_FFT_SIZE) throw createError(RangeError, "FFT_TOO_LARGE", { maximum: MAX_FFT_SIZE });
63
64
 
64
65
  const real = new Float64Array(size);
65
66
  const imaginary = new Float64Array(size);
@@ -78,7 +79,7 @@ export function computeSpectrum(data, {
78
79
  const imaginaryValue = imaginary[transformedIndex];
79
80
  // Divide after hypot, just as the PoC does, for amplitude compatibility.
80
81
  const amplitude = Math.hypot(realValue, imaginaryValue) / weight;
81
- if (!Number.isFinite(amplitude)) throw new RangeError("FFT calculation overflowed.");
82
+ if (!Number.isFinite(amplitude)) throw createError(RangeError, "FFT_OVERFLOW");
82
83
  return {
83
84
  hz: (index - size / 2) * 1000 / (size * sampleIntervalMs),
84
85
  real: realValue / weight,
@@ -1,3 +1,4 @@
1
+ import { createError } from "./errors.js";
1
2
  import { parseMeasurement } from "./record.js";
2
3
  import { frequencySteps, evaluateFrequency } from "./frequency-sweep.js";
3
4
  import { validateParameters } from "./protocol.js";
@@ -7,21 +8,21 @@ export const MAX_FREQUENCY_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 parseFrequencySweep(text) {
9
10
  if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_FREQUENCY_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 !== "frequency-sweep" || !Array.isArray(value.points) || !value.points.length || value.points.length > 201) {
16
- throw new TypeError("周波数調整の全データJSONを指定してください(1〜201点)。");
17
+ throw createError(TypeError, "INVALID_FREQUENCY_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 frequencies = frequencySteps(saved.startHz, saved.endHz, saved.stepHz);
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,11 +30,11 @@ export function parseFrequencySweep(text) {
29
30
  if (!record.parameters || record.source !== value.source || record.mode !== "single" ||
30
31
  point.frequencyHz !== frequencies[index] || record.parameters.frequencyHz !== frequencies[index] ||
31
32
  Object.keys(parameters).some(key => key !== "frequencyHz" && parameters[key] !== record.parameters[key])) {
32
- throw new TypeError("測定点と走査条件が一致しません。");
33
+ throw createError(TypeError, "SWEEP_RECORD_MISMATCH");
33
34
  }
34
35
  return evaluateFrequency(record, analysis);
35
36
  });
36
- if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw new TypeError("走査日時が正しくありません。");
37
+ if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw createError(TypeError, "INVALID_SWEEP_TIME");
37
38
  return { source: value.source, acquiredAt: value.acquiredAt,
38
39
  settings: { startHz: saved.startHz, endHz: saved.endHz, stepHz: saved.stepHz, frequencies, parameters, analysis },
39
40
  points };
@@ -1,3 +1,4 @@
1
+ import { createError } from "./errors.js";
1
2
  import { integerSteps, runSingleSweep } from "./sweep.js";
2
3
  import { analyzeMeasurement } from "./analysis.js";
3
4
 
@@ -10,10 +11,10 @@ export function frequencySteps(startHz, endHz, stepHz) {
10
11
  export function evaluateFrequency(record, {
11
12
  startMs = 1, endMs = 5, tailPoints = 100, window = "hann", minHz = -3000, maxHz = 3000,
12
13
  } = {}) {
13
- if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw new RangeError("探索帯域は下限より上限を大きく指定してください。");
14
+ if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw createError(RangeError, "INVALID_SEARCH_BAND");
14
15
  const analysis = analyzeMeasurement(record, { startMs, endMs, tailPoints, window });
15
16
  const bins = analysis.spectrum.bins.filter(bin => bin.hz >= minHz && bin.hz <= maxHz);
16
- if (!bins.length) throw new RangeError("探索帯域にFFTビンがありません。");
17
+ if (!bins.length) throw createError(RangeError, "NO_FFT_BINS");
17
18
  const peak = bins.reduce((best, bin) => bin.amplitude > best.amplitude ? bin : best);
18
19
  return { frequencyHz: record.parameters.frequencyHz, amplitude: peak.amplitude, peakHz: peak.hz, record };
19
20
  }
@@ -0,0 +1,88 @@
1
+ import { createError } from "./errors.js";
2
+ // Graph text is separate from rendering. Templates contain named values in {braces}.
3
+ const SIGNAL = { ja: "信号値 [a.u.]", en: "Signal [a.u.]" };
4
+ const AXES = {
5
+ ja: {
6
+ fid: { title: "FID:Data 1とData 2", xLabel: "時間 [ms]" },
7
+ fft: { title: "複素FFTの振幅スペクトル", xLabel: "受信周波数からの差 [kHz]" },
8
+ frequency: { title: "設定周波数とFFTピーク振幅", xLabel: "設定周波数 [kHz]" },
9
+ pulse: { title: "パルス周期数と符号付き信号", xLabel: "第1パルス [周期数]" },
10
+ pulseMagnitude: { title: "パルス周期数と信号の絶対値", xLabel: "第1パルス [周期数]" },
11
+ t1: { title: "T1・反転回復曲線", xLabel: "待ち時間 τ [ms]" },
12
+ t2: { title: "T2・エコー減衰曲線", xLabel: "2τ [ms]" },
13
+ },
14
+ en: {
15
+ fid: { title: "FID: Data 1 and Data 2", xLabel: "Time [ms]" },
16
+ fft: { title: "Complex FFT amplitude spectrum", xLabel: "Frequency offset [kHz]" },
17
+ frequency: { title: "Set frequency and FFT peak amplitude", xLabel: "Set frequency [kHz]" },
18
+ pulse: { title: "Pulse cycles and signed signal", xLabel: "First pulse [RF cycles]" },
19
+ pulseMagnitude: { title: "Pulse cycles and signal magnitude", xLabel: "First pulse [RF cycles]" },
20
+ t1: { title: "T1 inversion recovery", xLabel: "Delay τ [ms]" },
21
+ t2: { title: "T2 echo decay", xLabel: "2τ [ms]" },
22
+ },
23
+ };
24
+ const MESSAGES = {
25
+ ja: {
26
+ fidEmpty: "測定すると波形を表示します。",
27
+ fftEmpty: "測定するとスペクトルを表示します。",
28
+ peak: {
29
+ empty: "最大ピーク:未測定", none: "最大ピーク:信号なし", outside: "(表示範囲外)",
30
+ value: "最大ピーク:{hz} Hz(受信周波数からの差){outside}。全周波数から探索・FFTビン値。",
31
+ },
32
+ status: "末尾{tailPoints}点の平均で補正。FID表示は0〜{displayEndMs} ms、縦軸は{startMs}〜{endMs} msで自動調整(範囲外はクリップ)。薄い青の帯はFFT範囲。FFTは{startMs}〜{endMs} ms(終端を含まない)、{window}窓。周波数表示は±{frequencyLimitKHz} kHz。",
33
+ },
34
+ en: {
35
+ fidEmpty: "Measure to display the waveform.",
36
+ fftEmpty: "Measure to display the spectrum.",
37
+ peak: {
38
+ empty: "Maximum peak: no measurement", none: "Maximum peak: no signal", outside: " (outside display range)",
39
+ value: "Maximum peak: {hz} Hz offset from receiver{outside}. Searched across all frequencies; FFT bin value.",
40
+ },
41
+ status: "Baseline: mean of the last {tailPoints} samples. FID: 0–{displayEndMs} ms; vertical scale uses {startMs}–{endMs} ms (larger values are clipped). The shaded band marks the FFT interval: {startMs}–{endMs} ms (end excluded), {window} window. Frequency display: ±{frequencyLimitKHz} kHz.",
42
+ },
43
+ };
44
+
45
+ function checkLocale(locale) {
46
+ if (locale !== "ja" && locale !== "en") throw createError(TypeError, "INVALID_LOCALE");
47
+ }
48
+ function checkObject(value, name) {
49
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw createError(TypeError, "INVALID_LABEL_OBJECT", { name });
50
+ }
51
+ function mergeStrings(defaults, overrides, name) {
52
+ checkObject(overrides, name);
53
+ for (const [key, value] of Object.entries(overrides)) {
54
+ if (!Object.hasOwn(defaults, key) || typeof value !== "string") throw createError(TypeError, "INVALID_GRAPH_LABEL", { name, key });
55
+ }
56
+ return { ...defaults, ...overrides };
57
+ }
58
+ function checkTemplate(template, allowed, name) {
59
+ for (const match of template.matchAll(/\{(\w+)\}/g)) {
60
+ if (!allowed.includes(match[1])) throw createError(TypeError, "UNKNOWN_LABEL_PLACEHOLDER", { name, placeholder: match[1] });
61
+ }
62
+ }
63
+
64
+ export function resolvePlotLabels(kind, locale = "ja", labels = {}) {
65
+ checkLocale(locale);
66
+ return mergeStrings({ ...AXES[locale][kind], yLabel: SIGNAL[locale] }, labels, "labels");
67
+ }
68
+
69
+ export function resolveRecordLabels(locale = "ja", labels = {}) {
70
+ checkLocale(locale);
71
+ checkObject(labels, "labels");
72
+ for (const key of Object.keys(labels)) {
73
+ if (!["fid", "fft", "peak", "status"].includes(key)) throw createError(TypeError, "UNKNOWN_LABEL_KEY", { key });
74
+ }
75
+ const text = MESSAGES[locale];
76
+ const fid = mergeStrings({ ...resolvePlotLabels("fid", locale), empty: text.fidEmpty }, labels.fid === undefined ? {} : labels.fid, "labels.fid");
77
+ const fft = mergeStrings({ ...resolvePlotLabels("fft", locale), empty: text.fftEmpty }, labels.fft === undefined ? {} : labels.fft, "labels.fft");
78
+ const peak = mergeStrings(text.peak, labels.peak === undefined ? {} : labels.peak, "labels.peak");
79
+ const status = Object.hasOwn(labels, "status") ? labels.status : text.status;
80
+ if (typeof status !== "string") throw createError(TypeError, "INVALID_STATUS_LABEL");
81
+ checkTemplate(peak.value, ["hz", "outside"], "labels.peak.value");
82
+ checkTemplate(status, ["tailPoints", "displayEndMs", "startMs", "endMs", "window", "frequencyLimitKHz"], "labels.status");
83
+ return { fid, fft, peak, status };
84
+ }
85
+
86
+ export function formatGraphText(template, values) {
87
+ return template.replace(/\{(\w+)\}/g, (_, key) => String(values[key]));
88
+ }