dcmnorm 0.23.0

Fast DICOM toolkit: parse, render, transcode, reformat, de-identify and network (DIMSE) DICOM medical images.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
//! Region-of-interest rendering (`RenderPipelineOptions::region`, `plane_params_for_region`)
//! and whole slide image stitching (`super::wsi`), against fixtures whose pixels are known at
//! every coordinate - the synthetic slides in test/files/wsi_synth (see its README.md) and
//! the real CPTAC-derived test/files/wsi.dcm.

use std::path::PathBuf;

use super::io::read_dicom_file;
use super::region::{plane_params_for_region, Region};
use super::render::{
    render_all_dicom_frames, render_all_dicom_video_frames, render_dicom_frame,
    render_dicom_frame_pixels, RenderFrameOutput, RenderOutputFormat, RenderPipelineOptions,
};
use super::test_support::{remove_stack, write_synthetic_stack, SyntheticStack};
use super::types::RenderError;
use super::volume::{
    build_volume, reformat_plane_pixels, Interpolation, PlaneParams, SlabProjection,
};
use super::wsi::{
    describe_wsi, describe_wsi_files, is_whole_slide_file, is_whole_slide_object, render_wsi,
    render_wsi_files, WsiDimensionOrganization, WsiRenderOptions,
};

fn fixture(name: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("test/files")
        .join(name)
}

fn synth(name: &str) -> PathBuf {
    fixture("wsi_synth").join(name)
}

fn pyramid_paths() -> Vec<PathBuf> {
    // Deliberately not base-first: the level order comes from the matrix sizes.
    vec![
        synth("pyramid_l2_native.dcm"),
        synth("pyramid_l0_jpeg.dcm"),
        synth("pyramid_l1_jpeg.dcm"),
    ]
}

/// The pixel at (x, y) of rendered 8-bit output.
fn pixel(frame: &RenderFrameOutput, x: u32, y: u32) -> &[u8] {
    let spp = usize::from(frame.samples_per_pixel);
    let start = (y as usize * usize::from(frame.width) + x as usize) * spp;
    &frame.bytes[start..start + spp]
}

/// Crops `w x h` at (x, y) out of rendered 8-bit output.
fn crop(frame: &RenderFrameOutput, x: u32, y: u32, w: u32, h: u32) -> Vec<u8> {
    let spp = usize::from(frame.samples_per_pixel);
    let mut out = Vec::new();
    for row in y..y + h {
        let start = (row as usize * usize::from(frame.width) + x as usize) * spp;
        out.extend_from_slice(&frame.bytes[start..start + w as usize * spp]);
    }
    out
}

fn assert_close(actual: &[u8], expected: [u8; 3], tolerance: u8, context: &str) {
    for (channel, (&a, &e)) in actual.iter().zip(expected.iter()).enumerate() {
        assert!(
            a.abs_diff(e) <= tolerance,
            "{context}: channel {channel} is {a}, expected {e} +/- {tolerance} (pixel {actual:?})"
        );
    }
}

fn with_region(region: Region) -> RenderPipelineOptions {
    RenderPipelineOptions {
        region: Some(region),
        ..Default::default()
    }
}

// ---------------------------------------------------------------------------------------------
// Region parsing and clamping
// ---------------------------------------------------------------------------------------------

#[test]
fn region_parses_and_rejects_malformed_text() {
    assert_eq!(
        "10,-5,30,40".parse::<Region>().unwrap(),
        Region::new(10, -5, 30, 40)
    );
    assert_eq!(
        " 1 , 2 , 3 , 4 ".parse::<Region>().unwrap(),
        Region::new(1, 2, 3, 4)
    );
    for bad in [
        "",
        "1,2,3",
        "1,2,3,4,5",
        "a,2,3,4",
        "1,2,0,4",
        "1,2,3,-4",
        "1.5,2,3,4",
    ] {
        assert!(
            matches!(bad.parse::<Region>(), Err(RenderError::InvalidRegion(_))),
            "'{bad}' should be rejected"
        );
    }
}

