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/src/errors.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Stable codes identify diagnostics; English messages are for humans and may improve over time.
|
|
2
|
+
const messages = Object.freeze({
|
|
3
|
+
"INVALID_JSON": "The file is not valid JSON.",
|
|
4
|
+
"INVALID_RECORD_TEXT": "Measurement JSON must be text.",
|
|
5
|
+
"RECORD_TOO_LARGE": "Measurement JSON must be no larger than 2 MiB.",
|
|
6
|
+
"INVALID_RECORD_FILE": "Choose a measurement JSON file.",
|
|
7
|
+
"INVALID_RECORD": "Expected an NMRLink measurement record.",
|
|
8
|
+
"INVALID_RECORD_KIND": "The measurement source or mode is invalid.",
|
|
9
|
+
"INVALID_ACQUISITION_TIME": "The measurement acquisition date is invalid.",
|
|
10
|
+
"INVALID_RECORD_SAMPLING": "Expected 2048 samples at 0.02 ms intervals.",
|
|
11
|
+
"INVALID_RECORD_CHANNELS": "Each raw sample must contain two finite channel values.",
|
|
12
|
+
"INVALID_RECORD_PARAMETERS": "The saved measurement parameters are invalid.",
|
|
13
|
+
"INVALID_FILENAME_TIME": "The acquisition date used for the filename is invalid.",
|
|
14
|
+
"PNG_IMAGE_LOAD_FAILED": "Could not load the graph image.",
|
|
15
|
+
"PNG_CANVAS_UNAVAILABLE": "Canvas is unavailable for PNG export.",
|
|
16
|
+
"PNG_ENCODING_FAILED": "Could not create the PNG image.",
|
|
17
|
+
"RECORD_REQUIRED": "A measurement record is required.",
|
|
18
|
+
"SVG_REQUIRED": "An SVG graph element is required.",
|
|
19
|
+
"INVALID_PNG_SCALE": "PNG scale must be greater than zero and at most 4.",
|
|
20
|
+
"INVALID_PNG_DIMENSIONS": "PNG dimensions must be positive and within 8192 pixels and 16 megapixels.",
|
|
21
|
+
"INVALID_FFT_RANGE": "FFT range must satisfy 0 <= startMs < endMs <= acquisition duration, with a positive sampleIntervalMs.",
|
|
22
|
+
"INVALID_WINDOW": "Window must be hann or rect.",
|
|
23
|
+
"INSUFFICIENT_FFT_SAMPLES": "FFT requires at least four selected samples.",
|
|
24
|
+
"INVALID_BASELINE_TAIL": "tailPoints must be an integer from 1 to the sample count.",
|
|
25
|
+
"INVALID_TRUNCATE": "truncate must be boolean.",
|
|
26
|
+
"BASELINE_OVERFLOW": "Baseline calculation overflowed.",
|
|
27
|
+
"BASELINE_CORRECTION_OVERFLOW": "Baseline correction overflowed.",
|
|
28
|
+
"FFT_OVERFLOW": "FFT calculation overflowed.",
|
|
29
|
+
"CONTROLLER_DISPOSED": "Controller is disposed.",
|
|
30
|
+
"CONTROLLER_BUSY": "Controller is disposed or another operation is running.",
|
|
31
|
+
"CONTROLLER_DISPOSE_BUSY": "Wait for the current operation before disposing.",
|
|
32
|
+
"INVALID_TIMEOUT": "Timeouts must be positive finite numbers.",
|
|
33
|
+
"DEVICE_ACTIVE": "Device is already active.",
|
|
34
|
+
"DISCONNECT_WHILE_BUSY": "Wait for the current operation; disconnect does not stop a measurement.",
|
|
35
|
+
"INVALID_MODE": "Mode must be single or double.",
|
|
36
|
+
"DEVICE_BUSY": "Another device operation is in progress.",
|
|
37
|
+
"DEVICE_NOT_CONNECTED": "Device is not connected.",
|
|
38
|
+
"MEASUREMENT_CLEANUP_FAILED": "Measurement and cleanup failed.",
|
|
39
|
+
"PARAMETER_SETUP_REJECTED": "Controller did not accept parameter setup.",
|
|
40
|
+
"SERIAL_ACTIVE": "Serial connection is already active or changing.",
|
|
41
|
+
"WEB_SERIAL_UNAVAILABLE": "Web Serial is unavailable. Use a supported browser and HTTPS or localhost.",
|
|
42
|
+
"SERIAL_CONNECTION_INTERRUPTED": "Connection was interrupted.",
|
|
43
|
+
"SERIAL_INPUT_ENDED": "Serial input ended. Reconnect the device.",
|
|
44
|
+
"SERIAL_BUFFER_OVERFLOW": "Serial response buffer overflow.",
|
|
45
|
+
"INVALID_RESPONSE_TIMEOUT": "Invalid response timeout.",
|
|
46
|
+
"SERIAL_READER_BUSY": "Only one response reader is allowed.",
|
|
47
|
+
"RESPONSE_TIMEOUT": "Controller response timed out. Reconnect the device.",
|
|
48
|
+
"SERIAL_CLEAR_WHILE_READING": "Cannot clear input while awaiting a response.",
|
|
49
|
+
"SERIAL_CLOSED": "Serial connection closed.",
|
|
50
|
+
"SERIAL_CLEANUP_FAILED": "Serial cleanup failed.",
|
|
51
|
+
"INVALID_MAX_LINE_BYTES": "maxLineBytes must be a positive safe integer.",
|
|
52
|
+
"DECODER_FAILED": "Decoder failed; reset it only after communication is resynchronized.",
|
|
53
|
+
"INVALID_SERIAL_BYTES": "Serial input must be a Uint8Array.",
|
|
54
|
+
"NON_ASCII_RESPONSE": "Non-ASCII byte in controller response.",
|
|
55
|
+
"RESPONSE_LINE_TOO_LONG": "Controller response line exceeds maxLineBytes.",
|
|
56
|
+
"INCOMPLETE_RESPONSE": "Input ended with an invalid or incomplete response.",
|
|
57
|
+
"INVALID_PARAMETERS": "Measurement parameters must be an object.",
|
|
58
|
+
"INVALID_SAMPLE_LINE": "Expected two comma-separated signed integers.",
|
|
59
|
+
"SAMPLE_OUT_OF_RANGE": "Sample exceeds the safe integer range.",
|
|
60
|
+
"INVALID_SAMPLES": "Samples must be a non-empty array of channel pairs.",
|
|
61
|
+
"SWEEP_TOO_MANY_POINTS": "A sweep must contain at most 201 points.",
|
|
62
|
+
"INVALID_SEARCH_BAND": "The peak-search lower bound must be less than the upper bound.",
|
|
63
|
+
"NO_FFT_BINS": "No FFT bins are available in the search band.",
|
|
64
|
+
"NO_RECORDS": "At least one measurement record is required.",
|
|
65
|
+
"INVALID_PHASE": "Phase correction must be a finite number.",
|
|
66
|
+
"INCONSISTENT_RECORDS": "Measurement conditions, sample intervals and record sources must match.",
|
|
67
|
+
"INCONSISTENT_FFT_GRID": "FFT frequency grids must match.",
|
|
68
|
+
"NO_REFERENCE_SIGNAL": "No signal is available for a common reference.",
|
|
69
|
+
"INVALID_REFERENCE_INDEX": "The reference point index is invalid.",
|
|
70
|
+
"ZERO_REFERENCE_SIGNAL": "The selected reference point has zero signal.",
|
|
71
|
+
"INVALID_ANALYSIS_OPTIONS": "Analysis options are invalid.",
|
|
72
|
+
"MISSING_SWEEP_SETTINGS": "Sweep settings are missing.",
|
|
73
|
+
"SWEEP_RECORD_MISMATCH": "Measurement points do not match the sweep settings.",
|
|
74
|
+
"INVALID_SWEEP_TIME": "The sweep acquisition date is invalid.",
|
|
75
|
+
"INVALID_FIT_RANGE": "Fit range must have finite bounds with start less than end.",
|
|
76
|
+
"INVALID_FIT_PHASE": "Fit range or phase correction is invalid.",
|
|
77
|
+
"INVALID_FREQUENCY_ARCHIVE": "Expected a full frequency-sweep JSON with 1 to 201 points.",
|
|
78
|
+
"INVALID_PULSE_ARCHIVE": "Expected a full pulse-calibration JSON with 1 to 201 points.",
|
|
79
|
+
"INVALID_T1_ARCHIVE": "Expected a full T1 measurement JSON with 1 to 201 points.",
|
|
80
|
+
"INVALID_T2_ARCHIVE": "Expected a full T2 measurement JSON with 1 to 201 points.",
|
|
81
|
+
"ARCHIVE_TOO_LARGE": "Sweep JSON must be text no larger than 32 MiB.",
|
|
82
|
+
"INVALID_CALIBRATED_PULSES": "Pulse cycles must be integers with 0 < p90Cycles < p180Cycles.",
|
|
83
|
+
"INVALID_TAU": "Tau must be an integer from 1 to 32767 ms.",
|
|
84
|
+
"INVALID_T1_SEQUENCE": "T1 requires 180 degrees at phase 0, then tau, then 90 degrees at phase 0.",
|
|
85
|
+
"INVALID_T2_SEQUENCE": "T2 requires 90 degrees at phase 0, then tau, then 180 degrees at phase 90.",
|
|
86
|
+
"REPETITION_TOO_SHORT": "The repetition interval must exceed tau plus the acquisition duration (40.96 ms).",
|
|
87
|
+
"INVALID_RELAXATION_ANALYSIS": "The FFT window needs at least four samples and a search band within -25 to 25 kHz.",
|
|
88
|
+
"SEARCH_BAND_OUT_OF_RANGE": "The peak-search band must be within -25 to 25 kHz.",
|
|
89
|
+
"INVALID_SIGNED_PULSE_POINTS": "At least five distinct valid signed pulse points are required.",
|
|
90
|
+
"ZERO_SIGNAL": "The signal is zero.",
|
|
91
|
+
"PULSE_PEAK_NOT_FOUND": "The first positive peak was not found. Check phase and sweep range.",
|
|
92
|
+
"INSUFFICIENT_SHORT_PULSES": "More short-pulse measurements are required.",
|
|
93
|
+
"PULSE_ZERO_CROSSING_NOT_FOUND": "A positive-to-negative zero crossing is missing. Measure beyond the 180-degree pulse.",
|
|
94
|
+
"PULSE_FIT_BOUNDARY": "The pulse-fit optimum is at the search boundary.",
|
|
95
|
+
"PULSE_FIT_LOW_R2": "Agreement with the signed model is insufficient (R2 < 0.85).",
|
|
96
|
+
"PULSE_BACKGROUND_TOO_LARGE": "The background is too large. Check phase and analysis range.",
|
|
97
|
+
"PULSE_CANDIDATE_MISMATCH": "The estimated 180-degree pulse is outside the range or inconsistent with the zero crossing.",
|
|
98
|
+
"INSUFFICIENT_PULSE_FIT_POINTS": "Sine fitting requires at least three distinct finite pulse lengths.",
|
|
99
|
+
"ZERO_PULSE_FIT_SIGNAL": "Cannot fit a sine model to zero signal.",
|
|
100
|
+
"PULSE_FIT_FAILED": "Could not compute a sine fit.",
|
|
101
|
+
"INVALID_RELAXATION_SIGNAL": "Relaxation points must contain finite delay and signal values.",
|
|
102
|
+
"INSUFFICIENT_RELAXATION_POINTS": "The fit range needs distinct valid tau points: at least five for T1 or three for T2.",
|
|
103
|
+
"FLAT_RELAXATION_SIGNAL": "The signal is zero or flat.",
|
|
104
|
+
"T1_SIGN_CHANGE_REQUIRED": "T1 fitting needs negative and positive signals. Check delay range and phase reference.",
|
|
105
|
+
"NEGATIVE_ECHO_SIGNAL": "Echo amplitude must be nonnegative.",
|
|
106
|
+
"RELAXATION_FIT_BOUNDARY": "The relaxation-fit optimum is outside the search range.",
|
|
107
|
+
"RELAXATION_FIT_LOW_R2": "Agreement with the exponential model is insufficient (R2 < 0.95).",
|
|
108
|
+
"RELAXATION_RANGE_TOO_SHORT": "The observation range is too short to estimate relaxation.",
|
|
109
|
+
"INVALID_GRAPH_COLORS": "colors must be an object.",
|
|
110
|
+
"INVALID_GRAPH_COLOR": "Expected colors.data1, colors.data2 and colors.fft to be non-empty CSS color strings.",
|
|
111
|
+
"INVALID_PLOT_WIDTH": "Plot width must be at least 160 pixels.",
|
|
112
|
+
"INVALID_SVG_PREFIX": "Invalid SVG ID prefix.",
|
|
113
|
+
"INVALID_DISPLAY_LIMITS": "Display limits must be positive finite numbers.",
|
|
114
|
+
"GRAPH_ELEMENTS_REQUIRED": "FID and FFT elements are required.",
|
|
115
|
+
"INVALID_FREQUENCY_PLOT": "At least one frequency point and a width of 160 or greater are required.",
|
|
116
|
+
"INVALID_FREQUENCY_POINT": "Frequency and nonnegative amplitude must be finite.",
|
|
117
|
+
"INVALID_PULSE_PLOT": "Valid pulse points and plot width are required.",
|
|
118
|
+
"INVALID_PULSE_PLOT_MODE": "Invalid pulse plot mode.",
|
|
119
|
+
"INVALID_PULSE_POINT": "Pulse lengths and signed values must be finite.",
|
|
120
|
+
"INVALID_PULSE_FIT": "Invalid pulse fit.",
|
|
121
|
+
"INVALID_T1_PLOT": "Invalid T1 plot settings.",
|
|
122
|
+
"INVALID_T1_POINT": "T1 points must be finite.",
|
|
123
|
+
"INVALID_T1_FIT": "Invalid T1 fit.",
|
|
124
|
+
"INVALID_T2_PLOT": "Invalid T2 plot settings.",
|
|
125
|
+
"INVALID_T2_POINT": "T2 points must be finite and nonnegative.",
|
|
126
|
+
"INVALID_T2_FIT": "Invalid T2 fit.",
|
|
127
|
+
"INVALID_LOCALE": "locale must be \"ja\" or \"en\".",
|
|
128
|
+
"INVALID_STATUS_LABEL": "labels.status must be a string.",
|
|
129
|
+
"PHASE_INCOHERENT": "Measurement phases are not aligned with a common direction.",
|
|
130
|
+
"T1_PHASE_INCOHERENT": "Measurement phases are not aligned; T1 fitting was skipped.",
|
|
131
|
+
"PULSE_FIT_EXTRAPOLATED": "Estimated pulse lengths are outside the measured range and are extrapolated.",
|
|
132
|
+
"PULSE_FIT_LOW_AGREEMENT": "The sine fit has low agreement; treat the estimate as provisional.",
|
|
133
|
+
"MAGNITUDE_FIT_LOW_AGREEMENT": "The magnitude sine fit has low agreement; treat the estimate as provisional.",
|
|
134
|
+
"T1_INCOMPLETE_RECOVERY": "The maximum delay is less than three times estimated T1; incomplete recovery can make the estimate range-sensitive.",
|
|
135
|
+
"T2_FIT_LOW_AGREEMENT": "The exponential fit has low agreement; treat the estimate as provisional.",
|
|
136
|
+
"T2_SHORT_RANGE": "The measured range is short; estimated T2 may be sensitive to the fit range.",
|
|
137
|
+
"INVALID_SWEEP_RANGE": "Sweep bounds must be integers from 1 to {maximum}, start <= end, with a positive integer step.",
|
|
138
|
+
"INVALID_SAMPLE": "Sample {index} must contain exactly two finite numbers.",
|
|
139
|
+
"SAMPLE_TRANSFER_TIMEOUT": "Sample transfer timed out at {index}/{sampleCount}.",
|
|
140
|
+
"INVALID_ACKNOWLEDGEMENT": "Invalid controller acknowledgement.",
|
|
141
|
+
"INVALID_ECHO_WINDOW": "The echo window at tau={tauMs} ms must contain its center and remain within 0 to 40.96 ms.",
|
|
142
|
+
"FFT_TOO_LARGE": "FFT size exceeds {maximum} points.",
|
|
143
|
+
"INVALID_PARAMETER_RANGE": "{name} must be an integer from {minimum} to {maximum}.",
|
|
144
|
+
"INVALID_PARAMETER_PHASE": "{name} must be 0, 90, 180, or 270.",
|
|
145
|
+
"UNSUPPORTED_COMMAND": "Unsupported command.",
|
|
146
|
+
"INVALID_LABEL_OBJECT": "{name} must be an object.",
|
|
147
|
+
"INVALID_GRAPH_LABEL": "Invalid {name}.{key}; expected a supported string label.",
|
|
148
|
+
"UNKNOWN_LABEL_PLACEHOLDER": "Unknown {name} placeholder: {placeholder}.",
|
|
149
|
+
"UNKNOWN_LABEL_KEY": "Unknown labels.{key}.",
|
|
150
|
+
"SERIAL_CONNECTION_FAILED": "Could not connect to the serial device.",
|
|
151
|
+
"SERIAL_READ_FAILED": "Could not read from the serial device.",
|
|
152
|
+
"SERIAL_WRITE_FAILED": "Could not write to the serial device.",
|
|
153
|
+
"SERIAL_DISCONNECT_FAILED": "Could not disconnect the serial device.",
|
|
154
|
+
"PORT_SELECTION_CANCELLED": "Serial port selection was cancelled.",
|
|
155
|
+
"SERIAL_PERMISSION_DENIED": "Serial port access was denied.",
|
|
156
|
+
"OPERATION_FAILED": "The operation failed. See the cause for details.",
|
|
157
|
+
"ANALYSIS_FAILED": "Analysis failed. See the cause for details."
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
export const ERROR_CODES = Object.freeze(Object.fromEntries(Object.keys(messages).map(code => [code, code])));
|
|
161
|
+
|
|
162
|
+
export function createError(Type, code, details = {}, options = {}) {
|
|
163
|
+
const message = messages[code].replace(/\{(\w+)\}/g, (token, key) => String(details[key] ?? token));
|
|
164
|
+
const error = Type === AggregateError
|
|
165
|
+
? new AggregateError(options.errors, message, options.cause === undefined ? undefined : { cause: options.cause })
|
|
166
|
+
: new Type(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
167
|
+
error.code = code;
|
|
168
|
+
error.details = { ...details };
|
|
169
|
+
return error;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function normalizeError(error, fallbackCode = "OPERATION_FAILED") {
|
|
173
|
+
if (error && typeof error.code === "string" && Object.hasOwn(ERROR_CODES, error.code)) return error;
|
|
174
|
+
const code = error?.name === "NotFoundError" ? "PORT_SELECTION_CANCELLED"
|
|
175
|
+
: ["NotAllowedError", "SecurityError"].includes(error?.name) ? "SERIAL_PERMISSION_DENIED" : fallbackCode;
|
|
176
|
+
return createError(Error, code, {}, { cause: error });
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function createWarning(code, details = {}) {
|
|
180
|
+
const { message } = createError(Error, code, details);
|
|
181
|
+
return { code, message, details: { ...details } };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function warningFromError(error) {
|
|
185
|
+
const diagnostic = normalizeError(error, "ANALYSIS_FAILED");
|
|
186
|
+
return { code: diagnostic.code, message: diagnostic.message, details: { ...diagnostic.details } };
|
|
187
|
+
}
|
package/src/fft.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { validateSamples } from "./sample-validation.js";
|
|
2
3
|
|
|
3
4
|
// Bound allocations and bitwise-index operations; normal acquisitions use 2048 points.
|
|
@@ -49,17 +50,17 @@ export function computeSpectrum(data, {
|
|
|
49
50
|
if (![sampleIntervalMs, startMs, endMs].every(Number.isFinite) ||
|
|
50
51
|
sampleIntervalMs <= 0 || startMs < 0 || startMs >= endMs ||
|
|
51
52
|
endMs > data.length * sampleIntervalMs + 1e-9) {
|
|
52
|
-
throw
|
|
53
|
+
throw createError(RangeError, "INVALID_FFT_RANGE");
|
|
53
54
|
}
|
|
54
|
-
if (!["hann", "rect"].includes(window)) throw
|
|
55
|
+
if (!["hann", "rect"].includes(window)) throw createError(RangeError, "INVALID_WINDOW");
|
|
55
56
|
|
|
56
57
|
// Match the PoC's rounding tolerance at exact sample boundaries.
|
|
57
58
|
const first = Math.ceil(startMs / sampleIntervalMs - 1e-9);
|
|
58
59
|
const last = Math.min(data.length, Math.ceil(endMs / sampleIntervalMs - 1e-9));
|
|
59
60
|
const count = last - first;
|
|
60
|
-
if (count < 4) throw
|
|
61
|
+
if (count < 4) throw createError(RangeError, "INSUFFICIENT_FFT_SAMPLES");
|
|
61
62
|
const size = 2 ** Math.ceil(Math.log2(count));
|
|
62
|
-
if (size > MAX_FFT_SIZE) throw
|
|
63
|
+
if (size > MAX_FFT_SIZE) throw createError(RangeError, "FFT_TOO_LARGE", { maximum: MAX_FFT_SIZE });
|
|
63
64
|
|
|
64
65
|
const real = new Float64Array(size);
|
|
65
66
|
const imaginary = new Float64Array(size);
|
|
@@ -78,7 +79,7 @@ export function computeSpectrum(data, {
|
|
|
78
79
|
const imaginaryValue = imaginary[transformedIndex];
|
|
79
80
|
// Divide after hypot, just as the PoC does, for amplitude compatibility.
|
|
80
81
|
const amplitude = Math.hypot(realValue, imaginaryValue) / weight;
|
|
81
|
-
if (!Number.isFinite(amplitude)) throw
|
|
82
|
+
if (!Number.isFinite(amplitude)) throw createError(RangeError, "FFT_OVERFLOW");
|
|
82
83
|
return {
|
|
83
84
|
hz: (index - size / 2) * 1000 / (size * sampleIntervalMs),
|
|
84
85
|
real: realValue / weight,
|
package/src/frequency-record.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { parseMeasurement } from "./record.js";
|
|
2
3
|
import { frequencySteps, evaluateFrequency } from "./frequency-sweep.js";
|
|
3
4
|
import { validateParameters } from "./protocol.js";
|
|
@@ -7,21 +8,21 @@ export const MAX_FREQUENCY_JSON_BYTES = 32 * 1024 * 1024;
|
|
|
7
8
|
/** Restore raw records and recompute all derived values before replacing a UI's results. */
|
|
8
9
|
export function parseFrequencySweep(text) {
|
|
9
10
|
if (typeof text !== "string" || new TextEncoder().encode(text).length > MAX_FREQUENCY_JSON_BYTES) {
|
|
10
|
-
throw
|
|
11
|
+
throw createError(TypeError, "ARCHIVE_TOO_LARGE");
|
|
11
12
|
}
|
|
12
13
|
let value;
|
|
13
14
|
try { value = JSON.parse(text.replace(/^\uFEFF/, "")); }
|
|
14
|
-
catch { throw
|
|
15
|
+
catch (cause) { throw createError(TypeError, "INVALID_JSON", {}, { cause }); }
|
|
15
16
|
if (value?.kind !== "frequency-sweep" || !Array.isArray(value.points) || !value.points.length || value.points.length > 201) {
|
|
16
|
-
throw
|
|
17
|
+
throw createError(TypeError, "INVALID_FREQUENCY_ARCHIVE");
|
|
17
18
|
}
|
|
18
19
|
const saved = value.settings;
|
|
19
|
-
if (!saved) throw
|
|
20
|
+
if (!saved) throw createError(TypeError, "MISSING_SWEEP_SETTINGS");
|
|
20
21
|
const frequencies = frequencySteps(saved.startHz, saved.endHz, saved.stepHz);
|
|
21
22
|
const parameters = validateParameters(saved.parameters);
|
|
22
23
|
const a = saved.analysis;
|
|
23
24
|
if (!a || ![a.startMs, a.endMs, a.tailPoints, a.minHz, a.maxHz].every(Number.isFinite) || !["hann", "rect"].includes(a.window)) {
|
|
24
|
-
throw
|
|
25
|
+
throw createError(TypeError, "INVALID_ANALYSIS_OPTIONS");
|
|
25
26
|
}
|
|
26
27
|
const analysis = { startMs: a.startMs, endMs: a.endMs, tailPoints: a.tailPoints, window: a.window, minHz: a.minHz, maxHz: a.maxHz };
|
|
27
28
|
const points = value.points.map((point, index) => {
|
|
@@ -29,11 +30,11 @@ export function parseFrequencySweep(text) {
|
|
|
29
30
|
if (!record.parameters || record.source !== value.source || record.mode !== "single" ||
|
|
30
31
|
point.frequencyHz !== frequencies[index] || record.parameters.frequencyHz !== frequencies[index] ||
|
|
31
32
|
Object.keys(parameters).some(key => key !== "frequencyHz" && parameters[key] !== record.parameters[key])) {
|
|
32
|
-
throw
|
|
33
|
+
throw createError(TypeError, "SWEEP_RECORD_MISMATCH");
|
|
33
34
|
}
|
|
34
35
|
return evaluateFrequency(record, analysis);
|
|
35
36
|
});
|
|
36
|
-
if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw
|
|
37
|
+
if (typeof value.acquiredAt !== "string" || !Number.isFinite(Date.parse(value.acquiredAt))) throw createError(TypeError, "INVALID_SWEEP_TIME");
|
|
37
38
|
return { source: value.source, acquiredAt: value.acquiredAt,
|
|
38
39
|
settings: { startHz: saved.startHz, endHz: saved.endHz, stepHz: saved.stepHz, frequencies, parameters, analysis },
|
|
39
40
|
points };
|
package/src/frequency-sweep.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { integerSteps, runSingleSweep } from "./sweep.js";
|
|
2
3
|
import { analyzeMeasurement } from "./analysis.js";
|
|
3
4
|
|
|
@@ -10,10 +11,10 @@ export function frequencySteps(startHz, endHz, stepHz) {
|
|
|
10
11
|
export function evaluateFrequency(record, {
|
|
11
12
|
startMs = 1, endMs = 5, tailPoints = 100, window = "hann", minHz = -3000, maxHz = 3000,
|
|
12
13
|
} = {}) {
|
|
13
|
-
if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw
|
|
14
|
+
if (![minHz, maxHz].every(Number.isFinite) || minHz >= maxHz) throw createError(RangeError, "INVALID_SEARCH_BAND");
|
|
14
15
|
const analysis = analyzeMeasurement(record, { startMs, endMs, tailPoints, window });
|
|
15
16
|
const bins = analysis.spectrum.bins.filter(bin => bin.hz >= minHz && bin.hz <= maxHz);
|
|
16
|
-
if (!bins.length) throw
|
|
17
|
+
if (!bins.length) throw createError(RangeError, "NO_FFT_BINS");
|
|
17
18
|
const peak = bins.reduce((best, bin) => bin.amplitude > best.amplitude ? bin : best);
|
|
18
19
|
return { frequencyHz: record.parameters.frequencyHz, amplitude: peak.amplitude, peakHz: peak.hz, record };
|
|
19
20
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
2
|
+
// Graph text is separate from rendering. Templates contain named values in {braces}.
|
|
3
|
+
const SIGNAL = { ja: "信号値 [a.u.]", en: "Signal [a.u.]" };
|
|
4
|
+
const AXES = {
|
|
5
|
+
ja: {
|
|
6
|
+
fid: { title: "FID:Data 1とData 2", xLabel: "時間 [ms]" },
|
|
7
|
+
fft: { title: "複素FFTの振幅スペクトル", xLabel: "受信周波数からの差 [kHz]" },
|
|
8
|
+
frequency: { title: "設定周波数とFFTピーク振幅", xLabel: "設定周波数 [kHz]" },
|
|
9
|
+
pulse: { title: "パルス周期数と符号付き信号", xLabel: "第1パルス [周期数]" },
|
|
10
|
+
pulseMagnitude: { title: "パルス周期数と信号の絶対値", xLabel: "第1パルス [周期数]" },
|
|
11
|
+
t1: { title: "T1・反転回復曲線", xLabel: "待ち時間 τ [ms]" },
|
|
12
|
+
t2: { title: "T2・エコー減衰曲線", xLabel: "2τ [ms]" },
|
|
13
|
+
},
|
|
14
|
+
en: {
|
|
15
|
+
fid: { title: "FID: Data 1 and Data 2", xLabel: "Time [ms]" },
|
|
16
|
+
fft: { title: "Complex FFT amplitude spectrum", xLabel: "Frequency offset [kHz]" },
|
|
17
|
+
frequency: { title: "Set frequency and FFT peak amplitude", xLabel: "Set frequency [kHz]" },
|
|
18
|
+
pulse: { title: "Pulse cycles and signed signal", xLabel: "First pulse [RF cycles]" },
|
|
19
|
+
pulseMagnitude: { title: "Pulse cycles and signal magnitude", xLabel: "First pulse [RF cycles]" },
|
|
20
|
+
t1: { title: "T1 inversion recovery", xLabel: "Delay τ [ms]" },
|
|
21
|
+
t2: { title: "T2 echo decay", xLabel: "2τ [ms]" },
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
const MESSAGES = {
|
|
25
|
+
ja: {
|
|
26
|
+
fidEmpty: "測定すると波形を表示します。",
|
|
27
|
+
fftEmpty: "測定するとスペクトルを表示します。",
|
|
28
|
+
peak: {
|
|
29
|
+
empty: "最大ピーク:未測定", none: "最大ピーク:信号なし", outside: "(表示範囲外)",
|
|
30
|
+
value: "最大ピーク:{hz} Hz(受信周波数からの差){outside}。全周波数から探索・FFTビン値。",
|
|
31
|
+
},
|
|
32
|
+
status: "末尾{tailPoints}点の平均で補正。FID表示は0〜{displayEndMs} ms、縦軸は{startMs}〜{endMs} msで自動調整(範囲外はクリップ)。薄い青の帯はFFT範囲。FFTは{startMs}〜{endMs} ms(終端を含まない)、{window}窓。周波数表示は±{frequencyLimitKHz} kHz。",
|
|
33
|
+
},
|
|
34
|
+
en: {
|
|
35
|
+
fidEmpty: "Measure to display the waveform.",
|
|
36
|
+
fftEmpty: "Measure to display the spectrum.",
|
|
37
|
+
peak: {
|
|
38
|
+
empty: "Maximum peak: no measurement", none: "Maximum peak: no signal", outside: " (outside display range)",
|
|
39
|
+
value: "Maximum peak: {hz} Hz offset from receiver{outside}. Searched across all frequencies; FFT bin value.",
|
|
40
|
+
},
|
|
41
|
+
status: "Baseline: mean of the last {tailPoints} samples. FID: 0–{displayEndMs} ms; vertical scale uses {startMs}–{endMs} ms (larger values are clipped). The shaded band marks the FFT interval: {startMs}–{endMs} ms (end excluded), {window} window. Frequency display: ±{frequencyLimitKHz} kHz.",
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function checkLocale(locale) {
|
|
46
|
+
if (locale !== "ja" && locale !== "en") throw createError(TypeError, "INVALID_LOCALE");
|
|
47
|
+
}
|
|
48
|
+
function checkObject(value, name) {
|
|
49
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw createError(TypeError, "INVALID_LABEL_OBJECT", { name });
|
|
50
|
+
}
|
|
51
|
+
function mergeStrings(defaults, overrides, name) {
|
|
52
|
+
checkObject(overrides, name);
|
|
53
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
54
|
+
if (!Object.hasOwn(defaults, key) || typeof value !== "string") throw createError(TypeError, "INVALID_GRAPH_LABEL", { name, key });
|
|
55
|
+
}
|
|
56
|
+
return { ...defaults, ...overrides };
|
|
57
|
+
}
|
|
58
|
+
function checkTemplate(template, allowed, name) {
|
|
59
|
+
for (const match of template.matchAll(/\{(\w+)\}/g)) {
|
|
60
|
+
if (!allowed.includes(match[1])) throw createError(TypeError, "UNKNOWN_LABEL_PLACEHOLDER", { name, placeholder: match[1] });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function resolvePlotLabels(kind, locale = "ja", labels = {}) {
|
|
65
|
+
checkLocale(locale);
|
|
66
|
+
return mergeStrings({ ...AXES[locale][kind], yLabel: SIGNAL[locale] }, labels, "labels");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function resolveRecordLabels(locale = "ja", labels = {}) {
|
|
70
|
+
checkLocale(locale);
|
|
71
|
+
checkObject(labels, "labels");
|
|
72
|
+
for (const key of Object.keys(labels)) {
|
|
73
|
+
if (!["fid", "fft", "peak", "status"].includes(key)) throw createError(TypeError, "UNKNOWN_LABEL_KEY", { key });
|
|
74
|
+
}
|
|
75
|
+
const text = MESSAGES[locale];
|
|
76
|
+
const fid = mergeStrings({ ...resolvePlotLabels("fid", locale), empty: text.fidEmpty }, labels.fid === undefined ? {} : labels.fid, "labels.fid");
|
|
77
|
+
const fft = mergeStrings({ ...resolvePlotLabels("fft", locale), empty: text.fftEmpty }, labels.fft === undefined ? {} : labels.fft, "labels.fft");
|
|
78
|
+
const peak = mergeStrings(text.peak, labels.peak === undefined ? {} : labels.peak, "labels.peak");
|
|
79
|
+
const status = Object.hasOwn(labels, "status") ? labels.status : text.status;
|
|
80
|
+
if (typeof status !== "string") throw createError(TypeError, "INVALID_STATUS_LABEL");
|
|
81
|
+
checkTemplate(peak.value, ["hz", "outside"], "labels.peak.value");
|
|
82
|
+
checkTemplate(status, ["tailPoints", "displayEndMs", "startMs", "endMs", "window", "frequencyLimitKHz"], "labels.status");
|
|
83
|
+
return { fid, fft, peak, status };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function formatGraphText(template, values) {
|
|
87
|
+
return template.replace(/\{(\w+)\}/g, (_, key) => String(values[key]));
|
|
88
|
+
}
|
package/src/graphs.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
|
+
import { createError } from "./errors.js";
|
|
1
2
|
import { analyzeMeasurement } from "./analysis.js";
|
|
3
|
+
import { resolvePlotLabels, resolveRecordLabels, formatGraphText } from "./graph-labels.js";
|
|
2
4
|
|
|
3
5
|
// Unique SVG clip IDs allow multiple graph views on the same page.
|
|
4
6
|
let nextGraphId = 0;
|
|
5
7
|
const DEFAULT_COLORS = { data1: "#176caa", data2: "#b34e25", fft: "#176caa" };
|
|
6
8
|
|
|
7
9
|
function lineColors(options = {}) {
|
|
8
|
-
if (!options || typeof options !== "object" || Array.isArray(options)) throw
|
|
10
|
+
if (!options || typeof options !== "object" || Array.isArray(options)) throw createError(TypeError, "INVALID_GRAPH_COLORS");
|
|
9
11
|
const colors = { ...DEFAULT_COLORS, ...options };
|
|
10
12
|
for (const key of Object.keys(colors)) {
|
|
11
|
-
if (!(key in DEFAULT_COLORS) || typeof colors[key] !== "string" || !colors[key].trim()) throw
|
|
13
|
+
if (!(key in DEFAULT_COLORS) || typeof colors[key] !== "string" || !colors[key].trim()) throw createError(TypeError, "INVALID_GRAPH_COLOR");
|
|
12
14
|
}
|
|
13
15
|
return colors;
|
|
14
16
|
}
|
|
@@ -16,7 +18,7 @@ function lineColors(options = {}) {
|
|
|
16
18
|
const escapeAttribute = value => value.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<").replaceAll(">", ">");
|
|
17
19
|
|
|
18
20
|
/** 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 }) {
|
|
21
|
+
function plot(series, { title, xLabel, yLabel, xMinimum, xMaximum, nonnegative = false, scaleFrom = xMinimum, scaleUntil = xMaximum, clipId, width = 720, selection, colors, markers = false, xFormatter = null }) {
|
|
20
22
|
const height = 280;
|
|
21
23
|
const margin = { left: 68, right: 20, top: 20, bottom: 52 };
|
|
22
24
|
const plotWidth = width - margin.left - margin.right;
|
|
@@ -57,17 +59,18 @@ function plot(series, { title, xLabel, xMinimum, xMaximum, nonnegative = false,
|
|
|
57
59
|
elements.push(`<circle cx="${xPosition(x)}" cy="${yPosition(y)}" r="3" fill="${escapeAttribute(colors[index])}" clip-path="url(#${clipId})"/>`);
|
|
58
60
|
}
|
|
59
61
|
});
|
|
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"
|
|
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>`;
|
|
62
|
+
elements.push(`<text x="${margin.left + plotWidth / 2}" y="${height - 6}" text-anchor="middle">${escapeAttribute(xLabel)}</text>`);
|
|
63
|
+
elements.push(`<text x="16" y="${margin.top + plotHeight / 2}" transform="rotate(-90 16 ${margin.top + plotHeight / 2})" text-anchor="middle">${escapeAttribute(yLabel)}</text>`);
|
|
64
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeAttribute(title)}" style="font-family:inherit;font-size:12px;fill:#34454e"><title>${escapeAttribute(title)}</title>${elements.join("")}</svg>`;
|
|
63
65
|
}
|
|
64
66
|
|
|
65
67
|
/** 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
|
|
68
|
-
if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw
|
|
69
|
-
if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw
|
|
68
|
+
export function createRecordPlots(record, { width = 720, displayEndMs = 10, frequencyLimitHz = 10000, analysis = analyzeMeasurement(record), idPrefix = `nmr-${++nextGraphId}`, colors = {}, locale = "ja", labels = {} } = {}) {
|
|
69
|
+
if (!Number.isFinite(width) || width < 160) throw createError(RangeError, "INVALID_PLOT_WIDTH");
|
|
70
|
+
if (typeof idPrefix !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(idPrefix)) throw createError(TypeError, "INVALID_SVG_PREFIX");
|
|
71
|
+
if (!Number.isFinite(displayEndMs) || displayEndMs <= 0 || !Number.isFinite(frequencyLimitHz) || frequencyLimitHz <= 0) throw createError(RangeError, "INVALID_DISPLAY_LIMITS");
|
|
70
72
|
const palette = lineColors(colors);
|
|
73
|
+
const text = resolveRecordLabels(locale, labels);
|
|
71
74
|
const { data, spectrum, peak } = analysis;
|
|
72
75
|
const endMs = Math.min(displayEndMs, data.length * record.sampleIntervalMs);
|
|
73
76
|
const displayed = data.slice(0, Math.ceil(endMs / record.sampleIntervalMs - 1e-9));
|
|
@@ -75,9 +78,9 @@ export function createRecordPlots(record, { width = 720, displayEndMs = 10, freq
|
|
|
75
78
|
const visibleBins = spectrum.bins.filter(bin => Math.abs(bin.hz) <= frequencyLimitHz);
|
|
76
79
|
const displayLimit = Math.min(frequencyLimitHz, 500 / record.sampleIntervalMs);
|
|
77
80
|
return {
|
|
78
|
-
fid: plot(channels, {
|
|
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] }),
|
|
79
82
|
fft: plot([visibleBins.map(bin => [bin.hz / 1000, bin.amplitude])], {
|
|
80
|
-
|
|
83
|
+
...text.fft,
|
|
81
84
|
xMinimum: -displayLimit / 1000, xMaximum: displayLimit / 1000, nonnegative: true, clipId: `${idPrefix}-fft`, width, colors: [palette.fft],
|
|
82
85
|
}),
|
|
83
86
|
peak,
|
|
@@ -87,10 +90,12 @@ export function createRecordPlots(record, { width = 720, displayEndMs = 10, freq
|
|
|
87
90
|
|
|
88
91
|
/** Browser graph view. Resize redraws the saved analysis, without remeasuring. */
|
|
89
92
|
export class NMRGraphs {
|
|
90
|
-
constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {} }) {
|
|
91
|
-
if (!fid || !fft) throw
|
|
93
|
+
constructor({ fid, fft, peak = null, status = null, displayEndMs = 10, frequencyLimitHz = 10000, colors = {}, locale = "ja", labels = {} }) {
|
|
94
|
+
if (!fid || !fft) throw createError(TypeError, "GRAPH_ELEMENTS_REQUIRED");
|
|
92
95
|
Object.assign(this, { fid, fft, peakElement: peak, statusElement: status, displayEndMs, frequencyLimitHz });
|
|
93
96
|
this.colors = lineColors(colors);
|
|
97
|
+
this.labels = resolveRecordLabels(locale, labels);
|
|
98
|
+
this.locale = locale;
|
|
94
99
|
this.idPrefix = `nmr-${++nextGraphId}`;
|
|
95
100
|
this.widths = new Map();
|
|
96
101
|
this.observer = new ResizeObserver(entries => {
|
|
@@ -120,7 +125,7 @@ export class NMRGraphs {
|
|
|
120
125
|
const style = getComputedStyle(element);
|
|
121
126
|
return Math.max(160, element.clientWidth - parseFloat(style.paddingLeft || 0) - parseFloat(style.paddingRight || 0));
|
|
122
127
|
};
|
|
123
|
-
const options = { analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors };
|
|
128
|
+
const options = { analysis, displayEndMs: this.displayEndMs, frequencyLimitHz: this.frequencyLimitHz, idPrefix: this.idPrefix, colors: this.colors, locale: this.locale, labels: this.labels };
|
|
124
129
|
const fid = createRecordPlots(record, { ...options, width: widthOf(this.fid) });
|
|
125
130
|
const fft = createRecordPlots(record, { ...options, width: widthOf(this.fft) });
|
|
126
131
|
this.fid.innerHTML = fid.fid;
|
|
@@ -133,23 +138,26 @@ export class NMRGraphs {
|
|
|
133
138
|
}
|
|
134
139
|
if (this.peakElement) {
|
|
135
140
|
const peak = analysis.peak;
|
|
136
|
-
const outside = Math.abs(peak.hz) > this.frequencyLimitHz ?
|
|
137
|
-
this.peakElement.textContent = peak.amplitude === 0 ?
|
|
138
|
-
:
|
|
141
|
+
const outside = Math.abs(peak.hz) > this.frequencyLimitHz ? this.labels.peak.outside : "";
|
|
142
|
+
this.peakElement.textContent = peak.amplitude === 0 ? this.labels.peak.none
|
|
143
|
+
: formatGraphText(this.labels.peak.value, { hz: peak.hz.toFixed(1), outside });
|
|
139
144
|
}
|
|
140
145
|
if (this.statusElement) {
|
|
141
146
|
const { spectrum, baseline } = analysis;
|
|
142
|
-
|
|
143
|
-
|
|
147
|
+
this.statusElement.textContent = formatGraphText(this.labels.status, {
|
|
148
|
+
tailPoints: baseline.tailPoints, displayEndMs: this.displayEndMs,
|
|
149
|
+
startMs: spectrum.actualStartMs, endMs: spectrum.actualEndExclusiveMs,
|
|
150
|
+
window: spectrum.window, frequencyLimitKHz: this.frequencyLimitHz / 1000,
|
|
151
|
+
});
|
|
144
152
|
}
|
|
145
153
|
}
|
|
146
154
|
|
|
147
155
|
clear() {
|
|
148
156
|
this.record = null;
|
|
149
157
|
this.analysis = null;
|
|
150
|
-
this.fid.textContent =
|
|
151
|
-
this.fft.textContent =
|
|
152
|
-
if (this.peakElement) this.peakElement.textContent =
|
|
158
|
+
this.fid.textContent = this.labels.fid.empty;
|
|
159
|
+
this.fft.textContent = this.labels.fft.empty;
|
|
160
|
+
if (this.peakElement) this.peakElement.textContent = this.labels.peak.empty;
|
|
153
161
|
if (this.statusElement) this.statusElement.textContent = "";
|
|
154
162
|
}
|
|
155
163
|
|
|
@@ -160,76 +168,76 @@ export class NMRGraphs {
|
|
|
160
168
|
}
|
|
161
169
|
|
|
162
170
|
/** Build the frequency-response curve with the same SVG axes as FID/FFT graphs. */
|
|
163
|
-
export function createFrequencyPlot(points, { width = 720 } = {}) {
|
|
171
|
+
export function createFrequencyPlot(points, { width = 720, locale = "ja", labels = {} } = {}) {
|
|
164
172
|
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) {
|
|
165
|
-
throw
|
|
173
|
+
throw createError(TypeError, "INVALID_FREQUENCY_PLOT");
|
|
166
174
|
}
|
|
167
175
|
const sorted = [...points].sort((a, b) => a.frequencyHz - b.frequencyHz);
|
|
168
176
|
if (!sorted.every(point => Number.isFinite(point.frequencyHz) && Number.isFinite(point.amplitude) && point.amplitude >= 0)) {
|
|
169
|
-
throw
|
|
177
|
+
throw createError(TypeError, "INVALID_FREQUENCY_POINT");
|
|
170
178
|
}
|
|
171
179
|
let min = sorted[0].frequencyHz / 1000;
|
|
172
180
|
let max = sorted.at(-1).frequencyHz / 1000;
|
|
173
181
|
if (min === max) { min -= 0.1; max += 0.1; }
|
|
174
182
|
const svg = plot([sorted.map(point => [point.frequencyHz / 1000, point.amplitude])], {
|
|
175
|
-
|
|
183
|
+
...resolvePlotLabels("frequency", locale, labels), xMinimum: min, xMaximum: max,
|
|
176
184
|
nonnegative: true, scaleUntil: Infinity, clipId: `sweep-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.fft], markers: true, xFormatter: value => Number(value.toFixed(6)).toString(),
|
|
177
185
|
});
|
|
178
186
|
return svg;
|
|
179
187
|
}
|
|
180
188
|
|
|
181
189
|
/** 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
|
|
184
|
-
if (!["signed", "magnitude"].includes(mode)) throw
|
|
190
|
+
export function createPulsePlot(points, { width = 720, fit = null, mode = "signed", locale = "ja", labels = {} } = {}) {
|
|
191
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_PULSE_PLOT");
|
|
192
|
+
if (!["signed", "magnitude"].includes(mode)) throw createError(TypeError, "INVALID_PULSE_PLOT_MODE");
|
|
185
193
|
const magnitude = mode === "magnitude";
|
|
186
194
|
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
|
|
195
|
+
if (!sorted.every(point => Number.isFinite(point.length) && Number.isFinite(point.amplitude))) throw createError(TypeError, "INVALID_PULSE_POINT");
|
|
188
196
|
const min = sorted[0].length, max = sorted.at(-1).length;
|
|
189
197
|
const series = [sorted.map(point => [point.length, point.amplitude])];
|
|
190
198
|
if (fit) {
|
|
191
|
-
if (![fit.A, fit.B, fit.p90].every(Number.isFinite) || fit.p90 <= 0) throw
|
|
199
|
+
if (![fit.A, fit.B, fit.p90].every(Number.isFinite) || fit.p90 <= 0) throw createError(TypeError, "INVALID_PULSE_FIT");
|
|
192
200
|
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
193
201
|
const length = min + (max - min) * index / 200;
|
|
194
202
|
const value = Math.sin(Math.PI * length / (2 * fit.p90));
|
|
195
203
|
return [length, fit.A * (magnitude ? Math.abs(value) : value) + fit.B];
|
|
196
204
|
}));
|
|
197
205
|
}
|
|
198
|
-
return plot(series, {
|
|
206
|
+
return plot(series, { ...resolvePlotLabels(magnitude ? "pulseMagnitude" : "pulse", locale, labels), nonnegative: magnitude, xMinimum: 0,
|
|
199
207
|
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, clipId: `pulse-${++nextGraphId}`, width,
|
|
200
208
|
colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
201
209
|
}
|
|
202
210
|
|
|
203
211
|
/** 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
|
|
212
|
+
export function createT1Plot(points, { width = 720, fit = null, mode = "signed", locale = "ja", labels = {} } = {}) {
|
|
213
|
+
if (!["signed", "magnitude", "quadrature"].includes(mode) || !Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_T1_PLOT");
|
|
206
214
|
const key = mode === "signed" ? "signal" : mode;
|
|
207
215
|
const sorted = [...points].sort((a, b) => a.tau - b.tau);
|
|
208
|
-
if (!sorted.every(point => Number.isFinite(point.tau) && Number.isFinite(point[key]))) throw
|
|
216
|
+
if (!sorted.every(point => Number.isFinite(point.tau) && Number.isFinite(point[key]))) throw createError(TypeError, "INVALID_T1_POINT");
|
|
209
217
|
const min = sorted[0].tau, max = sorted.at(-1).tau;
|
|
210
218
|
const series = [sorted.map(point => [point.tau, point[key]])];
|
|
211
219
|
if (fit && mode === "signed") {
|
|
212
|
-
if (![fit.A, fit.B, fit.T, fit.from, fit.to].every(Number.isFinite) || fit.T <= 0) throw
|
|
220
|
+
if (![fit.A, fit.B, fit.T, fit.from, fit.to].every(Number.isFinite) || fit.T <= 0) throw createError(TypeError, "INVALID_T1_FIT");
|
|
213
221
|
series.push(Array.from({ length: 201 }, (_, index) => {
|
|
214
222
|
const tau = fit.from + (fit.to - fit.from) * index / 200;
|
|
215
223
|
return [tau, fit.A - fit.B * Math.exp(-tau / fit.T)];
|
|
216
224
|
}));
|
|
217
225
|
}
|
|
218
|
-
return plot(series, {
|
|
226
|
+
return plot(series, { ...resolvePlotLabels("t1", locale, labels), xMinimum: 0,
|
|
219
227
|
xMaximum: min === max ? max + 1 : max, scaleUntil: Infinity, nonnegative: mode === "magnitude",
|
|
220
228
|
clipId: `t1-${++nextGraphId}`, width, colors: [DEFAULT_COLORS.data1, DEFAULT_COLORS.data2], markers: true });
|
|
221
229
|
}
|
|
222
230
|
|
|
223
231
|
/** 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
|
|
232
|
+
export function createT2Plot(points, {width = 720, fit = null, locale = "ja", labels = {}} = {}) {
|
|
233
|
+
if (!Array.isArray(points) || !points.length || !Number.isFinite(width) || width < 160) throw createError(TypeError, "INVALID_T2_PLOT");
|
|
226
234
|
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
|
|
235
|
+
if (!sorted.every(p=>Number.isFinite(p.tau)&&p.tau>0&&Number.isFinite(p.signal)&&p.signal>=0)) throw createError(TypeError, "INVALID_T2_POINT");
|
|
228
236
|
const series = [sorted.map(p=>[2*p.tau,p.signal])];
|
|
229
237
|
if (fit) {
|
|
230
|
-
if (![fit.T,fit.A,fit.from,fit.to].every(Number.isFinite) || fit.T<=0) throw
|
|
238
|
+
if (![fit.T,fit.A,fit.from,fit.to].every(Number.isFinite) || fit.T<=0) throw createError(TypeError, "INVALID_T2_FIT");
|
|
231
239
|
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
240
|
}
|
|
233
|
-
return plot(series,{
|
|
241
|
+
return plot(series,{...resolvePlotLabels("t2", locale, labels),xMinimum:0,xMaximum:Math.max(...sorted.map(p=>2*p.tau)),scaleUntil:Infinity,nonnegative:true,
|
|
234
242
|
clipId:`t2-${++nextGraphId}`,width,colors:[DEFAULT_COLORS.data1,DEFAULT_COLORS.data2],markers:true});
|
|
235
243
|
}
|
package/src/index.js
CHANGED
|
@@ -28,3 +28,4 @@ export { measurementDurationMs } from "./timing.js";
|
|
|
28
28
|
export { t2Delays, t2Parameters, t2Window, evaluateT2, runT2Sweep, analyzeT2 } from "./t2-sweep.js";
|
|
29
29
|
export { fitT2 } from "./relaxation-fit.js";
|
|
30
30
|
export { parseT2Measurement, MAX_T2_JSON_BYTES } from "./t2-record.js";
|
|
31
|
+
export { ERROR_CODES } from "./errors.js";
|