medh5 2.0.0

The MEDH5 format engine: a self-describing HDF5 container for one medical imaging subject and all of its ground truth
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! The 0.x on-disk layout, read-only, and its migration to 1.0 (Appendix B).
//!
//! ```text
//! /images/<name>   one dataset per modality, all the same shape
//! /seg/<name>      one boolean dataset per mask name
//! /bboxes          (n, ndim, 2) integers, slice-like [min, max)
//! /bbox_scores     (n,) floats            (optional)
//! /bbox_labels     (n,) strings           (optional)
//! root attrs       schema_version, label, label_name, extra (JSON), ...
//! /images attrs    shape, spacing, origin, direction (flattened), axis_labels,
//!                  coord_system, patch_size
//! ```
//!
//! The denormalised 0.x flags (`has_seg`, `seg_names`, `image_names`) are
//! ignored in favour of what the file actually contains.  Four migration
//! steps are not mechanical and each is reported: the voxel encoding, the
//! half-voxel box shift, the minted label set, and the grouping.  So is the
//! geometry a file does not state, which is never invented: without a spacing
//! the grid is uncalibrated (`px`, §3.5).

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use ndarray::ArrayD;
use serde_json::{json, Map, Value};

use super::grouping::{
    group_by_subject, note_instance_ids, output_name, sanitize_key, sanitize_stem, Occasion, SubjectGroup,
};
use super::report::ConversionReport;
use crate::annotations::Assertions;
use crate::array::NdArray;
use crate::h5::attrs::{self, AttrValue};
use crate::h5::{data, ops};
use crate::json::repr_str;
use crate::labels::{ClassKey, LabelClass, LabelSet, MAX_CLASS_ID};
use crate::sample::{
    create, Annotated, AnnotationOptions, GridOptions, ImageOptions, ObjectFields, Placement, QualityArg,
    SegmentationOptions, SegmentationSource,
};
use crate::{Error, Result, VERSION};

/// The only 0.x schema version that ever shipped.
pub const SCHEMA_VERSION: &str = "1";
/// 0.x `[min, max)` integer boxes sit at voxel edges once shifted (§8.1).
pub const BOX_SHIFT: f64 = -0.5;

/// A 0.x sample-level label.
#[derive(Debug, Clone, PartialEq)]
pub enum LegacyLabel {
    Int(i64),
    Float(f64),
    Bool(bool),
    Text(String),
}

impl LegacyLabel {
    /// Python's `str()`.
    pub fn text(&self) -> String {
        match self {
            LegacyLabel::Int(i) => i.to_string(),
            LegacyLabel::Float(f) => crate::json::py_float(*f),
            LegacyLabel::Bool(b) => if *b { "True" } else { "False" }.into(),
            LegacyLabel::Text(t) => t.clone(),
        }
    }
}

/// 0.x geometry: one grid shared by every image in the file.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LegacySpatial {
    pub spacing: Option<Vec<f64>>,
    pub origin: Option<Vec<f64>>,
    pub direction: Option<Vec<Vec<f64>>>,
    pub axis_labels: Option<Vec<String>>,
    pub coord_system: Option<String>,
}

/// 0.x metadata, as far as a migration needs it.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct LegacyMeta {
    pub spatial: LegacySpatial,
    pub shape: Option<Vec<i64>>,
    pub image_names: Vec<String>,
    pub seg_names: Vec<String>,
    pub label: Option<LegacyLabel>,
    pub label_name: Option<String>,
    pub patch_size: Option<Vec<i64>>,
    pub extra: Map<String, Value>,
    pub schema_version: String,
}

/// A whole 0.x file in memory.
#[derive(Debug, Clone)]
pub struct LegacySample {
    pub images: IndexMap<String, NdArray>,
    pub seg: IndexMap<String, ArrayD<bool>>,
    pub bboxes: Option<ArrayD<f64>>,
    pub bbox_scores: Option<Vec<f64>>,
    pub bbox_labels: Option<Vec<String>>,
    pub meta: LegacyMeta,
}

