use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TransformDescription {
Translation {
offset: Vec<f64>,
},
Rigid {
rotation: Vec<f64>,
translation: Vec<f64>,
},
Affine {
matrix: Vec<f64>,
},
DisplacementField {
dims: Vec<usize>,
origin: Vec<f64>,
spacing: Vec<f64>,
components: Vec<Vec<f64>>,
},
BSpline {
grid_dims: Vec<usize>,
grid_origin: Vec<f64>,
grid_spacing: Vec<f64>,
components: Vec<Vec<f64>>,
},
}
impl TransformDescription {
pub fn implied_dimensionality(&self) -> Option<usize> {
match self {
Self::Translation { offset } => Some(offset.len()),
Self::Rigid {
rotation,
translation,
} => {
let d = translation.len();
if d > 0 && rotation.len() == d * d {
Some(d)
} else {
None
}
}
Self::Affine { matrix } => {
let n = matrix.len();
let side = (n as f64).sqrt() as usize;
if side >= 2 && side * side == n {
Some(side - 1)
} else {
None
}
}
Self::DisplacementField { components, .. } => Some(components.len()),
Self::BSpline { components, .. } => Some(components.len()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CompositeTransform {
pub dimensionality: usize,
#[serde(default)]
pub description: String,
pub transforms: Vec<TransformDescription>,
}
impl CompositeTransform {
pub fn new(dimensionality: usize) -> Self {
Self {
dimensionality,
description: String::new(),
transforms: Vec::new(),
}
}
pub fn push(&mut self, transform: TransformDescription) {
self.transforms.push(transform);
}
pub fn len(&self) -> usize {
self.transforms.len()
}
pub fn is_empty(&self) -> bool {
self.transforms.is_empty()
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn save_json<P: AsRef<Path>>(&self, path: P) -> Result<(), io::Error> {
let json = serde_json::to_string_pretty(self)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
fs::write(path, json)
}
pub fn load_json<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
let contents = fs::read_to_string(path)?;
serde_json::from_str(&contents).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
pub fn validate_dimensionality(&self) -> Vec<usize> {
self.transforms
.iter()
.enumerate()
.filter_map(|(i, t)| match t.implied_dimensionality() {
Some(d) if d == self.dimensionality => None,
_ => Some(i),
})
.collect()
}
}
#[cfg(test)]
#[path = "tests_composite_io.rs"]
mod tests_composite_io;