qualia_core_db/medical/dicom_frames/
quantitative.rs1use super::extract::{macro_item, single_item, FrameError};
2use crate::medical::dicom_dataset::{DatasetError, ItemId, Part10Dataset, WorkBudget};
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum ValueUnits<'a> {
5 Unspecified,
6 RescaleType(&'a str),
7 Code {
8 scheme: &'a str,
9 value: &'a str,
10 meaning: Option<&'a str>,
11 },
12}
13#[derive(Debug, Clone, Copy)]
14pub struct LinearTransform<'a> {
15 slope: f64,
16 intercept: f64,
17 units: ValueUnits<'a>,
18 source_blake3: [u8; 32],
19 frame_number: u32,
20 stored_range: Option<[f64; 2]>,
21}
22impl<'a> LinearTransform<'a> {
23 pub fn slope(&self) -> f64 {
24 self.slope
25 }
26 pub fn intercept(&self) -> f64 {
27 self.intercept
28 }
29 pub fn units(&self) -> ValueUnits<'a> {
30 self.units
31 }
32 pub fn source_blake3(&self) -> [u8; 32] {
33 self.source_blake3
34 }
35 pub fn frame_number(&self) -> u32 {
36 self.frame_number
37 }
38 pub fn stored_range(&self) -> Option<[f64; 2]> {
39 self.stored_range
40 }
41 pub fn apply(&self, stored: f64) -> Result<f64, DatasetError> {
42 if !stored.is_finite()
43 || self
44 .stored_range
45 .is_some_and(|r| stored < r[0] || stored > r[1])
46 {
47 return Err(DatasetError::Invalid(0x00409096));
48 }
49 let value = self.slope * stored + self.intercept;
50 if !value.is_finite() {
51 return Err(DatasetError::Invalid(0x00409096));
52 }
53 Ok(value)
54 }
55}
56#[derive(Debug, Clone, Copy, Default)]
58pub struct QuantitativeStatus<'a> {
59 pub modality: Option<LinearTransform<'a>>,
60 pub real_world: Option<LinearTransform<'a>>,
61 pub unsupported_real_world: Option<&'static str>,
62}
63fn required<'a>(v: Option<&'a str>, tag: u32) -> Result<&'a str, FrameError> {
64 v.ok_or(DatasetError::Missing(tag).into())
65}
66fn ds_number(
67 ds: &Part10Dataset<'_>,
68 scope: Option<ItemId>,
69 tag: u32,
70 w: &mut WorkBudget,
71) -> Result<Option<f64>, FrameError> {
72 ds.text(scope, tag, *b"DS", w)?
73 .map(|s| {
74 if s.len() > 16
75 || s.contains('\\')
76 || !s
77 .bytes()
78 .all(|b| b.is_ascii_digit() || matches!(b, b'+' | b'-' | b'.' | b'e' | b'E'))
79 {
80 return Err(DatasetError::Invalid(tag).into());
81 }
82 let n = s
83 .parse::<f64>()
84 .map_err(|_| FrameError::Dataset(DatasetError::Invalid(tag)))?;
85 if !n.is_finite() {
86 return Err(DatasetError::Invalid(tag).into());
87 }
88 Ok(n)
89 })
90 .transpose()
91}
92fn fd(
93 ds: &Part10Dataset<'_>,
94 item: ItemId,
95 tag: u32,
96 w: &mut WorkBudget,
97) -> Result<Option<f64>, FrameError> {
98 ds.expected_value(Some(item), tag, *b"FD", w)?
99 .map(|b| {
100 let arr: [u8; 8] = b.try_into().map_err(|_| DatasetError::Invalid(tag))?;
101 let n = f64::from_le_bytes(arr);
102 if !n.is_finite() {
103 return Err(DatasetError::Invalid(tag).into());
104 }
105 Ok(n)
106 })
107 .transpose()
108}
109pub(super) fn extract<'a>(
110 ds: &Part10Dataset<'a>,
111 shared: Option<ItemId>,
112 per: Option<ItemId>,
113 enhanced: bool,
114 frame_number: u32,
115 w: &mut WorkBudget,
116) -> Result<QuantitativeStatus<'a>, FrameError> {
117 let mut result = QuantitativeStatus::default();
118 let transform = macro_item(ds, shared, per, 0x00289145, w)?;
119 if enhanced {
120 for tag in [0x00281052, 0x00281053, 0x00281054] {
121 if ds.find(None, tag, w)?.is_some() {
122 return Err(FrameError::TopLevelConflict(tag));
123 }
124 }
125 }
126 let scope = if enhanced { transform } else { None };
127 if !enhanced || transform.is_some() {
128 let slope = ds_number(ds, scope, 0x00281053, w)?;
129 let intercept = ds_number(ds, scope, 0x00281052, w)?;
130 let units = ds.text(scope, 0x00281054, *b"LO", w)?;
131 if slope.is_some() || intercept.is_some() || units.is_some() {
132 let slope = slope.ok_or(DatasetError::Missing(0x00281053))?;
133 if slope == 0.0 {
134 return Err(DatasetError::Invalid(0x00281053).into());
135 }
136 let intercept = intercept.ok_or(DatasetError::Missing(0x00281052))?;
137 let units = required(units, 0x00281054)?;
138 result.modality = Some(LinearTransform {
139 slope,
140 intercept,
141 units: if units == "US" {
142 ValueUnits::Unspecified
143 } else {
144 ValueUnits::RescaleType(units)
145 },
146 source_blake3: ds.source_blake3(),
147 frame_number,
148 stored_range: None,
149 });
150 }
151 }
152 let top = ds.find(None, 0x00409096, w)?;
154 if enhanced && top.is_some() {
155 return Err(FrameError::TopLevelConflict(0x00409096));
156 }
157 let mut rw_scope = top;
158 for candidate in [shared, per].into_iter().flatten() {
159 if let Some(seq) = ds.find(Some(candidate), 0x00409096, w)? {
160 if rw_scope.is_some() {
161 return Err(FrameError::SharedPerFrameConflict(0x00409096));
162 }
163 rw_scope = Some(seq);
164 }
165 }
166 if let Some(seq) = rw_scope {
167 let mut items = ds.sequence_items(seq, w)?;
168 let first = items.next().ok_or(DatasetError::Invalid(0x00409096))?;
169 if items.next().is_some() {
170 result.unsupported_real_world =
171 Some("multiple RWVM alternatives require explicit selection");
172 return Ok(result);
173 }
174 if ds.find(Some(first), 0x00409212, w)?.is_some() {
175 result.unsupported_real_world = Some("nonlinear real-world LUT mapping not selected");
176 return Ok(result);
177 }
178 let slope = fd(ds, first, 0x00409225, w)?.ok_or(DatasetError::Missing(0x00409225))?;
179 let intercept = fd(ds, first, 0x00409224, w)?.ok_or(DatasetError::Missing(0x00409224))?;
180 let fa = fd(ds, first, 0x00409214, w)?;
181 let fb = fd(ds, first, 0x00409213, w)?;
182 let range = match (fa, fb) {
183 (Some(a), Some(b)) => {
184 if ds.find(Some(first), 0x00409216, w)?.is_some()
185 || ds.find(Some(first), 0x00409211, w)?.is_some()
186 {
187 return Err(DatasetError::Invalid(0x00409214).into());
188 }
189 [a, b]
190 }
191 (None, None) => {
192 let signed = ds
193 .unsigned_short(0x00280103, w)?
194 .ok_or(DatasetError::Missing(0x00280103))?;
195 if signed > 1 {
196 return Err(DatasetError::Invalid(0x00280103).into());
197 }
198 let mut range = [0.0; 2];
199 for (slot, tag) in [(0, 0x00409216), (1, 0x00409211)] {
200 let b = ds
201 .expected_value(
202 Some(first),
203 tag,
204 if signed == 1 { *b"SS" } else { *b"US" },
205 w,
206 )?
207 .ok_or(DatasetError::Missing(tag))?;
208 let a: [u8; 2] = b.try_into().map_err(|_| DatasetError::Invalid(tag))?;
209 range[slot] = if signed == 1 {
210 i16::from_le_bytes(a) as f64
211 } else {
212 u16::from_le_bytes(a) as f64
213 };
214 }
215 range
216 }
217 _ => return Err(DatasetError::Invalid(0x00409214).into()),
218 };
219 if range[0] > range[1] {
220 return Err(DatasetError::Invalid(0x00409216).into());
221 }
222 let unit = single_item(ds, Some(first), 0x004008ea, w)?
223 .ok_or(DatasetError::Missing(0x004008ea))?;
224 let scheme = required(ds.text(Some(unit), 0x00080102, *b"SH", w)?, 0x00080102)?;
225 let value = required(ds.text(Some(unit), 0x00080100, *b"SH", w)?, 0x00080100)?;
226 let meaning = ds.text(Some(unit), 0x00080104, *b"LO", w)?;
227 result.real_world = Some(LinearTransform {
228 slope,
229 intercept,
230 units: ValueUnits::Code {
231 scheme,
232 value,
233 meaning,
234 },
235 source_blake3: ds.source_blake3(),
236 frame_number,
237 stored_range: Some(range),
238 });
239 }
240 Ok(result)
241}