dicom-synth 1.8.0 → 1.9.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.
@@ -2,11 +2,14 @@
2
2
  import { readFileSync, writeFileSync } from 'node:fs'
3
3
  import { resolve } from 'node:path'
4
4
  import {
5
- generateCollectionFromSpec,
5
+ MAX_PIXEL_BYTES,
6
+ MAX_STREAM_BYTES,
7
+ previewCollection,
6
8
  resolveParametricSpec,
7
9
  validateDatasetSpec,
8
10
  withResolvedSeed,
9
11
  writeCollectionFromSpec,
12
+ writeLargeImageFile,
10
13
  } from '../dist/esm/index.js'
11
14
 
12
15
  function usage() {
@@ -14,13 +17,31 @@ function usage() {
14
17
  'Usage: dicom-synth-generate --schema <path> [--out <dir>] [--emit-spec <path>] [--dry-run]\n' +
15
18
  ' dicom-synth-generate --schema-inline <json> [--out <dir>] [--emit-spec <path>] [--dry-run]\n' +
16
19
  ' dicom-synth-generate --parametric <path> [--out <dir>] [--emit-spec <path>] [--dry-run]\n' +
20
+ ' dicom-synth-generate --large-file <path> --size <600mb|50gb> [--modality CT|PT|MR|CR]\n' +
17
21
  '\n' +
18
22
  'A seed is drawn when the spec omits one; pass --emit-spec to capture the\n' +
19
- 'effective spec (seed included) so the dataset can be re-created.',
23
+ 'effective spec (seed included) so the dataset can be re-created.\n' +
24
+ '\n' +
25
+ '--large-file streams a single DICOM (512 MB–50 GB) to disk; files above\n' +
26
+ '~4 GB use encapsulated fragments (valid container, zero pixel content).',
20
27
  )
21
28
  process.exit(1)
22
29
  }
23
30
 
31
+ const SIZE_UNITS = { b: 1, kb: 1024, mb: 1024 * 1024, gb: 1024 * 1024 * 1024 }
32
+
33
+ function parseSizeToBytes(s) {
34
+ // Unit is required so a bare number (e.g. "600", meant as MB) is not silently
35
+ // read as 600 bytes.
36
+ const m = /^([0-9]*\.?[0-9]+)\s*(b|kb|mb|gb)$/i.exec(s.trim())
37
+ if (!m) {
38
+ throw new Error(
39
+ `invalid --size "${s}" — include a unit, e.g. 600mb or 50gb`,
40
+ )
41
+ }
42
+ return Math.round(Number.parseFloat(m[1]) * SIZE_UNITS[m[2].toLowerCase()])
43
+ }
44
+
24
45
  const args = process.argv.slice(2)
25
46
 
26
47
  if (args.length === 0) usage()
@@ -30,6 +51,9 @@ let specSource
30
51
  let outDir = resolve('./fixtures/generated')
31
52
  let emitSpecPath
32
53
  let dryRun = false
54
+ let largeFilePath
55
+ let largeFileSize
56
+ let largeFileModality
33
57
 
