Skip to main content

qualia_core_db/medical/dicom_geometry/
metadata.rs

1use crate::dicom::DicomMetadata;
2use serde::{Deserialize, Serialize};
3
4/// Identifies missing or invalid source geometry without replacing it with zeros.
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum GeometryAttribute {
8    ImagePositionPatient,
9    ImageOrientationPatient,
10    PixelSpacing,
11    FrameOfReferenceUid,
12    AnatomicalOrientationType,
13}
14
15/// Strict DS multiplicity/lexical/finite parsing. Numeric DS values may be padded
16/// with spaces, but not NULs, lossy UTF-8, tabs, NaN or infinities.
17fn decimal_array<const N: usize>(value: &[u8]) -> Option<[f64; N]> {
18    let text = std::str::from_utf8(value).ok()?;
19    let mut parts = text.split('\\');
20    let mut values = [0.0; N];
21    for slot in &mut values {
22        let raw = parts.next()?;
23        if raw.len() > 16 {
24            return None;
25        }
26        let part = raw.trim_matches(' ');
27        if part.is_empty()
28            || !part
29                .bytes()
30                .all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E'))
31        {
32            return None;
33        }
34        let value = part.parse::<f64>().ok()?;
35        if !value.is_finite() {
36            return None;
37        }
38        *slot = value;
39    }
40    if parts.next().is_some() {
41        return None;
42    }
43    Some(values)
44}
45
46pub(super) fn valid_uid(value: &str) -> bool {
47    !value.is_empty()
48        && value.len() <= 64
49        && value.bytes().all(|b| b.is_ascii_digit() || b == b'.')
50        && value
51            .split('.')
52            .all(|part| !part.is_empty() && (part.len() == 1 || !part.starts_with('0')))
53}
54fn uid(value: &[u8]) -> Option<String> {
55    let value = value.strip_suffix(&[0]).unwrap_or(value);
56    let text = std::str::from_utf8(value).ok()?;
57    valid_uid(text).then(|| text.to_owned())
58}
59fn orientation_type(value: &[u8]) -> Option<String> {
60    let text = std::str::from_utf8(value).ok()?.trim_matches(' ');
61    matches!(text, "BIPED" | "QUADRUPED").then(|| text.to_owned())
62}
63
64/// Returns true for handled tags. Every duplicate is ambiguous and invalid,
65/// including equal values; invalid diagnostics are sticky. Only five unique
66/// diagnostic entries can arise from this parser.
67pub(crate) fn apply_geometry_value(
68    meta: &mut DicomMetadata,
69    tag: u32,
70    value: &[u8],
71    vr: Option<[u8; 2]>,
72) -> bool {
73    use GeometryAttribute::*;
74    let field = match tag {
75        0x0020_0032 => ImagePositionPatient,
76        0x0020_0037 => ImageOrientationPatient,
77        0x0028_0030 => PixelSpacing,
78        0x0020_0052 => FrameOfReferenceUid,
79        0x0010_2210 => AnatomicalOrientationType,
80        _ => return false,
81    };
82    if meta.geometry_parse_errors.contains(&field) {
83        return true;
84    }
85    let seen = match field {
86        ImagePositionPatient => meta.image_position_patient.is_some(),
87        ImageOrientationPatient => meta.image_orientation_patient.is_some(),
88        PixelSpacing => meta.pixel_spacing.is_some(),
89        FrameOfReferenceUid => meta.frame_of_reference_uid.is_some(),
90        AnatomicalOrientationType => meta.anatomical_orientation_type.is_some(),
91    };
92    if seen {
93        clear_value(meta, field);
94        meta.geometry_parse_errors.push(field);
95        return true;
96    }
97    let expected_vr = match field {
98        ImagePositionPatient | ImageOrientationPatient | PixelSpacing => *b"DS",
99        FrameOfReferenceUid => *b"UI",
100        AnatomicalOrientationType => *b"CS",
101    };
102    // None is the implicit-VR dataset path; explicit wrong VR is malformed.
103    if vr.is_some_and(|actual| actual != expected_vr) {
104        meta.geometry_parse_errors.push(field);
105        clear_value(meta, field);
106        return true;
107    }
108    let valid = match field {
109        ImagePositionPatient => {
110            meta.image_position_patient = decimal_array(value);
111            meta.image_position_patient.is_some()
112        }
113        ImageOrientationPatient => {
114            meta.image_orientation_patient = decimal_array(value);
115            meta.image_orientation_patient.is_some()
116        }
117        PixelSpacing => {
118            meta.pixel_spacing = decimal_array(value);
119            meta.pixel_spacing.is_some()
120        }
121        FrameOfReferenceUid => {
122            meta.frame_of_reference_uid = uid(value);
123            meta.frame_of_reference_uid.is_some()
124        }
125        AnatomicalOrientationType => {
126            meta.anatomical_orientation_type = orientation_type(value);
127            meta.anatomical_orientation_type.is_some()
128        }
129    };
130    if !valid {
131        meta.geometry_parse_errors.push(field);
132    }
133    true
134}
135
136fn clear_value(meta: &mut DicomMetadata, field: GeometryAttribute) {
137    match field {
138        GeometryAttribute::ImagePositionPatient => meta.image_position_patient = None,
139        GeometryAttribute::ImageOrientationPatient => meta.image_orientation_patient = None,
140        GeometryAttribute::PixelSpacing => meta.pixel_spacing = None,
141        GeometryAttribute::FrameOfReferenceUid => meta.frame_of_reference_uid = None,
142        GeometryAttribute::AnatomicalOrientationType => meta.anatomical_orientation_type = None,
143    }
144}