Mon, 06 Jan 2025 20:29:25 -0500
More Serialize / Deserialize / Debug derives
67 | 1 | /*! |
2 | Simple disrete gradient operators | |
3 | */ | |
4 | use numeric_literals::replace_float_literals; | |
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
5 | use serde::{Serialize, Deserialize}; |
67 | 6 | use nalgebra::{ |
7 | DVector, Matrix, U1, Storage, StorageMut, Dyn | |
8 | }; | |
9 | use crate::types::Float; | |
10 | use crate::instance::Instance; | |
11 | use crate::linops::{Mapping, Linear, BoundedLinear, Adjointable, GEMV}; | |
12 | use crate::norms::{Norm, L2}; | |
13 | ||
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
14 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] |
67 | 15 | /// Forward differences with Neumann boundary conditions |
16 | pub struct ForwardNeumann; | |
17 | ||
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
18 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] |
67 | 19 | /// Forward differences with Dirichlet boundary conditions |
20 | pub struct ForwardDirichlet; | |
21 | ||
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
22 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] |
67 | 23 | /// Backward differences with Dirichlet boundary conditions |
24 | pub struct BackwardDirichlet; | |
25 | ||
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
26 | #[derive(Copy, Clone, Debug, Serialize, Deserialize)] |
67 | 27 | /// Backward differences with Neumann boundary conditions |
28 | pub struct BackwardNeumann; | |
29 | ||
30 | /// Finite differences gradient | |
86
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
31 | #[derive(Clone, Debug, Serialize, Deserialize)] |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
32 | #[serde(bound( |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
33 | serialize = "[usize; N] : Serialize, |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
34 | B : Serialize, |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
35 | F : Serialize,", |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
36 | deserialize = "[usize; N] : for<'a> Deserialize<'a>, |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
37 | B : for<'a> Deserialize<'a>, |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
38 | F : for<'a> Deserialize<'a>," |
d5b0e496b72f
More Serialize / Deserialize / Debug derives
Tuomo Valkonen <tuomov@iki.fi>
parents:
74
diff
changeset
|
39 | ))] |
67 | 40 | pub struct Grad< |
41 | F : Float + nalgebra::RealField, | |
42 | B : Discretisation<F>, | |
43 | const N : usize | |
44 | > { | |
45 | dims : [usize; N], | |
46 | h : F, // may be negative to implement adjoints! | |
47 | discretisation : B, | |
48 | } | |
49 | ||
50 | ||
51 | /// Finite differences divergence | |
52 | pub struct Div< | |
53 | F : Float + nalgebra::RealField, | |
54 | B : Discretisation<F>, | |
55 | const N : usize | |
56 | > { | |
57 | dims : [usize; N], | |
58 | h : F, // may be negative to implement adjoints! | |
59 | discretisation : B, | |
60 | } | |
61 | ||
62 | /// Internal: classification of a point in a 1D discretisation | |
63 | pub enum DiscretisationOrInterior { | |
64 | /// center, forward | |
65 | LeftBoundary(usize, usize), | |
66 | /// center, backward | |
67 | RightBoundary(usize, usize), | |
68 | /// center, (backward, forward) | |
69 | Interior(usize, (usize, usize)), | |
70 | } | |
71 | ||
72 | use DiscretisationOrInterior::*; | |
73 | ||
74 | /// Trait for different discretisations | |
75 | pub trait Discretisation<F : Float + nalgebra::RealField> : Copy { | |
76 | /// Opposite discretisation, appropriate for adjoints with negated cell width. | |
77 | type Opposite : Discretisation<F>; | |
78 | ||
79 | /// Add to appropiate index of `v` (as determined by `b`) the appropriate difference | |
80 | /// of `x` with cell width `h`. | |
81 | fn add_diff_mut<SMut, S>( | |
82 | &self, | |
83 | v : &mut Matrix<F, Dyn, U1, SMut>, | |
84 | x : &Matrix<F, Dyn, U1, S>, | |
85 | α : F, | |
86 | b : DiscretisationOrInterior, | |
87 | ) where | |
88 | SMut : StorageMut<F, Dyn, U1>, | |
89 | S : Storage<F, Dyn, U1>; | |
90 | ||
91 | /// Give the opposite discretisation, appropriate for adjoints with negated `h`. | |
92 | fn opposite(&self) -> Self::Opposite; | |
93 | ||
94 | /// Bound for the corresponding operator norm. | |
95 | #[replace_float_literals(F::cast_from(literal))] | |
96 | fn opnorm_bound(&self, h : F) -> F { | |
97 | // See: Chambolle, “An Algorithm for Total Variation Minimization and Applications”. | |
98 | // Ok for forward and backward differences. | |
99 | // | |
100 | // Fuck nalgebra for polluting everything with its own shit. | |
101 | num_traits::Float::sqrt(8.0) / h | |
102 | } | |
103 | } | |
104 | ||
105 | impl<F : Float + nalgebra::RealField> Discretisation<F> for ForwardNeumann { | |
106 | type Opposite = BackwardDirichlet; | |
107 | ||
108 | #[inline] | |
109 | fn add_diff_mut<SMut, S>( | |
110 | &self, | |
111 | v : &mut Matrix<F, Dyn, U1, SMut>, | |
112 | x : &Matrix<F, Dyn, U1, S>, | |
113 | α : F, | |
114 | b : DiscretisationOrInterior, | |
115 | ) where | |
116 | SMut : StorageMut<F, Dyn, U1>, | |
117 | S : Storage<F, Dyn, U1> | |
118 | { | |
119 | match b { | |
120 | Interior(c, (_, f)) | LeftBoundary(c, f) => { v[c] += (x[f] - x[c]) * α }, | |
121 | RightBoundary(_c, _b) => { }, | |
122 | } | |
123 | } | |
124 | ||
125 | #[inline] | |
126 | fn opposite(&self) -> Self::Opposite { | |
127 | BackwardDirichlet | |
128 | } | |
129 | } | |
130 | ||
131 | impl<F : Float + nalgebra::RealField> Discretisation<F> for BackwardNeumann { | |
132 | type Opposite = ForwardDirichlet; | |
133 | ||
134 | #[inline] | |
135 | fn add_diff_mut<SMut, S>( | |
136 | &self, | |
137 | v : &mut Matrix<F, Dyn, U1, SMut>, | |
138 | x : &Matrix<F, Dyn, U1, S>, | |
139 | α : F, | |
140 | b : DiscretisationOrInterior, | |
141 | ) where | |
142 | SMut : StorageMut<F, Dyn, U1>, | |
143 | S : Storage<F, Dyn, U1> | |
144 | { | |
145 | match b { | |
146 | Interior(c, (b, _)) | RightBoundary(c, b) => { v[c] += (x[c] - x[b]) * α }, | |
147 | LeftBoundary(_c, _f) => { }, | |
148 | } | |
149 | } | |
150 | ||
151 | #[inline] | |
152 | fn opposite(&self) -> Self::Opposite { | |
153 | ForwardDirichlet | |
154 | } | |
155 | } | |
156 | ||
157 | impl<F : Float + nalgebra::RealField> Discretisation<F> for BackwardDirichlet { | |
158 | type Opposite = ForwardNeumann; | |
159 | ||
160 | #[inline] | |
161 | fn add_diff_mut<SMut, S>( | |
162 | &self, | |
163 | v : &mut Matrix<F, Dyn, U1, SMut>, | |
164 | x : &Matrix<F, Dyn, U1, S>, | |
165 | α : F, | |
166 | b : DiscretisationOrInterior, | |
167 | ) where | |
168 | SMut : StorageMut<F, Dyn, U1>, | |
169 | S : Storage<F, Dyn, U1> | |
170 | { | |
171 | match b { | |
172 | Interior(c, (b, _f)) => { v[c] += (x[c] - x[b]) * α }, | |
173 | LeftBoundary(c, _f) => { v[c] += x[c] * α }, | |
174 | RightBoundary(c, b) => { v[c] -= x[b] * α }, | |
175 | } | |
176 | } | |
177 | ||
178 | #[inline] | |
179 | fn opposite(&self) -> Self::Opposite { | |
180 | ForwardNeumann | |
181 | } | |
182 | } | |
183 | ||
184 | impl<F : Float + nalgebra::RealField> Discretisation<F> for ForwardDirichlet { | |
185 | type Opposite = BackwardNeumann; | |
186 | ||
187 | #[inline] | |
188 | fn add_diff_mut<SMut, S>( | |
189 | &self, | |
190 | v : &mut Matrix<F, Dyn, U1, SMut>, | |
191 | x : &Matrix<F, Dyn, U1, S>, | |
192 | α : F, | |
193 | b : DiscretisationOrInterior, | |
194 | ) where | |
195 | SMut : StorageMut<F, Dyn, U1>, | |
196 | S : Storage<F, Dyn, U1> | |
197 | { | |
198 | match b { | |
199 | Interior(c, (_b, f)) => { v[c] += (x[f] - x[c]) * α }, | |
200 | LeftBoundary(c, f) => { v[c] += x[f] * α }, | |
201 | RightBoundary(c, _b) => { v[c] -= x[c] * α }, | |
202 | } | |
203 | } | |
204 | ||
205 | #[inline] | |
206 | fn opposite(&self) -> Self::Opposite { | |
207 | BackwardNeumann | |
208 | } | |
209 | } | |
210 | ||
211 | struct Iter<'a, const N : usize> { | |
212 | /// Dimensions | |
213 | dims : &'a [usize; N], | |
214 | /// Dimension along which to calculate differences | |
215 | d : usize, | |
216 | /// Stride along coordinate d | |
217 | d_stride : usize, | |
218 | /// Cartesian indices | |
219 | i : [usize; N], | |
220 | /// Linear index | |
221 | k : usize, | |
222 | /// Maximal linear index | |
223 | len : usize | |
224 | } | |
225 | ||
226 | impl<'a, const N : usize> Iter<'a, N> { | |
227 | fn new(dims : &'a [usize; N], d : usize) -> Self { | |
228 | let d_stride = dims[0..d].iter().product::<usize>(); | |
229 | let len = dims.iter().product::<usize>(); | |
230 | Iter{ dims, d, d_stride, i : [0; N], k : 0, len } | |
231 | } | |
232 | } | |
233 | ||
234 | impl<'a, const N : usize> Iterator for Iter<'a, N> { | |
235 | type Item = DiscretisationOrInterior; | |
236 | fn next(&mut self) -> Option<Self::Item> { | |
237 | let res = if self.k >= self.len { | |
238 | None | |
239 | } else { | |
240 | let cartesian_idx = self.i[self.d]; | |
241 | let cartesian_max = self.dims[self.d]; | |
242 | let k = self.k; | |
243 | ||
244 | if cartesian_idx == 0 { | |
245 | Some(LeftBoundary(k, k + self.d_stride)) | |
246 | } else if cartesian_idx + 1 >= cartesian_max { | |
247 | Some(RightBoundary(k, k - self.d_stride)) | |
248 | } else { | |
249 | Some(Interior(k, (k - self.d_stride, k + self.d_stride))) | |
250 | } | |
251 | }; | |
252 | self.k += 1; | |
253 | for j in 0..N { | |
254 | if self.i[j] + 1 < self.dims[j] { | |
255 | self.i[j] += 1; | |
256 | break | |
257 | } | |
258 | self.i[j] = 0 | |
259 | } | |
260 | res | |
261 | } | |
262 | } | |
263 | ||
264 | impl<F, B, const N : usize> Mapping<DVector<F>> | |
265 | for Grad<F, B, N> | |
266 | where | |
267 | B : Discretisation<F>, | |
268 | F : Float + nalgebra::RealField, | |
269 | { | |
270 | type Codomain = DVector<F>; | |
271 | fn apply<I : Instance<DVector<F>>>(&self, i : I) -> DVector<F> { | |
272 | let mut y = DVector::zeros(N * self.len()); | |
273 | self.apply_add(&mut y, i); | |
274 | y | |
275 | } | |
276 | } | |
277 | ||
278 | #[replace_float_literals(F::cast_from(literal))] | |
279 | impl<F, B, const N : usize> GEMV<F, DVector<F>> | |
280 | for Grad<F, B, N> | |
281 | where | |
282 | B : Discretisation<F>, | |
283 | F : Float + nalgebra::RealField, | |
284 | { | |
285 | fn gemv<I : Instance<DVector<F>>>( | |
286 | &self, y : &mut DVector<F>, α : F, i : I, β : F | |
287 | ) { | |
288 | if β == 0.0 { | |
289 | y.as_mut_slice().iter_mut().for_each(|x| *x = 0.0); | |
290 | } else if β != 1.0 { | |
291 | //*y *= β; | |
292 | y.as_mut_slice().iter_mut().for_each(|x| *x *= β); | |
293 | } | |
294 | let h = self.h; | |
295 | let m = self.len(); | |
296 | i.eval(|x| { | |
297 | assert_eq!(x.len(), m); | |
298 | for d in 0..N { | |
299 | let mut v = y.generic_view_mut((d*m, 0), (Dyn(m), U1)); | |
300 | for b in Iter::new(&self.dims, d) { | |
301 | self.discretisation.add_diff_mut(&mut v, x, α/h, b) | |
302 | } | |
303 | } | |
304 | }) | |
305 | } | |
306 | } | |
307 | ||
308 | impl<F, B, const N : usize> Mapping<DVector<F>> | |
309 | for Div<F, B, N> | |
310 | where | |
311 | B : Discretisation<F>, | |
312 | F : Float + nalgebra::RealField, | |
313 | { | |
314 | type Codomain = DVector<F>; | |
315 | fn apply<I : Instance<DVector<F>>>(&self, i : I) -> DVector<F> { | |
316 | let mut y = DVector::zeros(self.len()); | |
317 | self.apply_add(&mut y, i); | |
318 | y | |
319 | } | |
320 | } | |
321 | ||
322 | #[replace_float_literals(F::cast_from(literal))] | |
323 | impl<F, B, const N : usize> GEMV<F, DVector<F>> | |
324 | for Div<F, B, N> | |
325 | where | |
326 | B : Discretisation<F>, | |
327 | F : Float + nalgebra::RealField, | |
328 | { | |
329 | fn gemv<I : Instance<DVector<F>>>( | |
330 | &self, y : &mut DVector<F>, α : F, i : I, β : F | |
331 | ) { | |
332 | if β == 0.0 { | |
333 | y.as_mut_slice().iter_mut().for_each(|x| *x = 0.0); | |
334 | } else if β != 1.0 { | |
335 | //*y *= β; | |
336 | y.as_mut_slice().iter_mut().for_each(|x| *x *= β); | |
337 | } | |
338 | let h = self.h; | |
339 | let m = self.len(); | |
340 | i.eval(|x| { | |
341 | assert_eq!(x.len(), N * m); | |
342 | for d in 0..N { | |
343 | let v = x.generic_view((d*m, 0), (Dyn(m), U1)); | |
344 | for b in Iter::new(&self.dims, d) { | |
345 | self.discretisation.add_diff_mut(y, &v, α/h, b) | |
346 | } | |
347 | } | |
348 | }) | |
349 | } | |
350 | } | |
351 | ||
352 | impl<F, B, const N : usize> Grad<F, B, N> | |
353 | where | |
354 | B : Discretisation<F>, | |
355 | F : Float + nalgebra::RealField | |
356 | { | |
357 | /// Creates a new discrete gradient operator for the vector `u`, verifying dimensions. | |
358 | pub fn new_for(u : &DVector<F>, h : F, dims : [usize; N], discretisation : B) | |
359 | -> Option<Self> | |
360 | { | |
361 | if u.len() == dims.iter().product::<usize>() { | |
362 | Some(Grad { dims, h, discretisation } ) | |
363 | } else { | |
364 | None | |
365 | } | |
366 | } | |
367 | ||
368 | fn len(&self) -> usize { | |
369 | self.dims.iter().product::<usize>() | |
370 | } | |
371 | } | |
372 | ||
373 | ||
374 | impl<F, B, const N : usize> Div<F, B, N> | |
375 | where | |
376 | B : Discretisation<F>, | |
377 | F : Float + nalgebra::RealField | |
378 | { | |
379 | /// Creates a new discrete gradient operator for the vector `u`, verifying dimensions. | |
380 | pub fn new_for(u : &DVector<F>, h : F, dims : [usize; N], discretisation : B) | |
381 | -> Option<Self> | |
382 | { | |
383 | if u.len() == dims.iter().product::<usize>() * N { | |
384 | Some(Div { dims, h, discretisation } ) | |
385 | } else { | |
386 | None | |
387 | } | |
388 | } | |
74 | 389 | |
67 | 390 | fn len(&self) -> usize { |
391 | self.dims.iter().product::<usize>() | |
392 | } | |
393 | } | |
394 | ||
395 | impl<F, B, const N : usize> Linear<DVector<F>> | |
396 | for Grad<F, B, N> | |
397 | where | |
398 | B : Discretisation<F>, | |
399 | F : Float + nalgebra::RealField, | |
400 | { | |
401 | } | |
402 | ||
403 | impl<F, B, const N : usize> Linear<DVector<F>> | |
404 | for Div<F, B, N> | |
405 | where | |
406 | B : Discretisation<F>, | |
407 | F : Float + nalgebra::RealField, | |
408 | { | |
409 | } | |
410 | ||
411 | impl<F, B, const N : usize> BoundedLinear<DVector<F>, L2, L2, F> | |
412 | for Grad<F, B, N> | |
413 | where | |
414 | B : Discretisation<F>, | |
415 | F : Float + nalgebra::RealField, | |
416 | DVector<F> : Norm<F, L2>, | |
417 | { | |
418 | fn opnorm_bound(&self, _ : L2, _ : L2) -> F { | |
419 | // Fuck nalgebra. | |
420 | self.discretisation.opnorm_bound(num_traits::Float::abs(self.h)) | |
421 | } | |
422 | } | |
423 | ||
424 | ||
425 | impl<F, B, const N : usize> BoundedLinear<DVector<F>, L2, L2, F> | |
426 | for Div<F, B, N> | |
427 | where | |
428 | B : Discretisation<F>, | |
429 | F : Float + nalgebra::RealField, | |
430 | DVector<F> : Norm<F, L2>, | |
431 | { | |
432 | fn opnorm_bound(&self, _ : L2, _ : L2) -> F { | |
433 | // Fuck nalgebra. | |
434 | self.discretisation.opnorm_bound(num_traits::Float::abs(self.h)) | |
435 | } | |
436 | } | |
437 | ||
438 | impl<F, B, const N : usize> | |
439 | Adjointable<DVector<F>, DVector<F>> | |
440 | for Grad<F, B, N> | |
441 | where | |
442 | B : Discretisation<F>, | |
443 | F : Float + nalgebra::RealField, | |
444 | { | |
445 | type AdjointCodomain = DVector<F>; | |
446 | type Adjoint<'a> = Div<F, B::Opposite, N> where Self : 'a; | |
447 | ||
448 | /// Form the adjoint operator of `self`. | |
449 | fn adjoint(&self) -> Self::Adjoint<'_> { | |
450 | Div { | |
451 | dims : self.dims, | |
452 | h : -self.h, | |
453 | discretisation : self.discretisation.opposite(), | |
454 | } | |
455 | } | |
456 | } | |
457 | ||
458 | ||
459 | impl<F, B, const N : usize> | |
460 | Adjointable<DVector<F>, DVector<F>> | |
461 | for Div<F, B, N> | |
462 | where | |
463 | B : Discretisation<F>, | |
464 | F : Float + nalgebra::RealField, | |
465 | { | |
466 | type AdjointCodomain = DVector<F>; | |
467 | type Adjoint<'a> = Grad<F, B::Opposite, N> where Self : 'a; | |
468 | ||
469 | /// Form the adjoint operator of `self`. | |
470 | fn adjoint(&self) -> Self::Adjoint<'_> { | |
471 | Grad { | |
472 | dims : self.dims, | |
473 | h : -self.h, | |
474 | discretisation : self.discretisation.opposite(), | |
475 | } | |
476 | } | |
477 | } | |
478 | ||
479 | #[cfg(test)] | |
480 | mod tests { | |
481 | use super::*; | |
482 | ||
483 | #[test] | |
484 | fn grad_adjoint() { | |
485 | let im = DVector::from( (0..9).map(|t| t as f64).collect::<Vec<_>>()); | |
486 | let v = DVector::from( (0..18).map(|t| t as f64).collect::<Vec<_>>()); | |
487 | ||
488 | let grad = Grad::new_for(&im, 1.0, [3, 3], ForwardNeumann).unwrap(); | |
489 | let a = grad.apply(&im).dot(&v); | |
490 | let b = grad.adjoint().apply(&v).dot(&im); | |
491 | assert_eq!(a, b); | |
492 | ||
493 | let grad = Grad::new_for(&im, 1.0, [3, 3], ForwardDirichlet).unwrap(); | |
494 | let a = grad.apply(&im).dot(&v); | |
495 | let b = grad.adjoint().apply(&v).dot(&im); | |
496 | assert_eq!(a, b); | |
497 | ||
498 | } | |
499 | } |