Skip to main content

qualia_core_db/medical/dicom_geometry/
plane.rs

1use super::{metadata::valid_uid, GeometryAttribute};
2use crate::dicom::DicomMetadata;
3
4/// Absolute tolerance for squared unit norms and vector dot products. Rounded
5/// DS direction cosines within this bound are retained, never silently repaired.
6pub const ORTHONORMAL_TOLERANCE: f64 = 1e-6;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum GeometryError {
10    Missing(GeometryAttribute),
11    Invalid(GeometryAttribute),
12    UnsupportedQuadruped,
13    NonFiniteMappedPosition,
14}
15impl std::fmt::Display for GeometryError {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        match self {
18            Self::Missing(field) => write!(f, "missing DICOM geometry: {field:?}"),
19            Self::Invalid(field) => write!(f, "invalid DICOM geometry: {field:?}"),
20            Self::UnsupportedQuadruped => write!(
21                f,
22                "QUADRUPED geometry is unsupported by the BIPED LPS adapter"
23            ),
24            Self::NonFiniteMappedPosition => {
25                write!(f, "pixel mapping exceeds finite patient-space coordinates")
26            }
27        }
28    }
29}
30impl std::error::Error for GeometryError {}
31
32/// Explicit metadata for exactly one frame. Enhanced-frame extraction can supply
33/// this input, but this API does not parse Shared/Per-Frame Functional Groups or
34/// copy one top-level plane across a multi-frame dataset.
35#[derive(Clone, Copy, Debug, Default)]
36pub struct FrameGeometryInput<'a> {
37    pub image_position_patient: Option<[f64; 3]>,
38    pub image_orientation_patient: Option<[f64; 6]>,
39    /// DICOM order: [row spacing, column spacing], in millimeters.
40    pub pixel_spacing: Option<[f64; 2]>,
41    pub frame_of_reference_uid: Option<&'a str>,
42    /// Missing means BIPED under DICOM C.7.6.2.1.1, not inferred anatomy.
43    pub anatomical_orientation_type: Option<&'a str>,
44    pub invalid_source_fields: &'a [GeometryAttribute],
45}
46
47/// Validated immutable image plane. +X is patient Left, +Y Posterior, +Z Superior;
48/// all positions/distances are millimeters. An absent frame UID stays absent;
49/// neither equal nor absent UIDs establish a registration transform.
50#[derive(Clone, Copy, Debug)]
51pub struct PatientImagePlane<'a> {
52    origin_mm: [f64; 3],
53    first_direction: [f64; 3],
54    second_direction: [f64; 3],
55    spacing_mm: [f64; 2],
56    frame_uid: Option<&'a str>,
57}
58impl<'a> PatientImagePlane<'a> {
59    /// Interpret only the metadata provided for a single frame; no enhanced-frame
60    /// extraction or missing-position/orientation/spacing fallback is performed.
61    pub fn from_metadata(meta: &'a DicomMetadata) -> Result<Self, GeometryError> {
62        Self::from_frame_geometry(FrameGeometryInput {
63            image_position_patient: meta.image_position_patient,
64            image_orientation_patient: meta.image_orientation_patient,
65            pixel_spacing: meta.pixel_spacing,
66            frame_of_reference_uid: meta.frame_of_reference_uid.as_deref(),
67            anatomical_orientation_type: meta.anatomical_orientation_type.as_deref(),
68            invalid_source_fields: &meta.geometry_parse_errors,
69        })
70    }
71    pub fn from_frame_geometry(input: FrameGeometryInput<'a>) -> Result<Self, GeometryError> {
72        use GeometryAttribute::*;
73        if let Some(field) = input.invalid_source_fields.first() {
74            return Err(GeometryError::Invalid(*field));
75        }
76        match input.anatomical_orientation_type {
77            None | Some("BIPED") => {}
78            Some("QUADRUPED") => return Err(GeometryError::UnsupportedQuadruped),
79            _ => return Err(GeometryError::Invalid(AnatomicalOrientationType)),
80        }
81        if input
82            .frame_of_reference_uid
83            .is_some_and(|uid| !valid_uid(uid))
84        {
85            return Err(GeometryError::Invalid(FrameOfReferenceUid));
86        }
87        let origin = input
88            .image_position_patient
89            .ok_or(GeometryError::Missing(ImagePositionPatient))?;
90        if !origin.iter().all(|v| v.is_finite()) {
91            return Err(GeometryError::Invalid(ImagePositionPatient));
92        }
93        let orientation = input
94            .image_orientation_patient
95            .ok_or(GeometryError::Missing(ImageOrientationPatient))?;
96        let first = [orientation[0], orientation[1], orientation[2]];
97        let second = [orientation[3], orientation[4], orientation[5]];
98        if !orientation.iter().all(|v| v.is_finite())
99            || (dot(first, first) - 1.0).abs() > ORTHONORMAL_TOLERANCE
100            || (dot(second, second) - 1.0).abs() > ORTHONORMAL_TOLERANCE
101            || dot(first, second).abs() > ORTHONORMAL_TOLERANCE
102        {
103            return Err(GeometryError::Invalid(ImageOrientationPatient));
104        }
105        let spacing = input
106            .pixel_spacing
107            .ok_or(GeometryError::Missing(PixelSpacing))?;
108        if !spacing.iter().all(|v| v.is_finite() && *v > 0.0) {
109            return Err(GeometryError::Invalid(PixelSpacing));
110        }
111        Ok(Self {
112            origin_mm: origin,
113            first_direction: first,
114            second_direction: second,
115            spacing_mm: spacing,
116            frame_uid: input.frame_of_reference_uid,
117        })
118    }
119    pub fn origin_lps_mm(&self) -> [f64; 3] {
120        self.origin_mm
121    }
122    /// First orientation vector (DICOM row direction), advanced by COLUMN index.
123    pub fn first_direction_lps(&self) -> [f64; 3] {
124        self.first_direction
125    }
126    /// Second orientation vector (DICOM column direction), advanced by ROW index.
127    pub fn second_direction_lps(&self) -> [f64; 3] {
128        self.second_direction
129    }
130    pub fn pixel_spacing_mm(&self) -> [f64; 2] {
131        self.spacing_mm
132    }
133    pub fn frame_of_reference_uid(&self) -> Option<&'a str> {
134        self.frame_uid
135    }
136    /// Cross product of the two supplied orientation vectors; no slice spacing is
137    /// inferred from this normal, SliceThickness or SliceLocation.
138    pub fn normal_lps(&self) -> [f64; 3] {
139        let a = self.first_direction;
140        let b = self.second_direction;
141        [
142            a[1] * b[2] - a[2] * b[1],
143            a[2] * b[0] - a[0] * b[2],
144            a[0] * b[1] - a[1] * b[0],
145        ]
146    }
147    /// Zero-based integer pixel CENTER mapping from C.7.6.2.1-1:
148    /// origin + column * first_direction * column_spacing
149    ///        + row * second_direction * row_spacing.
150    /// The plane has no raster extent: caller checks row/column bounds separately.
151    /// This is not the edge-based sub-pixel convention or a registration API.
152    pub fn pixel_center_lps_mm(
153        &self,
154        column_index: u32,
155        row_index: u32,
156    ) -> Result<[f64; 3], GeometryError> {
157        let column = column_index as f64 * self.spacing_mm[1];
158        let row = row_index as f64 * self.spacing_mm[0];
159        let mut point = self.origin_mm;
160        for (axis, value) in point.iter_mut().enumerate() {
161            *value += column * self.first_direction[axis] + row * self.second_direction[axis];
162        }
163        if !point.iter().all(|v| v.is_finite()) {
164            return Err(GeometryError::NonFiniteMappedPosition);
165        }
166        Ok(point)
167    }
168}
169fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
170    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
171}