nmrlink 0.1.3 → 0.2.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/t2-record.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createError } from "./errors.js";
1
2
  import { parseMeasurement } from "./record.js";
2
3
  import { validateParameters } from "./protocol.js";
3
4
  import { t2Delays, evaluateT2, analyzeT2 } from "./t2-sweep.js";
@@ -6,36 +7,36 @@ export const MAX_T2_JSON_BYTES = 32 * 1024 * 1024;
6
7
 
7
8
  /** Restore a complete or stopped T2 scan; recompute derived data from raw samples. */
8
9
  export function parseT2Measurement(text) {
9
- if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_T2_JSON_BYTES) throw new TypeError("T2のJSONは32 MiB以下で指定してください。");
10
+ if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_T2_JSON_BYTES) throw createError(TypeError, "ARCHIVE_TOO_LARGE");
10
11
  let saved;
11
12
  try { saved = JSON.parse(text.replace(/^\uFEFF/, "")); }
12
- catch { throw new TypeError("JSONの形式が正しくありません。"); }
13
+ catch (cause) { throw createError(TypeError, "INVALID_JSON", {}, { cause }); }
13
14
  if (saved?.kind !== "t2-measurement" || !Array.isArray(saved.points) || !saved.points.length || saved.points.length > 201) {
14
- throw new TypeError("T2の全データJSONを指定してください(1〜201点)。");
15
+ throw createError(TypeError, "INVALID_T2_ARCHIVE");
15
16
  }
16
17
  const s = saved.settings;
17
- if (!s) throw new TypeError("走査条件がありません。");
18
+ if (!s) throw createError(TypeError, "MISSING_SWEEP_SETTINGS");
18
19
  const delays = t2Delays(s.startMs, s.endMs, s.stepMs);
19
20
  const parameters = validateParameters(s.parameters);
20
21
  const a = s.analysis;
21
- if (!a || ![a.startMs, a.endMs, a.tailPoints, a.minHz, a.maxHz].every(Number.isFinite) || !["hann", "rect"].includes(a.window)) throw new TypeError("解析条件が正しくありません。");
22
+ if (!a || ![a.startMs, a.endMs, a.tailPoints, a.minHz, a.maxHz].every(Number.isFinite) || !["hann", "rect"].includes(a.window)) throw createError(TypeError, "INVALID_ANALYSIS_OPTIONS");
22
23
  const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, minHz: a.minHz, maxHz: a.maxHz, window: a.window };
23
24
  const points = saved.points.map((point, index) => {
24
25
  const record = parseMeasurement(JSON.stringify(point?.record));
25
26
  if (!record.parameters || record.mode !== "double" || record.source !== saved.source || point.tau !== delays[index] || record.parameters.pulseIntervalMs !== delays[index] ||
26
- Object.keys(parameters).some(key => key !== "pulseIntervalMs" && parameters[key] !== record.parameters[key])) throw new TypeError("測定点とT2走査条件が一致しません。");
27
+ Object.keys(parameters).some(key => key !== "pulseIntervalMs" && parameters[key] !== record.parameters[key])) throw createError(TypeError, "SWEEP_RECORD_MISMATCH");
27
28
  return evaluateT2(record, analysis);
28
29
  });
29
30
  const referenceIndex = saved.result?.reference?.referenceIndex ?? null;
30
31
  const fromMs = saved.result?.fromMs ?? 2 * s.startMs, toMs = saved.result?.toMs ?? 2 * s.endMs;
31
- if (![fromMs, toMs].every(Number.isFinite) || fromMs >= toMs) throw new TypeError("近似範囲が不正です。");
32
- if (referenceIndex !== null && (!Number.isInteger(referenceIndex) || referenceIndex < 0 || referenceIndex >= points.length)) throw new TypeError("基準点が不正です。");
32
+ if (![fromMs, toMs].every(Number.isFinite) || fromMs >= toMs) throw createError(TypeError, "INVALID_FIT_RANGE");
33
+ if (referenceIndex !== null && (!Number.isInteger(referenceIndex) || referenceIndex < 0 || referenceIndex >= points.length)) throw createError(TypeError, "INVALID_REFERENCE_INDEX");
33
34
  let result = null;