fn open_legacy(path: &Path) -> Result<hdf5::File> {
    crate::h5::init();
    let text = path.to_string_lossy().into_owned();
    let handle = hdf5::File::open(path)
        .map_err(|e| Error::File(format!("cannot open {} as a 0.x file: {e}", repr_str(&text))))?;
    crate::h5::ops::check_self_contained(&handle, Some(path))?;
    if ops::exists(&handle, "meta") {
        return Err(Error::Schema(format!("{} is a 1.0 file (it has `/meta`), not a 0.x file", repr_str(&text))));
    }
    if ops::child_group(&handle, "images").is_none() {
        return Err(Error::Schema(format!("{} has no 0.x `/images` group", repr_str(&text))));
    }
    let version = attrs::get_str(&handle, "schema_version")?.unwrap_or_else(|| SCHEMA_VERSION.into());
    if version != SCHEMA_VERSION {
        return Err(Error::Schema(format!(
            "{} declares 0.x schema version {}; this reader understands {}",
            repr_str(&text),
            repr_str(&version),
            repr_str(SCHEMA_VERSION)
        )));
    }
    Ok(handle)
}

/// Whether `path` is a readable 0.x file.
pub fn is_legacy(path: &Path) -> bool {
    open_legacy(path).is_ok()
}

fn read_meta_from(handle: &hdf5::File) -> Result<LegacyMeta> {
    let mut meta = LegacyMeta::default();
    let group = handle.group("images")?;
    meta.image_names = ops::members(&group)?;
    let spatial = &mut meta.spatial;
    spatial.spacing = attrs::get_f64s(&group, "spacing")?;
    spatial.origin = attrs::get_f64s(&group, "origin")?;
    spatial.axis_labels = attrs::get_strs(&group, "axis_labels")?;
    spatial.coord_system = attrs::get_str(&group, "coord_system")?;
    meta.shape = attrs::get_i64s(&group, "shape")?;
    meta.patch_size = attrs::get_i64s(&group, "patch_size")?;
    if let (Some(raw), Some(first)) = (attrs::get_f64s(&group, "direction")?, meta.image_names.first()) {
        let ndim = group.dataset(first)?.ndim();
        if raw.len() != ndim * ndim {
            return Err(Error::Schema(format!(
                "0.x `direction` has {} element(s), not {} for a {ndim}-D volume",
                raw.len(),
                ndim * ndim
            )));
        }
        meta.spatial.direction = Some(raw.chunks(ndim.max(1)).map(<[f64]>::to_vec).collect());
    }
    meta.label = match attrs::read(handle, "label")? {
        None => None,
        Some(AttrValue::Int(i)) => Some(LegacyLabel::Int(i)),
        Some(AttrValue::Float(f)) => Some(LegacyLabel::Float(f)),
        Some(AttrValue::Bool(b)) => Some(LegacyLabel::Bool(b)),
        Some(other) => {
            let text = other.as_str().unwrap_or_else(|| attrs::stringify_value(&other));
            Some(match text.trim().parse::<i64>() {
                Ok(i) => LegacyLabel::Int(i),
                Err(_) => LegacyLabel::Text(text),
            })
        }
    };
    meta.label_name = attrs::get_str(handle, "label_name")?;
    if let Some(text) = attrs::get_str(handle, "extra")? {
        let parsed =
            crate::json::loads(&text).map_err(|e| Error::Schema(format!("0.x attribute 'extra' is not JSON: {e}")))?;
        if let Value::Object(m) = parsed {
            meta.extra = m;
        }
    }
    meta.schema_version = attrs::get_str(handle, "schema_version")?.unwrap_or_else(|| SCHEMA_VERSION.into());
    meta.seg_names = match ops::child_group(handle, "seg") {
        Some(g) => ops::members(&g)?,
        None => Vec::new(),
    };
    Ok(meta)
}

/// Read 0.x metadata without touching the arrays.
pub fn read_meta(path: &Path) -> Result<LegacyMeta> {
    read_meta_from(&open_legacy(path)?)
}

/// The `bbox_labels` of a 0.x file, without reading anything else.
pub fn read_bbox_labels(path: &Path) -> Result<Option<Vec<String>>> {
    let handle = open_legacy(path)?;
    match ops::child_dataset(&handle, "bbox_labels") {
        None => Ok(None),
        Some(ds) => Ok(Some(data::read_strings(&ds)?)),
    }
}

/// Read a whole 0.x file: images, masks, boxes and metadata.
pub fn read_sample(path: &Path) -> Result<LegacySample> {
    let handle = open_legacy(path)?;
    let group = handle.group("images")?;
    let mut images = IndexMap::new();
    for name in ops::members(&group)? {
        images.insert(name.clone(), data::read(&group.dataset(&name)?)?);
    }
    let mut seg = IndexMap::new();
    if let Some(g) = ops::child_group(&handle, "seg") {
        for name in ops::members(&g)? {
            seg.insert(name.clone(), data::read(&g.dataset(&name)?)?.nonzero_mask());
        }
    }
    let bboxes = match ops::child_dataset(&handle, "bboxes") {
        Some(ds) => Some(data::read(&ds)?.to_f64()),
        None => None,
    };
    let bbox_scores = match ops::child_dataset(&handle, "bbox_scores") {
        Some(ds) => Some(data::read(&ds)?.to_f64().iter().copied().collect()),
        None => None,
    };
    let bbox_labels = match ops::child_dataset(&handle, "bbox_labels") {
        Some(ds) => Some(data::read_strings(&ds)?),
        None => None,
    };
    let meta = read_meta_from(&handle)?;
    Ok(LegacySample { images, seg, bboxes, bbox_scores, bbox_labels, meta })
}

