ritk_transform/transform/composition/io.rs
1//! Backend-independent composite transform serialization.
2//!
3//! # Design
4//!
5//! The [`Transform<B, D>`](crate::Transform) trait is generic over a Coeus
6//! tensor backend `B`, which makes direct serialization of live transform objects
7//! backend-dependent. This module provides a **parameter-only** representation
8//! ([`TransformDescription`]) that captures each supported transform type as plain
9//! `f64` vectors, and a **composite container** ([`CompositeTransform`]) that holds
10//! an ordered sequence of such descriptions.
11//!
12//! Both types derive `serde::Serialize` and `serde::Deserialize`, enabling
13//! round-trip JSON persistence that is independent of any particular Coeus backend.
14//!
15//! # Supported transform types
16//!
17//! | Variant | Parameters |
18//! |----------------------|----------------------------------------------------------|
19//! | `Translation` | offset vector \[D\] |
20//! | `Rigid` | rotation matrix D×D (row-major) + translation \[D\] |
21//! | `Affine` | homogeneous matrix (D+1)×(D+1) (row-major) |
22//! | `DisplacementField` | grid dims, origin, spacing, per-component displacement |
23//! | `BSpline` | grid dims, origin, spacing, per-component ctrl-pt displ. |
24//!
25//! # Composition order
26//!
27//! Transforms are applied **left-to-right** (first-to-last):
28//! a point `p` is mapped through `T[0]`, then `T[1]`, … , then `T[n-1]`.
29//! Mathematically this corresponds to `T_{n-1} ∘ … ∘ T_1 ∘ T_0`.
30//!
31//! # Dependencies
32//!
33//! This module requires `serde_json = "1.0"` in `[dependencies]` of
34//! `crates/ritk-core/Cargo.toml`. The crate already depends on `serde`.
35
36use serde::{Deserialize, Serialize};
37use std::fs;
38use std::io;
39use std::path::Path;
40
41// ---------------------------------------------------------------------------
42// TransformDescription
43// ---------------------------------------------------------------------------
44
45/// Backend-independent description of a single transform's parameters.
46///
47/// Each variant stores its parameters as flat `f64` vectors in row-major order
48/// so that no Coeus tensor types appear in the serialized representation.
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
50pub enum TransformDescription {
51 /// Translation: offset vector of length D.
52 Translation {
53 /// Offset per spatial dimension. Length must equal the composite's
54 /// `dimensionality`.
55 offset: Vec<f64>,
56 },
57
58 /// Rigid: rotation matrix (D×D, row-major) + translation vector (length D).
59 ///
60 /// The rotation matrix is stored as `D * D` elements in row-major order.
61 Rigid {
62 /// D×D rotation matrix, row-major.
63 rotation: Vec<f64>,
64 /// Translation vector of length D.
65 translation: Vec<f64>,
66 },
67
68 /// Affine: full homogeneous matrix ((D+1)×(D+1), row-major).
69 Affine {
70 /// (D+1)×(D+1) homogeneous matrix, row-major.
71 matrix: Vec<f64>,
72 },
73
74 /// Displacement field: dense voxel displacement vectors on a regular grid.
75 DisplacementField {
76 /// Grid dimensions (e.g. `[nz, ny, nx]` for 3-D).
77 dims: Vec<usize>,
78 /// Physical-space origin of the grid.
79 origin: Vec<f64>,
80 /// Physical-space spacing between voxels.
81 spacing: Vec<f64>,
82 /// Displacement components. One inner `Vec` per spatial dimension,
83 /// each of length `prod(dims)`. For 3-D: `[dz, dy, dx]`.
84 components: Vec<Vec<f64>>,
85 },
86
87 /// B-spline: control-point displacements on a regular lattice.
88 BSpline {
89 /// Control-point grid dimensions.
90 grid_dims: Vec<usize>,
91 /// Physical-space origin of the control grid.
92 grid_origin: Vec<f64>,
93 /// Physical-space spacing of control points.
94 grid_spacing: Vec<f64>,
95 /// Control-point displacement components. One inner `Vec` per
96 /// spatial dimension, each of length `prod(grid_dims)`.
97 components: Vec<Vec<f64>>,
98 },
99}
100
101impl TransformDescription {
102 /// Return the spatial dimensionality implied by the variant's data.
103 ///
104 /// Returns `None` when the data is internally inconsistent (e.g. a `Rigid`
105 /// whose rotation length is not a perfect square matching the translation
106 /// length).
107 pub fn implied_dimensionality(&self) -> Option<usize> {
108 match self {
109 Self::Translation { offset } => Some(offset.len()),
110 Self::Rigid {
111 rotation,
112 translation,
113 } => {
114 let d = translation.len();
115 if d > 0 && rotation.len() == d * d {
116 Some(d)
117 } else {
118 None
119 }
120 }
121 Self::Affine { matrix } => {
122 // (D+1)^2 elements → solve for D.
123 let n = matrix.len();
124 let side = (n as f64).sqrt() as usize;
125 if side >= 2 && side * side == n {
126 Some(side - 1)
127 } else {
128 None
129 }
130 }
131 Self::DisplacementField { components, .. } => Some(components.len()),
132 Self::BSpline { components, .. } => Some(components.len()),
133 }
134 }
135}
136
137// ---------------------------------------------------------------------------
138// CompositeTransform
139// ---------------------------------------------------------------------------
140
141/// Ordered composite transform: applied first-to-last.
142///
143/// `point → T[0] → T[1] → … → T[n-1]`
144///
145/// # Invariants
146///
147/// * `dimensionality ∈ {2, 3}` (enforced by convention, not by the type system,
148/// to allow forward-compatible payloads).
149/// * Every element of `transforms` must have parameter lengths consistent with
150/// `dimensionality`.
151#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
152pub struct CompositeTransform {
153 /// Spatial dimensionality (2 or 3).
154 pub dimensionality: usize,
155
156 /// Human-readable description (optional metadata).
157 #[serde(default)]
158 pub description: String,
159
160 /// Ordered list of transforms.
161 pub transforms: Vec<TransformDescription>,
162}
163
164impl CompositeTransform {
165 /// Create a new empty composite transform for the given dimensionality.
166 pub fn new(dimensionality: usize) -> Self {
167 Self {
168 dimensionality,
169 description: String::new(),
170 transforms: Vec::new(),
171 }
172 }
173
174 /// Append a transform description to the chain.
175 pub fn push(&mut self, transform: TransformDescription) {
176 self.transforms.push(transform);
177 }
178
179 /// Number of transforms in the chain.
180 pub fn len(&self) -> usize {
181 self.transforms.len()
182 }
183
184 /// Whether the chain is empty.
185 pub fn is_empty(&self) -> bool {
186 self.transforms.is_empty()
187 }
188
189 /// Serialize to a pretty-printed JSON string.
190 pub fn to_json(&self) -> Result<String, serde_json::Error> {
191 serde_json::to_string_pretty(self)
192 }
193
194 /// Deserialize from a JSON string.
195 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
196 serde_json::from_str(json)
197 }
198
199 /// Write to a JSON file at `path`.
200 ///
201 /// Creates or truncates the file. Parent directories must already exist.
202 pub fn save_json<P: AsRef<Path>>(&self, path: P) -> Result<(), io::Error> {
203 let json = serde_json::to_string_pretty(self)
204 .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
205 fs::write(path, json)
206 }
207
208 /// Read from a JSON file at `path`.
209 pub fn load_json<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
210 let contents = fs::read_to_string(path)?;
211 serde_json::from_str(&contents).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
212 }
213
214 /// Validate that every transform's implied dimensionality matches
215 /// `self.dimensionality`.
216 ///
217 /// Returns the indices of any mismatched transforms. An empty `Vec`
218 /// indicates a fully consistent composite.
219 pub fn validate_dimensionality(&self) -> Vec<usize> {
220 self.transforms
221 .iter()
222 .enumerate()
223 .filter_map(|(i, t)| match t.implied_dimensionality() {
224 Some(d) if d == self.dimensionality => None,
225 _ => Some(i),
226 })
227 .collect()
228 }
229}
230
231// ---------------------------------------------------------------------------
232// Tests
233// ---------------------------------------------------------------------------
234
235#[cfg(test)]
236#[path = "tests_composite_io.rs"]
237mod tests_composite_io;