34
35
  try { result = analyzeT2(points.map(point => point.record), { analysis, referenceIndex, fromMs, toMs }); }
35
36
  catch (error) {
36
37
  // A valid zero-signal scan is still useful for inspecting raw waveforms.
37
38
  if (error.code !== "NO_REFERENCE_SIGNAL") throw error;
38
39
  }
39
- if (typeof saved.acquiredAt !== "string" || !Number.isFinite(Date.parse(saved.acquiredAt))) throw new TypeError("走査日時が不正です。");
40
+ if (typeof saved.acquiredAt !== "string" || !Number.isFinite(Date.parse(saved.acquiredAt))) throw createError(TypeError, "INVALID_SWEEP_TIME");
40
41
  return { source: saved.source, acquiredAt: saved.acquiredAt, settings: { startMs: s.startMs, endMs: s.endMs, stepMs: s.stepMs, delays, parameters, analysis }, points, result, referenceIndex, fromMs, toMs };
41
42
  }
package/src/t2-sweep.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createError, createWarning, warningFromError } from "./errors.js";
1
2
  import { integerSteps, runSingleSweep } from "./sweep.js";
2
3
  import { evaluateFrequency } from "./frequency-sweep.js";
3
4
  import { analyzeMeasurement } from "./analysis.js";