fn key(name: &str) -> String {
    sanitize_key(name, "class")
}

/// A sample id from a subject id: §2.3's identifier rule, lowercased.
pub fn sample_key(subject_id: &str) -> String {
    let stem = sanitize_stem(subject_id.trim(), 128);
    if stem.is_empty() {
        "sample".to_string()
    } else {
        stem.to_lowercase()
    }
}

/// Mint one label set covering a whole cohort's mask names and box labels.
///
/// Cohort-wide rather than per file, so `liver` has one id everywhere; ids an
/// `extra.nnunetv2.labels` mapping already fixed are reused.  A class is a
/// key, so names that sanitize to one key (`liver`, `Liver`) are one class,
/// and the report names them; two files' mappings that disagree keep the
/// first one's id, as does an id two keys ask for, and each is a warning.
/// Keyed by name instead, `liver` and `Liver` were two classes with one key,
/// and the label set a curator is asked to review was refused (E302).
pub fn build_label_set(paths: &[&Path], mut report: Option<&mut ConversionReport>) -> Result<LabelSet> {
    let mut names: IndexMap<String, Vec<String>> = IndexMap::new();
    let mut add = |name: &str| {
        let spellings = names.entry(key(name)).or_default();
        if !spellings.iter().any(|n| n == name) {
            spellings.push(name.to_string());
        }
    };
    // key -> (id, the file whose mapping gave it)
    let mut reused: IndexMap<String, (i64, String)> = IndexMap::new();
    let mut conflicts: Vec<(String, String, i64, String, i64)> = Vec::new();
    for path in paths {
        let Ok(meta) = read_meta(path) else { continue };
        let source = path.to_string_lossy().into_owned();
        for name in &meta.seg_names {
            add(name);
        }
        if let Some(Value::Object(labels)) = meta.extra.get("nnunetv2").and_then(|n| n.get("labels")) {
            for (label, value) in labels {
                let Some(v) = value.as_i64().filter(|v| (1..=MAX_CLASS_ID).contains(v) && value.is_i64()) else {
                    continue;
                };
                match reused.get(&key(label)) {
                    None => {
                        reused.insert(key(label), (v, source.clone()));
                    }
                    Some((kept, first)) if *kept != v => {
                        conflicts.push((key(label), first.clone(), *kept, source.clone(), v));
                    }
                    Some(_) => {}
                }
            }
        }
        let has_boxes = open_legacy(path).map(|h| ops::exists(&h, "bboxes")).unwrap_or(false);
        match read_bbox_labels(path) {
            Ok(Some(labels)) => {
                for label in labels {
                    add(&label);
                }
            }
            // Unlabelled 0.x boxes migrate as class `object`, which the label
            // set must therefore declare.
            Ok(None) if has_boxes => add("object"),
            _ => {}
        }
    }
    // An id goes to the first key whose mapping asks for it; a later key
    // asking for it is minted another.
    let mut owner: IndexMap<i64, String> = IndexMap::new();
    let mut shared: Vec<(String, String, i64)> = Vec::new();
    for (k, (id, _)) in &reused {
        if !names.contains_key(k) {
            continue;
        }
        match owner.get(id) {
            Some(first) => shared.push((k.clone(), first.clone(), *id)),
            None => {
                owner.insert(*id, k.clone());
            }
        }
    }
    let mut classes = Vec::new();
    let mut used: BTreeSet<i64> = reused.values().map(|(id, _)| *id).collect();
    let mut next_id = 1;
    for (k, spellings) in &names {
        let class_id = match reused.get(k).filter(|(id, _)| owner.get(id) == Some(k)) {
            Some((id, _)) => *id,
            None => {
                while used.contains(&next_id) {
                    next_id += 1;
                }
                used.insert(next_id);
                next_id
            }
        };
        classes.push(LabelClass::new(class_id, k.clone(), spellings[0].clone())?);
    }
    if let Some(log) = report.as_deref_mut() {
        for (k, spellings) in names.iter().filter(|(_, s)| s.len() > 1) {
            log.guess(
                "label_set",
                format!(
                    "names {} all became class key {}, so they are one class; edit the label set if they are not",
                    crate::json::repr_list(spellings),
                    repr_str(k)
                ),
                json!({"key": k, "names": spellings}),
            );
        }
        for (k, first, kept, source, other) in &conflicts {
            log.warn(
                "label_set",
                format!(
                    "{source}: extra.nnunetv2.labels gives {} id {other}, and {first}'s gives it {kept}; the label set \
                     keeps {kept}",
                    repr_str(k)
                ),
                json!({"key": k, "kept": kept, "kept_from": first, "ignored": other, "source": source}),
            );
        }
        for (k, first, id) in &shared {
            let minted = classes.iter().find(|c| &c.key == k).map(|c| c.id).unwrap_or_default();
            log.warn(
                "label_set",
                format!(
                    "extra.nnunetv2.labels gives id {id} to {} and to {}; {} keeps it, and {} is id {minted}",
                    repr_str(first),
                    repr_str(k),
                    repr_str(first),
                    repr_str(k)
                ),
                json!({"id": id, "kept_by": first, "key": k, "minted": minted}),
            );
        }
    }
    if let Some(log) = report {
        let ids: Map<String, Value> = classes.iter().map(|c| (c.key.clone(), json!(c.id))).collect();
        let mut reused_keys: Vec<&String> = reused.keys().collect();
        reused_keys.sort();
        log.decision(
            "label_set",
            format!(
                "{} class(es) were minted across {} file(s); {}",
                classes.len(),
                paths.len(),
                if reused.is_empty() {
                    "no existing id mapping was found, so ids are sequential".to_string()
                } else {
                    format!("{} id(s) came from an existing extra.nnunetv2.labels mapping", reused.len())
                }
            ),
            json!({"ids": ids, "reused": reused_keys}),
        );
    }
    LabelSet::new("migrated", classes, "1.0.0", Vec::new(), Vec::new(), "inline", None, None)
}