#[test]
fn region_clamps_to_the_image_and_rejects_empty_or_outside_regions() {
    assert_eq!(
        Region::new(-10, -20, 50, 60).clamp_to(100, 100).unwrap(),
        Region::new(0, 0, 40, 40)
    );
    assert_eq!(
        Region::new(90, 95, 50, 50).clamp_to(100, 100).unwrap(),
        Region::new(90, 95, 10, 5)
    );
    assert!(Region::new(100, 0, 5, 5).clamp_to(100, 100).is_err());
    assert!(Region::new(-5, 0, 5, 5).clamp_to(100, 100).is_err());
    assert!(Region::new(0, 0, 0, 5).clamp_to(100, 100).is_err());
}

// ---------------------------------------------------------------------------------------------
// 2D rendering
// ---------------------------------------------------------------------------------------------

#[test]
fn region_crops_a_2d_render_to_exactly_the_source_pixels() {
    for name in ["mr.dcm", "us.dcm"] {
        let object = read_dicom_file(fixture(name)).unwrap();
        let full = render_dicom_frame_pixels(&object, &RenderPipelineOptions::default()).unwrap();
        let region = Region::new(37, 51, 120, 77);
        let cropped = render_dicom_frame_pixels(&object, &with_region(region)).unwrap();
        assert_eq!((cropped.width, cropped.height), (120, 77), "{name}");
        assert_eq!(cropped.samples_per_pixel, full.samples_per_pixel);
        assert_eq!(cropped.bytes, crop(&full, 37, 51, 120, 77), "{name}");
    }
}