@@ -11,14 +12,14 @@ export function t2Delays(startMs, endMs, stepMs) {
11
12
 
12
13
  /** Spin echo: 90°(0°), tau, 180°(90°). Acquisition starts after the second pulse. */
13
14
  export function t2Parameters({ frequencyHz, p90Cycles, p180Cycles, measurementIntervalMs, scans }, tauMs) {
14
- if (!Number.isInteger(p90Cycles) || !Number.isInteger(p180Cycles) || p90Cycles < 1 || p180Cycles <= p90Cycles) throw new RangeError("0 < 90°長 < 180°長の整数周期で指定してください。");
15
+ if (!Number.isInteger(p90Cycles) || !Number.isInteger(p180Cycles) || p90Cycles < 1 || p180Cycles <= p90Cycles) throw createError(RangeError, "INVALID_CALIBRATED_PULSES");
15
16
  const parameters = validateParameters({frequencyHz, pulse1Cycles:p90Cycles, phase1Degrees:0, pulse2Cycles:p180Cycles, phase2Degrees:90, pulseIntervalMs:tauMs, measurementIntervalMs, scans});
16
17
  validateT2Parameters(parameters);
17
18
  return parameters;
18
19
  }
19
20
  function validateT2Parameters(p) {
20
- if (p.pulseIntervalMs < 1 || p.phase1Degrees !== 0 || p.phase2Degrees !== 90 || p.pulse1Cycles < 1 || p.pulse2Cycles <= p.pulse1Cycles) throw new RangeError("T2は90°(0°) → τ → 180°(90°)で測定してください。");
21
- if (p.measurementIntervalMs <= p.pulseIntervalMs + SAMPLE_COUNT * SAMPLE_INTERVAL_MS) throw new RangeError("繰り返し間隔はτ+取得時間(40.96 ms)より長くしてください。");
21
+ if (p.pulseIntervalMs < 1 || p.phase1Degrees !== 0 || p.phase2Degrees !== 90 || p.pulse1Cycles < 1 || p.pulse2Cycles <= p.pulse1Cycles) throw createError(RangeError, "INVALID_T2_SEQUENCE");
22
+ if (p.measurementIntervalMs <= p.pulseIntervalMs + SAMPLE_COUNT * SAMPLE_INTERVAL_MS) throw createError(RangeError, "REPETITION_TOO_SHORT");
22
23
  }
23
24
 
24
25
  /** Input bounds are offsets from the echo center; output bounds follow tau. */
@@ -27,9 +28,9 @@ export function t2Window(tauMs, analysis = {}) {
27
28
  const startMs = tauMs + startOffset, endMs = tauMs + endOffset;
28
29
  if (![tauMs, startOffset, endOffset].every(Number.isFinite) || startOffset >= 0 || endOffset <= 0 ||
29
30
  startMs < 0 || endMs > SAMPLE_COUNT * SAMPLE_INTERVAL_MS + 1e-9 || endMs - startMs < 4 * SAMPLE_INTERVAL_MS - 1e-9) {
30
- throw new RangeError(`τ=${tauMs} msのエコー解析窓を取得範囲0〜40.96 ms内に収め、中心を含むように指定してください。`);
31
+ throw createError(RangeError, "INVALID_ECHO_WINDOW", { tauMs });
31
32
  }
32
- if ((analysis.minHz ?? -3000) < -25000 || (analysis.maxHz ?? 3000) > 25000) throw new RangeError("ピーク探索帯域は−25〜25 kHz内で指定してください。");
33
+ if ((analysis.minHz ?? -3000) < -25000 || (analysis.maxHz ?? 3000) > 25000) throw createError(RangeError, "SEARCH_BAND_OUT_OF_RANGE");
33
34
  return {...analysis, startMs, endMs};
34
35
  }
35
36
  export function evaluateT2(record, analysis = {}) {
@@ -47,20 +48,20 @@ export async function runT2Sweep(device, parameters, {startMs, endMs, stepMs, an
47
48
  return {...result,delays};
48
49
  }
49
50
  export function analyzeT2(records, {analysis = {}, referenceIndex = null, fromMs, toMs} = {}) {
50
- if (!Array.isArray(records) || !records.length) throw new Error("先にT2測定を行ってください。");
51
+ if (!Array.isArray(records) || !records.length) throw createError(Error, "NO_RECORDS");
51
52
  const first = records[0];
52
53
  const evaluated = records.map(record => {
53
54
  validateT2Parameters(validateParameters(record.parameters));
54
55
  if (record.mode !== "double" || record.source !== first.source || record.sampleIntervalMs !== first.sampleIntervalMs ||
55
- Object.keys(first.parameters).some(key => key !== "pulseIntervalMs" && first.parameters[key] !== record.parameters[key])) throw new Error("全点の周波数・パルス・積算条件を揃えてください。");
56
+ Object.keys(first.parameters).some(key => key !== "pulseIntervalMs" && first.parameters[key] !== record.parameters[key])) throw createError(Error, "INCONSISTENT_RECORDS");
56
57
  return evaluateT2(record,analysis);
57
58
  });
58
59
  let basis;
59
60
  if (referenceIndex !== null) {
60
- if (!Number.isInteger(referenceIndex) || !evaluated[referenceIndex]) throw new Error("基準点が不正です。");
61
+ if (!Number.isInteger(referenceIndex) || !evaluated[referenceIndex]) throw createError(Error, "INVALID_REFERENCE_INDEX");
61
62
  basis = evaluated[referenceIndex];
62
63
  } else basis = evaluated.reduce((best,point) => point.amplitude > best.amplitude ? point : best);
63
- if (basis.amplitude < 1e-9) throw Object.assign(new Error("共通周波数の基準に使えるエコーがありません。"), { code: "NO_REFERENCE_SIGNAL" });
64
+ if (basis.amplitude < 1e-9) throw createError(Error, "NO_REFERENCE_SIGNAL");
64
65
  const reference = {hz:basis.peakHz,referenceIndex};
65
66
  const points = evaluated.map(point => {
66
67
  const prepared = analyzeMeasurement(point.record,point.window);
@@ -70,11 +71,11 @@ export function analyzeT2(records, {analysis = {}, referenceIndex = null, fromMs
70
71
  });
71
72
  const range = {fromMs:fromMs ?? 2*Math.min(...points.map(p=>p.tau)),toMs:toMs ?? 2*Math.max(...points.map(p=>p.tau))};
72
73
  let fit = null;
73
- const warnings = [];
74
+ const warningDetails = [];
74
75
  try {
75
76
  fit = fitT2(points,range);
76
- if (fit.r2 < .95) warnings.push("指数関数との一致度が低いため、推定値は参考値です。");
77
- if ((fit.to-fit.from)/fit.T < .8) warnings.push("測定範囲が短いため、推定T2は範囲に敏感になる可能性があります。");
78
- } catch(error) { warnings.push(error.message); }
79
- return {points,reference,fit,warnings,...range};
77
+ if (fit.r2 < .95) warningDetails.push(createWarning("T2_FIT_LOW_AGREEMENT"));
78
+ if ((fit.to-fit.from)/fit.T < .8) warningDetails.push(createWarning("T2_SHORT_RANGE"));
79
+ } catch(error) { warningDetails.push(warningFromError(error)); }
80
+ return {points,reference,fit,warnings: warningDetails.map(warning => warning.message), warningDetails,...range};
80
81
  }
package/src/timing.js CHANGED
@@ -1,9 +1,10 @@
1
+ import { createError } from "./errors.js";
1
2
  import { validateParameters, SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
2
3
 
3
4
  /** PoC runtime estimate. Serial transfer and command overhead are not included. */
4
5
  export function measurementDurationMs(parameters, { mode = "single" } = {}) {
5
6
  const p = validateParameters(parameters);
6
- if (!["single", "double"].includes(mode)) throw new TypeError("測定モードが正しくありません。");
7
+ if (!["single", "double"].includes(mode)) throw createError(TypeError, "INVALID_MODE");
7
8
  return Math.ceil(p.scans * (p.measurementIntervalMs + SAMPLE_COUNT * SAMPLE_INTERVAL_MS +
8
9
  (mode === "double" ? p.pulseIntervalMs : 0)));
9
10
  }
@@ -1,3 +1,4 @@
1
+ import { createError, normalizeError } from "./errors.js";
1
2
  import { LineDecoder } from "./line-decoder.js";
2
3
  import { SERIAL_OPTIONS } from "./protocol.js";
3
4
 
@@ -19,9 +20,9 @@ export class WebSerialTransport {
19
20
  /** Call directly from a user gesture so the browser can display its chooser. */
20
21
  async connect() {
21
22
  if (this.state !== "disconnected" || this.closeTask) {
22
- throw new Error("Serial connection is already active or changing.");
23
+ throw createError(Error, "SERIAL_ACTIVE");
23
24
  }
24
- if (!this.serial) throw new Error("Web Serial is unavailable. Use a supported browser and HTTPS or localhost.");
25
+ if (!this.serial) throw createError(Error, "WEB_SERIAL_UNAVAILABLE");
25
26
  this.state = "connecting";
26
27
  this.lines = [];
27
28
  this.error = null;
@@ -35,11 +36,11 @@ export class WebSerialTransport {
35
36
  await this.port.setSignals({ dataTerminalReady: true, requestToSend: true });
36
37
  await new Promise(resolve => setTimeout(resolve, 1000));
37
38
  if (this.error) throw this.error;
38
- if (this.state !== "connecting") throw new Error("Connection was interrupted.");
39
+ if (this.state !== "connecting") throw createError(Error, "SERIAL_CONNECTION_INTERRUPTED");
39
40
  this.state = "connected";
40
41
  } catch (error) {
41
42
  await this.disconnect();
42
- throw error;
43
+ throw normalizeError(error, "SERIAL_CONNECTION_FAILED");
43
44
  }
44
45
  }
45
46
 
@@ -49,7 +50,7 @@ export class WebSerialTransport {
49
50
  const { value, done } = await this.reader.read();
50
51
  if (done) {
51
52
  this.decoder.finish();
52
- throw new Error("Serial input ended. Reconnect the device.");
53
+ throw createError(Error, "SERIAL_INPUT_ENDED");
53
54
  }
54
55
  for (const line of this.decoder.push(value)) {
55
56
  if (this.waiter) {
@@ -59,7 +60,7 @@ export class WebSerialTransport {
59
60
  waiter.resolve(line);
60
61
  } else {
61
62
  this.lines.push(line);
62
- if (this.lines.length > 4096) throw new Error("Serial response buffer overflow.");
63
+ if (this.lines.length > 4096) throw createError(Error, "SERIAL_BUFFER_OVERFLOW");
63
64
  }
64
65
  }
65
66
  }
@@ -75,7 +76,7 @@ export class WebSerialTransport {
75
76
  }
76
77
 
77
78
  fail(error) {
78
- this.error ??= error;
79
+ this.error ??= normalizeError(error, "SERIAL_READ_FAILED");
79
80
  if (this.waiter) {
80
81
  clearTimeout(this.waiter.timer);
81
82
  this.waiter.reject(this.error);
@@ -84,20 +85,21 @@ export class WebSerialTransport {
84
85
  }
85
86
 
86
87
  async write(bytes) {
87
- if (this.state !== "connected" || this.error) throw this.error ?? new Error("Device is not connected.");
88
- await this.writer.write(bytes);
88
+ if (this.state !== "connected" || this.error) throw this.error ?? createError(Error, "DEVICE_NOT_CONNECTED");
89
+ try { await this.writer.write(bytes); }
90
+ catch (error) { throw normalizeError(error, "SERIAL_WRITE_FAILED"); }
89
91
  }
90
92
 
91
93
  readLine(timeoutMs) {
92
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.reject(new RangeError("Invalid response timeout."));
94
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.reject(createError(RangeError, "INVALID_RESPONSE_TIMEOUT"));
93
95
  if (this.error) return Promise.reject(this.error);
94
- if (this.state !== "connected") return Promise.reject(new Error("Device is not connected."));
95
- if (this.waiter) return Promise.reject(new Error("Only one response reader is allowed."));
96
+ if (this.state !== "connected") return Promise.reject(createError(Error, "DEVICE_NOT_CONNECTED"));
97
+ if (this.waiter) return Promise.reject(createError(Error, "SERIAL_READER_BUSY"));
96
98
  if (this.lines.length) return Promise.resolve(this.lines.shift());
97
99
  return new Promise((resolve, reject) => {
98
100
  const timer = setTimeout(() => {
99
101
  this.waiter = null;
100
- const error = new Error("Controller response timed out. Reconnect the device.");
102
+ const error = createError(Error, "RESPONSE_TIMEOUT");
101
103
  this.fail(error);
102
104
  reject(error);
103
105
  }, timeoutMs);
@@ -107,7 +109,7 @@ export class WebSerialTransport {
107
109
 
108
110
  /** Discard buffered input only before a new command sequence. */
109
111
  clearInput() {
110
- if (this.waiter) throw new Error("Cannot clear input while awaiting a response.");
112
+ if (this.waiter) throw createError(Error, "SERIAL_CLEAR_WHILE_READING");
111
113
  if (this.error) throw this.error;
112
114
  this.lines = [];
113
115
  this.decoder.reset();
@@ -117,8 +119,8 @@ export class WebSerialTransport {
117
119
  if (this.closeTask) return this.closeTask;
118
120
  if (this.state === "disconnected") return Promise.resolve();
119
121
  this.state = "disconnecting";
120
- this.fail(new Error("Serial connection closed."));
121
- this.closeTask = this.close().finally(() => { this.closeTask = null; });
122
+ this.fail(createError(Error, "SERIAL_CLOSED"));
123
+ this.closeTask = this.close().catch(error => { throw normalizeError(error, "SERIAL_DISCONNECT_FAILED"); }).finally(() => { this.closeTask = null; });
122
124
  return this.closeTask;
123
125
  }
124
126
 
@@ -139,6 +141,6 @@ export class WebSerialTransport {
139
141
  this.lines = [];
140
142
  this.state = "disconnected";
141
143
  }
142
- if (errors.length) throw new AggregateError(errors, "Serial cleanup failed.");
144
+ if (errors.length) throw createError(AggregateError, "SERIAL_CLEANUP_FAILED", {}, { errors: errors });
143
145
  }
144
146
  }