nmrlink 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -159,3 +159,9 @@ try {
159
159
  ```
160
160
 
161
161
  `analyzePulseCalibration`・`analyzeT1`・`analyzeT2` は `warnings` の文字列配列を維持し、文は英語で返します。追加の `warningDetails` は同じ順序の `{ code, message, details }` 配列です。警告の翻訳にもコードを使います。グラフの `locale` はエラー・警告を翻訳しません。[エラーコードと警告の説明](https://masabando.github.io/nmrlink/reference/api/#error-codes)も参照してください。
162
+
163
+ ### 任意のローパスフィルター
164
+
165
+ `analyzeMeasurement(record, { lowpassHz: 1000 })` で、ベースライン補正後に2次Butterworthを前後方向へ適用します。カットオフは全処理後の−3 dB周波数です。先頭の送信過渡を除くため、FFT開始時刻から取得末尾までを処理し、それ以前の表示データは未処理のまま残します。未指定または `null` は従来の解析です。rawは変更せず、data・spectrumがフィルター後、baseline.dataがフィルター前です。lowpassにはカットオフ・開始時刻・方式・パディング・処理区間のデータを返します。
166
+
167
+ `lowpassFilter(data, { sampleIntervalMs, cutoffHz })` は、渡された2チャンネルの全配列を同一係数で処理し、新しいdataと条件を返す独立関数です。4点以上のデータと、0より大きくナイキスト周波数未満のカットオフが必要です。狭いLPFは信号自体も減衰させ、端点の波形に影響します。受信基準を共鳴に近づけ、未処理との比較で判断してください。
package/README.md CHANGED
@@ -157,3 +157,9 @@ try {
157
157
  MIT. Author: Masamitsu Bando. See the LICENSE file included in the package.
158
158
 
159
159
  The original Python program provided by Yasushi Kondo is also available under MIT in the repository's [`original/` directory](https://github.com/masabando/nmrlink/tree/main/original), with its own copyright notice. It is not included in this npm package.
160
+
161
+ ### Optional low-pass filtering
162
+
163
+ `analyzeMeasurement(record, { lowpassHz: 1000 })` applies a second-order Butterworth filter forward and backward after baseline correction. The cutoff is the final −3 dB frequency. Filtering starts at the FFT start and continues to the acquisition end, excluding earlier transmit transients; earlier waveform samples remain unfiltered. Omitting `lowpassHz` or using `null` preserves the original analysis. Raw samples are never modified. Filtered output is in `data` and `spectrum`; `baseline.data` remains unfiltered. `lowpass` records the cutoff, start, method, padding and filtered segment.
164
+
165
+ The standalone `lowpassFilter(data, { sampleIntervalMs, cutoffHz })` filters the entire supplied two-channel array and returns a new `data` array and metadata. Both channels use the same coefficients. It requires at least four samples and a positive cutoff below Nyquist. Narrow filtering can attenuate resonance and distort waveform endpoints; tune the receiver reference close to resonance and compare with unfiltered data before interpreting amplitudes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nmrlink",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "JavaScript library for educational NMR hardware control via Web Serial, signal analysis, and SVG graphs.",
5
5
  "type": "module",
6
6
  "keywords": [
package/src/analysis.js CHANGED
@@ -1,14 +1,28 @@
1
1
  import { correctBaseline } from "./baseline.js";
2
+ import { lowpassFilter } from "./lowpass.js";
2
3
  import { computeSpectrum } from "./fft.js";
3
4
 
4
5
  /** Common analysis pipeline. The acquired record is never modified. */
5
6
  export function analyzeMeasurement(record, {
6
- startMs = 1, endMs = 5, tailPoints = 100, truncate = true, window = "hann",
7
+ startMs = 1, endMs = 5, tailPoints = 100, truncate = true, window = "hann", lowpassHz = null,
7
8
  } = {}) {
8
9
  const baseline = correctBaseline(record.raw, { tailPoints, truncate });
9
- const spectrum = computeSpectrum(baseline.data, {
10
+ // Validate the FFT interval before using its start as the transient exclusion.
11
+ const unfilteredSpectrum = computeSpectrum(baseline.data, {
10
12
  sampleIntervalMs: record.sampleIntervalMs, startMs, endMs, window,
11
13
  });
14
+ const startIndex = Math.round(unfilteredSpectrum.actualStartMs / record.sampleIntervalMs);
15
+ const lowpass = lowpassHz === null ? null : {
16
+ ...lowpassFilter(baseline.data.slice(startIndex), {
17
+ sampleIntervalMs: record.sampleIntervalMs, cutoffHz: lowpassHz,
18
+ }),
19
+ startMs: unfilteredSpectrum.actualStartMs,
20
+ };
21
+ // The pre-start waveform remains unfiltered, and is outside the FFT interval.
22
+ const data = lowpass ? [...baseline.data.slice(0, startIndex), ...lowpass.data] : baseline.data;
23
+ const spectrum = lowpass ? computeSpectrum(data, {
24
+ sampleIntervalMs: record.sampleIntervalMs, startMs, endMs, window,
25
+ }) : unfilteredSpectrum;
12
26
  const peak = spectrum.bins.reduce((maximum, bin) => bin.amplitude > maximum.amplitude ? bin : maximum);
13
- return { data: baseline.data, baseline, spectrum, peak };
27
+ return { data, baseline, spectrum, peak, ...(lowpass ? { lowpass } : {}) };
14
28
  }
package/src/errors.js CHANGED
@@ -19,6 +19,7 @@ const messages = Object.freeze({
19
19
  "INVALID_PNG_SCALE": "PNG scale must be greater than zero and at most 4.",
20
20
  "INVALID_PNG_DIMENSIONS": "PNG dimensions must be positive and within 8192 pixels and 16 megapixels.",
21
21
  "INVALID_FFT_RANGE": "FFT range must satisfy 0 <= startMs < endMs <= acquisition duration, with a positive sampleIntervalMs.",
22
+ "INVALID_LOWPASS": "LPF requires finite sampling and cutoff values, 0 < cutoffHz < Nyquist, and at least four samples.",
22
23
  "INVALID_WINDOW": "Window must be hann or rect.",
23
24
  "INSUFFICIENT_FFT_SAMPLES": "FFT requires at least four selected samples.",
24
25
  "INVALID_BASELINE_TAIL": "tailPoints must be an integer from 1 to the sample count.",
package/src/graphs.js CHANGED
@@ -18,7 +18,7 @@ function lineColors(options = {}) {
18
18
  const escapeAttribute = value => value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
19
19
 
20
20
  /** Build a responsive SVG. All plotted values come from validated numeric data. */
21
- function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null }) {
21
+ function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null, annotation = null, hiddenSeries = [] }) {
22
22
  const height = 280;
23
23
  const margin = { left: 68, right: 20, top: 20, bottom: 52 };
24
24
  const plotWidth = width - margin.left - margin.right;
@@ -36,6 +36,7 @@ function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative =
36
36
  const yPosition = value => margin.top + (yMaximum - value) / (yMaximum - yMinimum) * plotHeight;
37
37
  const format = value => Math.abs(value) >= 10000 ? value.toExponential(1) : Number(value.toPrecision(4)).toString();
38
38
  const elements = [];
39
+ if (annotation) elements.push(`<text x="${margin.left}" y="12" style="font-size:10px">${escapeAttribute(annotation)}</text>`);
39
40
 
40
41
  for (let tick = 0; tick <= 4; tick++) {
41
42
  const x = xMinimum + (xMaximum - xMinimum) * tick / 4;
@@ -53,6 +54,7 @@ function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative =
53
54
  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>`);
