nmrlink 0.1.3 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +161 -0
- package/README.md +70 -42
- package/package.json +2 -1
- package/src/baseline.js +5 -4
- package/src/browser.js +15 -11
- package/src/controller.js +8 -6
- package/src/device.js +14 -12
- package/src/errors.js +187 -0
- package/src/fft.js +6 -5
- package/src/frequency-record.js +8 -7
- package/src/frequency-sweep.js +3 -2
- package/src/graph-labels.js +88 -0
- package/src/graphs.js +51 -43
- package/src/index.js +1 -0
- package/src/line-decoder.js +7 -6
- package/src/protocol.js +7 -6
- package/src/pulse-fit.js +13 -12
- package/src/pulse-record.js +10 -9
- package/src/pulse-sweep.js +10 -9
- package/src/record.js +10 -9
- package/src/relaxation-fit.js +10 -9
- package/src/sample-validation.js +3 -2
- package/src/signed-signal.js +10 -9
- package/src/sweep.js +4 -3
- package/src/t1-record.js +10 -9
- package/src/t1-sweep.js +12 -11
- package/src/t2-record.js +10 -9
- package/src/t2-sweep.js +15 -14
- package/src/timing.js +2 -1
- package/src/web-serial-transport.js +19 -17
package/README.ja.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# nmrlink
|
|
2
|
+
|
|
3
|
+
[English](https://github.com/masabando/nmrlink/blob/main/packages/nmrlink/README.md) | 日本語
|
|
4
|
+
|
|
5
|
+
[近藤 康(近畿大学)](https://researchmap.jp/kondo_yasushi)が開発を進めてきた学生実験用のNMR装置を制御するJavaScriptライブラリです。Web Serial APIによる接続、測定データの解析、グラフ表示を自分のWeb UIに組み込めます。
|
|
6
|
+
|
|
7
|
+
[ドキュメント](https://masabando.github.io/nmrlink/) · [API](https://masabando.github.io/nmrlink/reference/api/) · [標準Web UI](https://masabando.github.io/nmrlink/ui/?lang=ja) · [GitHub](https://github.com/masabando/nmrlink)
|
|
8
|
+
|
|
9
|
+
## 対象装置と入手について
|
|
10
|
+
|
|
11
|
+
実際の測定には、対応する学生実験用NMR装置が必要です。一般のNMR装置を共通に制御するライブラリではありません。実機なしでも、模擬データによる表示や操作のデモを試せます。
|
|
12
|
+
|
|
13
|
+
装置は教材販売会社を通じての販売が計画されています。
|
|
14
|
+
|
|
15
|
+
## 導入
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install nmrlink
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
ビルドなしの静的HTMLから使う方法は[導入ガイド](https://masabando.github.io/nmrlink/guide/install/)を参照してください。
|
|
22
|
+
|
|
23
|
+
## 対応環境と配布内容
|
|
24
|
+
|
|
25
|
+
- 実機の直接接続にはWeb Serial対応デスクトップブラウザとHTTPSまたは同じPCのlocalhostが必要です。接続する装置はNMRLinkの通信仕様に対応している必要があります。
|
|
26
|
+
- ES modules形式のJavaScriptを提供します。CommonJS形式とTypeScript型定義は含みません。
|
|
27
|
+
- ライブラリ自体の実行時依存パッケージはありません。Node.jsから解析やSVG生成を使う場合にDOMは不要です。
|
|
28
|
+
- パッケージには読みやすい `src/`、このREADME、MITライセンスを含みます。ソースは圧縮・難読化していません。
|
|
29
|
+
|
|
30
|
+
ブラウザアプリのViteなどのバンドラー環境ではパッケージ名でimportします。素のHTMLではimport mapか、ソースへの相対URLが必要です。[ビルドなしで使う方法](https://masabando.github.io/nmrlink/guide/install/)も参照してください。
|
|
31
|
+
|
|
32
|
+
## 自分のWeb UIから測定する
|
|
33
|
+
|
|
34
|
+
次の例はバンドラー環境のブラウザ用コードです。HTMLに接続・測定・切断・保存ボタン、状態欄、2つのグラフ表示先を用意します。
|
|
35
|
+
|
|
36
|
+
```html
|
|
37
|
+
<button id="connect">接続</button>
|
|
38
|
+
<button id="measure" disabled>測定</button>
|
|
39
|
+
<button id="disconnect" disabled>切断</button>
|
|
40
|
+
<button id="save" disabled>生データJSONを保存</button>
|
|
41
|
+
<p id="status" role="status">未接続</p>
|
|
42
|
+
<div id="fid"></div>
|
|
43
|
+
<div id="fft"></div>
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { NMRController, analyzeMeasurement } from "nmrlink";
|
|
48
|
+
import { NMRGraphs } from "nmrlink/graphs";
|
|
49
|
+
import { saveMeasurement } from "nmrlink/browser";
|
|
50
|
+
|
|
51
|
+
const get = id => document.getElementById(id);
|
|
52
|
+
const controller = new NMRController();
|
|
53
|
+
const graphs = new NMRGraphs({ fid: get("fid"), fft: get("fft") });
|
|
54
|
+
|
|
55
|
+
// 装置・試料に合わせて確認する値です。校正済みの値へ変更してください。
|
|
56
|
+
const parameters = {
|
|
57
|
+
frequencyHz: 402000,
|
|
58
|
+
pulse1Cycles: 21, phase1Degrees: 0,
|
|
59
|
+
pulse2Cycles: 42, phase2Degrees: 90,
|
|
60
|
+
pulseIntervalMs: 5, measurementIntervalMs: 200, scans: 128,
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
controller.onStateChange(state => {
|
|
64
|
+
get("connect").disabled = !state.canConnect;
|
|
65
|
+
get("measure").disabled = !state.canMeasure;
|
|
66
|
+
get("disconnect").disabled = !state.canDisconnect;
|
|
67
|
+
});
|
|
68
|
+
controller.onError(error => { get("status").textContent = error.message; });
|
|
69
|
+
controller.onResult(record => {
|
|
70
|
+
get("save").disabled = false;
|
|
71
|
+
try {
|
|
72
|
+
graphs.show(record, analyzeMeasurement(record));
|
|
73
|
+
get("status").textContent = "測定が完了しました。";
|
|
74
|
+
} catch (error) {
|
|
75
|
+
graphs.clear();
|
|
76
|
+
get("status").textContent = `解析できませんでした:${error.message}`;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// ポート選択はクリックから直接呼び出します。
|
|
81
|
+
get("connect").onclick = () => controller.connect();
|
|
82
|
+
get("measure").onclick = () => controller.measure(parameters, { mode: "single" });
|
|
83
|
+
get("disconnect").onclick = () => controller.disconnect();
|
|
84
|
+
get("save").onclick = () => {
|
|
85
|
+
if (controller.result) saveMeasurement(controller.result);
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
接続・測定のエラーは `onError` に通知され、操作は `{ ok, value, error }` を返します。低水準の `NMRDevice` はエラー時にrejectします。測定の自動再送や進行中の測定の即時停止は行いません。画面を破棄するときは、処理完了後に切断し、`graphs.dispose()` と `controller.dispose()` で監視を終了します。
|
|
90
|
+
|
|
91
|
+
## 実機なしで解析する
|
|
92
|
+
|
|
93
|
+
Node.jsまたはブラウザで実行できます。2チャンネルを複素信号として解析します。
|
|
94
|
+
|
|
95
|
+
```js
|
|
96
|
+
import { analyzeMeasurement } from "nmrlink";
|
|
97
|
+
import { createRecordPlots } from "nmrlink/graphs";
|
|
98
|
+
|
|
99
|
+
const record = {
|
|
100
|
+
source: "demo", acquiredAt: new Date().toISOString(),
|
|
101
|
+
mode: "single", parameters: null, points: 2048, sampleIntervalMs: 0.02,
|
|
102
|
+
raw: Array.from({ length: 2048 }, (_, index) => {
|
|
103
|
+
const t = index * 0.00002;
|
|
104
|
+
const amplitude = 1000 * Math.exp(-t / 0.003);
|
|
105
|
+
return [
|
|
106
|
+
amplitude * Math.cos(2 * Math.PI * 1200 * t),
|
|
107
|
+
amplitude * Math.sin(2 * Math.PI * 1200 * t),
|
|
108
|
+
];
|
|
109
|
+
}),
|
|
110
|
+
};
|
|
111
|
+
const analysis = analyzeMeasurement(record, { startMs: 1, endMs: 5 });
|
|
112
|
+
console.log(analysis.peak.hz); // 受信周波数からの差 [Hz]。FFTビン値。
|
|
113
|
+
const svg = createRecordPlots(record); // { fid, fft, ... }
|
|
114
|
+
console.log(svg.fid); // SVG文字列。Node.jsでも生成できます。
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## グラフの言語とラベル
|
|
118
|
+
|
|
119
|
+
グラフAPIは `locale: "ja"`(既定)と `"en"` に対応します。`labels` で指定した文字列だけ上書きでき、数値や単位の換算は行いません。
|
|
120
|
+
|
|
121
|
+
```js
|
|
122
|
+
const graphs = new NMRGraphs({
|
|
123
|
+
fid: fidElement, fft: fftElement,
|
|
124
|
+
locale: "en",
|
|
125
|
+
labels: { fid: { xLabel: "Time [ms]", yLabel: "Signal [a.u.]" } },
|
|
126
|
+
});
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
NMRGraphs・createRecordPlotsはlabels.fid / labels.fft、曲線関数はlabels直下にtitle・xLabel・yLabelを指定します。省略した項目は選択言語の既定値を使います。詳しい文言・テンプレートの指定は[APIリファレンス](https://masabando.github.io/nmrlink/reference/api/)を参照してください。
|
|
130
|
+
|
|
131
|
+
## import先
|
|
132
|
+
|
|
133
|
+
| 入口 | 主な機能 |
|
|
134
|
+
| --- | --- |
|
|
135
|
+
| `nmrlink` | NMRDevice、NMRController、条件検証、補正・FFT、走査、T1/T2解析、保存JSONの解析 |
|
|
136
|
+
| `nmrlink/graphs` | NMRGraphs、createRecordPlots、周波数・パルス・T1/T2のSVG生成 |
|
|
137
|
+
| `nmrlink/browser` | JSON・PNGの保存、測定JSONの読み込み、JSTファイル名の日時書式 |
|
|
138
|
+
|
|
139
|
+
[グラフの表示例とコピー用コード](https://masabando.github.io/nmrlink/guide/graphs/)や[APIリファレンス](https://masabando.github.io/nmrlink/reference/api/)から用途別に確認できます。
|
|
140
|
+
|
|
141
|
+
## ライセンス
|
|
142
|
+
|
|
143
|
+
MIT。作者:Masamitsu Bando。配布物内のLICENSEを参照してください。
|
|
144
|
+
|
|
145
|
+
GitHubの `original/` にある提供元のPythonプログラムもMITライセンスで公開しています。このnpmパッケージには含みません。
|
|
146
|
+
|
|
147
|
+
## エラーと警告
|
|
148
|
+
|
|
149
|
+
ライブラリが生成する例外は、英語の `message`、識別用の `code`、値を持つ `details` を持ちます。`TypeError`・`RangeError` などの種類は維持します。条件分岐やUIの翻訳には `nmrlink` から読み込める `ERROR_CODES`、またはコード文字列を使い、メッセージの文章を照合しないでください。操作境界で包んだブラウザ・OS由来の例外は `cause` に残ります。
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
try {
|
|
153
|
+
analyzeMeasurement(record, { startMs: 5, endMs: 1 });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
if (error.code === "INVALID_FFT_RANGE") {
|
|
156
|
+
// 画面の言語に合わせた案内を表示する。
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`analyzePulseCalibration`・`analyzeT1`・`analyzeT2` は `warnings` の文字列配列を維持し、文は英語で返します。追加の `warningDetails` は同じ順序の `{ code, message, details }` 配列です。警告の翻訳にもコードを使います。グラフの `locale` はエラー・警告を翻訳しません。[エラーコードと警告の説明](https://masabando.github.io/nmrlink/reference/api/#error-codes)も参照してください。
|
package/README.md
CHANGED
|
@@ -1,44 +1,42 @@
|
|
|
1
1
|
# nmrlink
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
English | [日本語](https://github.com/masabando/nmrlink/blob/main/packages/nmrlink/README.ja.md)
|
|
4
4
|
|
|
5
|
-
[
|
|
5
|
+
A JavaScript library for the educational NMR apparatus developed by [Yasushi Kondo (Kindai University)](https://researchmap.jp/kondo_yasushi). Add Web Serial connectivity, measurement control, signal analysis, and graphs to your own Web UI.
|
|
6
6
|
|
|
7
|
-
[
|
|
7
|
+
[Documentation](https://masabando.github.io/nmrlink/en/) · [API](https://masabando.github.io/nmrlink/en/reference/api/) · [Standard Web UI](https://masabando.github.io/nmrlink/ui/?lang=en) · [GitHub](https://github.com/masabando/nmrlink)
|
|
8
8
|
|
|
9
|
-
##
|
|
9
|
+
## Hardware
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
Real measurements require the supported educational NMR apparatus. NMRLink is specific to this apparatus; it is not a universal interface for NMR instruments. You can try analysis and graph generation with simulated data without hardware.
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Distribution of the apparatus through an educational equipment supplier is planned.
|
|
14
14
|
|
|
15
|
-
##
|
|
15
|
+
## Install
|
|
16
16
|
|
|
17
17
|
```sh
|
|
18
18
|
npm install nmrlink
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Use package imports with a browser bundler such as Vite. For static HTML without a build step, use an import map or relative URLs to the source modules; see the [installation guide](https://masabando.github.io/nmrlink/en/guide/install/).
|
|
22
22
|
|
|
23
|
-
##
|
|
23
|
+
## Requirements
|
|
24
24
|
|
|
25
|
-
-
|
|
26
|
-
- ES modules
|
|
27
|
-
-
|
|
28
|
-
-
|
|
25
|
+
- Direct hardware access requires a desktop browser with Web Serial support, HTTPS or localhost on the same PC, and a USB serial connection. See [browser support and connection troubleshooting](https://masabando.github.io/nmrlink/en/guide/browsers/).
|
|
26
|
+
- The package provides ES modules, with no runtime dependencies. CommonJS builds and TypeScript declarations are not included.
|
|
27
|
+
- Analysis and SVG generation also work in Node.js without a DOM.
|
|
28
|
+
- The package includes readable, unminified `src/` files, English and Japanese READMEs, and the MIT license.
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
## Measure from your own Web UI
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
次の例はバンドラー環境のブラウザ用コードです。HTMLに接続・測定・切断・保存ボタン、状態欄、2つのグラフ表示先を用意します。
|
|
32
|
+
This example runs in a browser with a bundler. Add buttons, a status field, and two graph containers to your HTML:
|
|
35
33
|
|
|
36
34
|
```html
|
|
37
|
-
<button id="connect"
|
|
38
|
-
<button id="measure" disabled
|
|
39
|
-
<button id="disconnect" disabled
|
|
40
|
-
<button id="save" disabled
|
|
41
|
-
<p id="status" role="status"
|
|
35
|
+
<button id="connect">Connect</button>
|
|
36
|
+
<button id="measure" disabled>Measure</button>
|
|
37
|
+
<button id="disconnect" disabled>Disconnect</button>
|
|
38
|
+
<button id="save" disabled>Save raw JSON</button>
|
|
39
|
+
<p id="status" role="status">Disconnected</p>
|
|
42
40
|
<div id="fid"></div>
|
|
43
41
|
<div id="fft"></div>
|
|
44
42
|
```
|
|
@@ -50,9 +48,9 @@ import { saveMeasurement } from "nmrlink/browser";
|
|
|
50
48
|
|
|
51
49
|
const get = id => document.getElementById(id);
|
|
52
50
|
const controller = new NMRController();
|
|
53
|
-
const graphs = new NMRGraphs({ fid: get("fid"), fft: get("fft") });
|
|
51
|
+
const graphs = new NMRGraphs({ fid: get("fid"), fft: get("fft"), locale: "en" });
|
|
54
52
|
|
|
55
|
-
//
|
|
53
|
+
// Check these settings for your apparatus and sample. Use calibrated values.
|
|
56
54
|
const parameters = {
|
|
57
55
|
frequencyHz: 402000,
|
|
58
56
|
pulse1Cycles: 21, phase1Degrees: 0,
|
|
@@ -70,14 +68,14 @@ controller.onResult(record => {
|
|
|
70
68
|
get("save").disabled = false;
|
|
71
69
|
try {
|
|
72
70
|
graphs.show(record, analyzeMeasurement(record));
|
|
73
|
-
get("status").textContent = "
|
|
71
|
+
get("status").textContent = "Measurement complete.";
|
|
74
72
|
} catch (error) {
|
|
75
73
|
graphs.clear();
|
|
76
|
-
get("status").textContent =
|
|
74
|
+
get("status").textContent = `Analysis failed: ${error.message}`;
|
|
77
75
|
}
|
|
78
76
|
});
|
|
79
77
|
|
|
80
|
-
//
|
|
78
|
+
// Request a port directly from a user click.
|
|
81
79
|
get("connect").onclick = () => controller.connect();
|
|
82
80
|
get("measure").onclick = () => controller.measure(parameters, { mode: "single" });
|
|
83
81
|
get("disconnect").onclick = () => controller.disconnect();
|
|
@@ -86,11 +84,11 @@ get("save").onclick = () => {
|
|
|
86
84
|
};
|
|
87
85
|
```
|
|
88
86
|
|
|
89
|
-
|
|
87
|
+
Connection and measurement errors are reported through `onError`; controller operations return `{ ok, value, error }`. The lower-level `NMRDevice` rejects on errors. Measurements are not automatically retried, and an active measurement cannot be stopped immediately. When removing the UI, wait for any operation to finish, disconnect, and call `graphs.dispose()` and `controller.dispose()` to release listeners.
|
|
90
88
|
|
|
91
|
-
##
|
|
89
|
+
## Analyze without hardware
|
|
92
90
|
|
|
93
|
-
Node.js
|
|
91
|
+
Run this example in Node.js or a browser. The two channels form a complex signal.
|
|
94
92
|
|
|
95
93
|
```js
|
|
96
94
|
import { analyzeMeasurement } from "nmrlink";
|
|
@@ -109,23 +107,53 @@ const record = {
|
|
|
109
107
|
}),
|
|
110
108
|
};
|
|
111
109
|
const analysis = analyzeMeasurement(record, { startMs: 1, endMs: 5 });
|
|
112
|
-
console.log(analysis.peak.hz); //
|
|
113
|
-
const svg = createRecordPlots(record); // { fid, fft, ... }
|
|
114
|
-
console.log(svg.fid); // SVG
|
|
110
|
+
console.log(analysis.peak.hz); // Offset from the receive frequency [Hz], at an FFT bin.
|
|
111
|
+
const svg = createRecordPlots(record, { locale: "en" }); // { fid, fft, ... }
|
|
112
|
+
console.log(svg.fid); // SVG string; also works in Node.js.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Graph language and labels
|
|
116
|
+
|
|
117
|
+
Graph APIs accept `locale: "ja"` (the default) or `"en"`. Override individual strings with `labels`; this does not convert numeric values or units.
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
const graphs = new NMRGraphs({
|
|
121
|
+
fid: fidElement, fft: fftElement,
|
|
122
|
+
locale: "en",
|
|
123
|
+
labels: { fid: { xLabel: "Time [ms]", yLabel: "Signal [a.u.]" } },
|
|
124
|
+
});
|
|
115
125
|
```
|
|
116
126
|
|
|
117
|
-
|
|
127
|
+
`NMRGraphs` and `createRecordPlots` use `labels.fid` and `labels.fft`. Curve functions accept `title`, `xLabel`, and `yLabel` directly within `labels`. Omitted labels use the selected language's defaults. See the [graph API](https://masabando.github.io/nmrlink/en/reference/api/graphs/) for all labels and templates.
|
|
128
|
+
|
|
129
|
+
## Entry points
|
|
118
130
|
|
|
119
|
-
|
|
|
131
|
+
| Import | Main features |
|
|
120
132
|
| --- | --- |
|
|
121
|
-
| `nmrlink` | NMRDevice
|
|
122
|
-
| `nmrlink/graphs` | NMRGraphs
|
|
123
|
-
| `nmrlink/browser` | JSON
|
|
133
|
+
| `nmrlink` | NMRDevice, NMRController, parameter validation, baseline correction, FFT, sweeps, T1/T2 analysis, saved JSON parsing |
|
|
134
|
+
| `nmrlink/graphs` | NMRGraphs, createRecordPlots, frequency/pulse/T1/T2 SVG plots |
|
|
135
|
+
| `nmrlink/browser` | JSON/PNG downloads, measurement JSON loading, JST filename timestamps |
|
|
136
|
+
|
|
137
|
+
See the [graph examples](https://masabando.github.io/nmrlink/en/guide/graphs/) and [API reference](https://masabando.github.io/nmrlink/en/reference/api/) for examples you can copy.
|
|
138
|
+
|
|
139
|
+
## Errors and warnings
|
|
140
|
+
|
|
141
|
+
Library-generated exceptions have an English `message`, a stable `code`, and structured `details`. They retain their error types, such as `TypeError` or `RangeError`. Use `ERROR_CODES` exported from `nmrlink`, or code strings, for branching and UI translation; do not match message text. Browser or OS exceptions wrapped at operation boundaries are preserved as `cause`.
|
|
142
|
+
|
|
143
|
+
```js
|
|
144
|
+
try {
|
|
145
|
+
analyzeMeasurement(record, { startMs: 5, endMs: 1 });
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (error.code === "INVALID_FFT_RANGE") {
|
|
148
|
+
// Show a message in the language of your UI.
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
124
152
|
|
|
125
|
-
|
|
153
|
+
`analyzePulseCalibration`, `analyzeT1`, and `analyzeT2` return English strings in `warnings` and corresponding `{ code, message, details }` entries in `warningDetails`, in the same order. Use codes to translate warnings as well. Graph `locale` does not translate errors or warnings. See [error codes and warnings](https://masabando.github.io/nmrlink/en/reference/api/#error-codes).
|
|
126
154
|
|
|
127
|
-
##
|
|
155
|
+
## License
|
|
128
156
|
|
|
129
|
-
MIT
|
|
157
|
+
MIT. Author: Masamitsu Bando. See the LICENSE file included in the package.
|
|
130
158
|
|
|
131
|
-
|
|
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.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nmrlink",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.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": [
|
|
@@ -37,6 +37,7 @@
|
|
|
37
37
|
"files": [
|
|
38
38
|
"src/",
|
|
39
39
|
"README.md",
|
|
40
|
+
"README.ja.md",
|
|
40
41
|
"LICENSE"
|
|
41
42
|
],
|
|
42
43
|
"main": "./src/index.js"
|
package/src/baseline.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { validateSamples } from "./sample-validation.js";
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -8,9 +9,9 @@ import { validateSamples } from "./sample-validation.js";
|
|
|
8
9
|
export function correctBaseline(raw, { tailPoints = 100, truncate = true } = {}) {
|
|
9
10
|
validateSamples(raw);
|
|
10
11
|
if (!Number.isSafeInteger(tailPoints) || tailPoints < 1 || tailPoints > raw.length) {
|
|
11
|
-
throw
|
|
12
|
+
throw createError(RangeError, "INVALID_BASELINE_TAIL");
|
|
12
13
|
}
|
|
13
|
-
if (typeof truncate !== "boolean") throw
|
|
14
|
+
if (typeof truncate !== "boolean") throw createError(TypeError, "INVALID_TRUNCATE");
|
|
14
15
|
|
|
15
16
|
const base = [0, 0];
|
|
16
17
|
for (let channel = 0; channel < 2; channel++) {
|
|
@@ -19,12 +20,12 @@ export function correctBaseline(raw, { tailPoints = 100, truncate = true } = {})
|
|
|
19
20
|
sum += raw[index][channel];
|
|
20
21
|
}
|
|
21
22
|
base[channel] = sum / tailPoints;
|
|
22
|
-
if (!Number.isFinite(base[channel])) throw
|
|
23
|
+
if (!Number.isFinite(base[channel])) throw createError(RangeError, "BASELINE_OVERFLOW");
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
const data = raw.map(pair => pair.map((value, channel) => {
|
|
26
27
|
const corrected = value - base[channel];
|
|
27
|
-
if (!Number.isFinite(corrected)) throw
|
|
28
|
+
if (!Number.isFinite(corrected)) throw createError(RangeError, "BASELINE_CORRECTION_OVERFLOW");
|
|
28
29
|
return truncate ? Math.trunc(corrected) : corrected;
|
|
29
30
|
}));
|
|
30
31
|
return { base, data, tailPoints, truncate };
|
package/src/browser.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import { createError, normalizeError } from "./errors.js";
|
|
1
2
|
import { parseMeasurement, MAX_MEASUREMENT_JSON_BYTES } from "./record.js";
|
|
2
3
|
|
|
3
4
|
/** Format an acquisition instant in Japan time, independent of the browser's timezone. */
|
|
4
5
|
export function formatFileTimestamp(acquiredAt) {
|
|
5
6
|
const date = new Date(acquiredAt);
|
|
6
7
|
if (typeof acquiredAt !== "string" || !Number.isFinite(date.getTime())) {
|
|
7
|
-
throw
|
|
8
|
+
throw createError(TypeError, "INVALID_FILENAME_TIME");
|
|
8
9
|
}
|
|
9
10
|
const formatter = new Intl.DateTimeFormat("en-GB", {
|
|
10
11
|
timeZone: "Asia/Tokyo", year: "numeric", month: "2-digit", day: "2-digit",
|
|
@@ -17,7 +18,7 @@ export function formatFileTimestamp(acquiredAt) {
|
|
|
17
18
|
|
|
18
19
|
/** Download an unmodified record as readable JSON. Browser-only utility. */
|
|
19
20
|
export function saveMeasurement(record) {
|
|
20
|
-
if (!record) throw
|
|
21
|
+
if (!record) throw createError(TypeError, "RECORD_REQUIRED");
|
|
21
22
|
const blob = new Blob([JSON.stringify(record, null, 2) + "\n"], { type: "application/json" });
|
|
22
23
|
const url = URL.createObjectURL(blob);
|
|
23
24
|
const link = document.createElement("a");
|
|
@@ -30,16 +31,16 @@ export function saveMeasurement(record) {
|
|
|
30
31
|
/** Save an NMRGraphs SVG as an opaque PNG, at twice its SVG resolution by default. */
|
|
31
32
|
export async function saveGraphPng(svg, { filename = "nmrlink-graph.png", scale = 2 } = {}) {
|
|
32
33
|
if (svg?.localName !== "svg" || svg.namespaceURI !== "http://www.w3.org/2000/svg") {
|
|
33
|
-
throw
|
|
34
|
+
throw createError(TypeError, "SVG_REQUIRED");
|
|
34
35
|
}
|
|
35
36
|
if (!Number.isFinite(scale) || scale <= 0 || scale > 4) {
|
|
36
|
-
throw
|
|
37
|
+
throw createError(RangeError, "INVALID_PNG_SCALE");
|
|
37
38
|
}
|
|
38
39
|
const bounds = svg.viewBox.baseVal;
|
|
39
40
|
const width = Math.round(bounds.width * scale);
|
|
40
41
|
const height = Math.round(bounds.height * scale);
|
|
41
42
|
if (width < 1 || height < 1 || width > 8192 || height > 8192 || width * height > 16777216) {
|
|
42
|
-
throw
|
|
43
|
+
throw createError(RangeError, "INVALID_PNG_DIMENSIONS");
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
// Snapshot the current plot before awaiting image decoding or any later UI updates.
|
|
@@ -54,19 +55,19 @@ export async function saveGraphPng(svg, { filename = "nmrlink-graph.png", scale
|
|
|
54
55
|
const image = new Image();
|
|
55
56
|
await new Promise((resolve, reject) => {
|
|
56
57
|
image.onload = resolve;
|
|
57
|
-
image.onerror = () => reject(
|
|
58
|
+
image.onerror = () => reject(createError(Error, "PNG_IMAGE_LOAD_FAILED"));
|
|
58
59
|
image.src = sourceUrl;
|
|
59
60
|
});
|
|
60
61
|
const canvas = document.createElement("canvas");
|
|
61
62
|
canvas.width = width;
|
|
62
63
|
canvas.height = height;
|
|
63
64
|
const context = canvas.getContext("2d");
|
|
64
|
-
if (!context) throw
|
|
65
|
+
if (!context) throw createError(Error, "PNG_CANVAS_UNAVAILABLE");
|
|
65
66
|
context.fillStyle = "#ffffff";
|
|
66
67
|
context.fillRect(0, 0, width, height);
|
|
67
68
|
context.drawImage(image, 0, 0, width, height);
|
|
68
69
|
png = await new Promise((resolve, reject) => canvas.toBlob(
|
|
69
|
-
blob => blob ? resolve(blob) : reject(
|
|
70
|
+
blob => blob ? resolve(blob) : reject(createError(Error, "PNG_ENCODING_FAILED")), "image/png",
|
|
70
71
|
));
|
|
71
72
|
} finally {
|
|
72
73
|
URL.revokeObjectURL(sourceUrl);
|
|
@@ -86,8 +87,11 @@ export async function saveGraphPng(svg, { filename = "nmrlink-graph.png", scale
|
|
|
86
87
|
/** Read a local file only; parsing never opens a serial port or sends a command. */
|
|
87
88
|
export async function readMeasurement(file) {
|
|
88
89
|
if (!file || typeof file.text !== "function" || !Number.isFinite(file.size)) {
|
|
89
|
-
throw
|
|
90
|
+
throw createError(TypeError, "INVALID_RECORD_FILE");
|
|
90
91
|
}
|
|
91
|
-
if (file.size > MAX_MEASUREMENT_JSON_BYTES) throw
|
|
92
|
-
|
|
92
|
+
if (file.size > MAX_MEASUREMENT_JSON_BYTES) throw createError(RangeError, "RECORD_TOO_LARGE");
|
|
93
|
+
let text;
|
|
94
|
+
try { text = await file.text(); }
|
|
95
|
+
catch (error) { throw normalizeError(error); }
|
|
96
|
+
return parseMeasurement(text);
|
|
93
97
|
}
|
package/src/controller.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError, normalizeError } from "./errors.js";
|
|
1
2
|
import { NMRDevice } from "./device.js";
|
|
2
3
|
import { runFrequencySweep } from "./frequency-sweep.js";
|
|
3
4
|
import { runT2Sweep } from "./t2-sweep.js";
|
|
@@ -30,7 +31,7 @@ export class NMRController {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
subscribe(type, callback) {
|
|
33
|
-
if (this.disposed) throw
|
|
34
|
+
if (this.disposed) throw createError(Error, "CONTROLLER_DISPOSED");
|
|
34
35
|
this.listeners[type].add(callback);
|
|
35
36
|
return () => this.listeners[type].delete(callback);
|
|
36
37
|
}
|
|
@@ -48,7 +49,7 @@ export class NMRController {
|
|
|
48
49
|
try { listener(value); }
|
|
49
50
|
catch (error) {
|
|
50
51
|
// A UI/analysis error must not invalidate a successful hardware operation.
|
|
51
|
-
if (type !== "error") this.emit("error", error);
|
|
52
|
+
if (type !== "error") this.emit("error", normalizeError(error));
|
|
52
53
|
else console.error(error);
|
|
53
54
|
}
|
|
54
55
|
}
|
|
@@ -65,8 +66,8 @@ export class NMRController {
|
|
|
65
66
|
|
|
66
67
|
async run(operation, action) {
|
|
67
68
|
if (this.disposed || this.operation) {
|
|
68
|
-
const error =
|
|
69
|
-
this.emit("error", error);
|
|
69
|
+
const error = createError(Error, "CONTROLLER_BUSY");
|
|
70
|
+
this.emit("error", normalizeError(error));
|
|
70
71
|
return { ok: false, error };
|
|
71
72
|
}
|
|
72
73
|
this.operation = operation;
|
|
@@ -79,7 +80,8 @@ export class NMRController {
|
|
|
79
80
|
this.emit("result", value);
|
|
80
81
|
}
|
|
81
82
|
return { ok: true, value };
|
|
82
|
-
} catch (
|
|
83
|
+
} catch (cause) {
|
|
84
|
+
const error = normalizeError(cause);
|
|
83
85
|
this.emit("error", error);
|
|
84
86
|
return { ok: false, error };
|
|
85
87
|
} finally {
|
|
@@ -111,7 +113,7 @@ export class NMRController {
|
|
|
111
113
|
|
|
112
114
|
/** Stop UI monitoring only; never stop or disconnect the hardware implicitly. */
|
|
113
115
|
dispose() {
|
|
114
|
-
if (this.operation) throw
|
|
116
|
+
if (this.operation) throw createError(Error, "CONTROLLER_DISPOSE_BUSY");
|
|
115
117
|
clearInterval(this.timer);
|
|
116
118
|
this.disposed = true;
|
|
117
119
|
for (const listeners of Object.values(this.listeners)) listeners.clear();
|
package/src/device.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError, normalizeError } from "./errors.js";
|
|
1
2
|
import { encodeCommand, encodeParameters, validateParameters, parseSampleLine,
|
|
2
3
|
SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
|
|
3
4
|
import { measurementDurationMs } from "./timing.js";
|
|
@@ -14,7 +15,7 @@ export class NMRDevice {
|
|
|
14
15
|
constructor({ transport = new WebSerialTransport(), responseTimeoutMs = 5000,
|
|
15
16
|
dataTimeoutMs = 30000, measurementMarginMs = 20000 } = {}) {
|
|
16
17
|
for (const value of [responseTimeoutMs, dataTimeoutMs, measurementMarginMs]) {
|
|
17
|
-
if (!Number.isFinite(value) || value <= 0) throw
|
|
18
|
+
if (!Number.isFinite(value) || value <= 0) throw createError(RangeError, "INVALID_TIMEOUT");
|
|
18
19
|
}
|
|
19
20
|
this.transport = transport;
|
|
20
21
|
this.responseTimeoutMs = responseTimeoutMs;
|
|
@@ -35,7 +36,7 @@ export class NMRDevice {
|
|
|
35
36
|
set state(value) { this.currentState = value; }
|
|
36
37
|
|
|
37
38
|
async connect() {
|
|
38
|
-
if (this.busy || this.state !== "disconnected") throw
|
|
39
|
+
if (this.busy || this.state !== "disconnected") throw createError(Error, "DEVICE_ACTIVE");
|
|
39
40
|
this.busy = true;
|
|
40
41
|
this.state = "connecting";
|
|
41
42
|
try {
|
|
@@ -43,7 +44,7 @@ export class NMRDevice {
|
|
|
43
44
|
this.state = "connected";
|
|
44
45
|
} catch (error) {
|
|
45
46
|
this.state = "disconnected";
|
|
46
|
-
throw error;
|
|
47
|
+
throw normalizeError(error, "SERIAL_CONNECTION_FAILED");
|
|
47
48
|
} finally {
|
|
48
49
|
this.busy = false;
|
|
49
50
|
}
|
|
@@ -51,9 +52,10 @@ export class NMRDevice {
|
|
|
51
52
|
|
|
52
53
|
/** Disconnecting is not a firmware stop command. */
|
|
53
54
|
async disconnect() {
|
|
54
|
-
if (this.busy) throw
|
|
55
|
+
if (this.busy) throw createError(Error, "DISCONNECT_WHILE_BUSY");
|
|
55
56
|
this.busy = true;
|
|
56
57
|
try { await this.transport.disconnect(); }
|
|
58
|
+
catch (error) { throw normalizeError(error, "SERIAL_DISCONNECT_FAILED"); }
|
|
57
59
|
finally { this.state = "disconnected"; this.busy = false; }
|
|
58
60
|
}
|
|
59
61
|
|
|
@@ -65,9 +67,9 @@ export class NMRDevice {
|
|
|
65
67
|
async measure(input, { mode = "single" } = {}) {
|
|
66
68
|
// Invalid local input must not send commands or invalidate a good connection.
|
|
67
69
|
const parameters = validateParameters(input);
|
|
68
|
-
if (!["single", "double"].includes(mode)) throw
|
|
69
|
-
if (this.busy) throw
|
|
70
|
-
if (this.state !== "connected") throw
|
|
70
|
+
if (!["single", "double"].includes(mode)) throw createError(RangeError, "INVALID_MODE");
|
|
71
|
+
if (this.busy) throw createError(Error, "DEVICE_BUSY");
|
|
72
|
+
if (this.state !== "connected") throw createError(Error, "DEVICE_NOT_CONNECTED");
|
|
71
73
|
this.busy = true;
|
|
72
74
|
this.state = "measuring";
|
|
73
75
|
try {
|
|
@@ -85,7 +87,7 @@ export class NMRDevice {
|
|
|
85
87
|
const deadline = performance.now() + this.dataTimeoutMs;
|
|
86
88
|
for (let index = 0; index < SAMPLE_COUNT; index++) {
|
|
87
89
|
const remainingMs = deadline - performance.now();
|
|
88
|
-
if (remainingMs <= 0) throw
|
|
90
|
+
if (remainingMs <= 0) throw createError(Error, "SAMPLE_TRANSFER_TIMEOUT", { index, sampleCount: SAMPLE_COUNT });
|
|
89
91
|
const line = await this.transport.readLine(Math.min(remainingMs, this.responseTimeoutMs));
|
|
90
92
|
raw.push(parseSampleLine(line));
|
|
91
93
|
}
|
|
@@ -104,8 +106,8 @@ export class NMRDevice {
|
|
|
104
106
|
// the next operation. Require reconnection rather than retrying commands.
|
|
105
107
|
this.state = "disconnected";
|
|
106
108
|
try { await this.transport.disconnect(); }
|
|
107
|
-
catch (cleanupError) { throw
|
|
108
|
-
throw error;
|
|
109
|
+
catch (cleanupError) { throw createError(AggregateError, "MEASUREMENT_CLEANUP_FAILED", {}, { errors: [error, cleanupError] }); }
|
|
110
|
+
throw normalizeError(error);
|
|
109
111
|
} finally {
|
|
110
112
|
this.busy = false;
|
|
111
113
|
}
|
|
@@ -116,7 +118,7 @@ export class NMRDevice {
|
|
|
116
118
|
await this.transport.write(encodeCommand("parameters"));
|
|
117
119
|
await delay(50);
|
|
118
120
|
const acknowledgement = await this.response(this.responseTimeoutMs);
|
|
119
|
-
if (!acknowledgement.includes("CMD_P_OK")) throw
|
|
121
|
+
if (!acknowledgement.includes("CMD_P_OK")) throw createError(Error, "PARAMETER_SETUP_REJECTED");
|
|
120
122
|
await this.transport.write(encodeParameters(parameters));
|
|
121
123
|
await delay(50);
|
|
122
124
|
await this.response(this.responseTimeoutMs);
|
|
@@ -125,7 +127,7 @@ export class NMRDevice {
|
|
|
125
127
|
async response(timeoutMs) {
|
|
126
128
|
const line = (await this.transport.readLine(timeoutMs)).trim();
|
|
127
129
|
if (!line || /error|fail|reject/i.test(line)) {
|
|
128
|
-
throw
|
|
130
|
+
throw createError(Error, "INVALID_ACKNOWLEDGEMENT", { line });
|
|
129
131
|
}
|
|
130
132
|
return line;
|
|
131
133
|
}
|