/// Migrate one 0.x file into one 1.0 sample.
pub fn migrate(
    path: &Path,
    out: &Path,
    label_set: Option<&LabelSet>,
    codec: &str,
    report: Option<ConversionReport>,
) -> Result<ConversionReport> {
    let mut log = report.unwrap_or_else(|| ConversionReport::new("migrate", ""));
    log.source = path.to_string_lossy().into_owned();
    let labels = match label_set {
        Some(l) => l.clone(),
        None => build_label_set(&[path], Some(&mut log))?,
    };
    let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
    let group = SubjectGroup {
        subject_id: stem,
        occasions: vec![Occasion { key: log.source.clone(), payload: 0, ..Default::default() }],
        ordered_by: "given".into(),
    };
    write_group(&group, &[path.to_path_buf()], out, &labels, codec, &mut log)?;
    Ok(log)
}

fn date_of(meta: &LegacyMeta) -> Option<String> {
    for k in ["study_date", "date", "acquisition_date"] {
        if let Some(v) = meta.extra.get(k) {
            let truthy = match v {
                Value::Null => false,
                Value::Bool(b) => *b,
                Value::String(s) => !s.is_empty(),
                Value::Number(n) => n.as_f64() != Some(0.0),
                Value::Array(a) => !a.is_empty(),
                Value::Object(o) => !o.is_empty(),
            };
            if truthy {
                return Some(crate::json::py_str(v));
            }
        }
    }
    None
}

fn subject_key_of(meta: &LegacyMeta, path_key: Option<&str>) -> Option<String> {
    let path_key = path_key.filter(|k| !k.is_empty())?;
    let mut node = json!({"extra": meta.extra});
    for part in path_key.split('.') {
        node = node.as_object()?.get(part)?.clone();
    }
    match &node {
        Value::Null => None,
        Value::String(s) if s.is_empty() => None,
        other => Some(crate::json::py_str(other)),
    }
}

