nmrlink 0.0.0-stage → 0.1.1

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,86 @@
1
+ // The original PoC fit is retained as the first choice for well-resolved signed data.
2
+ function signedPulseCandidates(points) {
3
+ 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
+ const scale = Math.max(...p.map((q) => Math.abs(q.amplitude)));
6
+ if (scale < 1e-9) throw new Error("信号がゼロです。");
7
+ 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("短いパルスの点が不足しています。");
10
+ let crossing = -1;
11
+ for (let i = peak; i < p.length - 1; i++) if (p[i].amplitude >= 0 && p[i + 1].amplitude < 0) {
12
+ crossing = i;
13
+ break;
14
+ }
15
+ if (crossing < 0) throw new Error("正から負へのゼロ交差が未測定です。180\xB0の先まで測定してください。");
16
+ const a = p[crossing], b = p[crossing + 1], p180 = a.length + (b.length - a.length) * a.amplitude / (a.amplitude - b.amplitude);
17
+ return { p90: p[peak].length, p180, peakIndex: peak, crossingIndex: crossing, points: p, zeroBracket: [a.length, b.length] };
18
+ }
19
+ function strictPulseFit(points) {
20
+ const measured = signedPulseCandidates(points), p = measured.points, k = measured.peakIndex, lower = p[k - 1].length, upper = p[k + 1].length;
21
+ function evaluate(p90) {
22
+ const g = p.map((q) => Math.sin(Math.PI * q.length / (2 * p90))), n = p.length, sg = g.reduce((a2, b2) => a2 + b2, 0), sg2 = g.reduce((a2, b2) => a2 + b2 * b2, 0), sy = p.reduce((a2, b2) => a2 + b2.amplitude, 0), sgy = p.reduce((a2, q, i) => a2 + g[i] * q.amplitude, 0), den = n * sg2 - sg * sg;
23
+ if (den < 1e-12) return { sse: Infinity };
24
+ const A = (n * sgy - sg * sy) / den, B = (sy - A * sg) / n;
25
+ if (A <= 0) return { sse: Infinity };
26
+ return { p90, A, B, sse: p.reduce((s, q, i) => s + (q.amplitude - A * g[i] - B) ** 2, 0) };
27
+ }
28
+ let best = { sse: Infinity }, index = 0;
29
+ const steps = 800;
30
+ for (let i = 0; i <= steps; i++) {
31
+ const f = evaluate(lower + (upper - lower) * i / steps);
32
+ if (f.sse < best.sse) {
33
+ best = f;
34
+ index = i;
35
+ }
36
+ }
37
+ if (index === 0 || index === steps) throw new Error("近似の最適点が探索範囲の端です。");
38
+ let l = lower + (upper - lower) * (index - 1) / steps, h = lower + (upper - lower) * (index + 1) / steps;
39
+ for (let i = 0; i < 45; i++) {
40
+ const a2 = l + (h - l) / 3, b2 = h - (h - l) / 3;
41
+ if (evaluate(a2).sse < evaluate(b2).sse) h = b2;
42
+ else l = a2;
43
+ }
44
+ best = evaluate((l + h) / 2);
45
+ 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("背景成分が大きすぎます。基準位相や解析範囲を確認してください。");
48
+ 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
+ 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
+ /** Least-squares sine estimate even when a peak or zero crossing was not measured. */
53
+ function fitPulseCalibration(points, { magnitude = false } = {}) {
54
+ if (!magnitude) {
55
+ try { return strictPulseFit(points); } catch { /* Continue with a wider search. */ }
56
+ }
57
+ const p = [...points].sort((a, b) => a.length - b.length);
58
+ 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
+ }
61
+ const scale = Math.max(...p.map(q => Math.abs(q.amplitude)));
62
+ if (scale < 1e-9) throw new Error("信号がゼロのためサイン近似を求められません。");
63
+ const y = p.map(q => q.amplitude / scale), n = p.length, sy = y.reduce((s,v) => s+v,0);
64
+ const mean = sy / n, sst = y.reduce((s,v) => s+(v-mean)**2,0);
65
+ function solve(logLength) {
66
+ const p90 = Math.exp(logLength);
67
+ const g = p.map(q => { const v = Math.sin(Math.PI*q.length/(2*p90)); return magnitude ? Math.abs(v) : v; });
68
+ const sg = g.reduce((s,v)=>s+v,0), sg2 = g.reduce((s,v)=>s+v*v,0), sgy = g.reduce((s,v,i)=>s+v*y[i],0);
69
+ const den = n*sg2-sg*sg;
70
+ if (den < 1e-12) return {sse:Infinity};
71
+ const A = (n*sgy-sg*sy)/den, B = (sy-A*sg)/n;
72
+ if (A <= 0) return {sse:Infinity};
73
+ return {p90,A:A*scale,B:B*scale,sse:y.reduce((s,v,i)=>s+(v-A*g[i]-B)**2,0)};
74
+ }
75
+ const step = Math.min(...p.slice(1).map((q,i)=>q.length-p[i].length));
76
+ const lo = Math.log(step/2), hi = Math.log(p.at(-1).length*10), steps = 4000;
77
+ let best = {sse:Infinity}, index = 0;
78
+ 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
+ let l=lo+(hi-lo)*Math.max(0,index-1)/steps, h=lo+(hi-lo)*Math.min(steps,index+1)/steps;
81
+ 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
+ best=solve((l+h)/2);
83
+ return {p90:best.p90,p180:2*best.p90,A:best.A,B:best.B,r2:sst>1e-20?1-best.sse/sst:0,rmse:Math.sqrt(best.sse/n)*scale,
84
+ from:p[0].length,to:p.at(-1).length,n,magnitude,model:magnitude?"A*abs(sin(pi*length/(2*p90)))+B":"A*sin(pi*length/(2*p90))+B"};
85
+ }
86
+ export { fitPulseCalibration, signedPulseCandidates };
@@ -0,0 +1,50 @@
1
+ import { parseMeasurement } from "./record.js";
2
+ import { pulseSteps, evaluatePulse, analyzePulseCalibration } from "./pulse-sweep.js";
3
+ import { validateParameters } from "./protocol.js";
4
+
5
+ export const MAX_PULSE_JSON_BYTES = 32 * 1024 * 1024;
6
+
7
+ /** Restore raw records and recompute all derived values before replacing a UI's results. */
8
+ export function parsePulseCalibration(text) {
9
+ if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_PULSE_JSON_BYTES) {
10
+ throw new TypeError("パルス走査JSONは32 MiB以下の文字列を指定してください。");
11
+ }
12
+ let value;
13
+ try { value = JSON.parse(text.replace(/^\uFEFF/, "")); }
14
+ catch { throw new TypeError("JSONの形式が正しくありません。"); }
15
+ if (value?.kind !== "pulse-calibration" || !Array.isArray(value.points) || !value.points.length || value.points.length > 201) {
16
+ throw new TypeError("パルス校正の全データJSONを指定してください(1〜201点)。");
17
+ }
18
+ const saved = value.settings;
19
+ if (!saved) throw new TypeError("走査条件がありません。");
20
+ const lengths = pulseSteps(saved.startCycles, saved.endCycles, saved.stepCycles);
21
+ const parameters = validateParameters(saved.parameters);
22
+ const a = saved.analysis;
23
+ 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
+ }
26
+ const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, window: a.window, minHz: a.minHz, maxHz: a.maxHz };
27
+ const points = value.points.map((point, index) => {
28
+ const record = parseMeasurement(JSON.stringify(point?.record));
29
+ if (!record.parameters || record.source !== value.source || record.mode !== "single" ||
30
+ point.length !== lengths[index] || record.parameters.pulse1Cycles !== lengths[index] ||
31
+ Object.keys(parameters).some(key => key !== "pulse1Cycles" && parameters[key] !== record.parameters[key])) {
32
+ throw new TypeError("測定点と走査条件が一致しません。");
33
+ }
34
+ return evaluatePulse(record, analysis);
35
+ });
36
+ const referenceIndex = value.calibration?.reference?.referenceIndex ?? null;
37
+ 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("位相補正が不正です。");
40
+ let calibration = null;
41
+ try { calibration = analyzePulseCalibration(points.map(point => point.record), { analysis, referenceIndex, phaseDegrees }); }
42
+ catch (error) {
43
+ // A valid zero-signal scan is still useful for inspecting raw waveforms.
44
+ if (error.code !== "NO_REFERENCE_SIGNAL") throw error;
45
+ }
46
+ if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw new TypeError("走査日時が正しくありません。");
47
+ return { source: value.source, acquiredAt: value.acquiredAt,
48
+ settings: { startCycles: saved.startCycles, endCycles: saved.endCycles, stepCycles: saved.stepCycles, lengths, parameters, analysis },
49
+ points, calibration, referenceIndex, phaseDegrees };
50
+ }
@@ -0,0 +1,40 @@
1
+ import { integerSteps, runSingleSweep } from "./sweep.js";
2
+ import { evaluateFrequency } from "./frequency-sweep.js";
3
+ import { analyzeSignedRecords } from "./signed-signal.js";
4
+ import { signedPulseCandidates, fitPulseCalibration } from "./pulse-fit.js";
5
+
6
+ export function pulseSteps(startCycles, endCycles, stepCycles) {
7
+ return integerSteps(startCycles, endCycles, stepCycles, 32767);
8
+ }
9
+ export function evaluatePulse(record, analysis = {}) {
10
+ const point = evaluateFrequency(record, analysis);
11
+ return { length: record.parameters.pulse1Cycles, amplitude: point.amplitude, peakHz: point.peakHz, record };
12
+ }
13
+ export async function runPulseSweep(device, parameters, {
14
+ startCycles, endCycles, stepCycles, analysis = {}, signal, onPoint,
15
+ } = {}) {
16
+ const lengths = pulseSteps(startCycles, endCycles, stepCycles);
17
+ const result = await runSingleSweep(device, parameters, {
18
+ field: "pulse1Cycles", values: lengths, analysis, evaluate: evaluatePulse, signal, onPoint,
19
+ });
20
+ return { ...result, lengths };
21
+ }
22
+
23
+ /** Keep signs with one phase reference for all points; never phase-align each point. */
24
+ export function analyzePulseCalibration(records, options = {}) {
25
+ const result = analyzeSignedRecords(records, { ...options, field: "pulse1Cycles", mode: "single" });
26
+ const { points, reference } = result;
27
+ const coherence = reference.coherence;
28
+ 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); }
33
+ let magnitudeFit = null;
34
+ 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 };
40
+ }
package/src/record.js ADDED
@@ -0,0 +1,40 @@
1
+ import { SAMPLE_COUNT, SAMPLE_INTERVAL_MS, validateParameters } from "./protocol.js";
2
+ import { validateSamples } from "./sample-validation.js";
3
+
4
+ export const MAX_MEASUREMENT_JSON_BYTES = 2 * 1024 * 1024;
5
+
6
+ /** Parse a saved NMRLink record; discard derived fields and never coerce sample values. */
7
+ export function parseMeasurement(text) {
8
+ if (typeof text !== "string") throw new TypeError("測定JSONは文字列で指定してください。");
9
+ if (new TextEncoder().encode(text).length > MAX_MEASUREMENT_JSON_BYTES) {
10
+ throw new RangeError("測定JSONは2 MiB以下のファイルを指定してください。");
11
+ }
12
+ let value;
13
+ try { value = JSON.parse(text.replace(/^\uFEFF/, "")); }
14
+ catch { throw new TypeError("JSONの形式が正しくありません。"); }
15
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
16
+ throw new TypeError("NMRLinkの測定結果JSONを指定してください。");
17
+ }
18
+ if (!["instrument", "demo"].includes(value.source) || !["single", "double"].includes(value.mode)) {
19
+ throw new TypeError("測定データのsourceまたはmodeが正しくありません。");
20
+ }
21
+ const validTime = typeof value.acquiredAt === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value.acquiredAt) && Number.isFinite(Date.parse(value.acquiredAt));
22
+ // Date.parse normalizes dates such as February 30; reject that normalization.
23
+ if (!validTime || new Date(value.acquiredAt.slice(0, 10) + "T00:00:00Z").toISOString().slice(0, 10) !== value.acquiredAt.slice(0, 10)) {
24
+ throw new TypeError("測定データの取得日時が正しくありません。");
25
+ }
26
+ if (value.points !== SAMPLE_COUNT || value.raw?.length !== SAMPLE_COUNT || value.sampleIntervalMs !== SAMPLE_INTERVAL_MS) {
27
+ throw new RangeError("2048点・0.02 ms間隔のNMRLink測定データを指定してください。");
28
+ }
29
+ try { validateSamples(value.raw); }
30
+ catch { throw new TypeError("生データには各点2チャンネルの有限数値が必要です。"); }
31
+ let parameters = null;
32
+ if (value.source !== "demo" || value.parameters !== null) {
33
+ try { parameters = validateParameters(value.parameters); }
34
+ catch { throw new TypeError("保存された測定条件が正しくありません。"); }
35
+ }
36
+ return {
37
+ source: value.source, acquiredAt: value.acquiredAt, mode: value.mode, parameters,
38
+ sampleIntervalMs: value.sampleIntervalMs, points: value.points, raw: value.raw,
39
+ };
40
+ }
@@ -0,0 +1,69 @@
1
+ function meanRelaxationPoints(points) {
2
+ const groups = /* @__PURE__ */ new Map();
3
+ for (const p of points) {
4
+ if (!Number.isFinite(p.tau) || !Number.isFinite(p.signal)) throw new Error("有効な信号がありません。");
5
+ const g = groups.get(p.tau) || { tau: p.tau, signal: 0, count: 0 };
6
+ g.signal += p.signal;
7
+ g.count++;
8
+ groups.set(p.tau, g);
9
+ }
10
+ return [...groups.values()].map((p) => ({ ...p, signal: p.signal / p.count })).sort((a, b) => a.tau - b.tau);
11
+ }
12
+ function relaxationValue(kind, fit, x) {
13
+ return kind === "t1" ? fit.A - fit.B * Math.exp(-x / fit.T) : fit.A * Math.exp(-x / fit.T);
14
+ }
15
+ function fitRelaxation(kind, points, from, to, { relaxed = false } = {}) {
16
+ if (!["t1", "t2"].includes(kind) || ![from, to].every(Number.isFinite) || from >= to) throw new Error("近似範囲は開始 < 終了にしてください。");
17
+ const p = meanRelaxationPoints(points).map((q) => ({ ...q, x: kind === "t1" ? q.tau : 2 * q.tau })).filter((q) => q.x >= from && q.x <= to);
18
+ if (p.length < (relaxed ? 3 : 5)) throw new Error("近似範囲に異なるτの有効な点(T1は5点、T2は3点以上)が必要です。");
19
+ const scale = Math.max(...p.map((q) => Math.abs(q.signal))), low = Math.min(...p.map((q) => q.signal)), high = Math.max(...p.map((q) => q.signal));
20
+ if (scale < 1e-9 || high - low < scale * 1e-4) throw new Error("信号がゼロまたは平坦です。");
21
+ if (kind === "t1" && !(low < 0 && high > 0)) throw new Error("T1には負と正の信号が必要です。τの範囲や位相基準を確認してください。");
22
+ if (kind === "t2" && low < 0) throw new Error("エコー振幅は非負です。");
23
+ const n = p.length, sy = p.reduce((s, q) => s + q.signal / scale, 0);
24
+ function solve(logT) {
25
+ const T = Math.exp(logT), g = p.map((q) => Math.exp(-q.x / T)), sg = g.reduce((s, q) => s + q, 0), sgg = g.reduce((s, q) => s + q * q, 0), sgy = g.reduce((s, q, i) => s + q * p[i].signal / scale, 0), den = n * sgg - sg * sg;
26
+ if (kind === "t2") {
27
+ if (sgg < 1e-30) return { sse: Infinity };
28
+ const A = sgy / sgg;
29
+ if (A <= 0) return { sse: Infinity };
30
+ return { T, A: A * scale, B: null, C: 0, sse: p.reduce((s, q, i) => s + (q.signal / scale - A * g[i]) ** 2, 0) };
31
+ }
32
+ if (den < 1e-14) return { sse: Infinity };
33
+ const slope = (n * sgy - sg * sy) / den, offset = (sy - slope * sg) / n;
34
+ if (kind === "t1" ? offset <= 0 || slope >= 0 : slope <= 0) return { sse: Infinity };
35
+ return { T, A: (kind === "t1" ? offset : slope) * scale, B: kind === "t1" ? -slope * scale : null, C: kind === "t2" ? offset * scale : null, sse: p.reduce((s, q, i) => s + (q.signal / scale - offset - slope * g[i]) ** 2, 0) };
36
+ }
37
+ const span = p.at(-1).x - p[0].x, minStep = Math.min(...p.slice(1).map((q, i) => q.x - p[i].x)), lo = Math.log(minStep * 0.02), hi = Math.log(Math.max(p.at(-1).x, span) * 100), steps = 700;
38
+ let best = { sse: Infinity }, index = -1;
39
+ for (let i = 0; i <= steps; i++) {
40
+ const f = solve(lo + (hi - lo) * i / steps);
41
+ if (f.sse < best.sse) {
42
+ best = f;
43
+ index = i;
44
+ }
45
+ }
46
+ if (index <= 0 || index >= steps) throw new Error("緩和時間の最適値が探索範囲外です。");
47
+ let l = lo + (hi - lo) * (index - 1) / steps, h = lo + (hi - lo) * (index + 1) / steps;
48
+ for (let i = 0; i < 40; i++) {
49
+ const a = l + (h - l) / 3, b = h - (h - l) / 3;
50
+ if (solve(a).sse < solve(b).sse) h = b;
51
+ else l = a;
52
+ }
53
+ best = solve((l + h) / 2);
54
+ const mean = sy / n, sst = p.reduce((s, q) => s + (q.signal / scale - mean) ** 2, 0), r2 = 1 - best.sse / sst;
55
+ if (!Number.isFinite(r2) || (!relaxed && r2 < 0.95)) throw new Error("指数関数との一致が不十分です(R\xB2 < 0.95)。");
56
+ if (!relaxed && span / best.T < 0.8) throw new Error("緩和を観測する時間範囲が不足しています。");
57
+ return { ...best, sse: best.sse * scale * scale, r2, rmse: Math.sqrt(best.sse / n) * scale, n, from: p[0].x, to: p.at(-1).x, model: kind === "t1" ? "A-B*exp(-tau/T1)" : "A*exp(-2*tau/T2)" };
58
+ }
59
+ function fitT1(points, { fromMs, toMs }) {
60
+ return fitRelaxation("t1", points, fromMs, toMs);
61
+ }
62
+ export {
63
+ fitRelaxation,
64
+ fitT1,
65
+ meanRelaxationPoints,
66
+ relaxationValue
67
+ };
68
+
69
+ export function fitT2(points, {fromMs, toMs}) { return fitRelaxation("t2", points, fromMs, toMs, {relaxed:true}); }
@@ -0,0 +1,13 @@
1
+ /** Validate plain two-channel sample arrays without coercing corrupt values. */
2
+ export function validateSamples(samples) {
3
+ if (!Array.isArray(samples) || samples.length === 0) {
4
+ throw new TypeError("Samples must be a non-empty array of channel pairs.");
5
+ }
6
+ for (let index = 0; index < samples.length; index++) {
7
+ const pair = samples[index];
8
+ if (!Array.isArray(pair) || pair.length !== 2 ||
9
+ !Number.isFinite(pair[0]) || !Number.isFinite(pair[1])) {
10
+ throw new TypeError(`Sample ${index} must contain exactly two finite numbers.`);
11
+ }
12
+ }
13
+ }
@@ -0,0 +1,83 @@
1
+ import { analyzeMeasurement } from "./analysis.js";
2
+
3
+ /** Complex projection at one common frequency, with the selected window's time origin. */
4
+ export function complexAt(data, spectrum, intervalMs, hz) {
5
+ let real = 0, imaginary = 0, weight = 0;
6
+ for (let index = spectrum.first; index < spectrum.last; index++) {
7
+ const j = index - spectrum.first;
8
+ const w = spectrum.window === "hann" ? 0.5 * (1 - Math.cos(2 * Math.PI * j / (spectrum.count - 1))) : 1;
9
+ const angle = -2 * Math.PI * hz * j * intervalMs / 1000;
10
+ const c = Math.cos(angle), s = Math.sin(angle);
11
+ real += w * (data[index][0] * c - data[index][1] * s);
12
+ imaginary += w * (data[index][0] * s + data[index][1] * c);
13
+ weight += w;
14
+ }
15
+ return { real: real / weight, imaginary: imaginary / weight };
16
+ }
17
+
18
+ /** One common frequency and phase; preserve sign reversals between records. */
19
+ export function analyzeSignedRecords(records, {
20
+ analysis = {}, referenceIndex = null, phaseDegrees = 0, field = "pulse1Cycles", mode = "single",
21
+ } = {}) {
22
+ if (!Array.isArray(records) || !records.length) throw new Error("先にパルス走査を行ってください。");
23
+ if (!Number.isFinite(phaseDegrees)) throw new Error("位相補正は有限数値で指定してください。");
24
+ const first = records[0];
25
+ for (const record of records) {
26
+ if (record.mode !== mode || record.source !== first.source || record.sampleIntervalMs !== first.sampleIntervalMs ||
27
+ Object.keys(first.parameters).some(key => key !== field && record.parameters[key] !== first.parameters[key])) {
28
+ throw new Error("周波数・位相・積算などの共通測定条件とデータ種別を揃えてください。");
29
+ }
30
+ }
31
+ const minHz = analysis.minHz ?? -3000, maxHz = analysis.maxHz ?? 3000;
32
+ if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw new Error("ピーク探索帯域が不正です。");
33
+ const prepared = records.map(record => ({ record, ...analyzeMeasurement(record, analysis) }));
34
+ const grid = prepared[0].spectrum.bins.filter(bin => bin.hz >= minHz && bin.hz <= maxHz).map(bin => bin.hz);
35
+ if (!grid.length) throw new Error("探索帯域にFFTビンがありません。");
36
+ const counts = new Map();
37
+ for (const record of records) counts.set(record.parameters[field], (counts.get(record.parameters[field]) ?? 0) + 1);
38
+ const power = new Float64Array(grid.length);
39
+ for (const item of prepared) {
40
+ const bins = item.spectrum.bins.filter(bin => bin.hz >= minHz && bin.hz <= maxHz);
41
+ if (bins.length !== grid.length || bins.some((bin, index) => bin.hz !== grid[index])) throw new Error("FFTの周波数軸が一致しません。");
42
+ bins.forEach((bin, index) => { power[index] += bin.amplitude ** 2 / counts.get(item.record.parameters[field]); });
43
+ }
44
+ const strongestBin = power.reduce((best, value, index) => value > power[best] ? index : best, 0);
45
+ const hz = grid[strongestBin];
46
+ const values = prepared.map(item => ({ ...complexAt(item.data, item.spectrum, item.record.sampleIntervalMs, hz), record: item.record }));
47
+ const maximum = Math.max(...values.map(value => Math.hypot(value.real, value.imaginary)));
48
+ if (maximum < 1e-9) throw Object.assign(new Error("共通位相基準に使える信号がありません。"), { code: "NO_REFERENCE_SIGNAL" });
49
+ const strong = values.filter(value => Math.hypot(value.real, value.imaginary) >= maximum * 0.25);
50
+ let c = 0, s = 0, total = 0;
51
+ for (const value of strong) {
52
+ const count = counts.get(value.record.parameters[field]);
53
+ c += (value.real ** 2 - value.imaginary ** 2) / count;
54
+ s += 2 * value.real * value.imaginary / count;
55
+ total += (value.real ** 2 + value.imaginary ** 2) / count;
56
+ }
57
+ let phaseRad = 0.5 * Math.atan2(s, c);
58
+ if (referenceIndex !== null) {
59
+ if (!Number.isInteger(referenceIndex) || !values[referenceIndex]) throw new Error("位相基準の測定点が不正です。");
60
+ const ref = values[referenceIndex];
61
+ if (Math.hypot(ref.real, ref.imaginary) < 1e-9) throw new Error("選択点の信号がゼロです。");
62
+ phaseRad = Math.atan2(ref.imaginary, ref.real);
63
+ } else {
64
+ const earliest = strong.reduce((best, value) => value.record.parameters[field] < best.record.parameters[field] ? value : best);
65
+ let direction = earliest.real * Math.cos(phaseRad) + earliest.imaginary * Math.sin(phaseRad);
66
+ if (field === "pulseIntervalMs") {
67
+ const mean = strong.reduce((sum, value) => sum + value.record.parameters[field], 0) / strong.length;
68
+ direction = strong.reduce((sum, value) => sum + (value.record.parameters[field] - mean) *
69
+ (value.real * Math.cos(phaseRad) + value.imaginary * Math.sin(phaseRad)), 0);
70
+ }
71
+ if (direction < 0 || (field === "pulseIntervalMs" && Math.abs(direction) < 1e-9 &&
72
+ (earliest.real * Math.cos(phaseRad) + earliest.imaginary * Math.sin(phaseRad)) < 0)) phaseRad += Math.PI;
73
+ }
74
+ phaseRad += phaseDegrees * Math.PI / 180;
75
+ const points = values.map(value => ({
76
+ length: value.record.parameters[field],
77
+ amplitude: value.real * Math.cos(phaseRad) + value.imaginary * Math.sin(phaseRad),
78
+ quadrature: -value.real * Math.sin(phaseRad) + value.imaginary * Math.cos(phaseRad),
79
+ magnitude: Math.hypot(value.real, value.imaginary), record: value.record,
80
+ }));
81
+ const coherence = Math.hypot(c, s) / Math.max(total, 1e-30);
82
+ return { points, reference: { hz, phaseRad, phaseDegrees, referenceIndex, coherence } };
83
+ }
package/src/sweep.js ADDED
@@ -0,0 +1,32 @@
1
+ import { validateParameters, SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
2
+
3
+ /** Shared integer grid for frequency and pulse scans. */
4
+ export function integerSteps(start, end, step, maximum) {
5
+ if (![start, end, step].every(Number.isInteger) || start < 1 || end > maximum || end < start || step < 1) {
6
+ throw new RangeError(`走査範囲は1〜${maximum}の整数、開始≤終了、刻み幅は1以上で指定してください。`);
7
+ }
8
+ const count = Math.floor((end - start) / step) + 1;
9
+ if (count > 201) throw new RangeError("走査は201点以内で指定してください。");
10
+ return Array.from({ length: count }, (_, index) => start + index * step);
11
+ }
12
+
13
+ /** Validate the complete plan, then measure sequentially without retries. */
14
+ export async function runSingleSweep(device, parameters, {
15
+ field, values, analysis = {}, evaluate, signal, onPoint = () => {}, mode = "single", validateMeasurement = () => {},
16
+ }) {
17
+ const common = validateParameters(parameters);
18
+ const planned = values.map(value => validateParameters({ ...common, [field]: value }));
19
+ if (!["single", "double"].includes(mode)) throw new TypeError("Invalid measurement mode.");
20
+ planned.forEach(validateMeasurement);
21
+ const settings = { ...analysis };
22
+ evaluate({ parameters: common, sampleIntervalMs: SAMPLE_INTERVAL_MS, raw: Array.from({ length: SAMPLE_COUNT }, () => [0, 0]) }, settings);
23
+ const points = [];
24
+ for (const measurement of planned) {
25
+ if (signal?.aborted) break;
26
+ const record = await device.measure(measurement, { mode });
27
+ const point = evaluate(record, settings);
28
+ points.push(point);
29
+ await onPoint(point, points.length, planned.length);
30
+ }
31
+ return { points, stopped: Boolean(signal?.aborted), analysis: settings, parameters: common };
32
+ }
@@ -0,0 +1,42 @@
1
+ import { parseMeasurement } from "./record.js";
2
+ import { validateParameters } from "./protocol.js";
3
+ import { t1Delays, evaluateT1, analyzeT1 } from "./t1-sweep.js";
4
+
5
+ export const MAX_T1_JSON_BYTES = 32 * 1024 * 1024;
6
+
7
+ /** Restore a complete or stopped T1 scan; recompute derived data from raw samples. */
8
+ export function parseT1Measurement(text) {
9
+ if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_T1_JSON_BYTES) throw new TypeError("T1のJSONは32 MiB以下で指定してください。");
10
+ let saved;
11
+ try { saved = JSON.parse(text.replace(/^\uFEFF/, "")); }
12
+ catch { throw new TypeError("JSONの形式が正しくありません。"); }
13
+ if (saved?.kind !== "t1-measurement" || !Array.isArray(saved.points) || !saved.points.length || saved.points.length > 201) {
14
+ throw new TypeError("T1の全データJSONを指定してください(1〜201点)。");
15
+ }
16
+ const s = saved.settings;
17
+ if (!s) throw new TypeError("走査条件がありません。");
18
+ const delays = t1Delays(s.startMs, s.endMs, s.stepMs);
19
+ const parameters = validateParameters(s.parameters);
20
+ 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
+ const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, minHz: a.minHz, maxHz: a.maxHz, window: a.window };
23
+ const points = saved.points.map((point, index) => {
24
+ const record = parseMeasurement(JSON.stringify(point?.record));
25
+ 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("測定点とT1走査条件が一致しません。");
27
+ return evaluateT1(record, analysis);
28
+ });
29
+ const referenceIndex = saved.result?.reference?.referenceIndex ?? null;
30
+ const phaseDegrees = saved.result?.reference?.phaseDegrees ?? 0;
31
+ const fromMs = saved.result?.fromMs ?? s.startMs, toMs = saved.result?.toMs ?? s.endMs;
32
+ if (![fromMs, toMs, phaseDegrees].every(Number.isFinite) || fromMs >= toMs) throw new TypeError("近似範囲または位相補正が不正です。");
33
+ if (referenceIndex !== null && (!Number.isInteger(referenceIndex) || referenceIndex < 0 || referenceIndex >= points.length)) throw new TypeError("基準点が不正です。");
34
+ let result = null;
35
+ try { result = analyzeT1(points.map(point => point.record), { analysis, referenceIndex, phaseDegrees, fromMs, toMs }); }
36
+ catch (error) {
37
+ // A valid zero-signal scan is still useful for inspecting raw waveforms.
38
+ if (error.code !== "NO_REFERENCE_SIGNAL") throw error;
39
+ }
40
+ if (typeof saved.acquiredAt !== "string" || !Number.isFinite(Date.parse(saved.acquiredAt))) throw new TypeError("走査日時が不正です。");
41
+ return { source: saved.source, acquiredAt: saved.acquiredAt, settings: { startMs: s.startMs, endMs: s.endMs, stepMs: s.stepMs, delays, parameters, analysis }, points, result, referenceIndex, phaseDegrees, fromMs, toMs };
42
+ }
@@ -0,0 +1,66 @@
1
+ import { integerSteps, runSingleSweep } from "./sweep.js";
2
+ import { evaluateFrequency } from "./frequency-sweep.js";
3
+ import { validateParameters, SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
4
+ import { analyzeSignedRecords } from "./signed-signal.js";
5
+ import { fitT1 } from "./relaxation-fit.js";
6
+
7
+ export function t1Delays(startMs, endMs, stepMs) {
8
+ return integerSteps(startMs, endMs, stepMs, 32767);
9
+ }
10
+
11
+ /** PoC inversion recovery: 180°(0°), tau, 90°(0°), then acquire FID. */
12
+ export function t1Parameters({ frequencyHz, p90Cycles, p180Cycles, measurementIntervalMs, scans }, tauMs) {
13
+ if (!Number.isInteger(p90Cycles) || !Number.isInteger(p180Cycles) || p90Cycles < 1 || p180Cycles <= p90Cycles) {
14
+ throw new RangeError("0 < 90°長 < 180°長の整数周期で指定してください。");
15
+ }
16
+ const parameters = validateParameters({ frequencyHz, pulse1Cycles: p180Cycles, phase1Degrees: 0,
17
+ pulse2Cycles: p90Cycles, phase2Degrees: 0, pulseIntervalMs: tauMs, measurementIntervalMs, scans });
18
+ validateT1Parameters(parameters);
19
+ return parameters;
20
+ }
21
+
22
+ function validateT1Parameters(parameters) {
23
+ if (!Number.isInteger(parameters.pulseIntervalMs) || parameters.pulseIntervalMs < 1) throw new RangeError("τは1〜32767 msの整数で指定してください。");
24
+ if (parameters.phase1Degrees !== 0 || parameters.phase2Degrees !== 0 || parameters.pulse2Cycles < 1 || parameters.pulse1Cycles <= parameters.pulse2Cycles) {
25
+ throw new RangeError("T1は180°(0°) → τ → 90°(0°)で測定してください。");
26
+ }
27
+ if (parameters.measurementIntervalMs <= parameters.pulseIntervalMs + SAMPLE_COUNT * SAMPLE_INTERVAL_MS) {
28
+ throw new RangeError("繰り返し間隔はτ+取得時間(40.96 ms)より長くしてください。");
29
+ }
30
+ }
31
+
32
+ export function evaluateT1(record, analysis = {}) {
33
+ const start = analysis.startMs ?? 1, end = analysis.endMs ?? 5;
34
+ if (![start, end].every(Number.isFinite) || end - start < 4 * SAMPLE_INTERVAL_MS - 1e-9 ||
35
+ (analysis.minHz ?? -3000) < -25000 || (analysis.maxHz ?? 3000) > 25000) {
36
+ throw new RangeError("FFT窓は4点以上、ピーク探索帯域は−25〜25 kHz内で指定してください。");
37
+ }
38
+ const point = evaluateFrequency(record, analysis);
39
+ return { tau: record.parameters.pulseIntervalMs, amplitude: point.amplitude, peakHz: point.peakHz, record };
40
+ }
41
+
42
+ export async function runT1Sweep(device, parameters, { startMs, endMs, stepMs, analysis = {}, signal, onPoint } = {}) {
43
+ const delays = t1Delays(startMs, endMs, stepMs);
44
+ const result = await runSingleSweep(device, parameters, { field: "pulseIntervalMs", values: delays, mode: "double",
45
+ validateMeasurement: validateT1Parameters, analysis, evaluate: evaluateT1, signal, onPoint });
46
+ return { ...result, delays };
47
+ }
48
+
49
+ export function analyzeT1(records, { analysis = {}, referenceIndex = null, phaseDegrees = 0, fromMs, toMs } = {}) {
50
+ if (!Array.isArray(records) || !records.length) throw new Error("先にT1測定を行ってください。");
51
+ records.forEach(record => { validateT1Parameters(validateParameters(record.parameters)); evaluateT1(record, analysis); });
52
+ const result = analyzeSignedRecords(records, { analysis, referenceIndex, phaseDegrees, field: "pulseIntervalMs", mode: "double" });
53
+ const points = result.points.map(({ length, amplitude, ...point }) => ({ ...point, tau: length, signal: amplitude }));
54
+ const range = { fromMs: fromMs ?? Math.min(...points.map(point => point.tau)), toMs: toMs ?? Math.max(...points.map(point => point.tau)) };
55
+ const warnings = [];
56
+ let fit = null;
57
+ if (result.reference.coherence < 0.85) warnings.push("測定点間の位相が共通方向に揃っていません。T1の近似は行いません。");
58
+ else {
59
+ try {
60
+ fit = fitT1(points, range);
61
+ if (fit.to < 3 * fit.T) warnings.push("最大τが推定T1の3倍未満です。回復後の信号が十分に測定されていないため、推定値は測定範囲に敏感になる可能性があります。");
62
+ }
63
+ catch (error) { warnings.push(error.message); }
64
+ }
65
+ return { points, reference: result.reference, fit, warnings, ...range };
66
+ }
@@ -0,0 +1,41 @@
1
+ import { parseMeasurement } from "./record.js";
2
+ import { validateParameters } from "./protocol.js";
3
+ import { t2Delays, evaluateT2, analyzeT2 } from "./t2-sweep.js";
4
+
5
+ export const MAX_T2_JSON_BYTES = 32 * 1024 * 1024;
6
+
7
+ /** Restore a complete or stopped T2 scan; recompute derived data from raw samples. */
8
+ 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
+ let saved;
11
+ try { saved = JSON.parse(text.replace(/^\uFEFF/, "")); }
12
+ catch { throw new TypeError("JSONの形式が正しくありません。"); }
13
+ 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
+ }
16
+ const s = saved.settings;
17
+ if (!s) throw new TypeError("走査条件がありません。");
18
+ const delays = t2Delays(s.startMs, s.endMs, s.stepMs);
19
+ const parameters = validateParameters(s.parameters);
20
+ 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
+ const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, minHz: a.minHz, maxHz: a.maxHz, window: a.window };
23
+ const points = saved.points.map((point, index) => {
24
+ const record = parseMeasurement(JSON.stringify(point?.record));
25
+ 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
+ return evaluateT2(record, analysis);
28
+ });
29
+ const referenceIndex = saved.result?.reference?.referenceIndex ?? null;
30
+ 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("基準点が不正です。");
33
+ let result = null;
34
+ try { result = analyzeT2(points.map(point => point.record), { analysis, referenceIndex, fromMs, toMs }); }
35
+ catch (error) {
36
+ // A valid zero-signal scan is still useful for inspecting raw waveforms.
37
+ if (error.code !== "NO_REFERENCE_SIGNAL") throw error;
38
+ }
39
+ if (typeof saved.acquiredAt !== "string" || !Number.isFinite(Date.parse(saved.acquiredAt))) throw new TypeError("走査日時が不正です。");
40
+ 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
+ }