nmrlink 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,80 @@
1
+ import { integerSteps, runSingleSweep } from "./sweep.js";
2
+ import { evaluateFrequency } from "./frequency-sweep.js";
3
+ import { analyzeMeasurement } from "./analysis.js";
4
+ import { complexAt } from "./signed-signal.js";
5
+ import { validateParameters, SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
6
+ import { fitT2 } from "./relaxation-fit.js";
7
+
8
+ export function t2Delays(startMs, endMs, stepMs) {
9
+ return integerSteps(startMs, endMs, stepMs, 32767);
10
+ }
11
+
12
+ /** Spin echo: 90°(0°), tau, 180°(90°). Acquisition starts after the second pulse. */
13
+ 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
+ const parameters = validateParameters({frequencyHz, pulse1Cycles:p90Cycles, phase1Degrees:0, pulse2Cycles:p180Cycles, phase2Degrees:90, pulseIntervalMs:tauMs, measurementIntervalMs, scans});
16
+ validateT2Parameters(parameters);
17
+ return parameters;
18
+ }
19
+ 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)より長くしてください。");
22
+ }
23
+
24
+ /** Input bounds are offsets from the echo center; output bounds follow tau. */
25
+ export function t2Window(tauMs, analysis = {}) {
26
+ const startOffset = analysis.startMs ?? -4, endOffset = analysis.endMs ?? 4;
27
+ const startMs = tauMs + startOffset, endMs = tauMs + endOffset;
28
+ if (![tauMs, startOffset, endOffset].every(Number.isFinite) || startOffset >= 0 || endOffset <= 0 ||
29
+ 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
+ }
32
+ if ((analysis.minHz ?? -3000) < -25000 || (analysis.maxHz ?? 3000) > 25000) throw new RangeError("ピーク探索帯域は−25〜25 kHz内で指定してください。");
33
+ return {...analysis, startMs, endMs};
34
+ }
35
+ export function evaluateT2(record, analysis = {}) {
36
+ const tau = record.parameters.pulseIntervalMs;
37
+ const window = t2Window(tau, analysis);
38
+ const point = evaluateFrequency(record, window);
39
+ return {tau, amplitude:point.amplitude, peakHz:point.peakHz, window, record};
40
+ }
41
+ export async function runT2Sweep(device, parameters, {startMs, endMs, stepMs, analysis = {}, signal, onPoint} = {}) {
42
+ const delays = t2Delays(startMs, endMs, stepMs);
43
+ // Validate every moving window before the first hardware command.
44
+ const raw = Array.from({length:SAMPLE_COUNT}, () => [0,0]);
45
+ for (const tau of delays) evaluateT2({parameters:{...parameters,pulseIntervalMs:tau},sampleIntervalMs:SAMPLE_INTERVAL_MS,raw},analysis);
46
+ const result = await runSingleSweep(device,parameters,{field:"pulseIntervalMs",values:delays,mode:"double",validateMeasurement:validateT2Parameters,analysis,evaluate:evaluateT2,signal,onPoint});
47
+ return {...result,delays};
48
+ }
49
+ export function analyzeT2(records, {analysis = {}, referenceIndex = null, fromMs, toMs} = {}) {
50
+ if (!Array.isArray(records) || !records.length) throw new Error("先にT2測定を行ってください。");
51
+ const first = records[0];
52
+ const evaluated = records.map(record => {
53
+ validateT2Parameters(validateParameters(record.parameters));
54
+ 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
+ return evaluateT2(record,analysis);
57
+ });
58
+ let basis;
59
+ if (referenceIndex !== null) {
60
+ if (!Number.isInteger(referenceIndex) || !evaluated[referenceIndex]) throw new Error("基準点が不正です。");
61
+ basis = evaluated[referenceIndex];
62
+ } 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
+ const reference = {hz:basis.peakHz,referenceIndex};
65
+ const points = evaluated.map(point => {
66
+ const prepared = analyzeMeasurement(point.record,point.window);
67
+ const z = complexAt(prepared.data,prepared.spectrum,point.record.sampleIntervalMs,reference.hz);
68
+ const magnitude = Math.hypot(z.real,z.imaginary);
69
+ return {...point,signal:magnitude,magnitude};
70
+ });
71
+ const range = {fromMs:fromMs ?? 2*Math.min(...points.map(p=>p.tau)),toMs:toMs ?? 2*Math.max(...points.map(p=>p.tau))};
72
+ let fit = null;
73
+ const warnings = [];
74
+ try {
75
+ 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};
80
+ }
package/src/timing.js ADDED
@@ -0,0 +1,9 @@
1
+ import { validateParameters, SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
2
+
3
+ /** PoC runtime estimate. Serial transfer and command overhead are not included. */
4
+ export function measurementDurationMs(parameters, { mode = "single" } = {}) {
5
+ const p = validateParameters(parameters);
6
+ if (!["single", "double"].includes(mode)) throw new TypeError("測定モードが正しくありません。");
7
+ return Math.ceil(p.scans * (p.measurementIntervalMs + SAMPLE_COUNT * SAMPLE_INTERVAL_MS +
8
+ (mode === "double" ? p.pulseIntervalMs : 0)));
9
+ }
@@ -0,0 +1,144 @@
1
+ import { LineDecoder } from "./line-decoder.js";
2
+ import { SERIAL_OPTIONS } from "./protocol.js";
3
+
4
+ /** Browser-only byte transport. No device commands or UI dependencies. */
5
+ export class WebSerialTransport {
6
+ constructor({ serial = globalThis.navigator?.serial } = {}) {
7
+ this.serial = serial;
8
+ this.state = "disconnected";
9
+ this.port = null;
10
+ this.reader = null;
11
+ this.writer = null;
12
+ this.lines = [];
13
+ this.waiter = null;
14
+ this.error = null;
15
+ this.readTask = null;
16
+ this.closeTask = null;
17
+ }
18
+
19
+ /** Call directly from a user gesture so the browser can display its chooser. */
20
+ async connect() {
21
+ if (this.state !== "disconnected" || this.closeTask) {
22
+ throw new Error("Serial connection is already active or changing.");
23
+ }
24
+ if (!this.serial) throw new Error("Web Serial is unavailable. Use a supported browser and HTTPS or localhost.");
25
+ this.state = "connecting";
26
+ this.lines = [];
27
+ this.error = null;
28
+ this.decoder = new LineDecoder();
29
+ try {
30
+ this.port = await this.serial.requestPort();
31
+ await this.port.open({ ...SERIAL_OPTIONS });
32
+ this.reader = this.port.readable.getReader();
33
+ this.writer = this.port.writable.getWriter();
34
+ this.readTask = this.readLoop();
35
+ await this.port.setSignals({ dataTerminalReady: true, requestToSend: true });
36
+ await new Promise(resolve => setTimeout(resolve, 1000));
37
+ if (this.error) throw this.error;
38
+ if (this.state !== "connecting") throw new Error("Connection was interrupted.");
39
+ this.state = "connected";
40
+ } catch (error) {
41
+ await this.disconnect();
42
+ throw error;
43
+ }
44
+ }
45
+
46
+ async readLoop() {
47
+ try {
48
+ while (true) {
49
+ const { value, done } = await this.reader.read();
50
+ if (done) {
51
+ this.decoder.finish();
52
+ throw new Error("Serial input ended. Reconnect the device.");
53
+ }
54
+ for (const line of this.decoder.push(value)) {
55
+ if (this.waiter) {
56
+ const waiter = this.waiter;
57
+ this.waiter = null;
58
+ clearTimeout(waiter.timer);
59
+ waiter.resolve(line);
60
+ } else {
61
+ this.lines.push(line);
62
+ if (this.lines.length > 4096) throw new Error("Serial response buffer overflow.");
63
+ }
64
+ }
65
+ }
66
+ } catch (error) {
67
+ this.fail(error);
68
+ } finally {
69
+ this.reader.releaseLock();
70
+ // Avoid awaiting disconnect here: it waits for this read loop to finish.
71
+ if (this.state !== "disconnecting") {
72
+ this.disconnect().catch(error => { this.error = error; });
73
+ }
74
+ }
75
+ }
76
+
77
+ fail(error) {
78
+ this.error ??= error;
79
+ if (this.waiter) {
80
+ clearTimeout(this.waiter.timer);
81
+ this.waiter.reject(this.error);
82
+ this.waiter = null;
83
+ }
84
+ }
85
+
86
+ 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);
89
+ }
90
+
91
+ readLine(timeoutMs) {
92
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.reject(new RangeError("Invalid response timeout."));
93
+ 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.lines.length) return Promise.resolve(this.lines.shift());
97
+ return new Promise((resolve, reject) => {
98
+ const timer = setTimeout(() => {
99
+ this.waiter = null;
100
+ const error = new Error("Controller response timed out. Reconnect the device.");
101
+ this.fail(error);
102
+ reject(error);
103
+ }, timeoutMs);
104
+ this.waiter = { resolve, reject, timer };
105
+ });
106
+ }
107
+
108
+ /** Discard buffered input only before a new command sequence. */
109
+ clearInput() {
110
+ if (this.waiter) throw new Error("Cannot clear input while awaiting a response.");
111
+ if (this.error) throw this.error;
112
+ this.lines = [];
113
+ this.decoder.reset();
114
+ }
115
+
116
+ disconnect() {
117
+ if (this.closeTask) return this.closeTask;
118
+ if (this.state === "disconnected") return Promise.resolve();
119
+ this.state = "disconnecting";
120
+ this.fail(new Error("Serial connection closed."));
121
+ this.closeTask = this.close().finally(() => { this.closeTask = null; });
122
+ return this.closeTask;
123
+ }
124
+
125
+ async close() {
126
+ const errors = [];
127
+ try {
128
+ try {
129
+ if (this.port?.readable?.locked) await this.reader?.cancel();
130
+ } catch (error) { errors.push(error); }
131
+ await this.readTask;
132
+ try { this.writer?.releaseLock(); } catch (error) { errors.push(error); }
133
+ try { await this.port?.close(); } catch (error) { errors.push(error); }
134
+ } finally {
135
+ this.port = null;
136
+ this.reader = null;
137
+ this.writer = null;
138
+ this.readTask = null;
139
+ this.lines = [];
140
+ this.state = "disconnected";
141
+ }
142
+ if (errors.length) throw new AggregateError(errors, "Serial cleanup failed.");
143
+ }
144
+ }