/// Migrate a cohort, minting one label set for all of it.
///
/// A file that is not 0.x is reported (`unreadable`), and so is one whose
/// content cannot be written (`failed`, with nothing written for the sample
/// it belongs to); the rest of the cohort is migrated.
pub fn migrate_paths(
    paths: &[&Path],
    outdir: &Path,
    group_by: &str,
    subject_key: Option<&str>,
    label_set: Option<&LabelSet>,
    codec: &str,
) -> Result<ConversionReport> {
    std::fs::create_dir_all(outdir)?;
    let mut log = ConversionReport::new("migrate", &format!("{} file(s)", paths.len()));
    let labels = match label_set {
        Some(l) => l.clone(),
        None => build_label_set(paths, Some(&mut log))?,
    };
    let mut occasions = Vec::new();
    let mut sources = Vec::new();
    for path in paths {
        let text = path.to_string_lossy().into_owned();
        let meta = match read_meta(path) {
            Ok(m) => m,
            Err(e) => {
                log.warn("unreadable", format!("{text}: {e}"), json!({"path": text}));
                continue;
            }
        };
        let mtime = std::fs::metadata(path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| d.as_secs_f64());
        occasions.push(Occasion {
            key: text,
            subject_id: subject_key_of(&meta, subject_key),
            date: date_of(&meta),
            order_hint: mtime,
            demographics: IndexMap::new(),
            payload: sources.len(),
        });
        sources.push(path.to_path_buf());
    }
    if group_by == "subject" && subject_key.is_none() {
        log.warn(
            "grouping",
            "--group-by subject needs --subject-key: a 0.x file has no subject field of its own, and identity is never \
             inferred from filenames",
            json!({}),
        );
    }
    let groups = group_by_subject(occasions, group_by, Some(&mut log))?;
    let mut used = BTreeSet::new();
    for group in groups {
        let name = output_name(&group, &mut used, &|s: &str| sample_key(s));
        let target = outdir.join(format!("{name}.medh5"));
        // A file whose content cannot be migrated is reported, and the rest
        // of the cohort is: the first such file used to end the migration,
        // with the files after it never written.
        if let Err(e) = write_group(&group, &sources, &target, &labels, codec, &mut log) {
            let inputs: Vec<&str> = group.occasions.iter().map(|o| o.key.as_str()).collect();
            log.warn(
                "failed",
                format!("{}: {e}; nothing was written for it", inputs.join(", ")),
                json!({"inputs": inputs, "output": target.to_string_lossy()}),
            );
        }
    }
    Ok(log)
}

fn write_group(
    group: &SubjectGroup,
    sources: &[PathBuf],
    target: &Path,
    label_set: &LabelSet,
    codec: &str,
    log: &mut ConversionReport,
) -> Result<()> {
    // An order by mtime is reported where the grouping chose it.
    note_instance_ids(group, log);
    let days = group.days_from_baseline();
    let mut writer = create(target, Some(&sample_key(&group.subject_id)), Some(&group.subject_id), codec, &[])?;
    let result = (|| -> Result<()> {
        writer.label_set(label_set.clone());
        let tool = writer.software("medh5", Some(VERSION), Map::new())?;
        for (index, d) in days.iter().enumerate() {
            let mut fields = Map::new();
            fields.insert("index".into(), json!(index));
            fields.insert("days_from_baseline".into(), json!(d));
            writer.add_timepoint(&format!("tp{index}"), fields)?;
        }
        let single = group.occasions.len() == 1;
        let mut extra = LegacyExtra::default();
        for (index, occasion) in group.occasions.iter().enumerate() {
            let source = &sources[occasion.payload];
            let sample = read_sample(source)?;
            let timepoint = format!("tp{index}");
            migrate_one(&mut writer, &sample, &source.to_string_lossy(), &timepoint, label_set, &tool.id, log, single)?;
            extra.add(&sample.meta.extra, &timepoint, &source.to_string_lossy(), log);
        }
        extra.write(&mut writer);
        writer.commit(true)?;
        Ok(())
    })();
    if let Err(e) = result {
        writer.abort();
        return Err(e);
    }
    log.outputs.push(target.to_string_lossy().into_owned());
    Ok(())
}

/// The 0.x `extra` of a subject's files, as `/meta` keeps it (Appendix B).
///
/// `extra.nnunetv2` is preserved verbatim at `/meta → extra.nnunetv2`, where
/// the nnU-Net exporter reads a stashed `dataset.json`; the other keys are
/// kept under `extra.legacy`, one entry per timepoint.  Every file's whole
/// `extra` went to `extra.legacy`, so the stash was never where it is read,
/// and in a grouped migration each file's replaced the one before.  A later
/// file whose `nnunetv2` differs from the first's
/// keeps it in its own entry, and the report says so: one sample has one
/// `dataset.json`.
#[derive(Default)]
struct LegacyExtra {
    nnunetv2: Option<(Value, String)>,
    legacy: Map<String, Value>,
}