54
55
  }
55
56
  series.forEach((points, index) => {
57
+ if (hiddenSeries?.[index]) return;
56
58
  const coordinates = points.map(([x, y]) => `${xPosition(x).toFixed(2)},${yPosition(y).toFixed(2)}`).join(" ");
57
59
  elements.push(`<polyline points="${coordinates}" fill="none" stroke="${escapeAttribute(colors[index])}" stroke-width="1.5" stroke-linejoin="round" clip-path="url(#${clipId})"/>`);
58
60
  if (markers && index === 0) for (const [x, y] of points) {
@@ -65,23 +67,25 @@ function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative =
65
67
  }
66
68
 
67
69
  /** Analyze without modifying record.raw; share the same pipeline in browser/tests. */
68
- export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {}, locale = "ja", labels = {} } = {}) {
70
+ export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {}, locale = "ja", labels = {}, fftSeries = null } = {}) {
69
71
  if (!Number.isFinite(width) || width < 160) throw createError(RangeError, "INVALID_PLOT_WIDTH");
70
72
  if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw createError(TypeError, "INVALID_SVG_PREFIX");
71
73
  if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw createError(RangeError, "INVALID_DISPLAY_LIMITS");
72
74
  const palette = lineColors(colors);
73
75
  const text = resolveRecordLabels(locale, labels);
74
76
  const { data, spectrum, peak } = analysis;
77
+ const annotation = analysis.lowpass ? `LPF ${analysis.lowpass.cutoffHz} Hz (−3 dB), t ≥ ${analysis.lowpass.startMs} ms` : null;
75
78
  const endMs = Math.min(displayEndMs, data.length * record.sampleIntervalMs);
76
79
  const displayed = data.slice(0, Math.ceil(endMs / record.sampleIntervalMs - 1e-9));
77
80
  const channels = [0, 1].map(channel => displayed.map((pair, index) => [index * record.sampleIntervalMs, pair[channel]]));
78
81
  const visibleBins = spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz);
