dcmnorm 0.14.0 → 0.16.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.md CHANGED
@@ -43,6 +43,61 @@ npm run build:docker # Linux release build inside node:22-bullseye-slim (glibc 2
43
43
  npm test # runs test/smoke.js against the fixtures in ../../test/files
44
44
  ```
45
45
 
46
+ ## Typed datasets
47
+
48
+ `require("dcmnorm")` (the package entry point, `dcmnorm.js`) adds a typed dataset API to the
49
+ calls below (#6). A source is a path, a `Buffer`/`Uint8Array`, or a readable stream (collected
50
+ into a Buffer first: the native reader needs the bytes).
51
+
52
+ ```js
53
+ const { read, toDicomJson, write, renderPixels, Tag, VR, TransferSyntax } = require("dcmnorm");
54
+
55
+ const ds = await read("in.dcm", { untilPixelData: true }); // DicomDataset, no native handles
56
+ ds.getString(Tag.StudyInstanceUID);
57
+ ds.getInt(Tag.NumberOfFrames, 1);
58
+ ds.getSequence(Tag.ReferencedSeriesSequence); // DicomDataset[]
59
+ ds.getPersonName(Tag.PatientName).familyName;
60
+ ds.getBulkDataRef(Tag.PixelData); // { tag, vr, offset, length }
61
+
62
+ const json = await toDicomJson("in.dcm", { // PS3.18 Annex F, PixelData never read
63
+ excludeTags: [Tag.PatientComments],
64
+ bulkDataUriBuilder: (ref) => `${base}/bulk/${ref.offset}/${ref.length}`,
65
+ });
66
+
67
+ const edited = (await read("in.dcm")).toBuilder().set(Tag.PatientName, VR.PN, "Doe^Jane").build();
68
+ await write(edited, "out.dcm", { transferSyntax: TransferSyntax.ExplicitVRLittleEndian });
69
+
70
+ const { width, height, channels, pixels } = await renderPixels("in.dcm", 0, { windowCenter: 40, windowWidth: 400 });
71
+ ```
72
+
73
+ - `read(source, { untilPixelData, loadBulkData })`: `untilPixelData` stops at the PixelData
74
+ header; bulk values (PixelData, binary values over 32 bytes) stay in the source as references
75
+ unless `loadBulkData`. Accessors: `getString`, `getStrings`, `getInt`, `getFloat`,
76
+ `getNumbers`, `getBytes`, `getSequence`, `getNestedDataset`, `getPersonName`,
77
+ `getBulkDataRef`, `vr`, `tags`, `fileMeta`, `transferSyntaxUid`, `numberOfFrames`,
78
+ `frameTimeMillis`, `pixelAspectRatio`; iterate for `{ tag, vr, type, value }` elements.
79
+ Integers are JS numbers (SV/UV beyond 2^53 lose precision).
80
+ - `toDicomJson(source | dataset, options)`: `includeTags`, `excludeTags`, `bulkData`
81
+ (`"uri"` | `"inline"`), `bulkDataUriBase`, `bulkDataUriBuilder(ref)`, `includeFileMeta`,
82
+ `keywordAndVM`.
83
+ - `toBuilder()` → `set(tag, vr, ...values)` / `set(tag, [values])` (dictionary VR), `setInt`,
84
+ `setDouble`, `setTags`, `setBytes`, `setSequence`, `addSequenceItem`, `editSequenceItem`,
85
+ `remove`, `removePrivateTags`, `build()`. `write(dataset, path | null, { transferSyntax,
86
+ bulkDataSource })` / `toBuffer`: File Meta Information is created; references (PixelData) are
87
+ read natively from the source, not passed through JS.
88
+ - `renderPixels(source, frame, params)`: 8-bit pixels without image encoding, `pixels` a
89
+ Buffer of `width * height * channels` (1 gray, 3 RGB). Params: `windowCenter`/`windowWidth`,
90
+ `voiLut`, `modalityLut`, `iccProfile`, `outputWidth`, `outputHeight`, `showOverlays`,
91
+ `overlayIndex`, `overlayColor`. The pipeline is the one described in
92
+ [the Java guide](../java/GUIDE.md#3-frame-rendering).
93
+ - `transcodeTo(source, uid, path?)`, `transferSyntaxSupport()`, `keywordOf` / `vrOf` /
94
+ `tagForKeyword`, `sopClassName(uid)`.
95
+ - Generated constants: `Tag`, `VR`, `VR_KIND`, `TransferSyntax`, `TRANSFER_SYNTAX_INFO`
96
+ (`lossy`, `encapsulated`, `explicitVR`, ...), `SOPClassUID`.
97
+ - Errors: `DcmnormError` and `InvalidDicomError`, `UnsupportedTransferSyntaxError`,
98
+ `DecodeError`, `EncodeError`, `RenderError`, `DimseError`, with `kind`, `code`
99
+ (`ERR_DCMNORM_<KIND>`), `sourceTransferSyntaxUid`, `targetTransferSyntaxUid`, `frameIndex`.
100
+
46
101
  ## API
47
102
 
48
103
  - `readTags(filePath, tags: string[]): Promise<string>` — JSON (flat, hex-keyed,
@@ -93,7 +148,7 @@ npm test # runs test/smoke.js against the fixtures in ../../test/fil
93
148
  — computes a pixel-value histogram per frame, over the same modality-LUT-applied grayscale
94
149
  values `renderFrame` decodes from (so e.g. a CT frame's bins are in Hounsfield units). Mirrors
95
150
  the CLI's `--histogram`/`--histogram-bins`/`--histogram-frame`/`--histogram-min`/`--histogram-max`
96
- — see the main [README](../../README.md#compute-a-pixel-histogram-with---histogram) for the
151
+ — see the [CLI docs](../../docs/cli.md#compute-a-pixel-histogram-with---histogram) for the
97
152
  field-by-field output shape. `binCount` defaults to 256; `frameIndex` (0-based) restricts the
98
153
  result to one frame instead of every frame in the instance (and, like `renderFrame`, reads only
99
154
  that frame's bytes of a native multi-frame file, and decodes only that frame of a compressed
@@ -110,15 +165,23 @@ npm test # runs test/smoke.js against the fixtures in ../../test/fil
110
165
 
111
166
  - `buildVolume(filePaths: string[]): Promise<DicomVolumeHandle>` — reads and decodes every slice
112
167
  of a parallel stack (e.g. one CT/MR/PT series), spatially re-sorted by `ImagePositionPatient`
113
- regardless of input order. Rejects fewer than 2 files, mismatched Rows/Columns, or a
114
- non-parallel/gantry-tilt-inconsistent stack. This is the expensive step — build once per series
115
- and keep the returned handle resident (e.g. in a volume cache) so every subsequent `reformat()`
116
- call is cheap.
168
+ regardless of input order.
169
+ - Enhanced multi-frame objects work too: a single Enhanced CT/MR/PET file is a whole volume.
170
+ Each frame's Plane Position, Plane Orientation and Pixel Measures functional groups and its
171
+ own rescale are used. Frames that repeat a position are skipped (later temporal positions or
172
+ echoes): the first in file and frame order is kept.
173
+ - A gantry-tilted stack, whose slice origins drift within the slice plane, is desheared onto an
174
+ orthogonal grid that covers every slice. `rows`/`cols` can then exceed the source images.
175
+ - Rejects fewer than 2 slices, mismatched Rows/Columns, or a non-parallel stack.
176
+ - This is the expensive step. Build once per series and keep the returned handle resident (e.g.
177
+ in a volume cache), so every later `reformat()` call is cheap.
117
178
  - `DicomVolumeHandle` — an opaque, read-only handle around the built volume:
118
179
  - getters: `rows`, `cols`, `numSlices`, `nativeBasis` (`[rowDir(3), colDir(3)]`, the volume's own
119
180
  acquisition-native orientation — a reasonable seed for an "axial" reformat), `center`
120
181
  (`[x,y,z]` LPS mm, the volume's physical center), `minSpacingMm` (its smallest voxel
121
- dimension, a reasonable default output spacing)
182
+ dimension, a reasonable default output spacing), `modality`, `frameOfReferenceUid`,
183
+ `seriesInstanceUid`, `studyInstanceUid` (from the files, or `null`), `gantryTiltDeg`,
184
+ `desheared`, `irregularSpacing`, `voxelToPatient` (row-major 4x4, `(col, row, slice, 1)` to LPS mm)
122
185
  - `reformat(options): Promise<RenderedFrame>` — resamples one plane through the volume and
123
186
  encodes it exactly like `renderFrame`'s output shape, so callers reuse their existing
124
187
  image-display code path. `options`: `{ origin: number[3], rowDir: number[3], colDir: number[3],
@@ -130,13 +193,81 @@ npm test # runs test/smoke.js against the fixtures in ../../test/fil
130
193
  - `exportTexture(options?): Promise<TextureExportResult>` — see
131
194
  [Texture export](#texture-export) below.
132
195
 
196
+ ### Registration
197
+
198
+ Every matrix is 16 numbers, row-major, mapping MOVING patient LPS mm to FIXED patient LPS mm
199
+ (`p_fixed = M * [x, y, z, 1]`). That is the DICOM Spatial Registration convention, with the item's
200
+ Frame of Reference the moving one and the REG's own the fixed one, so a result goes into
201
+ `writeSpatialRegistration` unchanged. Volumes are `buildVolume` handles. The algorithm is described
202
+ in [the CLI docs](../../docs/cli.md#register-two-volumes).
203
+
204
+ - `registerVolumes(fixed, moving, options?, cancel?: RegistrationCancelToken): Promise<RegistrationResult>`
205
+ - What it does: rigid 6-DOF registration of any CT/MR/PT pairing.
206
+ - `options`:
207
+ - `metric` (`'auto'` | `'ncc'` | `'mattes-mi'`)
208
+ - `fixedModality` / `movingModality`: override the files' Modality
209
+ - `initialMatrix` (number[16]): a starting moving -> fixed transform
210
+ - `initialize` (`'translation'` default | `'centroid'` | `'none'`): used without `initialMatrix`
211
+ - `levelsMm` (default `[8, 4, 2]`)
212
+ - `maxIterations` (per level, default 40)
213
+ - `timeLimitMs` (default 30000)
214
+ - `mask` (`'auto'` | `'none'`)
215
+ - `roiMinMm` / `roiMaxMm`: a box in fixed patient coordinates
216
+ - `histogramBins` (32), `maxSamples` (100000), `maxMemoryBytes` (256 MiB; a level that would
217
+ exceed it is coarsened)
218
+ - Result fields:
219
+ - `matrix`, `rotationDeg` and `translationMm` (of the matrix), `centerMm`
220
+ - `metric`, `metricValue`, `initialMetricValue`, `normalizedMetric`, `overlapFraction`
221
+ - `quality` (0..1) and `qualityLabel` (`'good'` | `'fair'` | `'poor'`)
222
+ - `iterations`, `metricEvaluations`, `levels[]`, `initialization`
223
+ - `converged`, `stopReason` (`'converged'` | `'max-iterations'` | `'time-limit'`)
224
+ - `timingMs`, `workingBytes`
225
+ - Rejects when a volume was released, when there are no body voxels or no overlap, on invalid
226
+ options, and when cancelled (the message starts "registration cancelled"). Results are
227
+ deterministic across runs and thread counts.
228
+ - `new RegistrationCancelToken()`: `.cancel()`, `.cancelled`.
229
+ - `estimateTranslation(fixed, moving, options?): Promise<TranslationEstimate>`
230
+ - What it does: the fast translation-only estimate, which also seeds `registerVolumes`.
231
+ - `options`: `fixedModality`, `movingModality`, `minOverlapMm` (60), `maxShiftMm`.
232
+ - Result: `matrix`, `translationMm`, `confidence` (0..1; below about 0.3, fall back to
233
+ capture-on-link), `peakCorrelation`, `secondPeakCorrelation`, `overlapMm`, `profiles`,
234
+ `timingMs`.
235
+ - `readSpatialRegistration(filePath): Promise<string>`
236
+ - What it does: a Spatial Registration object (`.66.1`, or the pre/post matrices of a
237
+ Deformable `.66.3`) as a JSON string.
238
+ - Top-level fields: `frameOfReferenceUid` (the REG's own registered frame), the SOP, series,
239
+ study and patient identifiers, `contentLabel`, `contentDate`, `deformable`.
240
+ - `registrations[]`: `frameOfReferenceUid`, `matrix` (the item frame -> REG frame, composed over
241
+ its Matrix Sequence in order), `matrixType`, `matrices[]`, `registrationType`, `comment`,
242
+ `referencedImages[]`, `isIdentity`.
243
+ - Also `referencedSeries[]` (the Common Instance Reference) and `warnings[]` (IOD problems).
244
+ - Rejects any other SOP Class.
245
+ - `writeSpatialRegistration(specJson: string, outputPath?): Promise<{ json, dataset, sopInstanceUid, seriesInstanceUid, data? }>`
246
+ - What it does: builds a conformant REG in the fixed study. Item 1 holds the fixed Frame of
247
+ Reference with the identity, item 2 the moving one with `matrix`.
248
+ - Spec fields:
249
+ - `matrix`, `matrixType` (`'RIGID'` default, validated orthonormal; `'RIGID_SCALE'`; `'AFFINE'`)
250
+ - `registrationType` (`'auto'` → DCM 125024 | `'manual'` → 125025 | `'identity'` → 125021)
251
+ - `fixed` / `moving`: `{ frameOfReferenceUid, studyInstanceUid, seriesInstanceUid, instances?: [{ sopClassUid, sopInstanceUid }] }`
252
+ - `copyPatientStudyFrom`: a path to one fixed-study file
253
+ - `patient` / `study` overrides
254
+ - `sopInstanceUid`, `seriesInstanceUid` (generated when omitted), `seriesNumber` (9902),
255
+ `seriesDescription`, `instanceNumber`, `contentLabel`, `contentDescription`,
256
+ `contentCreatorName`, `manufacturer`, `comment`
257
+ - Returns:
258
+ - `json`: the object in `readSpatialRegistration`'s form
259
+ - `dataset`: standard PS3.18 DICOM JSON, ready for `writeJson`
260
+ - `data`: the Part 10 bytes, when `outputPath` is omitted
261
+ - Rejects specs that would not make a conformant object, for example fixed and moving in one
262
+ Frame of Reference, or a non-rigid `'RIGID'` matrix.
263
+
133
264
  ### Texture export
134
265
 
135
266
  Packs a volume, a single frame, or several independent frames as a lossless, GPU-upload-ready
136
267
  payload (16-bit samples, row-major, optionally gzip-compressed) instead of an 8-bit windowed
137
268
  render — the client does its own window/level and oblique reslicing in a GPU shader instead of
138
269
  round-tripping to the server per interaction. Mirrors the CLI's `--output-type texture`/`.gputex`
139
- (`exportTexture`/`exportFrameTexture`) — see the main [README](../../README.md#export-a-gpu-texture-gputex)
270
+ (`exportTexture`/`exportFrameTexture`) — see the [CLI docs](../../docs/cli.md#export-a-gpu-texture-gputex)
140
271
  and `dcmnorm::dicom_io::texture_export`'s own module doc for the full format contract.
141
272
 
142
273
  - `DicomVolumeHandle.exportTexture(options?: { targetMaxDim?, compression?: 'gzip'|'none', windowCenter?, windowWidth? }): Promise<TextureExportResult>`
package/dcmnorm.d.ts ADDED
@@ -0,0 +1,181 @@
1
+ // Types of the package entry point (dcmnorm.js): the native addon's API (index.d.ts), the
2
+ // generated DICOM constants (dicom-constants.d.ts) and the typed dataset API of #6.
3
+
4
+ export * from "./index";
5
+ export * from "./dicom-constants";
6
+
7
+ import type { VR, TransferSyntaxInfo } from "./dicom-constants";
8
+
9
+ /** A path, a Buffer/Uint8Array, or a readable stream / async iterable of chunks (collected first). */
10
+ export type DicomSource = string | URL | Uint8Array | AsyncIterable<Uint8Array | string>;
11
+
12
+ export type DicomErrorKind =
13
+ | "InvalidDicom"
14
+ | "UnsupportedTransferSyntax"
15
+ | "Decode"
16
+ | "Encode"
17
+ | "Render"
18
+ | "Dimse"
19
+ | "Io"
20
+ | "InvalidArgument"
21
+ | "Internal"
22
+ | "Other";
23
+
24
+ /** Every dataset API failure; `code` is `ERR_DCMNORM_<KIND>`. */
25
+ export declare class DcmnormError extends Error {
26
+ readonly kind: DicomErrorKind;
27
+ readonly code: string;
28
+ readonly sourceTransferSyntaxUid: string | null;
29
+ readonly targetTransferSyntaxUid: string | null;
30
+ readonly frameIndex: number | null;
31
+ }
32
+ export declare class InvalidDicomError extends DcmnormError {}
33
+ export declare class UnsupportedTransferSyntaxError extends DcmnormError {}
34
+ export declare class DecodeError extends DcmnormError {}
35
+ export declare class EncodeError extends DcmnormError {}
36
+ export declare class RenderError extends DcmnormError {}
37
+ export declare class DimseError extends DcmnormError {}
38
+
39
+ /** A value left in its source: absolute byte offset and length (-1: undefined). */
40
+ export interface BulkDataRef {
41
+ readonly tag: number;
42
+ readonly vr: VR;
43
+ readonly offset: number;
44
+ readonly length: number;
45
+ }
46
+
47
+ export type DicomElement =
48
+ | { readonly tag: number; readonly vr: VR; readonly type: "empty"; readonly value: null }
49
+ | { readonly tag: number; readonly vr: VR; readonly type: "strings"; readonly value: readonly string[] }
50
+ | { readonly tag: number; readonly vr: VR; readonly type: "ints" | "doubles" | "tags"; readonly value: readonly number[] }
51
+ | { readonly tag: number; readonly vr: VR; readonly type: "bytes"; readonly value: Buffer }
52
+ | { readonly tag: number; readonly vr: VR; readonly type: "bulkData"; readonly value: BulkDataRef }
53
+ | { readonly tag: number; readonly vr: VR; readonly type: "fragments"; readonly value: { offsetTable: number[]; fragments: Buffer[] } }
54
+ | { readonly tag: number; readonly vr: "SQ"; readonly type: "sequence"; readonly value: readonly DicomDataset[] };
55
+
56
+ export interface PersonNameGroup {
57
+ readonly familyName: string;
58
+ readonly givenName: string;
59
+ readonly middleName: string;
60
+ readonly namePrefix: string;
61
+ readonly nameSuffix: string;
62
+ }
63
+
64
+ export declare class PersonName {
65
+ constructor(value: string);
66
+ readonly value: string;
67
+ readonly alphabetic: PersonNameGroup;
68
+ readonly ideographic: PersonNameGroup;
69
+ readonly phonetic: PersonNameGroup;
70
+ readonly familyName: string;
71
+ readonly givenName: string;
72
+ }
73
+
74
+ /** A read-only data set as plain JS values. */
75
+ export declare class DicomDataset implements Iterable<DicomElement> {
76
+ static empty(): DicomDataset;
77
+ readonly size: number;
78
+ readonly transferSyntaxUid: string | null;
79
+ readonly transferSyntax: TransferSyntaxInfo | null;
80
+ readonly fileMeta: DicomDataset;
81
+ readonly numberOfFrames: number;
82
+ /** FrameTime (ms), or null. */
83
+ readonly frameTimeMillis: number | null;
84
+ readonly frameTimeVector: number[] | null;
85
+ /** Vertical / horizontal pixel size. */
86
+ readonly pixelAspectRatio: number;
87
+ [Symbol.iterator](): Iterator<DicomElement>;
88
+ tags(): number[];
89
+ has(tag: number): boolean;
90
+ get(tag: number): DicomElement | undefined;
91
+ vr(tag: number): VR | null;
92
+ getString(tag: number, defaultValue?: string | null, index?: number): string | null;
93
+ getStrings(tag: number): string[] | null;
94
+ getNumber(tag: number, defaultValue?: number | null, index?: number): number | null;
95
+ getInt(tag: number, defaultValue?: number | null, index?: number): number | null;
96
+ getFloat(tag: number, defaultValue?: number | null, index?: number): number | null;
97
+ getNumbers(tag: number): number[] | null;
98
+ getInts(tag: number): number[] | null;
99
+ getFloats(tag: number): number[] | null;
100
+ getBytes(tag: number): Buffer | null;
101
+ getBulkDataRef(tag: number): BulkDataRef | null;
102
+ getSequence(tag: number): DicomDataset[] | null;
103
+ getNestedDataset(tag: number, index?: number): DicomDataset | null;
104
+ getPersonName(tag: number, index?: number): PersonName | null;
105
+ toBuilder(): DicomDatasetBuilder;
106
+ }
107
+
108
+ export declare class DicomDatasetBuilder {
109
+ set(tag: number, vr: VR, ...values: Array<string | number>): this;
110
+ set(tag: number, values: Array<string | number>): this;
111
+ setInt(tag: number, vr: VR, ...values: number[]): this;
112
+ setDouble(tag: number, vr: VR, ...values: number[]): this;
113
+ setTags(tag: number, ...tags: number[]): this;
114
+ setBytes(tag: number, vr: VR, bytes: Uint8Array): this;
115
+ setNull(tag: number, vr: VR): this;
116
+ setSequence(tag: number, items: DicomDataset[]): this;
117
+ addSequenceItem(tag: number, item: DicomDataset): this;
118
+ editSequenceItem(tag: number, index: number, edit: (item: DicomDatasetBuilder) => void): this;
119
+ removeSequenceItem(tag: number, index: number): this;
120
+ remove(tag: number): this;
121
+ removePrivateTags(): this;
122
+ build(): DicomDataset;
123
+ }
124
+
125
+ export interface ReadOptions {
126
+ /** Stop at the PixelData header (PixelData is then a BulkDataRef). */
127
+ untilPixelData?: boolean;
128
+ /** Read bulk values instead of leaving them in the source as references. */
129
+ loadBulkData?: boolean;
130
+ }
131
+
132
+ export interface DicomJsonOptions {
133
+ includeTags?: number[];
134
+ excludeTags?: number[];
135
+ bulkData?: "uri" | "inline";
136
+ bulkDataUriBase?: string;
137
+ bulkDataUriBuilder?: (ref: BulkDataRef) => string;
138
+ includeFileMeta?: boolean;
139
+ keywordAndVM?: boolean;
140
+ }
141
+
142
+ export interface WriteDatasetOptions {
143
+ /** Transcode to this transfer syntax UID. */
144
+ transferSyntax?: string;
145
+ /** Where the data set's bulk data references are read from, instead of its own source. */
146
+ bulkDataSource?: string | Uint8Array;
147
+ }
148
+
149
+ export interface RenderParams {
150
+ windowCenter?: number;
151
+ windowWidth?: number;
152
+ voiLut?: boolean;
153
+ modalityLut?: boolean;
154
+ iccProfile?: boolean;
155
+ outputWidth?: number;
156
+ outputHeight?: number;
157
+ showOverlays?: boolean;
158
+ overlayIndex?: number;
159
+ overlayColor?: string;
160
+ }
161
+
162
+ export interface RenderedPixels {
163
+ width: number;
164
+ height: number;
165
+ /** 1 (gray) or 3 (RGB interleaved). */
166
+ channels: number;
167
+ /** width * height * channels bytes, rows top to bottom. */
168
+ pixels: Buffer;
169
+ overlays: Array<{ index: number; group: number; rows: number; columns: number; overlayType?: string; label?: string }>;
170
+ selectedOverlayIndex?: number;
171
+ }
172
+
173
+ export declare function read(source: DicomSource, options?: ReadOptions): Promise<DicomDataset>;
174
+ export declare function toDicomJson(source: DicomSource | DicomDataset, options?: DicomJsonOptions): Promise<string>;
175
+ export declare function write(dataset: DicomDataset, outputPath: string, options?: WriteDatasetOptions): Promise<void>;
176
+ export declare function write(dataset: DicomDataset, outputPath: null, options?: WriteDatasetOptions): Promise<Buffer>;
177
+ export declare function toBuffer(dataset: DicomDataset, options?: WriteDatasetOptions): Promise<Buffer>;
178
+ export declare function renderPixels(source: DicomSource, frameIndex?: number, params?: RenderParams): Promise<RenderedPixels>;
179
+ export declare function transcodeTo(source: DicomSource, transferSyntaxUid: string, outputPath: string): Promise<void>;
180
+ export declare function transcodeTo(source: DicomSource, transferSyntaxUid: string, outputPath?: null): Promise<Buffer>;
181
+ export declare function sopClassName(uid: string): string | null;