impl LegacyExtra {
    fn add(&mut self, extra: &Map<String, Value>, timepoint: &str, source: &str, log: &mut ConversionReport) {
        let mut rest = extra.clone();
        if let Some(stash) = rest.remove("nnunetv2") {
            match &self.nnunetv2 {
                None => self.nnunetv2 = Some((stash, source.to_string())),
                Some((kept, _)) if *kept == stash => {}
                Some((_, first)) => {
                    log.warn(
                        "nnunetv2",
                        format!(
                            "{source}: extra.nnunetv2 differs from {first}'s, which the sample keeps as its \
                             extra.nnunetv2; this one stays in extra.legacy.{timepoint}.nnunetv2"
                        ),
                        json!({"source": source, "kept": first, "timepoint": timepoint}),
                    );
                    rest.insert("nnunetv2".into(), stash);
                }
            }
        }
        if !rest.is_empty() {
            self.legacy.insert(timepoint.to_string(), Value::Object(rest));
        }
    }

    fn write(self, writer: &mut crate::sample::SampleWriter) {
        if let Some((stash, _)) = self.nnunetv2 {
            writer.extra("nnunetv2", stash);
        }
        if !self.legacy.is_empty() {
            writer.extra("legacy", Value::Object(self.legacy));
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn migrate_one(
    writer: &mut crate::sample::SampleWriter,
    sample: &LegacySample,
    source: &str,
    timepoint: &str,
    label_set: &LabelSet,
    tool: &str,
    log: &mut ConversionReport,
    single: bool,
) -> Result<()> {
    let meta = &sample.meta;
    let suffix = if single { String::new() } else { format!("_{timepoint}") };
    let mut fields = Map::new();
    fields.insert("tool".into(), json!("medh5 migrate"));
    fields.insert("inputs".into(), json!([format!("medh5-0.x:{source}")]));
    let activity = writer.activity("import", Some(tool), None, fields)?;
    let grid_id = format!("ref{suffix}");
    let spatial = &meta.spatial;
    let (_, first) = sample.images.first().ok_or_else(|| Error::Schema(format!("{source}: 0.x file has no images")))?;
    let shape: Vec<i64> = first.shape().iter().map(|v| *v as i64).collect();
    let direction = match &spatial.direction {
        Some(rows) => {
            Some(ndarray::Array2::from_shape_vec((rows.len(), rows.len()), rows.iter().flatten().copied().collect())?)
        }
        None => None,
    };
    // A 0.x file need not state its geometry.  Without a spacing the grid is
    // uncalibrated (§3.5) rather than one of millimetre voxels nobody
    // measured, and a coord_system it does not state is an assumption.
    let (spacing, units) = match &spatial.spacing {
        Some(spacing) => (spacing.clone(), None),
        None => {
            log.decision(
                "geometry",
                format!(
                    "{source}: the file states no spacing, so grid {} is uncalibrated --- units 'px' (§3.5), one per \
                     voxel --- rather than given a size nobody measured",
                    repr_str(&grid_id)
                ),
                json!({"source": source, "grid": grid_id, "units": "px"}),
            );
            (vec![1.0; shape.len()], Some("px".to_string()))
        }
    };
    let coord_system = match &spatial.coord_system {
        Some(coord_system) => coord_system.clone(),
        None => {
            log.guess(
                "geometry",
                format!(
                    "{source}: the file states no coord_system, and grid {} was written as 'LPS', which nothing in it \
                     confirms",
                    repr_str(&grid_id)
                ),
                json!({"source": source, "grid": grid_id, "coord_system": "LPS"}),
            );
            "LPS".to_string()
        }
    };
    writer.add_grid(
        &grid_id,
        &shape,
        &spacing,
        GridOptions {
            origin: spatial.origin.clone(),
            direction,
            axis_names: spatial.axis_labels.clone(),
            coord_system: Some(coord_system),
            units,
            timepoint: Some(timepoint.into()),
            patch_hint: meta.patch_size.clone(),
            ..Default::default()
        },
    )?;
    let mut names: Vec<&String> = sample.images.keys().collect();
    names.sort();
    for name in names {
        writer.add_image(
            &format!("{name}{suffix}"),
            &sample.images[name],
            &grid_id,
            "OT",
            ImageOptions { prov: Some(activity.id.clone()), ..Default::default() },
        )?;
    }
    // The review is of what the file held: each annotation migrated from it
    // carries the review's quality record, and the review names them.
    let review = match meta.extra.get("review") {
        Some(Value::Object(review)) => Some(LegacyReview::read(writer, review)?),
        _ => None,
    };
    let quality = review.as_ref().map(|r| QualityArg::Record(r.quality.clone()));
    let mut written: Vec<String> = Vec::new();
    if !sample.seg.is_empty() {
        let mut seg_names: Vec<&String> = sample.seg.keys().collect();
        seg_names.sort();
        let mut masks: Vec<(ClassKey, ArrayD<bool>)> = Vec::new();
        let mut annotated = Vec::new();
        for name in &seg_names {
            let class = ClassKey::Id(label_set.lookup(&ClassKey::Key(key(name)))?.id);
            let mask = &sample.seg[*name];
            // Names of one class key are one class, so their masks are its
            // voxels together; passed apart, the second replaced the first.
            match masks.iter_mut().find(|(k, _)| *k == class) {
                Some((_, kept)) if kept.shape() == mask.shape() => kept.zip_mut_with(mask, |a, b| *a |= *b),
                Some(_) => {
                    return Err(Error::coded(
                        "E405",
                        format!("{source}: the masks of class {} differ in shape", repr_str(&key(name))),
                    ))
                }
                None => {
                    masks.push((class.clone(), mask.clone()));
                    annotated.push(class);
                }
            }
        }
        if masks.len() < seg_names.len() {
            log.decision(
                "label_set",
                format!(
                    "{source}: {} masks are {} classes; the masks of names that became one class key are stored as \
                     their union",
                    seg_names.len(),
                    masks.len()
                ),
                json!({"source": source, "masks": seg_names, "classes": masks.len()}),
            );
        }
        let ann_id = format!("seg{suffix}");
        let (kind, stats) = writer.add_segmentation(
            &ann_id,
            &grid_id,
            SegmentationSource::Masks(masks),
            SegmentationOptions {
                common: AnnotationOptions {
                    annotated_classes: Annotated::Classes(annotated),
                    prov: Some(activity.id.clone()),
                    quality: quality.clone(),
                    ..Default::default()
                },
                ..Default::default()
            },
        )?;
        written.push(ann_id);
        log.decision(
            "encoding",
            format!("{source}: {} mask(s) were measured and stored as {}", seg_names.len(), repr_str(&kind)),
            json!({"source": source, "kind": kind, "overlapping_pairs": stats.map(|s| s.edges.len()).unwrap_or(0)}),
        );
        log.guess(
            "coverage",
            format!(
                "{source}: annotated_class_ids was set to the migrated mask names --- the only defensible inference. Widen \
                 or narrow it if the curator knows which classes were actually searched for (§11.3)"
            ),
            json!({"source": source, "classes": seg_names}),
        );
    }
    if let Some(boxes) = sample.bboxes.as_ref().filter(|b| b.shape().first().copied().unwrap_or(0) > 0) {
        let shifted = boxes.mapv(|v| v + BOX_SHIFT);
        let n = shifted.shape()[0];
        let labels = sample.bbox_labels.clone().unwrap_or_else(|| vec!["object".into(); n]);
        let class_ids: Vec<ClassKey> = labels
            .iter()
            .map(|l| Ok(ClassKey::Id(label_set.lookup(&ClassKey::Key(key(l)))?.id)))
            .collect::<Result<_>>()?;
        let stored = shifted.mapv(|v| f64::from(v as f32));
        let ann_id = format!("boxes{suffix}");
        writer.add_boxes(
            &ann_id,
            &stored,
            &class_ids,
            ObjectFields { scores: sample.bbox_scores.clone(), ..Default::default() },
            None,
            Placement { grid: Some(grid_id.clone()), space: Some("index".into()), frame_uid: None },
            AnnotationOptions {
                task: Some("detection".into()),
                prov: Some(activity.id.clone()),
                quality: quality.clone(),
                ..Default::default()
            },
        )?;
        written.push(ann_id);
        log.decision(
            "box_convention",
            format!(
                "{source}: {n} box(es) were shifted by -0.5 on every axis --- 0.x stored slice-like [min, max) integers, \
                 1.0 stores voxel edges, and the numbers differ by half a voxel (§8.1)"
            ),
            json!({"source": source, "boxes": n, "shift": BOX_SHIFT}),
        );
    }
    if let Some(label) = &meta.label {
        let name = meta.label_name.clone().filter(|n| !n.is_empty()).unwrap_or_else(|| label.text());
        match label_set.get(&ClassKey::Key(key(&name))) {
            Some(entry) => {
                let ann_id = format!("label{suffix}");
                writer.add_classification(
                    &ann_id,
                    Assertions { class_ids: vec![entry.id], values: vec![1.0], ..Default::default() },
                    "sample",
                    true,
                    None,
                    AnnotationOptions {
                        timepoints: Some(vec![timepoint.into()]),
                        prov: Some(activity.id.clone()),
                        quality: quality.clone(),
                        ..Default::default()
                    },
                )?;
                written.push(ann_id);
            }
            None => {
                log.warn(
                    "label",
                    format!("{source}: sample label {} is not in the label set and was not migrated", repr_str(&name)),
                    json!({"source": source, "label": name}),
                );
            }
        }
    }
    if let Some(review) = review {
        review.write(writer, &written, log, source)?;
    }
    Ok(())
}

fn timestamp(value: Option<&Value>) -> Option<String> {
    let text = match value? {
        Value::Null => return None,
        Value::String(s) if s.is_empty() => return None,
        other => crate::json::py_str(other),
    };
    if text.ends_with('Z') && text.contains('T') {
        return Some(text);
    }
    if text.chars().count() == 10 && text.chars().nth(4) == Some('-') {
        return Some(format!("{text}T00:00:00Z"));
    }
    None
}

/// A 0.x `extra.review`: who reviewed the file, and their verdict.
///
/// It became a quality record keyed `seg`, whatever the file held, which no
/// annotation named, and a `review` activity whose output was `seg` even in
/// a file of boxes.  The record now rides on each annotation migrated from
/// the file, and the activity names those annotations.  The dict itself
/// stays in the file's `extra.legacy` entry, verbatim, with whatever else it
/// held (Appendix B).
struct LegacyReview {
    agent: Option<String>,
    verdict: String,
    ended: Option<String>,
    quality: Map<String, Value>,
}

impl LegacyReview {
    fn read(writer: &mut crate::sample::SampleWriter, review: &Map<String, Value>) -> Result<LegacyReview> {
        let reviewer =
            review.get("reviewer").or_else(|| review.get("by")).filter(|v| !v.is_null() && v.as_str() != Some(""));
        let agent = match reviewer {
            Some(r) => Some(writer.person(&crate::json::py_str(r), None, Map::new())?.id),
            None => None,
        };
        let verdict = review.get("status").map(crate::json::py_str).unwrap_or_else(|| "reviewed".into());
        let status = verdict.to_lowercase();
        let allowed = ["draft", "submitted", "reviewed", "approved", "rejected", "deprecated"];
        let mut quality = Map::new();
        quality.insert("status".into(), json!(if allowed.contains(&status.as_str()) { &status } else { "reviewed" }));
        quality.insert("reviewed_by".into(), json!(agent.iter().collect::<Vec<_>>()));
        let ended = timestamp(review.get("date").filter(|v| !v.is_null()).or_else(|| review.get("reviewed_at")));
        Ok(LegacyReview { agent, verdict, ended, quality })
    }

    /// The `review` activity, whose outputs are the annotations reviewed.
    fn write(
        self,
        writer: &mut crate::sample::SampleWriter,
        annotations: &[String],
        log: &mut ConversionReport,
        source: &str,
    ) -> Result<()> {
        let mut fields = Map::new();
        if let Some(t) = &self.ended {
            fields.insert("ended".into(), json!(t));
        }
        fields.insert("params".into(), json!({"verdict": self.verdict}));
        let outputs: Vec<String> = annotations.iter().map(|a| format!("annotations/{a}")).collect();
        fields.insert("outputs".into(), json!(outputs));
        writer.activity("review", self.agent.as_deref(), None, fields)?;
        log.decision(
            "review",
            format!(
                "{source}: extra.review became a `review` activity and the quality record of {} --- what the file \
                 held; 0.x kept review state in an ad-hoc dict that could not say what produced the data being \
                 reviewed (§11.1)",
                if annotations.is_empty() { "no annotation".to_string() } else { crate::json::repr_list(annotations) }
            ),
            json!({"source": source, "status": self.verdict.to_lowercase(), "annotations": annotations}),
        );
        Ok(())
    }
}

/// Write the minted label set for review before a cohort-wide migration.
pub fn write_sidecar(label_set: &LabelSet, path: &Path) -> Result<PathBuf> {
    let text = crate::json::dumps(&label_set.to_json(None), crate::json::Style::PYTHON.with_indent(Some(2)));
    std::fs::write(path, format!("{text}\n"))?;
    Ok(path.to_path_buf())
}

/// Read a label-set sidecar back.
pub fn load_sidecar(path: &Path) -> Result<LabelSet> {
    let text = std::fs::read_to_string(path)?;
    let doc = crate::json::loads(&text)?;
    LabelSet::from_json(Some(&doc))?
        .ok_or_else(|| Error::Value(format!("{} holds no label set", path.to_string_lossy())))
}