79
82
  const displayLimit = Math.min(frequencyLimitHz, 500 / record.sampleIntervalMs);
80
83
  return {
81
- fid: plot(channels, { ...text.fid, xMinimum: 0, xMaximum: endMs, scaleFrom: spectrum.actualStartMs, scaleUntil: spectrum.actualEndExclusiveMs, clipId: `${idPrefix}-fid`, width, selection: [spectrum.actualStartMs, spectrum.actualEndExclusiveMs], colors: [palette.data1, palette.data2] }),
82
- fft: plot([visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
83
- ...text.fft,
84
- xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: [palette.fft],
84
+ fid: plot(channels, { ...text.fid, annotation, xMinimum: 0, xMaximum: endMs, scaleFrom: spectrum.actualStartMs, scaleUntil: spectrum.actualEndExclusiveMs, clipId: `${idPrefix}-fid`, width, selection: [spectrum.actualStartMs, spectrum.actualEndExclusiveMs], colors: [palette.data1, palette.data2] }),
85
+ fft: plot(fftSeries ? fftSeries.map(line => line.spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz).map(bin => [bin.hz / 1000, bin.amplitude])) : [visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
86
+ ...text.fft, annotation: fftSeries ? fftSeries.filter(line => !line.hidden).map(line => line.label).join(" / ") : annotation,
87
+ hiddenSeries: fftSeries?.map(line => line.hidden),
88
+ xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: fftSeries ? fftSeries.map(line => line.color) : [palette.fft],
85
89
  }),
86
90
  peak,
87
91
  spectrum,
@@ -90,9 +94,10 @@ export function createRecordPlots(record, { width = 720, displayEndMs = 10, freq
90
94
 
91
95
  /** Browser graph view. Resize redraws the saved analysis, without remeasuring. */
92
96
  export class NMRGraphs {
93
- constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {}, locale = "ja", labels = {} }) {
97
+ constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {}, locale = "ja", labels = {}, fftSeries = null }) {
94
98
  if (!fid || !fft) throw createError(TypeError, "GRAPH_ELEMENTS_REQUIRED");
95
99
  Object.assign(this, { fid, fft, peakElement: peak, statusElement: status, displayEndMs, frequencyLimitHz });
100
+ this.fftSeries = fftSeries;
96
101
  this.colors = lineColors(colors);
97
102
  this.labels = resolveRecordLabels(locale, labels);
98
103
  this.locale = locale;
@@ -125,7 +130,7 @@ export class NMRGraphs {
125
130
  const style = getComputedStyle(element);
126
131
  return Math.max(160, element.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
127
132
  };
128
- const options = { analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors, locale: this.locale, labels: this.labels };
133
+ const options = { fftSeries: this.fftSeries, analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors, locale: this.locale, labels: this.labels };
129
134
  const fid = createRecordPlots(record, { ...options, width: widthOf(this.fid) });
130
135
  const fft = createRecordPlots(record, { ...options, width: widthOf(this.fft) });
131
136
  this.fid.innerHTML = fid.fid;
package/src/index.js CHANGED
@@ -11,6 +11,7 @@ export {
11
11
  export { LineDecoder } from "./line-decoder.js";
12
12
  export { WebSerialTransport } from "./web-serial-transport.js";
13
13
  export { NMRDevice } from "./device.js";
14
+ export { lowpassFilter } from "./lowpass.js";
14
15
  export { correctBaseline } from "./baseline.js";
15
16
  export { computeSpectrum } from "./fft.js";
16
17
  export { analyzeMeasurement } from "./analysis.js";
package/src/lowpass.js ADDED
@@ -0,0 +1,43 @@
1
+ import { validateSamples } from './sample-validation.js';
2
+ import { createError } from './errors.js';
3
+
4
+ /** Offline LPF: second-order Butterworth in each direction, with odd reflection.
5
+ * cutoffHz is the FINAL -3.0103 dB frequency after both passes, in Hz.
6
+ * Each channel uses identical coefficients. Input samples are never modified.
7
+ */
8
+ export function lowpassFilter(data, { sampleIntervalMs, cutoffHz }) {
9
+ validateSamples(data);
10
+ const sampleRate = 1000 / sampleIntervalMs;
11
+ if (!Number.isFinite(sampleRate) || sampleRate <= 0 || !Number.isFinite(cutoffHz) || cutoffHz <= 0 || cutoffHz >= sampleRate / 2 || data.length < 4) {
12
+ throw createError(RangeError, 'INVALID_LOWPASS');
13
+ }
14
+ // Bilinear prewarping compensates for the squared response of two passes.
15
+ const k = Math.tan(Math.PI * cutoffHz / sampleRate) / (Math.SQRT2 - 1) ** 0.25;
16
+ const norm = 1 / (1 + Math.SQRT2 * k + k * k);
17
+ const b0 = k * k * norm, b1 = 2 * b0, b2 = b0;
18
+ const a1 = 2 * (k * k - 1) * norm;
19
+ const a2 = (1 - Math.SQRT2 * k + k * k) * norm;
20
+ const padding = Math.min(data.length - 1, Math.ceil(3 * sampleRate / cutoffHz));
21
+ function pass(values) {
22
+ // Steady-state initialization for the first value avoids a DC startup step.
23
+ let z1 = (1 - b0) * values[0], z2 = (b2 - a2) * values[0];
24
+ return values.map(x => {
25
+ const y = b0 * x + z1;
26
+ z1 = b1 * x - a1 * y + z2;
27
+ z2 = b2 * x - a2 * y;
28
+ if (!Number.isFinite(y)) throw createError(RangeError, 'INVALID_LOWPASS');
29
+ return y;
30
+ });
31
+ }
32
+ const channels = [0, 1].map(channel => {
33
+ const values = data.map(pair => pair[channel]);
34
+ const left = Array.from({ length: padding }, (_, i) => 2 * values[0] - values[padding - i]);
35
+ const right = Array.from({ length: padding }, (_, i) => 2 * values.at(-1) - values[values.length - 2 - i]);
36
+ const forward = pass([...left, ...values, ...right]);
37
+ return pass(forward.reverse()).reverse().slice(padding, padding + values.length);
38
+ });
39
+ return {
40
+ data: data.map((_, i) => [channels[0][i], channels[1][i]]),
41
+ cutoffHz, method: 'butterworth-2-forward-backward', paddingSamples: padding,
42
+ };
43
+ }