34
58
  function readSpecArg(flag, value) {
35
59
  if (rawSpec !== undefined) {
@@ -70,12 +94,73 @@ for (let i = 0; i < args.length; i++) {
70
94
  emitSpecPath = resolve(args[++i])
71
95
  } else if (args[i] === '--dry-run') {
72
96
  dryRun = true
97
+ } else if (args[i] === '--large-file' && args[i + 1]) {
98
+ largeFilePath = resolve(args[++i])
99
+ } else if (args[i] === '--size' && args[i + 1]) {
100
+ largeFileSize = args[++i]
101
+ } else if (args[i] === '--modality' && args[i + 1]) {
102
+ largeFileModality = args[++i]
73
103
  } else {
74
104
  console.error(`Unknown argument: ${args[i]}`)
75
105
  usage()
76
106
  }
77
107
  }
78
108
 
109
+ if (largeFilePath !== undefined) {
110
+ if (rawSpec !== undefined) {
111
+ console.error('Error: --large-file cannot be combined with a spec mode')
112
+ process.exit(1)
113
+ }
114
+ if (largeFileSize === undefined) {
115
+ console.error('Error: --large-file requires --size')
116
+ usage()
117
+ }
118
+ if (
119
+ largeFileModality !== undefined &&
120
+ !['CT', 'PT', 'MR', 'CR'].includes(largeFileModality)
121
+ ) {
122
+ console.error(`Error: invalid --modality "${largeFileModality}"`)
123
+ process.exit(1)
124
+ }
125
+ let targetBytes
126
+ try {
127
+ targetBytes = parseSizeToBytes(largeFileSize)
128
+ } catch (err) {
129
+ console.error(`Error: ${err.message}`)
130
+ process.exit(1)
131
+ }
132
+ // Validate bounds here so --dry-run reflects what a real run would accept.
133
+ if (targetBytes <= MAX_PIXEL_BYTES) {
134
+ console.error(
135
+ 'Error: --size must exceed the 512 MB in-memory limit — use a spec with targetSizeKb for smaller files',
136
+ )
137
+ process.exit(1)
138
+ }
139
+ if (targetBytes > MAX_STREAM_BYTES) {
140
+ console.error('Error: --size exceeds the 50 GB limit')
141
+ process.exit(1)
142
+ }
143
+ if (dryRun) {
144
+ console.log(
145
+ `Dry run: would write ~${(targetBytes / 1024 / 1024).toFixed(1)} MB to ${largeFilePath} — nothing written`,
146
+ )
147
+ process.exit(0)
148
+ }
149
+ try {
150
+ const result = writeLargeImageFile(
151
+ { targetBytes, modality: largeFileModality },
152
+ largeFilePath,
153
+ )
154
+ console.log(
155
+ `Wrote ${(result.bytesWritten / 1024 / 1024).toFixed(1)} MB ${result.encoding} DICOM to ${result.path}`,
156
+ )
157
+ } catch (err) {
158
+ console.error(`Error writing large file: ${err.message}`)
159
+ process.exit(1)
160
+ }
161
+ process.exit(0)
162
+ }
163
+
79
164
  if (rawSpec === undefined) usage()
80
165
 
81
166
  function printTypeCounts(counts) {
@@ -120,13 +205,13 @@ if (dryRun) {
120
205
  let fileCount = 0
121
206
  let byteCount = 0
122
207
  try {
123
- for await (const file of generateCollectionFromSpec(spec)) {
208
+ for await (const file of previewCollection(spec)) {
124
209
  console.log(
125
- `${file.relativePath} (${file.type}, ${(file.buffer.length / 1024).toFixed(1)} KB)`,
210
+ `${file.relativePath} (${file.type}, ${(file.approxBytes / 1024).toFixed(1)} KB)`,
126
211
  )
127
212
  counts[file.type] = (counts[file.type] ?? 0) + 1
128
213
  fileCount++
129
- byteCount += file.buffer.length
214
+ byteCount += file.approxBytes
130
215
  }
131
216
  } catch (err) {
132
217
  console.error(`Error generating collection: ${err.message}`)
@@ -1,8 +1,12 @@
1
1
  // src/collection/writer.ts
2
2
  import { randomBytes as randomBytes2 } from "node:crypto";
3
- import { mkdirSync as mkdirSync2 } from "node:fs";
3
+ import { mkdirSync as mkdirSync3 } from "node:fs";
4
4
  import { writeFile } from "node:fs/promises";
5
- import { dirname, resolve as resolve2 } from "node:path";
5
+ import { dirname, resolve as resolve3 } from "node:path";
6
+
7
+ // src/schema/limits.ts
8
+ var MAX_PIXEL_BYTES = 512 * 1024 * 1024;
9
+ var MAX_STREAM_BYTES = 50 * 1024 * 1024 * 1024;
6
10
 
7
11
  // src/loadDcmjs.ts
8
12
  import dcmjsDefaultImport, * as dcmjsNamespace from "dcmjs";
@@ -46,7 +50,6 @@ function buildDicomdirBuffer() {
46
50
  }
47
51
 
48
52
  // src/schema/validate.ts
49
- var MAX_PIXEL_BYTES = 512 * 1024 * 1024;
50
53
  var HEX_TAG_RE = /^[0-9a-fA-F]{8}$/;
51
54
 
52
55
  // src/syntheticFixtures/generator.ts
@@ -220,9 +223,17 @@ function buildBufferForSpec(spec, uid) {
220
223
  return buildNonDicomBuffer(spec.content);
221
224
  case "dicomdir":
222
225
  return buildDicomdirBuffer();
226
+ case "large-image":
227
+ throw new Error(
228
+ "large-image cannot be generated in memory \u2014 use writeCollectionFromSpec (disk-only streaming)"
229
+ );
223
230
  }
224
231
  }
225
232
 
233
+ // src/syntheticFixtures/streamWrite.ts
234
+ import { closeSync, mkdirSync as mkdirSync2, openSync, writeSync } from "node:fs";
235
+ import { resolve as resolve2 } from "node:path";
236
+
226
237
  // src/syntheticFixtures/uid.ts
227
238
  import { randomBytes } from "node:crypto";
228
239
  var ROLE_CODE = { study: 1, series: 2, sop: 3 };
@@ -288,6 +299,153 @@ function makeUidGenerator(seed) {
288
299
  };
289
300
  }
290
301
 
302
+ // src/syntheticFixtures/streamWrite.ts
303
+ var OW_MAX_BYTES = 4294967294;
304
+ var FRAGMENT_MAX_BYTES = 4294967294;
305
+ var DEFAULT_CHUNK_BYTES = 8 * 1024 * 1024;
306
+ var RLE_TRANSFER_SYNTAX_UID = "1.2.840.10008.1.2.5";
307
+ var PIXEL_DATA_OW_HEADER = Buffer.from([224, 127, 16, 0, 79, 87]);
308
+ var PIXEL_DATA_OB_HEADER = Buffer.from([224, 127, 16, 0, 79, 66]);
309
+ var ITEM_TAG_GROUP = 65534;
310
+ var ITEM_TAG_ELEMENT = 57344;
311
+ var SEQUENCE_DELIMITER_ELEMENT = 57565;
312
+ function itemTag(element, byteLength = 0) {
313
+ const b = Buffer.alloc(8);
314
+ b.writeUInt16LE(ITEM_TAG_GROUP, 0);
315
+ b.writeUInt16LE(element, 2);
316
+ b.writeUInt32LE(byteLength, 4);
317
+ return b;
318
+ }
319
+ function nativeDimensions(pixelBytes) {
320
+ const cells = Math.max(1, Math.floor(pixelBytes / 2));
321
+ const rows = Math.min(65535, Math.max(1, Math.round(Math.sqrt(cells))));
322
+ const columns = Math.min(65535, Math.max(1, Math.floor(cells / rows)));
323
+ return { rows, columns, bytes: rows * columns * 2 };
324
+ }
325
+ function streamZeros(fd, totalBytes, zeroChunk) {
326
+ let remaining = totalBytes;
327
+ while (remaining > 0) {
328
+ const n = Math.min(zeroChunk.length, remaining);
329
+ writeSync(fd, zeroChunk, 0, n);
330
+ remaining -= n;
331
+ }
332
+ }
333
+ function writeNative(outPath, params, dims, zeroChunk) {
334
+ const { modality, uid, tags } = params;
335
+ const meta = buildMeta(uid, modality);
336
+ const dataset = buildBaseImageDataset(uid, modality);
337
+ applyTagOverrides(dataset, tags);
338
+ dataset.Rows = dims.rows;
339
+ dataset.Columns = dims.columns;
340
+ const minimalPixelBytes = dataset.PixelData.byteLength;
341
+ const probe = serializeDict(meta, dataset);
342
+ const pixelElement = Buffer.alloc(12);
343
+ PIXEL_DATA_OW_HEADER.copy(pixelElement);
344
+ pixelElement.writeUInt32LE(minimalPixelBytes, 8);
345
+ const owIdx = probe.indexOf(pixelElement);
346
+ if (owIdx < 0) {
347
+ throw new Error("failed to locate native PixelData element header");
348
+ }
349
+ const dataStart = owIdx + 12;
350
+ const header = Buffer.from(probe.subarray(0, dataStart));
351
+ header.writeUInt32LE(dims.bytes, owIdx + 8);
352
+ const trailing = probe.subarray(dataStart + minimalPixelBytes);
353
+ const fd = openSync(outPath, "w");
354
+ try {
355
+ writeSync(fd, header);
356
+ streamZeros(fd, dims.bytes, zeroChunk);
357
+ if (trailing.length > 0) writeSync(fd, trailing);
358
+ } finally {
359
+ closeSync(fd);
360
+ }
361
+ return header.length + dims.bytes + trailing.length;
362
+ }
363
+ function writeEncapsulated(outPath, params, pixelBytes, fragmentBytes, zeroChunk) {
364
+ const { modality, uid, tags } = params;
365
+ const meta = {
366
+ ...buildMeta(uid, modality),
367
+ TransferSyntaxUID: RLE_TRANSFER_SYNTAX_UID
368
+ };
369
+ const dataset = buildBaseImageDataset(uid, modality);
370
+ applyTagOverrides(dataset, tags);
371
+ dataset.PixelData = [new Uint8Array([]).buffer, new Uint8Array([0, 0]).buffer];
372
+ dataset._vrMap = { PixelData: "OB" };
373
+ const probe = serializeDict(meta, dataset);
374
+ const idx = probe.indexOf(PIXEL_DATA_OB_HEADER);
375
+ if (idx < 0 || probe.readUInt32LE(idx + 8) !== 4294967295) {
376
+ throw new Error("failed to locate encapsulated PixelData element header");
377
+ }
378
+ const prefix = Buffer.from(probe.subarray(0, idx + 12));
379
+ const fd = openSync(outPath, "w");
380
+ let bytesWritten = 0;
381
+ try {
382
+ writeSync(fd, prefix);
383
+ bytesWritten += prefix.length;
384
+ const bot = itemTag(ITEM_TAG_ELEMENT, 0);
385
+ writeSync(fd, bot);
386
+ bytesWritten += bot.length;
387
+ let remaining = pixelBytes;
388
+ while (remaining > 0) {
389
+ const fragLen = Math.min(fragmentBytes, remaining);
390
+ const fh = itemTag(ITEM_TAG_ELEMENT, fragLen);
391
+ writeSync(fd, fh);
392
+ streamZeros(fd, fragLen, zeroChunk);
393
+ bytesWritten += fh.length + fragLen;
394
+ remaining -= fragLen;
395
+ }
396
+ const delimiter = itemTag(SEQUENCE_DELIMITER_ELEMENT);
397
+ writeSync(fd, delimiter);
398
+ bytesWritten += delimiter.length;
399
+ } finally {
400
+ closeSync(fd);
401
+ }
402
+ return bytesWritten;
403
+ }
404
+ function streamLargeImage(outPath, options) {
405
+ const {
406
+ targetBytes,
407
+ chunkBytes = DEFAULT_CHUNK_BYTES,
408
+ owMaxBytes = OW_MAX_BYTES,
409
+ fragmentBytes = FRAGMENT_MAX_BYTES
410
+ } = options;
411
+ const modality = options.modality ?? "CT";
412
+ const uid = options.uid ?? makeUidGenerator(options.seed)(0);
413
+ const identity = { modality, uid, tags: options.tags };
414
+ mkdirSync2(resolve2(outPath, ".."), { recursive: true });
415
+ const zeroChunk = Buffer.alloc(Math.max(1, chunkBytes));
416
+ const probe = serializeDict(
417
+ buildMeta(uid, modality),
418
+ buildBaseImageDataset(uid, modality)
419
+ );
420
+ const nativeHeaderLen = probe.length - 2;
421
+ const requestedPixel = Math.max(2, targetBytes - nativeHeaderLen);
422
+ if (requestedPixel <= owMaxBytes) {
423
+ const dims = nativeDimensions(requestedPixel);
424
+ const bytesWritten2 = writeNative(outPath, identity, dims, zeroChunk);
425
+ return {
426
+ path: outPath,
427
+ bytesWritten: bytesWritten2,
428
+ encoding: "native",
429
+ pixelBytes: dims.bytes
430
+ };
431
+ }
432
+ const estimateFrags = Math.max(
433
+ 1,
434
+ Math.ceil((targetBytes - nativeHeaderLen - 16) / fragmentBytes)
435
+ );
436
+ const overhead = nativeHeaderLen + 8 + estimateFrags * 8 + 8;
437
+ let pixelBytes = Math.max(2, targetBytes - overhead);
438
+ pixelBytes -= pixelBytes % 2;
439
+ const bytesWritten = writeEncapsulated(
440
+ outPath,
441
+ identity,
442
+ pixelBytes,
443
+ fragmentBytes - fragmentBytes % 2,
444
+ zeroChunk
445
+ );
446
+ return { path: outPath, bytesWritten, encoding: "encapsulated", pixelBytes };
447
+ }
448
+
291
449
  // src/syntheticFixtures/violations.ts
292
450
  var dcmjsAny = dcmjs;
293
451
  function parseBuffer(buffer) {
@@ -401,11 +559,13 @@ function studyFileCount(studies) {
401
559
  0
402
560
  );
403
561
  }
562
+ function resolveUid(seed, index, override) {
563
+ return { ...makeUidGenerator(seed)(index), ...override };
564
+ }
404
565
  async function generateFile(spec, options) {
405
566
  const index = options?.index ?? 0;
406
567
  const padWidth = options?.padWidth ?? 3;
407
- const uidGen = makeUidGenerator(options?.seed);
408
- const uid = { ...uidGen(index), ...options?.uid };
568
+ const uid = resolveUid(options?.seed, index, options?.uid);
409
569
  let buffer = buildBufferForSpec(spec, uid);
410
570
  const violations = "violations" in spec ? spec.violations : void 0;
411
571
  if (violations?.length) {
@@ -473,25 +633,42 @@ function hierarchicalName(studyOrdinal, seriesIndex, instanceNumber) {
473
633
  function withResolvedSeed(spec) {
474
634
  return spec.seed === void 0 ? { ...spec, seed: randomBytes2(4).readUInt32BE(0) } : spec;
475
635
  }
476
- async function* generateCollectionFromSpec(spec) {
636
+ function computeNames(type, index, padWidth, grouped, quirks) {
637
+ let names;
638
+ if (grouped) {
639
+ names = hierarchicalName(
640
+ grouped.studyOrdinal,
641
+ grouped.seriesIndex,
642
+ grouped.instanceNumber
643
+ );
644
+ } else {
645
+ const name = filename(type, index, padWidth);
646
+ names = { filename: name, relativePath: name };
647
+ }
648
+ return quirks.length === 0 ? names : applyPathQuirks(names.relativePath, quirks);
649
+ }
650
+ function* planCollection(spec) {
477
651
  const flatEntries = spec.entries ?? [];
478
652
  const studies = spec.studies ?? [];
479
653
  const totalFiles = entryCount(flatEntries) + studyFileCount(studies);
480
654
  const padWidth = String(totalFiles).length;
481
655
  const hierarchical = spec.layout === "hierarchical";
482
656
  const quirks = spec.pathQuirks ?? [];
483
- const decorate = (file) => quirks.length === 0 ? file : { ...file, ...applyPathQuirks(file.relativePath, quirks) };
484
657
  let globalIndex = 0;
485
658
  for (const entry of flatEntries) {
486
659
  const { count = 1, ...fileSpec } = entry;
487
660
  for (let i = 0; i < count; i++) {
488
- yield decorate(
489
- await generateFile(fileSpec, {
490
- index: globalIndex,
491
- seed: spec.seed,
492
- padWidth
493
- })
494
- );
661
+ yield {
662
+ fileSpec,
663
+ index: globalIndex,
664
+ ...computeNames(
665
+ fileSpec.type,
666
+ globalIndex,
667
+ padWidth,
668
+ void 0,
669
+ quirks
670
+ )
671
+ };
495
672
  globalIndex++;
496
673
  }
497
674
  }
@@ -514,25 +691,18 @@ async function* generateCollectionFromSpec(spec) {
514
691
  ...series.tags,
515
692
  ...fileSpec.tags
516
693
  };
517
- const file = await generateFile(
518
- { ...fileSpec, tags },
519
- {
520
- index: globalIndex,
521
- seed: spec.seed,
694
+ yield {
695
+ fileSpec: { ...fileSpec, tags },
696
+ index: globalIndex,
697
+ uidOverride: { study: studyUid, series: seriesUid },
698
+ ...computeNames(
699
+ fileSpec.type,
700
+ globalIndex,
522
701
  padWidth,
523
- uid: { study: studyUid, series: seriesUid }
524
- }
525
- );
526
- yield decorate(
527
- hierarchical ? {
528
- ...file,
529
- ...hierarchicalName(
530
- studyOrdinal,
531
- seriesIndex,
532
- instanceNumber
533
- )
534
- } : file
535
- );
702
+ hierarchical ? { studyOrdinal, seriesIndex, instanceNumber } : void 0,
703
+ quirks
704
+ )
705
+ };
536
706
  globalIndex++;
537
707
  }
538
708
  }
@@ -541,26 +711,84 @@ async function* generateCollectionFromSpec(spec) {
541
711
  }
542
712
  }
543
713
  }
714
+ async function materialisePlan(plan, seed) {
715
+ const file = await generateFile(plan.fileSpec, {
716
+ index: plan.index,
717
+ seed,
718
+ uid: plan.uidOverride
719
+ });
720
+ return { ...file, filename: plan.filename, relativePath: plan.relativePath };
721
+ }
722
+ async function* generateCollectionFromSpec(spec) {
723
+ for (const plan of planCollection(spec)) {
724
+ yield await materialisePlan(plan, spec.seed);
725
+ }
726
+ }
727
+ async function* previewCollection(spec) {
728
+ for (const plan of planCollection(spec)) {
729
+ if (plan.fileSpec.type === "large-image") {
730
+ yield {
731
+ relativePath: plan.relativePath,
732
+ type: "large-image",
733
+ index: plan.index,
734
+ approxBytes: plan.fileSpec.targetBytes
735
+ };
736
+ } else {
737
+ const file = await materialisePlan(plan, spec.seed);
738
+ yield {
739
+ relativePath: plan.relativePath,
740
+ type: plan.fileSpec.type,
741
+ index: plan.index,
742
+ approxBytes: file.buffer.length
743
+ };
744
+ }
745
+ }
746
+ }
544
747
  async function writeCollectionFromSpec(spec, outDir) {
545
- const root = resolve2(outDir);
546
- mkdirSync2(root, { recursive: true });
748
+ const root = resolve3(outDir);
749
+ mkdirSync3(root, { recursive: true });
547
750
  const manifest = [];
548
751
  const createdDirs = /* @__PURE__ */ new Set([root]);
549
- for await (const file of generateCollectionFromSpec(spec)) {
550
- const filePath = resolve2(root, file.relativePath);
752
+ const ensureDir = (filePath) => {
551
753
  const dir = dirname(filePath);
552
754
  if (!createdDirs.has(dir)) {
553
- mkdirSync2(dir, { recursive: true });
755
+ mkdirSync3(dir, { recursive: true });
554
756
  createdDirs.add(dir);
555
757
  }
556
- await writeFile(filePath, file.buffer);
557
- manifest.push({ path: filePath, type: file.type, index: file.index });
758
+ };
759
+ for (const plan of planCollection(spec)) {
760
+ const filePath = resolve3(root, plan.relativePath);
761
+ ensureDir(filePath);
762
+ if (plan.fileSpec.type === "large-image") {
763
+ const large = plan.fileSpec;
764
+ if (large.targetBytes > MAX_STREAM_BYTES) {
765
+ throw new Error(
766
+ `large-image targetBytes (${large.targetBytes}) exceeds the 50 GB limit`
767
+ );
768
+ }
769
+ const uid = resolveUid(spec.seed, plan.index, plan.uidOverride);
770
+ streamLargeImage(filePath, {
771
+ targetBytes: large.targetBytes,
772
+ modality: large.modality,
773
+ uid,
774
+ tags: large.tags
775
+ });
776
+ } else {
777
+ const file = await materialisePlan(plan, spec.seed);
778
+ await writeFile(filePath, file.buffer);
779
+ }
780
+ manifest.push({
781
+ path: filePath,
782
+ type: plan.fileSpec.type,
783
+ index: plan.index
784
+ });
558
785
  }
559
786
  return manifest;
560
787
  }
561
788
  export {
562
789
  generateCollectionFromSpec,
563
790
  generateFile,
791
+ previewCollection,
564
792
  withResolvedSeed,
565
793
  writeCollectionFromSpec
566
794
  };