#[test]
fn region_is_applied_before_output_scaling_and_padding() {
    let object = read_dicom_file(fixture("mr.dcm")).unwrap();
    let options = RenderPipelineOptions {
        region: Some(Region::new(100, 200, 200, 100)),
        scale_max_size: Some(512),
        ..Default::default()
    };
    let scaled = render_dicom_frame_pixels(&object, &options).unwrap();
    assert_eq!((scaled.width, scaled.height), (512, 256));

    let padded = render_dicom_frame_pixels(
        &object,
        &RenderPipelineOptions {
            pad: true,
            pad_color: [10, 20, 30],
            ..options.clone()
        },
    )
    .unwrap();
    assert_eq!((padded.width, padded.height), (512, 512));

    let exact = render_dicom_frame_pixels(
        &object,
        &RenderPipelineOptions {
            region: Some(Region::new(0, 0, 64, 64)),
            output_width: Some(32),
            output_height: Some(16),
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!((exact.width, exact.height), (32, 16));

    // Encoded output carries the cropped+scaled size too.
    let png = render_dicom_frame(&object, RenderOutputFormat::Png, &options).unwrap();
    let decoded = image::load_from_memory(&png.bytes).unwrap();
    assert_eq!((decoded.width(), decoded.height()), (512, 256));
}

#[test]
fn region_partly_outside_is_clamped_and_fully_outside_is_an_error() {
    let object = read_dicom_file(fixture("mr.dcm")).unwrap();
    let full = render_dicom_frame_pixels(&object, &RenderPipelineOptions::default()).unwrap();
    let clamped =
        render_dicom_frame_pixels(&object, &with_region(Region::new(-30, 480, 100, 100))).unwrap();
    assert_eq!((clamped.width, clamped.height), (70, 32));
    assert_eq!(clamped.bytes, crop(&full, 0, 480, 70, 32));

    let error =
        render_dicom_frame_pixels(&object, &with_region(Region::new(600, 0, 10, 10))).unwrap_err();
    assert!(matches!(error, RenderError::InvalidRegion(_)), "{error}");
}

#[test]
fn region_crops_raw_stored_pixel_output() {
    let object = read_dicom_file(fixture("mr.dcm")).unwrap();
    let full = render_dicom_frame(&object, RenderOutputFormat::Raw, &Default::default()).unwrap();
    assert_eq!(full.bits_allocated, 16);
    let region = Region::new(5, 7, 11, 13);
    let raw = render_dicom_frame(&object, RenderOutputFormat::Raw, &with_region(region)).unwrap();
    assert_eq!((raw.width, raw.height), (11, 13));
    let mut expected = Vec::new();
    for row in 7..20usize {
        let start = (row * 512 + 5) * 2;
        expected.extend_from_slice(&full.bytes[start..start + 22]);
    }
    assert_eq!(raw.bytes, expected);
}

#[test]
fn region_applies_to_one_frame_of_a_multi_frame_image_and_to_every_frame() {
    // wsi.dcm: 96 JPEG Baseline frames of 240x240.
    let object = read_dicom_file(fixture("wsi.dcm")).unwrap();
    let frame_options = |region| RenderPipelineOptions {
        frame_index: 17,
        region,
        ..Default::default()
    };
    let full = render_dicom_frame_pixels(&object, &frame_options(None)).unwrap();
    let region = Region::new(200, 10, 100, 50);
    let cropped = render_dicom_frame_pixels(&object, &frame_options(Some(region))).unwrap();
    assert_eq!((cropped.width, cropped.height), (40, 50));
    assert_eq!(cropped.bytes, crop(&full, 200, 10, 40, 50));

    let mr = read_dicom_file(fixture("mr.dcm")).unwrap();
    let all = render_all_dicom_frames(&mr, RenderOutputFormat::Raw, &with_region(region)).unwrap();
    assert!(all
        .iter()
        .all(|frame| (frame.width, frame.height) == (100, 50)));

    let video = render_all_dicom_video_frames(
        &object,
        &RenderPipelineOptions {
            region: Some(Region::new(0, 0, 120, 90)),
            scale_max_size: Some(60),
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!(video.len(), 96);
    assert!(video
        .iter()
        .all(|frame| (frame.width, frame.height) == (60, 45)));
}

// ---------------------------------------------------------------------------------------------
// MPR
// ---------------------------------------------------------------------------------------------

#[test]
fn mpr_region_samples_exactly_the_matching_part_of_the_full_plane() {
    let stack = SyntheticStack {
        rows: 48,
        cols: 40,
        row_vector: [1.0, 0.0, 0.0],
        col_vector: [0.0, 1.0, 0.0],
        pixel_spacing: [1.0, 1.0],
        positions: (0..24).map(|k| [-20.0, -24.0, k as f64 * 2.0]).collect(),
        modality: "CT",
        frame_of_reference_uid: "2.25.7001".into(),
        study_instance_uid: "2.25.7002".into(),
        series_instance_uid: "2.25.7003".into(),
    };
    let paths = write_synthetic_stack(&stack, |p| 10.0 * p[0] + 3.0 * p[1] + 7.0 * p[2]);
    let volume = build_volume(&paths).unwrap();
    remove_stack(&paths);

    // A coronal plane through the middle, wider than the volume so part of it is background.
    let full = PlaneParams {
        origin: volume.center(),
        row_dir: [1.0, 0.0, 0.0],
        col_dir: [0.0, 0.0, -1.0],
        output_width: 64,
        output_height: 50,
        spacing_mm: 0.75,
        window_center: Some(0.0),
        window_width: Some(800.0),
        interpolation: Interpolation::Trilinear,
        slab_thickness_mm: 0.0,
        slab_projection: SlabProjection::MaximumIntensity,
    };
    let full_pixels = reformat_plane_pixels(&volume, &full).unwrap();
    let region = Region::new(9, 13, 30, 21);
    let sub = plane_params_for_region(&full, &region).unwrap();
    assert_eq!((sub.output_width, sub.output_height), (30, 21));
    let sub_pixels = reformat_plane_pixels(&volume, &sub).unwrap();
    for row in 0..21usize {
        for col in 0..30usize {
            let expected = full_pixels[(row + 13) * 64 + col + 9];
            let actual = sub_pixels[row * 30 + col];
            assert!(
                expected.abs_diff(actual) <= 1,
                "({col},{row}): region {actual} vs full {expected}"
            );
        }
    }

    // Clamped at the plane edge, error when outside.
    let edge = plane_params_for_region(&full, &Region::new(50, -5, 30, 10)).unwrap();
    assert_eq!((edge.output_width, edge.output_height), (14, 5));
    assert!(plane_params_for_region(&full, &Region::new(64, 0, 5, 5)).is_err());
}

// ---------------------------------------------------------------------------------------------
// Whole slide images
// ---------------------------------------------------------------------------------------------

/// sparse_native.dcm's position code (see make_fixtures.py).
fn sparse_expected(x: u32, y: u32) -> [u8; 3] {
    [
        (x % 256) as u8,
        (y % 256) as u8,
        (((x + 2 * y) / 16) % 256) as u8,
    ]
}

/// Tiles absent from sparse_native.dcm, as (tile column, tile row) of its 128px grid.
fn sparse_missing(x: u32, y: u32) -> bool {
    matches!((x / 128, y / 128), (1, 1) | (4, 0) | (2, 2))
}

fn wsi_raw(
    objects: &[&dcmnorm_object::DefaultDicomObject],
    options: &WsiRenderOptions,
) -> super::wsi::WsiRenderOutput {
    render_wsi(objects, RenderOutputFormat::Raw, options).unwrap()
}

#[test]
fn wsi_fixtures_are_recognized_and_described() {
    let sparse = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    assert!(is_whole_slide_object(&sparse));
    assert!(is_whole_slide_file(synth("pyramid_l0_jpeg.dcm")));
    assert!(!is_whole_slide_file(fixture("mr.dcm")));

    let levels = describe_wsi(&[&sparse]).unwrap();
    assert_eq!(levels.len(), 1);
    let level = &levels[0];
    assert_eq!((level.total_columns, level.total_rows), (520, 330));
    assert_eq!((level.tile_columns, level.tile_rows), (128, 128));
    assert_eq!(level.number_of_frames, 13);
    assert_eq!(
        level.dimension_organization,
        WsiDimensionOrganization::TiledSparse
    );
    assert_eq!(level.pixel_spacing_mm, Some([0.0005, 0.0005]));

    let mono = describe_wsi_files(&[synth("full_mono_2planes.dcm")]).unwrap();
    assert_eq!(mono[0].focal_planes, 2);
    assert_eq!(
        mono[0].dimension_organization,
        WsiDimensionOrganization::TiledFull
    );
}

#[test]
fn wsi_tiled_sparse_stitches_every_tile_in_place_with_background_for_missing_tiles() {
    let object = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    let output = wsi_raw(&[&object], &WsiRenderOptions::default());
    let frame = &output.frame;
    // Partial edge tiles are clipped: the output is exactly the total pixel matrix.
    assert_eq!((frame.width, frame.height), (520, 330));
    assert_eq!(frame.samples_per_pixel, 3);
    assert_eq!(output.tiles_decoded, 13);
    for y in 0..330 {
        for x in 0..520 {
            let expected = if sparse_missing(x, y) {
                [255, 255, 255]
            } else {
                sparse_expected(x, y)
            };
            assert_eq!(pixel(frame, x, y), expected, "pixel ({x},{y})");
        }
    }
}

#[test]
fn wsi_region_across_tile_boundaries_decodes_only_the_tiles_it_touches() {
    let object = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    let options = WsiRenderOptions {
        render: with_region(Region::new(100, 100, 200, 100)),
        background_color: [1, 2, 3],
        ..Default::default()
    };
    let output = wsi_raw(&[&object], &options);
    assert_eq!((output.frame.width, output.frame.height), (200, 100));
    assert_eq!(output.region, Region::new(100, 100, 200, 100));
    for y in 0..100 {
        for x in 0..200 {
            let (sx, sy) = (x + 100, y + 100);
            let expected = if sparse_missing(sx, sy) {
                [1, 2, 3]
            } else {
                sparse_expected(sx, sy)
            };
            assert_eq!(pixel(&output.frame, x, y), expected, "pixel ({sx},{sy})");
        }
    }
    // Tiles (0,0) (1,0) (2,0) (0,1) (2,1) and the off-grid overlap tile at x=192 - (1,1) is
    // missing and nothing to the right of x=300 or below y=200 is touched.
    assert_eq!(output.tiles_decoded, 6);

    // Inside one tile: only that tile is decoded.
    let one = wsi_raw(
        &[&object],
        &WsiRenderOptions {
            render: with_region(Region::new(10, 140, 20, 20)),
            ..Default::default()
        },
    );
    assert_eq!(one.tiles_decoded, 1);
    assert_eq!(pixel(&one.frame, 0, 0), sparse_expected(10, 140));
}

#[test]
fn wsi_region_is_clamped_to_the_matrix_and_rejected_outside_it() {
    let object = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    let output = wsi_raw(
        &[&object],
        &WsiRenderOptions {
            render: with_region(Region::new(500, 300, 100, 100)),
            ..Default::default()
        },
    );
    assert_eq!(output.region, Region::new(500, 300, 20, 30));
    assert_eq!((output.frame.width, output.frame.height), (20, 30));
    // The bottom-right corner of the partial edge tile (4, 2), right up to the matrix edge.
    assert_eq!(pixel(&output.frame, 19, 29), sparse_expected(519, 329));

    let error = render_wsi(
        &[&object],
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            render: with_region(Region::new(520, 0, 10, 10)),
            ..Default::default()
        },
    )
    .unwrap_err();
    assert!(matches!(error, RenderError::InvalidRegion(_)), "{error}");
}

#[test]
fn wsi_tiled_full_monochrome_selects_the_focal_plane_by_frame_order() {
    let object = read_dicom_file(synth("full_mono_2planes.dcm")).unwrap();
    for plane in 0..2 {
        let output = wsi_raw(
            &[&object],
            &WsiRenderOptions {
                focal_plane_index: plane,
                ..Default::default()
            },
        );
        let frame = &output.frame;
        assert_eq!(
            (frame.width, frame.height, frame.samples_per_pixel),
            (300, 200, 1)
        );
        assert_eq!(output.tiles_decoded, 20);
        for y in 0..200u32 {
            for x in 0..300u32 {
                let v = ((x + 3 * y) % 251) as u8;
                let expected = if plane == 0 { v } else { 255 - v };
                assert_eq!(pixel(frame, x, y), [expected], "plane {plane} ({x},{y})");
            }
        }
    }
    let error = render_wsi(
        &[&object],
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            focal_plane_index: 2,
            ..Default::default()
        },
    )
    .unwrap_err();
    assert!(error.to_string().contains("focal plane 2"), "{error}");
}

#[test]
fn wsi_tiled_full_jpeg_level_places_markers_across_tile_boundaries() {
    // pyramid_l0_jpeg.dcm: YBR_FULL_422 JPEG tiles of 256, matrix 1000x750.
    let object = read_dicom_file(synth("pyramid_l0_jpeg.dcm")).unwrap();
    let output = wsi_raw(&[&object], &WsiRenderOptions::default());
    let frame = &output.frame;
    assert_eq!((frame.width, frame.height), (1000, 750));
    assert_eq!(output.tiles_decoded, 12);
    // The blue marker spans x=232..280 across the tile column boundary at x=256: both sides.
    assert_close(
        pixel(frame, 240, 64),
        [0, 0, 255],
        12,
        "blue left of boundary",
    );
    assert_close(
        pixel(frame, 270, 64),
        [0, 0, 255],
        12,
        "blue right of boundary",
    );
    assert_close(
        pixel(frame, 290, 64),
        [238, 234, 242],
        12,
        "glass right of blue",
    );
    // The red marker spans y=480..544 across the row boundary at y=512.
    assert_close(
        pixel(frame, 512, 490),
        [220, 0, 0],
        12,
        "red above boundary",
    );
    assert_close(
        pixel(frame, 512, 535),
        [220, 0, 0],
        12,
        "red below boundary",
    );
    // The green marker sits in the partial bottom-right tile (768..1000 x 512..750).
    assert_close(
        pixel(frame, 932, 710),
        [0, 200, 0],
        12,
        "green in edge tile",
    );
    // The edge tiles' magenta padding must never show.
    assert_close(
        pixel(frame, 999, 749),
        [238, 234, 242],
        12,
        "bottom-right corner",
    );
}

#[test]
fn wsi_tiles_are_identical_to_their_frames_in_a_real_slide() {
    // wsi.dcm (CPTAC, TILED_FULL JPEG): 3610x1367 in 240px tiles, 16 per row - the last column
    // is 10px wide, the last row 167px tall.
    let object = read_dicom_file(fixture("wsi.dcm")).unwrap();
    let frame_pixels = |frame_index| {
        render_dicom_frame_pixels(
            &object,
            &RenderPipelineOptions {
                frame_index,
                show_overlays: false,
                ..Default::default()
            },
        )
        .unwrap()
    };
    let region = |x, y, w, h| WsiRenderOptions {
        render: with_region(Region::new(x, y, w, h)),
        ..Default::default()
    };
    // Tile (1, 2) = frame 2 * 16 + 1.
    let stitched = wsi_raw(&[&object], &region(240, 480, 240, 240));
    assert_eq!(stitched.tiles_decoded, 1);
    assert_eq!(stitched.frame.bytes, frame_pixels(33).bytes);
    // The partial last column of row 0 (frame 15): only its first 10 columns are in the slide.
    let edge = wsi_raw(&[&object], &region(3600, 0, 50, 240));
    assert_eq!((edge.frame.width, edge.frame.height), (10, 240));
    assert_eq!(edge.frame.bytes, crop(&frame_pixels(15), 0, 0, 10, 240));
    // A region straddling four tiles matches the four frames' corners.
    let quad = wsi_raw(&[&object], &region(230, 230, 20, 20));
    assert_eq!(quad.tiles_decoded, 4);
    assert_eq!(pixel(&quad.frame, 0, 0), pixel(&frame_pixels(0), 230, 230));
    assert_eq!(pixel(&quad.frame, 19, 0), pixel(&frame_pixels(1), 9, 230));
    assert_eq!(pixel(&quad.frame, 0, 19), pixel(&frame_pixels(16), 230, 9));
    assert_eq!(pixel(&quad.frame, 19, 19), pixel(&frame_pixels(17), 9, 9));
}

#[test]
fn wsi_pyramid_levels_are_ordered_and_chosen_by_output_size() {
    let levels = describe_wsi_files(&pyramid_paths()).unwrap();
    let sizes: Vec<_> = levels
        .iter()
        .map(|level| (level.total_columns, level.total_rows, level.input_index))
        .collect();
    assert_eq!(sizes, vec![(1000, 750, 1), (500, 375, 2), (250, 188, 0)]);
    assert_eq!(levels[0].image_type[0], "ORIGINAL");
    assert_eq!(levels[1].image_type[3], "RESAMPLED");
    assert_eq!(levels[2].downsample, 4.0);

    let render = |render: RenderPipelineOptions| {
        render_wsi_files(
            &pyramid_paths(),
            RenderOutputFormat::Raw,
            &WsiRenderOptions {
                render,
                ..Default::default()
            },
        )
        .unwrap()
    };
    let scaled = |max| RenderPipelineOptions {
        scale_max_size: Some(max),
        ..Default::default()
    };
    // Native size: the base level. 500px wide: exactly level 1. 300px: level 1 is the coarsest
    // with enough resolution. 250 and 100: level 2.
    for (options, expected_level, expected_size) in [
        (RenderPipelineOptions::default(), 0, (1000, 750)),
        (scaled(500), 1, (500, 375)),
        (scaled(300), 1, (300, 225)),
        (scaled(250), 2, (250, 188)),
        (scaled(100), 2, (100, 75)),
    ] {
        let output = render(options);
        assert_eq!(output.level.index, expected_level);
        assert_eq!((output.frame.width, output.frame.height), expected_size);
    }

    // A region maps onto the chosen level by the matrix ratio: base (800,600)+200x150 at 50px
    // wide needs 4x - level 2, level region (200,150)+50x38 (rounded outward).
    let output = render(RenderPipelineOptions {
        region: Some(Region::new(800, 600, 200, 150)),
        output_width: Some(50),
        ..Default::default()
    });
    assert_eq!(output.level.index, 2);
    assert_eq!(output.level_region, Region::new(200, 150, 50, 38));
    assert_eq!((output.frame.width, output.frame.height), (50, 38));
    // The green marker (base 900..964 x 680..740) lands at ~(25..41, 20..35).
    assert_close(
        pixel(&output.frame, 33, 27),
        [0, 200, 0],
        16,
        "green at level 2",
    );

    // A forced level ignores the output size for selection.
    let forced = render_wsi_files(
        &pyramid_paths(),
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            render: scaled(100),
            level: Some(0),
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!(forced.level.index, 0);
    assert_eq!((forced.frame.width, forced.frame.height), (100, 75));
}

#[test]
fn wsi_levels_agree_on_the_same_region() {
    let objects: Vec<_> = pyramid_paths()
        .iter()
        .map(|path| read_dicom_file(path).unwrap())
        .collect();
    let refs: Vec<_> = objects.iter().collect();
    let at_level = |level| {
        wsi_raw(
            &refs,
            &WsiRenderOptions {
                render: RenderPipelineOptions {
                    region: Some(Region::new(200, 0, 400, 300)),
                    output_width: Some(100),
                    output_height: Some(75),
                    ..Default::default()
                },
                level: Some(level),
                ..Default::default()
            },
        )
        .frame
    };
    let base = at_level(0);
    for level in 1..3 {
        let other = at_level(level);
        let mean_error = base
            .bytes
            .iter()
            .zip(other.bytes.iter())
            .map(|(a, b)| f64::from(a.abs_diff(*b)))
            .sum::<f64>()
            / base.bytes.len() as f64;
        assert!(
            mean_error < 8.0,
            "level {level} differs by {mean_error:.2} on average"
        );
    }
}

#[test]
fn wsi_whole_slide_downsample_from_a_single_level_box_averages_tiles() {
    let object = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    // 520x330 -> 52x33: a decimation of exactly 10, so every output pixel is the mean of a
    // 10x10 block, background-filled where tiles are missing.
    let output = wsi_raw(
        &[&object],
        &WsiRenderOptions {
            render: RenderPipelineOptions {
                output_width: Some(52),
                ..Default::default()
            },
            ..Default::default()
        },
    );
    assert_eq!((output.frame.width, output.frame.height), (52, 33));
    let block_mean = |bx: u32, by: u32| {
        let mut sums = [0u32; 3];
        for y in by * 10..by * 10 + 10 {
            for x in bx * 10..bx * 10 + 10 {
                let value = if sparse_missing(x, y) {
                    [255, 255, 255]
                } else {
                    sparse_expected(x, y)
                };
                for channel in 0..3 {
                    sums[channel] += u32::from(value[channel]);
                }
            }
        }
        sums.map(|sum| ((sum + 50) / 100) as u8)
    };
    for (bx, by) in [(0, 0), (5, 3), (15, 15), (30, 30), (51, 32), (20, 13)] {
        assert_eq!(
            pixel(&output.frame, bx, by),
            block_mean(bx, by),
            "block ({bx},{by})"
        );
    }

    // The real slide, whole, to a 512px thumbnail.
    let real = read_dicom_file(fixture("wsi.dcm")).unwrap();
    let thumbnail = render_wsi(
        &[&real],
        RenderOutputFormat::Png,
        &WsiRenderOptions {
            render: RenderPipelineOptions {
                scale_max_size: Some(512),
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!((thumbnail.frame.width, thumbnail.frame.height), (512, 194));
    assert_eq!(thumbnail.tiles_decoded, 96);
    assert!(image::load_from_memory(&thumbnail.frame.bytes).is_ok());
}

#[test]
fn wsi_output_size_is_capped() {
    let object = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    let error = render_wsi(
        &[&object],
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            max_output_pixels: 10_000,
            ..Default::default()
        },
    )
    .unwrap_err();
    assert!(error.to_string().contains("over the limit"), "{error}");
    // Asking for a smaller output fits.
    let small = render_wsi(
        &[&object],
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            max_output_pixels: 10_000,
            render: RenderPipelineOptions {
                scale_max_size: Some(100),
                ..Default::default()
            },
            ..Default::default()
        },
    )
    .unwrap();
    assert_eq!((small.frame.width, small.frame.height), (100, 63));
}

#[test]
fn wsi_rejects_mixed_series_and_bad_level() {
    let a = read_dicom_file(synth("sparse_native.dcm")).unwrap();
    let b = read_dicom_file(synth("full_mono_2planes.dcm")).unwrap();
    let error = describe_wsi(&[&a, &b]).unwrap_err();
    assert!(error.to_string().contains("different series"), "{error}");
    let error = render_wsi(
        &[&a],
        RenderOutputFormat::Raw,
        &WsiRenderOptions {
            level: Some(3),
            ..Default::default()
        },
    )
    .unwrap_err();
    assert!(error.to_string().contains("level 3"), "{error}");
}