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.
- package/LICENSE +24 -0
- package/README.md +132 -2
- package/package.json +39 -4
- package/src/analysis.js +14 -0
- package/src/baseline.js +31 -0
- package/src/browser.js +93 -0
- package/src/controller.js +119 -0
- package/src/device.js +132 -0
- package/src/fft.js +100 -0
- package/src/frequency-record.js +40 -0
- package/src/frequency-sweep.js +30 -0
- package/src/graphs.js +235 -0
- package/src/index.js +30 -0
- package/src/line-decoder.js +56 -0
- package/src/protocol.js +107 -0
- package/src/pulse-fit.js +86 -0
- package/src/pulse-record.js +50 -0
- package/src/pulse-sweep.js +40 -0
- package/src/record.js +40 -0
- package/src/relaxation-fit.js +69 -0
- package/src/sample-validation.js +13 -0
- package/src/signed-signal.js +83 -0
- package/src/sweep.js +32 -0
- package/src/t1-record.js +42 -0
- package/src/t1-sweep.js +66 -0
- package/src/t2-record.js +41 -0
- package/src/t2-sweep.js +80 -0
- package/src/timing.js +9 -0
- package/src/web-serial-transport.js +144 -0
package/src/fft.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { validateSamples } from "./sample-validation.js";
|
|
2
|
+
|
|
3
|
+
// Bound allocations and bitwise-index operations; normal acquisitions use 2048 points.
|
|
4
|
+
const MAX_FFT_SIZE = 2 ** 20;
|
|
5
|
+
|
|
6
|
+
/** In-place radix-2 forward FFT. The forward exponent has a negative sign. */
|
|
7
|
+
function forwardTransform(real, imaginary) {
|
|
8
|
+
const size = real.length;
|
|
9
|
+
for (let index = 1, reversed = 0; index < size; index++) {
|
|
10
|
+
let bit = size >> 1;
|
|
11
|
+
for (; reversed & bit; bit >>= 1) reversed ^= bit;
|
|
12
|
+
reversed ^= bit;
|
|
13
|
+
if (index < reversed) {
|
|
14
|
+
[real[index], real[reversed]] = [real[reversed], real[index]];
|
|
15
|
+
[imaginary[index], imaginary[reversed]] = [imaginary[reversed], imaginary[index]];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
for (let length = 2; length <= size; length *= 2) {
|
|
19
|
+
const angle = -2 * Math.PI / length;
|
|
20
|
+
for (let offset = 0; offset < size; offset += length) {
|
|
21
|
+
for (let index = 0; index < length / 2; index++) {
|
|
22
|
+
const cosine = Math.cos(angle * index);
|
|
23
|
+
const sine = Math.sin(angle * index);
|
|
24
|
+
const first = offset + index;
|
|
25
|
+
const second = first + length / 2;
|
|
26
|
+
const rotatedReal = real[second] * cosine - imaginary[second] * sine;
|
|
27
|
+
const rotatedImaginary = real[second] * sine + imaginary[second] * cosine;
|
|
28
|
+
real[second] = real[first] - rotatedReal;
|
|
29
|
+
imaginary[second] = imaginary[first] - rotatedImaginary;
|
|
30
|
+
real[first] += rotatedReal;
|
|
31
|
+
imaginary[first] += rotatedImaginary;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Complex spectrum of channel 1 + i * channel 2, with receiver-relative Hz.
|
|
39
|
+
* Range is [startMs, endMs); output frequencies are ascending, negative first.
|
|
40
|
+
* A symmetric Hann or rectangular window is normalized by its summed weights.
|
|
41
|
+
*/
|
|
42
|
+
export function computeSpectrum(data, {
|
|
43
|
+
sampleIntervalMs,
|
|
44
|
+
startMs = 0,
|
|
45
|
+
endMs = data?.length * sampleIntervalMs,
|
|
46
|
+
window = "hann",
|
|
47
|
+
} = {}) {
|
|
48
|
+
validateSamples(data);
|
|
49
|
+
if (![sampleIntervalMs, startMs, endMs].every(Number.isFinite) ||
|
|
50
|
+
sampleIntervalMs <= 0 || startMs < 0 || startMs >= endMs ||
|
|
51
|
+
endMs > data.length * sampleIntervalMs + 1e-9) {
|
|
52
|
+
throw new RangeError("FFT range must satisfy 0 <= startMs < endMs <= acquisition duration, with a positive sampleIntervalMs.");
|
|
53
|
+
}
|
|
54
|
+
if (!["hann", "rect"].includes(window)) throw new RangeError("Window must be hann or rect.");
|
|
55
|
+
|
|
56
|
+
// Match the PoC's rounding tolerance at exact sample boundaries.
|
|
57
|
+
const first = Math.ceil(startMs / sampleIntervalMs - 1e-9);
|
|
58
|
+
const last = Math.min(data.length, Math.ceil(endMs / sampleIntervalMs - 1e-9));
|
|
59
|
+
const count = last - first;
|
|
60
|
+
if (count < 4) throw new RangeError("FFT requires at least four selected samples.");
|
|
61
|
+
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
|
+
|
|
64
|
+
const real = new Float64Array(size);
|
|
65
|
+
const imaginary = new Float64Array(size);
|
|
66
|
+
let weight = 0;
|
|
67
|
+
for (let index = 0; index < count; index++) {
|
|
68
|
+
const value = window === "hann" ? 0.5 * (1 - Math.cos(2 * Math.PI * index / (count - 1))) : 1;
|
|
69
|
+
real[index] = data[first + index][0] * value;
|
|
70
|
+
imaginary[index] = data[first + index][1] * value;
|
|
71
|
+
weight += value;
|
|
72
|
+
}
|
|
73
|
+
forwardTransform(real, imaginary);
|
|
74
|
+
|
|
75
|
+
const bins = Array.from({ length: size }, (_, index) => {
|
|
76
|
+
const transformedIndex = (index + size / 2) % size;
|
|
77
|
+
const realValue = real[transformedIndex];
|
|
78
|
+
const imaginaryValue = imaginary[transformedIndex];
|
|
79
|
+
// Divide after hypot, just as the PoC does, for amplitude compatibility.
|
|
80
|
+
const amplitude = Math.hypot(realValue, imaginaryValue) / weight;
|
|
81
|
+
if (!Number.isFinite(amplitude)) throw new RangeError("FFT calculation overflowed.");
|
|
82
|
+
return {
|
|
83
|
+
hz: (index - size / 2) * 1000 / (size * sampleIntervalMs),
|
|
84
|
+
real: realValue / weight,
|
|
85
|
+
imaginary: imaginaryValue / weight,
|
|
86
|
+
amplitude,
|
|
87
|
+
phaseRadians: Math.atan2(imaginaryValue, realValue),
|
|
88
|
+
};
|
|
89
|
+
});
|
|
90
|
+
return {
|
|
91
|
+
startMs, endMs, first, last, count, size, window,
|
|
92
|
+
actualStartMs: first * sampleIntervalMs,
|
|
93
|
+
actualEndExclusiveMs: last * sampleIntervalMs,
|
|
94
|
+
durationMs: count * sampleIntervalMs,
|
|
95
|
+
spacingHz: 1000 / (size * sampleIntervalMs),
|
|
96
|
+
resolutionHz: 1000 / (count * sampleIntervalMs),
|
|
97
|
+
convention: "Data 1 + i Data 2",
|
|
98
|
+
bins,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { parseMeasurement } from "./record.js";
|
|
2
|
+
import { frequencySteps, evaluateFrequency } from "./frequency-sweep.js";
|
|
3
|
+
import { validateParameters } from "./protocol.js";
|
|
4
|
+
|
|
5
|
+
export const MAX_FREQUENCY_JSON_BYTES = 32 * 1024 * 1024;
|
|
6
|
+
|
|
7
|
+
/** Restore raw records and recompute all derived values before replacing a UI's results. */
|
|
8
|
+
export function parseFrequencySweep(text) {
|
|
9
|
+
if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_FREQUENCY_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 !== "frequency-sweep" || !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 frequencies = frequencySteps(saved.startHz, saved.endHz, saved.stepHz);
|
|
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.frequencyHz !== frequencies[index] || record.parameters.frequencyHz !== frequencies[index] ||
|
|
31
|
+
Object.keys(parameters).some(key => key !== "frequencyHz" && parameters[key] !== record.parameters[key])) {
|
|
32
|
+
throw new TypeError("測定点と走査条件が一致しません。");
|
|
33
|
+
}
|
|
34
|
+
return evaluateFrequency(record, analysis);
|
|
35
|
+
});
|
|
36
|
+
if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw new TypeError("走査日時が正しくありません。");
|
|
37
|
+
return { source: value.source, acquiredAt: value.acquiredAt,
|
|
38
|
+
settings: { startHz: saved.startHz, endHz: saved.endHz, stepHz: saved.stepHz, frequencies, parameters, analysis },
|
|
39
|
+
points };
|
|
40
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { integerSteps, runSingleSweep } from "./sweep.js";
|
|
2
|
+
import { analyzeMeasurement } from "./analysis.js";
|
|
3
|
+
|
|
4
|
+
/** Plan an ascending scan without inventing an endpoint beyond the requested grid. */
|
|
5
|
+
export function frequencySteps(startHz, endHz, stepHz) {
|
|
6
|
+
return integerSteps(startHz, endHz, stepHz, 2147483647);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Compare every record with the same time interval, window and peak search band. */
|
|
10
|
+
export function evaluateFrequency(record, {
|
|
11
|
+
startMs = 1, endMs = 5, tailPoints = 100, window = "hann", minHz = -3000, maxHz = 3000,
|
|
12
|
+
} = {}) {
|
|
13
|
+
if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw new RangeError("探索帯域は下限より上限を大きく指定してください。");
|
|
14
|
+
const analysis = analyzeMeasurement(record, { startMs, endMs, tailPoints, window });
|
|
15
|
+
const bins = analysis.spectrum.bins.filter(bin => bin.hz >= minHz && bin.hz <= maxHz);
|
|
16
|
+
if (!bins.length) throw new RangeError("探索帯域にFFTビンがありません。");
|
|
17
|
+
const peak = bins.reduce((best, bin) => bin.amplitude > best.amplitude ? bin : best);
|
|
18
|
+
return { frequencyHz: record.parameters.frequencyHz, amplitude: peak.amplitude, peakHz: peak.hz, record };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Sequential Single scans; abort takes effect only between complete measurements. */
|
|
22
|
+
export async function runFrequencySweep(device, parameters, {
|
|
23
|
+
startHz, endHz, stepHz, analysis = {}, signal, onPoint = () => {},
|
|
24
|
+
} = {}) {
|
|
25
|
+
const frequencies = frequencySteps(startHz, endHz, stepHz);
|
|
26
|
+
const result = await runSingleSweep(device, parameters, {
|
|
27
|
+
field: "frequencyHz", values: frequencies, analysis, evaluate: evaluateFrequency, signal, onPoint,
|
|
28
|
+
});
|
|
29
|
+
return { ...result, frequencies };
|
|
30
|
+
}
|
package/src/graphs.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { analyzeMeasurement } from "./analysis.js";
|
|
2
|
+
|
|
3
|
+
// Unique SVG clip IDs allow multiple graph views on the same page.
|
|
4
|
+
let nextGraphId = 0;
|
|
5
|
+
const DEFAULT_COLORS = { data1: "#176caa", data2: "#b34e25", fft: "#176caa" };
|
|
6
|
+
|
|
7
|
+
function lineColors(options = {}) {
|
|
8
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError("colors must be an object.");
|
|
9
|
+
const colors = { ...DEFAULT_COLORS, ...options };
|
|
10
|
+
for (const key of Object.keys(colors)) {
|
|
11
|
+
if (!(key in DEFAULT_COLORS) || typeof colors[key] !== "string" || !colors[key].trim()) throw new TypeError("Expected colors.data1, colors.data2 and colors.fft to be non-empty CSS color strings.");
|
|
12
|
+
}
|
|
13
|
+
return colors;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const escapeAttribute = value => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
17
|
+
|
|
18
|
+
/** Build a responsive SVG. All plotted values come from validated numeric data. */
|
|
19
|
+
function plot(series, { title, xLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null }) {
|
|
20
|
+
const height = 280;
|
|
21
|
+
const margin = { left: 68, right: 20, top: 20, bottom: 52 };
|
|
22
|
+
const plotWidth = width - margin.left - margin.right;
|
|
23
|
+
const plotHeight = height - margin.top - margin.bottom;
|
|
24
|
+
let largest = 0;
|
|
25
|
+
for (const points of series) {
|
|
26
|
+
for (const [x, y] of points) {
|
|
27
|
+
if (x >= scaleFrom && x < scaleUntil) largest = Math.max(largest, Math.abs(y));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
largest = largest > 0 ? largest * 1.1 : 1;
|
|
31
|
+
const yMinimum = nonnegative ? 0 : -largest;
|
|
32
|
+
const yMaximum = largest;
|
|
33
|
+
const xPosition = value => margin.left + (value - xMinimum) / (xMaximum - xMinimum) * plotWidth;
|
|
34
|
+
const yPosition = value => margin.top + (yMaximum - value) / (yMaximum - yMinimum) * plotHeight;
|
|
35
|
+
const format = value => Math.abs(value) >= 10000 ? value.toExponential(1) : Number(value.toPrecision(4)).toString();
|
|
36
|
+
const elements = [];
|
|
37
|
+
|
|
38
|
+
for (let tick = 0; tick <= 4; tick++) {
|
|
39
|
+
const x = xMinimum + (xMaximum - xMinimum) * tick / 4;
|
|
40
|
+
const y = yMinimum + (yMaximum - yMinimum) * tick / 4;
|
|
41
|
+
elements.push(`<path d="M ${xPosition(x)} ${margin.top} V ${margin.top + plotHeight}" stroke="#e0e5e8"/>`);
|
|
42
|
+
elements.push(`<path d="M ${margin.left} ${yPosition(y)} H ${width - margin.right}" stroke="#e0e5e8"/>`);
|
|
43
|
+
elements.push(`<text x="${xPosition(x)}" y="${height - 30}" text-anchor="middle">${xFormatter ? xFormatter(x) : format(x)}</text>`);
|
|
44
|
+
elements.push(`<text x="${margin.left - 8}" y="${yPosition(y) + 4}" text-anchor="end">${format(y)}</text>`);
|
|
45
|
+
}
|
|
46
|
+
elements.push(`<path d="M ${margin.left} ${margin.top} V ${margin.top + plotHeight} H ${width - margin.right}" fill="none" stroke="#66757c"/>`);
|
|
47
|
+
elements.push(`<defs><clipPath id="${clipId}"><rect x="${margin.left}" y="${margin.top}" width="${plotWidth}" height="${plotHeight}"/></clipPath></defs>`);
|
|
48
|
+
if (selection) {
|
|
49
|
+
const left = xPosition(selection[0]);
|
|
50
|
+
const right = xPosition(selection[1]);
|
|
51
|
+
elements.push(`<g clip-path="url(#${clipId})"><rect x="${left}" y="${margin.top}" width="${right - left}" height="${plotHeight}" fill="#176caa" fill-opacity="0.1"/><path d="M ${left} ${margin.top} V ${margin.top + plotHeight} M ${right} ${margin.top} V ${margin.top + plotHeight}" stroke="#176caa" stroke-dasharray="4 3"/></g>`);
|
|
52
|
+
}
|
|
53
|
+
series.forEach((points, index) => {
|
|
54
|
+
const coordinates = points.map(([x, y]) => `${xPosition(x).toFixed(2)},${yPosition(y).toFixed(2)}`).join(" ");
|
|
55
|
+
elements.push(`<polyline points="${coordinates}" fill="none" stroke="${escapeAttribute(colors[index])}" stroke-width="1.5" stroke-linejoin="round" clip-path="url(#${clipId})"/>`);
|
|
56
|
+
if (markers && index === 0) for (const [x, y] of points) {
|
|
57
|
+
elements.push(`<circle cx="${xPosition(x)}" cy="${yPosition(y)}" r="3" fill="${escapeAttribute(colors[index])}" clip-path="url(#${clipId})"/>`);
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
elements.push(`<text x="${margin.left + plotWidth / 2}" y="${height - 6}" text-anchor="middle">${xLabel}</text>`);
|
|
61
|
+
elements.push(`<text x="16" y="${margin.top + plotHeight / 2}" transform="rotate(-90 16 ${margin.top + plotHeight / 2})" text-anchor="middle">信号値 [a.u.]</text>`);
|
|
62
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${title}" style="font-family:inherit;font-size:12px;fill:#34454e"><title>${title}</title>${elements.join("")}</svg>`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Analyze without modifying record.raw; share the same pipeline in browser/tests. */
|
|
66
|
+
export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {} } = {}) {
|
|
67
|
+
if (!Number.isFinite(width) || width < 160) throw new RangeError("Plot width must be at least 160 pixels.");
|
|
68
|
+
if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw new TypeError("Invalid SVG ID prefix.");
|
|
69
|
+
if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw new RangeError("Display limits must be positive finite numbers.");
|
|
70
|
+
const palette = lineColors(colors);
|
|
71
|
+
const { data, spectrum, peak } = analysis;
|
|
72
|
+
const endMs = Math.min(displayEndMs, data.length * record.sampleIntervalMs);
|
|
73
|
+
const displayed = data.slice(0, Math.ceil(endMs / record.sampleIntervalMs - 1e-9));
|
|
74
|
+
const channels = [0, 1].map(channel => displayed.map((pair, index) => [index * record.sampleIntervalMs, pair[channel]]));
|
|
75
|
+
const visibleBins = spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz);
|
|
76
|
+
const displayLimit = Math.min(frequencyLimitHz, 500 / record.sampleIntervalMs);
|
|
77
|
+
return {
|
|
78
|
+
fid: plot(channels, { title: "FID:Data 1とData 2", xLabel: "時間 [ms]", xMinimum: 0, xMaximum: endMs, scaleFrom: spectrum.actualStartMs, scaleUntil: spectrum.actualEndExclusiveMs, clipId: `${idPrefix}-fid`, width, selection: [spectrum.actualStartMs, spectrum.actualEndExclusiveMs], colors: [palette.data1, palette.data2] }),
|
|
79
|
+
fft: plot([visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
|
|
80
|
+
title: "複素FFTの振幅スペクトル", xLabel: "受信周波数からの差 [kHz]",
|
|
81
|
+
xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: [palette.fft],
|
|
82
|
+
}),
|
|
83
|
+
peak,
|
|
84
|
+
spectrum,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Browser graph view. Resize redraws the saved analysis, without remeasuring. */
|
|
89
|
+
export class NMRGraphs {
|
|
90
|
+
constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {} }) {
|
|
91
|
+
if (!fid || !fft) throw new TypeError("FID and FFT elements are required.");
|
|
92
|
+
Object.assign(this, { fid, fft, peakElement: peak, statusElement: status, displayEndMs, frequencyLimitHz });
|
|
93
|
+
this.colors = lineColors(colors);
|
|
94
|
+
this.idPrefix = `nmr-${++nextGraphId}`;
|
|
95
|
+
this.widths = new Map();
|
|
96
|
+
this.observer = new ResizeObserver(entries => {
|
|
97
|
+
let changed = false;
|
|
98
|
+
for (const entry of entries) {
|
|
99
|
+
if (this.widths.get(entry.target) !== entry.contentRect.width) {
|
|
100
|
+
this.widths.set(entry.target, entry.contentRect.width);
|
|
101
|
+
changed = true;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (changed && this.record) this.render();
|
|
105
|
+
});
|
|
106
|
+
this.observer.observe(fid);
|
|
107
|
+
this.observer.observe(fft);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
show(record, analysis = analyzeMeasurement(record)) {
|
|
111
|
+
this.record = record;
|
|
112
|
+
this.analysis = analysis;
|
|
113
|
+
try { this.render(); }
|
|
114
|
+
catch (error) { this.clear(); throw error; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
render() {
|
|
118
|
+
const { record, analysis } = this;
|
|
119
|
+
const widthOf = element => {
|
|
120
|
+
const style = getComputedStyle(element);
|
|
121
|
+
return Math.max(160, element.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
|
|
122
|
+
};
|
|
123
|
+
const options = { analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors };
|
|
124
|
+
const fid = createRecordPlots(record, { ...options, width: widthOf(this.fid) });
|
|
125
|
+
const fft = createRecordPlots(record, { ...options, width: widthOf(this.fft) });
|
|
126
|
+
this.fid.innerHTML = fid.fid;
|
|
127
|
+
this.fft.innerHTML = fft.fft;
|
|
128
|
+
for (const element of [this.fid, this.fft]) {
|
|
129
|
+
const svg = element.querySelector("svg");
|
|
130
|
+
svg.style.display = "block";
|
|
131
|
+
svg.style.width = "100%";
|
|
132
|
+
svg.style.height = "280px";
|
|
133
|
+
}
|
|
134
|
+
if (this.peakElement) {
|
|
135
|
+
const peak = analysis.peak;
|
|
136
|
+
const outside = Math.abs(peak.hz) > this.frequencyLimitHz ? "(表示範囲外)" : "";
|
|
137
|
+
this.peakElement.textContent = peak.amplitude === 0 ? "最大ピーク:信号なし"
|
|
138
|
+
: `最大ピーク:${peak.hz.toFixed(1)} Hz(受信周波数からの差)${outside}。全周波数から探索・FFTビン値。`;
|
|
139
|
+
}
|
|
140
|
+
if (this.statusElement) {
|
|
141
|
+
const { spectrum, baseline } = analysis;
|
|
142
|
+
const interval = `${spectrum.actualStartMs}〜${spectrum.actualEndExclusiveMs} ms`;
|
|
143
|
+
this.statusElement.textContent = `末尾${baseline.tailPoints}点の平均で補正。FID表示は0〜${this.displayEndMs} ms、縦軸は${interval}で自動調整(範囲外はクリップ)。薄い青の帯はFFT範囲。FFTは${interval}(終端を含まない)、${spectrum.window}窓。周波数表示は±${this.frequencyLimitHz / 1000} kHz。`;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
clear() {
|
|
148
|
+
this.record = null;
|
|
149
|
+
this.analysis = null;
|
|
150
|
+
this.fid.textContent = "測定すると波形を表示します。";
|
|
151
|
+
this.fft.textContent = "測定するとスペクトルを表示します。";
|
|
152
|
+
if (this.peakElement) this.peakElement.textContent = "最大ピーク:未測定";
|
|
153
|
+
if (this.statusElement) this.statusElement.textContent = "";
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
dispose() {
|
|
157
|
+
this.observer.disconnect();
|
|
158
|
+
this.clear();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Build the frequency-response curve with the same SVG axes as FID/FFT graphs. */
|
|
163
|
+
export function createFrequencyPlot(points, { width = 720 } = {}) {
|
|
164
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) {
|
|
165
|
+
throw new TypeError("At least one frequency point and a width of 160 or greater are required.");
|
|
166
|
+
}
|
|
167
|
+
const sorted = [...points].sort((a, b) => a.frequencyHz - b.frequencyHz);
|
|
168
|
+
if (!sorted.every(point => Number.isFinite(point.frequencyHz) && Number.isFinite(point.amplitude) && point.amplitude >= 0)) {
|
|
169
|
+
throw new TypeError("Frequency and nonnegative amplitude must be finite.");
|
|
170
|
+
}
|
|
171
|
+
let min = sorted[0].frequencyHz / 1000;
|
|
172
|
+
let max = sorted.at(-1).frequencyHz / 1000;
|
|
173
|
+
if (min === max) { min -= 0.1; max += 0.1; }
|
|
174
|
+
const svg = plot([sorted.map(point => [point.frequencyHz / 1000, point.amplitude])], {
|
|
175
|
+
title: "設定周波数とFFTピーク振幅", xLabel: "設定周波数 [kHz]", xMinimum: min, xMaximum: max,
|
|
176
|
+
nonnegative: true, scaleUntil: Infinity, clipId: `sweep-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.fft], markers: true, xFormatter: value => Number(value.toFixed(6)).toString(),
|
|
177
|
+
});
|
|
178
|
+
return svg;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Signed pulse response and optional fitted curve, at a fixed vertical height. */
|
|
182
|
+
export function createPulsePlot(points, { width = 720, fit = null, mode = "signed" } = {}) {
|
|
183
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw new TypeError("Valid pulse points and plot width are required.");
|
|
184
|
+
if (!["signed", "magnitude"].includes(mode)) throw new TypeError("Invalid pulse plot mode.");
|
|
185
|
+
const magnitude = mode === "magnitude";
|
|
186
|
+
const sorted = points.map(point => ({ ...point, amplitude: magnitude ? point.magnitude : point.amplitude })).sort((a, b) => a.length - b.length);
|
|
187
|
+
if (!sorted.every(point => Number.isFinite(point.length) && Number.isFinite(point.amplitude))) throw new TypeError("Pulse lengths and signed values must be finite.");
|
|
188
|
+
const min = sorted[0].length, max = sorted.at(-1).length;
|
|
189
|
+
const series = [sorted.map(point => [point.length, point.amplitude])];
|
|
190
|
+
if (fit) {
|
|
191
|
+
if (![fit.A, fit.B, fit.p90].every(Number.isFinite) || fit.p90 <= 0) throw new TypeError("Invalid pulse fit.");
|
|
192
|
+
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
193
|
+
const length = min + (max - min) * index / 200;
|
|
194
|
+
const value = Math.sin(Math.PI * length / (2 * fit.p90));
|
|
195
|
+
return [length, fit.A * (magnitude ? Math.abs(value) : value) + fit.B];
|
|
196
|
+
}));
|
|
197
|
+
}
|
|
198
|
+
return plot(series, { title: magnitude ? "パルス周期数と信号の絶対値" : "パルス周期数と符号付き信号", nonnegative: magnitude, xLabel: "第1パルス [周期数]", xMinimum: 0,
|
|
199
|
+
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, clipId: `pulse-${++nextGraphId}`, width,
|
|
200
|
+
colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** T1 response: preserve signed recovery; magnitude/quadrature are display-only. */
|
|
204
|
+
export function createT1Plot(points, { width = 720, fit = null, mode = "signed" } = {}) {
|
|
205
|
+
if (!["signed", "magnitude", "quadrature"].includes(mode) || !Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw new TypeError("Invalid T1 plot settings.");
|
|
206
|
+
const key = mode === "signed" ? "signal" : mode;
|
|
207
|
+
const sorted = [...points].sort((a, b) => a.tau - b.tau);
|
|
208
|
+
if (!sorted.every(point => Number.isFinite(point.tau) && Number.isFinite(point[key]))) throw new TypeError("T1 points must be finite.");
|
|
209
|
+
const min = sorted[0].tau, max = sorted.at(-1).tau;
|
|
210
|
+
const series = [sorted.map(point => [point.tau, point[key]])];
|
|
211
|
+
if (fit && mode === "signed") {
|
|
212
|
+
if (![fit.A, fit.B, fit.T, fit.from, fit.to].every(Number.isFinite) || fit.T <= 0) throw new TypeError("Invalid T1 fit.");
|
|
213
|
+
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
214
|
+
const tau = fit.from + (fit.to - fit.from) * index / 200;
|
|
215
|
+
return [tau, fit.A - fit.B * Math.exp(-tau / fit.T)];
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
return plot(series, { title: "T1・反転回復曲線", xLabel: "待ち時間 τ [ms]", xMinimum: 0,
|
|
219
|
+
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, nonnegative: mode === "magnitude",
|
|
220
|
+
clipId: `t1-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Echo amplitude versus 2*tau; background is fixed at zero. */
|
|
224
|
+
export function createT2Plot(points, {width = 720, fit = null} = {}) {
|
|
225
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw new TypeError("Invalid T2 plot settings.");
|
|
226
|
+
const sorted = [...points].sort((a,b)=>a.tau-b.tau);
|
|
227
|
+
if (!sorted.every(p=>Number.isFinite(p.tau)&&p.tau>0&&Number.isFinite(p.signal)&&p.signal>=0)) throw new TypeError("T2 points must be finite and nonnegative.");
|
|
228
|
+
const series = [sorted.map(p=>[2*p.tau,p.signal])];
|
|
229
|
+
if (fit) {
|
|
230
|
+
if (![fit.T,fit.A,fit.from,fit.to].every(Number.isFinite) || fit.T<=0) throw new TypeError("Invalid T2 fit.");
|
|
231
|
+
series.push(Array.from({length:201},(_,i)=>{const x=fit.from+(fit.to-fit.from)*i/200;return [x,fit.A*Math.exp(-x/fit.T)];}));
|
|
232
|
+
}
|
|
233
|
+
return plot(series,{title:"T2・エコー減衰曲線",xLabel:"2τ [ms]",xMinimum:0,xMaximum:Math.max(...sorted.map(p=>2*p.tau)),scaleUntil:Infinity,nonnegative:true,
|
|
234
|
+
clipId:`t2-${++nextGraphId}`,width,colors:[DEFAULT_COLORS.data1,DEFAULT_COLORS.data2],markers:true});
|
|
235
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export {
|
|
2
|
+
SAMPLE_COUNT,
|
|
3
|
+
SAMPLE_INTERVAL_MS,
|
|
4
|
+
PARAMETER_BYTES,
|
|
5
|
+
SERIAL_OPTIONS,
|
|
6
|
+
validateParameters,
|
|
7
|
+
encodeParameters,
|
|
8
|
+
encodeCommand,
|
|
9
|
+
parseSampleLine,
|
|
10
|
+
} from "./protocol.js";
|
|
11
|
+
export { LineDecoder } from "./line-decoder.js";
|
|
12
|
+
export { WebSerialTransport } from "./web-serial-transport.js";
|
|
13
|
+
export { NMRDevice } from "./device.js";
|
|
14
|
+
export { correctBaseline } from "./baseline.js";
|
|
15
|
+
export { computeSpectrum } from "./fft.js";
|
|
16
|
+
export { analyzeMeasurement } from "./analysis.js";
|
|
17
|
+
export { NMRController } from "./controller.js";
|
|
18
|
+
export { parseMeasurement } from "./record.js";
|
|
19
|
+
export { frequencySteps, evaluateFrequency, runFrequencySweep } from "./frequency-sweep.js";
|
|
20
|
+
export { pulseSteps, evaluatePulse, runPulseSweep, analyzePulseCalibration } from "./pulse-sweep.js";
|
|
21
|
+
export { signedPulseCandidates, fitPulseCalibration } from "./pulse-fit.js";
|
|
22
|
+
export { parsePulseCalibration, MAX_PULSE_JSON_BYTES } from "./pulse-record.js";
|
|
23
|
+
export { parseFrequencySweep, MAX_FREQUENCY_JSON_BYTES } from "./frequency-record.js";
|
|
24
|
+
export { t1Delays, t1Parameters, evaluateT1, runT1Sweep, analyzeT1 } from "./t1-sweep.js";
|
|
25
|
+
export { fitT1 } from "./relaxation-fit.js";
|
|
26
|
+
export { parseT1Measurement, MAX_T1_JSON_BYTES } from "./t1-record.js";
|
|
27
|
+
export { measurementDurationMs } from "./timing.js";
|
|
28
|
+
export { t2Delays, t2Parameters, t2Window, evaluateT2, runT2Sweep, analyzeT2 } from "./t2-sweep.js";
|
|
29
|
+
export { fitT2 } from "./relaxation-fit.js";
|
|
30
|
+
export { parseT2Measurement, MAX_T2_JSON_BYTES } from "./t2-record.js";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Assemble ASCII protocol lines from arbitrary serial byte chunks.
|
|
3
|
+
* Keeps only the incomplete line; complete lines are returned to the caller.
|
|
4
|
+
*/
|
|
5
|
+
export class LineDecoder {
|
|
6
|
+
constructor({ maxLineBytes = 65536 } = {}) {
|
|
7
|
+
if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
|
|
8
|
+
throw new RangeError("maxLineBytes must be a positive safe integer.");
|
|
9
|
+
}
|
|
10
|
+
this.maxLineBytes = maxLineBytes;
|
|
11
|
+
this.partial = "";
|
|
12
|
+
this.failed = false;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
push(bytes) {
|
|
16
|
+
if (this.failed) {
|
|
17
|
+
throw new Error("Decoder failed; reset it only after communication is resynchronized.");
|
|
18
|
+
}
|
|
19
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
20
|
+
throw new TypeError("Serial input must be a Uint8Array.");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const lines = [];
|
|
24
|
+
for (const byte of bytes) {
|
|
25
|
+
if (byte > 0x7f) {
|
|
26
|
+
this.failed = true;
|
|
27
|
+
throw new Error("Non-ASCII byte in controller response.");
|
|
28
|
+
}
|
|
29
|
+
if (byte === 0x0a) {
|
|
30
|
+
lines.push(this.partial.replace(/\r$/, ""));
|
|
31
|
+
this.partial = "";
|
|
32
|
+
} else {
|
|
33
|
+
this.partial += String.fromCharCode(byte);
|
|
34
|
+
if (this.partial.length > this.maxLineBytes) {
|
|
35
|
+
this.failed = true;
|
|
36
|
+
throw new Error("Controller response line exceeds maxLineBytes.");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return lines;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Call when the input stream ends, to detect truncated responses. */
|
|
44
|
+
finish() {
|
|
45
|
+
if (this.failed || this.partial.length !== 0) {
|
|
46
|
+
this.failed = true;
|
|
47
|
+
throw new Error("Input ended with an invalid or incomplete response.");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Discard state only at a known protocol boundary, such as reconnection. */
|
|
52
|
+
reset() {
|
|
53
|
+
this.partial = "";
|
|
54
|
+
this.failed = false;
|
|
55
|
+
}
|
|
56
|
+
}
|
package/src/protocol.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/** Wire format used by the prototype controller. See docs/PROTOCOL.md. */
|
|
2
|
+
export const SAMPLE_COUNT = 2048;
|
|
3
|
+
export const SAMPLE_INTERVAL_MS = 0.02;
|
|
4
|
+
export const PARAMETER_BYTES = 18;
|
|
5
|
+
|
|
6
|
+
export const SERIAL_OPTIONS = Object.freeze({
|
|
7
|
+
baudRate: 115200,
|
|
8
|
+
dataBits: 8,
|
|
9
|
+
stopBits: 1,
|
|
10
|
+
parity: "none",
|
|
11
|
+
flowControl: "none",
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
// These are PoC input/encoding limits, not certified hardware safety limits.
|
|
15
|
+
const INTEGER_RANGES = {
|
|
16
|
+
frequencyHz: [1, 2147483647],
|
|
17
|
+
pulse1Cycles: [0, 32767],
|
|
18
|
+
pulse2Cycles: [0, 32767],
|
|
19
|
+
pulseIntervalMs: [0, 32767],
|
|
20
|
+
measurementIntervalMs: [1, 32767],
|
|
21
|
+
scans: [1, 32767],
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @typedef {Object} MeasurementParameters
|
|
26
|
+
* @property {number} frequencyHz Value sent unchanged to the controller.
|
|
27
|
+
* @property {number} pulse1Cycles RF cycle count, not microseconds.
|
|
28
|
+
* @property {number} phase1Degrees One of 0, 90, 180, 270.
|
|
29
|
+
* @property {number} pulse2Cycles RF cycle count, not microseconds.
|
|
30
|
+
* @property {number} phase2Degrees One of 0, 90, 180, 270.
|
|
31
|
+
* @property {number} pulseIntervalMs Inter-pulse delay.
|
|
32
|
+
* @property {number} measurementIntervalMs Controller interval setting.
|
|
33
|
+
* @property {number} scans Acquisition count.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** Validate and copy only the supported fields. @param {MeasurementParameters} input */
|
|
37
|
+
export function validateParameters(input) {
|
|
38
|
+
if (input === null || typeof input !== "object" || Array.isArray(input)) {
|
|
39
|
+
throw new TypeError("Measurement parameters must be an object.");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const parameters = {};
|
|
43
|
+
for (const [name, [minimum, maximum]] of Object.entries(INTEGER_RANGES)) {
|
|
44
|
+
const value = input[name];
|
|
45
|
+
if (!Number.isInteger(value) || value < minimum || value > maximum) {
|
|
46
|
+
throw new RangeError(`${name} must be an integer from ${minimum} to ${maximum}.`);
|
|
47
|
+
}
|
|
48
|
+
parameters[name] = value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (const name of ["phase1Degrees", "phase2Degrees"]) {
|
|
52
|
+
if (![0, 90, 180, 270].includes(input[name])) {
|
|
53
|
+
throw new RangeError(`${name} must be 0, 90, 180, or 270.`);
|
|
54
|
+
}
|
|
55
|
+
parameters[name] = input[name];
|
|
56
|
+
}
|
|
57
|
+
return parameters;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Encode Python struct.pack('<i7h', ...), little endian. */
|
|
61
|
+
export function encodeParameters(input) {
|
|
62
|
+
const parameters = validateParameters(input);
|
|
63
|
+
const bytes = new Uint8Array(PARAMETER_BYTES);
|
|
64
|
+
const view = new DataView(bytes.buffer);
|
|
65
|
+
view.setInt32(0, parameters.frequencyHz, true);
|
|
66
|
+
|
|
67
|
+
// The firmware phase code advances in 45-degree units.
|
|
68
|
+
const shortValues = [
|
|
69
|
+
parameters.pulse1Cycles,
|
|
70
|
+
parameters.phase1Degrees / 45,
|
|
71
|
+
parameters.pulse2Cycles,
|
|
72
|
+
parameters.phase2Degrees / 45,
|
|
73
|
+
parameters.pulseIntervalMs,
|
|
74
|
+
parameters.measurementIntervalMs,
|
|
75
|
+
parameters.scans,
|
|
76
|
+
];
|
|
77
|
+
shortValues.forEach((value, index) => {
|
|
78
|
+
view.setInt16(4 + index * 2, value, true);
|
|
79
|
+
});
|
|
80
|
+
return bytes;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Return a fresh command buffer; parameter setup deliberately has no CRLF. */
|
|
84
|
+
export function encodeCommand(command) {
|
|
85
|
+
const commands = {
|
|
86
|
+
parameters: [0x50],
|
|
87
|
+
single: [0x73, 0x0d, 0x0a],
|
|
88
|
+
double: [0x64, 0x0d, 0x0a],
|
|
89
|
+
read: [0x72, 0x0d, 0x0a],
|
|
90
|
+
};
|
|
91
|
+
if (!Object.hasOwn(commands, command)) {
|
|
92
|
+
throw new RangeError(`Unsupported command: ${command}`);
|
|
93
|
+
}
|
|
94
|
+
return new Uint8Array(commands[command]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Decode one complete channel-pair line. Invalid data is never replaced by zero. */
|
|
98
|
+
export function parseSampleLine(line) {
|
|
99
|
+
if (typeof line !== "string" || !/^-?\d+,-?\d+$/.test(line.trim())) {
|
|
100
|
+
throw new TypeError("Expected two comma-separated signed integers.");
|
|
101
|
+
}
|
|
102
|
+
const sample = line.trim().split(",").map(Number);
|
|
103
|
+
if (!sample.every(Number.isSafeInteger)) {
|
|
104
|
+
throw new RangeError("Sample exceeds the safe integer range.");
|
|
105
|
+
}
|
|
106
|
+
return sample;
|
|
107
|
+
}
|