1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use nalgebra::{RowVector3, Vector4};
#[cfg(feature = "nifti_images")]
use ndarray::{ArrayBase, Axis, DataMut, Dimension, Zip};
#[cfg(feature = "nifti_images")]
use nifti::DataElement;
use crate::{Affine, Affine4, Translation};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Direction {
Normal,
Reversed,
}
impl Direction {
pub fn to_f32(&self) -> f32 {
if *self == Direction::Normal {
1.0
} else {
-1.0
}
}
}
pub type Orientation = (usize, Direction);
pub type Orientations = [Orientation; 3];
pub fn affine_to_axcodes(affine: &Affine) -> String {
let orientations = io_orientations(affine);
orientations_to_axcodes(orientations)
}
pub fn io_orientations(affine: &Affine) -> Orientations {
let rzs2 = affine.component_mul(affine);
let mut zooms = RowVector3::new(
(rzs2[0] + rzs2[1] + rzs2[2]).sqrt(),
(rzs2[3] + rzs2[4] + rzs2[5]).sqrt(),
(rzs2[6] + rzs2[7] + rzs2[8]).sqrt(),
);
zooms.apply(|z| if z == 0.0 { 1.0 } else { z });
#[rustfmt::skip]
let rs = Affine::new(
affine[0] / zooms[0], affine[3] / zooms[1], affine[6] / zooms[2],
affine[1] / zooms[0], affine[4] / zooms[1], affine[7] / zooms[2],
affine[2] / zooms[0], affine[5] / zooms[1], affine[8] / zooms[2],
);
let svd = rs.svd(true, true);
let (u, s, v_t) = (svd.u.unwrap(), svd.singular_values, svd.v_t.unwrap());
let tol = s.as_slice().iter().cloned().fold(0.0, f32::max) * 3.0 * f32::EPSILON;
let s = Affine::from_rows(&[s.transpose(), s.transpose(), s.transpose()]);
let u = u.zip_map(&s, |u, s| if s > tol { u } else { 0.0 });
let v_t = v_t.zip_map(&s, |v, s| if s > tol { v } else { 0.0 });
let mut r = u * v_t;
let mut orientations = [(0, Direction::Normal), (0, Direction::Normal), (0, Direction::Normal)];
for c in 0..3 {
let mut argmax = 0;
let mut max = 0.0;
let mut sign_max = 0.0;
for (i, e) in r.column(c).iter().enumerate() {
let e_abs = e.abs();
if e_abs > max {
argmax = i;
max = e_abs;
sign_max = *e;
}
}
if sign_max >= 0.0 {
orientations[c] = (argmax, Direction::Normal);
} else {
orientations[c] = (argmax, Direction::Reversed);
}
for e in r.column_mut(c).iter_mut() {
*e = 0.0;
}
}
orientations
}
pub fn orientations_to_axcodes(orientations: Orientations) -> String {
let labels = [['R', 'L'], ['A', 'P'], ['S', 'I']];
orientations
.into_iter()
.map(|(axis, direction)| labels[axis][(direction == Direction::Reversed) as usize])
.collect()
}
pub fn axcodes_to_orientations(axcodes: &str) -> Orientations {
let labels = [('R', 'L'), ('A', 'P'), ('S', 'I')];
let mut orientations = [(0, Direction::Normal), (0, Direction::Normal), (0, Direction::Normal)];
for (code_idx, code) in axcodes.chars().enumerate() {
for (label_idx, codes) in labels.iter().enumerate() {
if code == codes.0 {
orientations[code_idx] = (label_idx, Direction::Normal);
} else if code == codes.1 {
orientations[code_idx] = (label_idx, Direction::Reversed);
}
}
}
orientations
}
pub fn orientations_transform(
start_orientations: &Orientations,
end_orientations: &Orientations,
) -> Orientations {
let mut result = [(0, Direction::Normal), (0, Direction::Normal), (0, Direction::Normal)];
for (end_in_idx, &(ref end_out_idx, ref end_flip)) in end_orientations.iter().enumerate() {
for (start_in_idx, &(ref start_out_idx, ref start_flip)) in
start_orientations.iter().enumerate()
{
if end_out_idx == start_out_idx {
if start_flip == end_flip {
result[start_in_idx] = (end_in_idx, Direction::Normal)
} else {
result[start_in_idx] = (end_in_idx, Direction::Reversed)
}
break;
}
}
}
result
}
#[cfg(feature = "nifti_images")]
pub fn apply_orientation<S, A, D>(
mut arr: ArrayBase<S, D>,
orientations: Orientations,
) -> ArrayBase<S, D>
where
S: DataMut<Elem = A>,
A: DataElement,
D: Dimension,
{
for (axis, &(_, direction)) in orientations.iter().enumerate() {
if direction == Direction::Reversed {
Zip::from(arr.lanes_mut(Axis(axis))).for_each(|mut arr| {
let n = arr.len();
for i in 0..n / 2 {
let tmp = arr[n - 1 - i];
arr[n - 1 - i] = arr[i];
arr[i] = tmp;
}
});
}
}
let mut x = (orientations[0].0, 0);
let mut y = (orientations[1].0, 1);
let mut z = (orientations[2].0, 2);
if x > y {
std::mem::swap(&mut x, &mut y);
}
if y > z {
std::mem::swap(&mut y, &mut z);
}
if x > y {
std::mem::swap(&mut x, &mut y);
}
let mut axes = arr.raw_dim();
axes[0] = x.1;
axes[1] = y.1;
axes[2] = z.1;
for i in 3..arr.ndim() {
axes[i] = i;
}
arr.permuted_axes(axes)
}
pub fn inverse_orientations_affine(orientations: &Orientations, dim: [i16; 3]) -> Affine4 {
let mut undo_reorder = Affine4::zeros();
for (i, &(j, _)) in orientations.iter().enumerate() {
undo_reorder[(i, j)] = 1.0;
}
undo_reorder[(3, 3)] = 1.0;
let center = Translation::new(
-(dim[0] - 1) as f32 / 2.0,
-(dim[1] - 1) as f32 / 2.0,
-(dim[2] - 1) as f32 / 2.0,
);
let mut undo_flip = Affine4::from_diagonal(&Vector4::new(
orientations[0].1.to_f32(),
orientations[1].1.to_f32(),
orientations[2].1.to_f32(),
1.0,
));
undo_flip[(0, 3)] = undo_flip[(0, 0)] * center[0] - center[0];
undo_flip[(1, 3)] = undo_flip[(1, 1)] * center[1] - center[1];
undo_flip[(2, 3)] = undo_flip[(2, 2)] * center[2] - center[2];
undo_flip * undo_reorder
}