Tue, 06 Dec 2022 08:58:49 +0200
README improvements
5 | 1 | /*! |
2 | Multi-dimensional cubes. | |
3 | ||
4 | This module provides the [`Cube`] type for multi-dimensional cubes $∏_{i=1}^N [a_i, b_i)$. | |
5 | ||
6 | As an example, to create a the two-dimensional cube $[0, 1] × [-1, 1]$, you can | |
7 | ``` | |
8 | # use alg_tools::sets::cube::Cube; | |
9 | let cube = Cube::new([[0.0, 1.0], [-1.0, 1.0]]); | |
10 | ``` | |
11 | or | |
12 | ``` | |
13 | # use alg_tools::sets::cube::Cube; | |
14 | # use alg_tools::types::float; | |
15 | let cube : Cube<float, 2> = [[0.0, 1.0], [-1.0, 1.0]].into(); | |
16 | ``` | |
17 | */ | |
0 | 18 | |
19 | use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; | |
20 | use crate::types::*; | |
21 | use crate::loc::Loc; | |
22 | use crate::sets::SetOrd; | |
23 | use crate::maputil::{ | |
24 | FixedLength, | |
25 | FixedLengthMut, | |
26 | map1, | |
27 | map1_indexed, | |
28 | map2, | |
29 | }; | |
30 | ||
5 | 31 | /// A multi-dimensional cube $∏_{i=1}^N [a_i, b_i)$ with the starting and ending points |
32 | /// along $a_i$ and $b_i$ along each dimension of type `U`. | |
0 | 33 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
34 | pub struct Cube<U : Num, const N : usize>(pub(super) [[U; 2]; N]); | |
35 | ||
36 | // Need to manually implement as [F; N] serialisation is provided only for some N. | |
37 | impl<F : Num + Serialize, const N : usize> Serialize for Cube<F, N> | |
38 | where | |
39 | F: Serialize, | |
40 | { | |
41 | fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> | |
42 | where | |
43 | S: Serializer, | |
44 | { | |
45 | let mut ts = serializer.serialize_tuple_struct("Cube", N)?; | |
46 | for e in self.0.iter() { | |
47 | ts.serialize_field(e)?; | |
48 | } | |
49 | ts.end() | |
50 | } | |
51 | } | |
52 | ||
53 | impl<A : Num, const N : usize> FixedLength<N> for Cube<A,N> { | |
54 | type Iter = std::array::IntoIter<[A; 2], N>; | |
55 | type Elem = [A; 2]; | |
56 | #[inline] | |
57 | fn fl_iter(self) -> Self::Iter { | |
58 | self.0.into_iter() | |
59 | } | |
60 | } | |
61 | ||
62 | impl<A : Num, const N : usize> FixedLengthMut<N> for Cube<A,N> { | |
63 | type IterMut<'a> = std::slice::IterMut<'a, [A; 2]>; | |
64 | #[inline] | |
65 | fn fl_iter_mut(&mut self) -> Self::IterMut<'_> { | |
66 | self.0.iter_mut() | |
67 | } | |
68 | } | |
69 | ||
70 | impl<'a, A : Num, const N : usize> FixedLength<N> for &'a Cube<A,N> { | |
71 | type Iter = std::slice::Iter<'a, [A; 2]>; | |
72 | type Elem = &'a [A; 2]; | |
73 | #[inline] | |
74 | fn fl_iter(self) -> Self::Iter { | |
75 | self.0.iter() | |
76 | } | |
77 | } | |
78 | ||
79 | ||
80 | /// Iterator for [`Cube`] corners. | |
81 | pub struct CubeCornersIter<'a, U : Num, const N : usize> { | |
82 | index : usize, | |
83 | cube : &'a Cube<U, N>, | |
84 | } | |
85 | ||
86 | impl<'a, U : Num, const N : usize> Iterator for CubeCornersIter<'a, U, N> { | |
87 | type Item = Loc<U, N>; | |
88 | #[inline] | |
89 | fn next(&mut self) -> Option<Self::Item> { | |
90 | if self.index >= N { | |
91 | None | |
92 | } else { | |
93 | let i = self.index; | |
94 | self.index += 1; | |
95 | let arr = self.cube.map_indexed(|k, a, b| if (i>>k)&1 == 0 { a } else { b }); | |
96 | Some(arr.into()) | |
97 | } | |
98 | } | |
99 | } | |
100 | ||
101 | impl<U : Num, const N : usize> Cube<U, N> { | |
5 | 102 | /// Maps `f` over the triples $\\{(i, a\_i, b\_i)\\}\_{i=1}^N$ |
103 | /// of the cube $∏_{i=1}^N [a_i, b_i)$. | |
0 | 104 | #[inline] |
105 | pub fn map_indexed<T>(&self, f : impl Fn(usize, U, U) -> T) -> [T; N] { | |
106 | map1_indexed(self, |i, &[a, b]| f(i, a, b)) | |
107 | } | |
108 | ||
5 | 109 | /// Maps `f` over the tuples $\\{(a\_i, b\_i)\\}\_{i=1}^N$ |
110 | /// of the cube $∏_{i=1}^N [a_i, b_i)$. | |
0 | 111 | #[inline] |
112 | pub fn map<T>(&self, f : impl Fn(U, U) -> T) -> [T; N] { | |
113 | map1(self, |&[a, b]| f(a, b)) | |
114 | } | |
115 | ||
5 | 116 | /// Iterates over the start and end coordinates $\{(a_i, b_i)\}_{i=1}^N$ of the cube along |
117 | /// each dimension. | |
0 | 118 | #[inline] |
119 | pub fn iter_coords(&self) -> std::slice::Iter<'_, [U; 2]> { | |
120 | self.0.iter() | |
121 | } | |
122 | ||
5 | 123 | /// Returns the “start” coordinate $a_i$ of the cube $∏_{i=1}^N [a_i, b_i)$. |
0 | 124 | #[inline] |
125 | pub fn start(&self, i : usize) -> U { | |
126 | self.0[i][0] | |
127 | } | |
128 | ||
5 | 129 | /// Returns the end coordinate $a_i$ of the cube $∏_{i=1}^N [a_i, b_i)$. |
0 | 130 | #[inline] |
131 | pub fn end(&self, i : usize) -> U { | |
132 | self.0[i][1] | |
133 | } | |
5 | 134 | |
135 | /// Returns the “start” $(a_1, … ,a_N)$ of the cube $∏_{i=1}^N [a_i, b_i)$ | |
136 | /// spanned between $(a_1, … ,a_N)$ and $(b_1, … ,b_N)$. | |
0 | 137 | #[inline] |
138 | pub fn span_start(&self) -> Loc<U, N> { | |
139 | Loc::new(self.map(|a, _b| a)) | |
140 | } | |
141 | ||
5 | 142 | /// Returns the end $(b_1, … ,b_N)$ of the cube $∏_{i=1}^N [a_i, b_i)$ |
143 | /// spanned between $(a_1, … ,a_N)$ and $(b_1, … ,b_N)$. | |
0 | 144 | #[inline] |
145 | pub fn span_end(&self) -> Loc<U, N> { | |
146 | Loc::new(self.map(|_a, b| b)) | |
147 | } | |
148 | ||
5 | 149 | /// Iterates over the corners $\{(c_1, … ,c_N) | c_i ∈ \{a_i, b_i\}\}$ of the cube |
150 | /// $∏_{i=1}^N [a_i, b_i)$. | |
0 | 151 | #[inline] |
152 | pub fn iter_corners(&self) -> CubeCornersIter<'_, U, N> { | |
153 | CubeCornersIter{ index : 0, cube : self } | |
154 | } | |
155 | ||
5 | 156 | /// Returns the width-`N`-tuple $(b_1-a_1, … ,b_N-a_N)$ of the cube $∏_{i=1}^N [a_i, b_i)$. |
0 | 157 | #[inline] |
158 | pub fn width(&self) -> Loc<U, N> { | |
159 | Loc::new(self.map(|a, b| b-a)) | |
160 | } | |
161 | ||
5 | 162 | /// Translates the cube $∏_{i=1}^N [a_i, b_i)$ by the `shift` $(s_1, … , s_N)$ to |
163 | /// $∏_{i=1}^N [a_i+s_i, b_i+s_i)$. | |
0 | 164 | #[inline] |
165 | pub fn shift(&self, shift : &Loc<U, N>) -> Self { | |
166 | let mut cube = self.clone(); | |
167 | for i in 0..N { | |
168 | cube.0[i][0] += shift[i]; | |
169 | cube.0[i][1] += shift[i]; | |
170 | } | |
171 | cube | |
172 | } | |
173 | ||
5 | 174 | /// Creates a new cube from an array. |
0 | 175 | #[inline] |
176 | pub fn new(data : [[U; 2]; N]) -> Self { | |
177 | Cube(data) | |
178 | } | |
179 | } | |
180 | ||
181 | impl<F : Float, const N : usize> Cube<F, N> { | |
182 | /// Returns the centre of the cube | |
183 | pub fn center(&self) -> Loc<F, N> { | |
184 | map1(self, |&[a, b]| (a + b) / F::TWO).into() | |
185 | } | |
186 | } | |
187 | ||
188 | impl<U : Num> Cube<U, 1> { | |
189 | /// Get the corners of the cube. | |
5 | 190 | /// |
0 | 191 | /// TODO: generic implementation once const-generics can be involved in |
192 | /// calculations. | |
193 | #[inline] | |
194 | pub fn corners(&self) -> [Loc<U, 1>; 2] { | |
195 | let [[a, b]] = self.0; | |
196 | [a.into(), b.into()] | |
197 | } | |
198 | } | |
199 | ||
200 | impl<U : Num> Cube<U, 2> { | |
201 | /// Get the corners of the cube in counter-clockwise order. | |
5 | 202 | /// |
0 | 203 | /// TODO: generic implementation once const-generics can be involved in |
204 | /// calculations. | |
205 | #[inline] | |
206 | pub fn corners(&self) -> [Loc<U, 2>; 4] { | |
207 | let [[a1, b1], [a2, b2]]=self.0; | |
208 | [[a1, a2].into(), | |
209 | [b1, a2].into(), | |
210 | [b1, b2].into(), | |
211 | [a1, b2].into()] | |
212 | } | |
213 | } | |
214 | ||
215 | impl<U : Num> Cube<U, 3> { | |
216 | /// Get the corners of the cube. | |
5 | 217 | /// |
0 | 218 | /// TODO: generic implementation once const-generics can be involved in |
219 | /// calculations. | |
220 | #[inline] | |
221 | pub fn corners(&self) -> [Loc<U, 3>; 8] { | |
222 | let [[a1, b1], [a2, b2], [a3, b3]]=self.0; | |
223 | [[a1, a2, a3].into(), | |
224 | [b1, a2, a3].into(), | |
225 | [b1, b2, a3].into(), | |
226 | [a1, b2, a3].into(), | |
227 | [a1, b2, b3].into(), | |
228 | [b1, b2, b3].into(), | |
229 | [b1, a2, b3].into(), | |
230 | [a1, a2, b3].into()] | |
231 | } | |
232 | } | |
233 | ||
234 | // TODO: Implement Add and Sub of Loc to Cube, and Mul and Div by U : Num. | |
235 | ||
236 | impl<U : Num, const N : usize> From<[[U; 2]; N]> for Cube<U, N> { | |
237 | #[inline] | |
238 | fn from(data : [[U; 2]; N]) -> Self { | |
239 | Cube(data) | |
240 | } | |
241 | } | |
242 | ||
243 | impl<U : Num, const N : usize> From<Cube<U, N>> for [[U; 2]; N] { | |
244 | #[inline] | |
245 | fn from(Cube(data) : Cube<U, N>) -> Self { | |
246 | data | |
247 | } | |
248 | } | |
249 | ||
250 | ||
251 | impl<U, const N : usize> Cube<U, N> where U : Num + PartialOrd { | |
252 | /// Checks whether the cube is non-degenerate, i.e., the start coordinate | |
253 | /// of each axis is strictly less than the end coordinate. | |
254 | #[inline] | |
255 | pub fn nondegenerate(&self) -> bool { | |
256 | self.0.iter().all(|range| range[0] < range[1]) | |
257 | } | |
258 | ||
259 | /// Checks whether the cube intersects some `other` cube. | |
260 | /// Matching boundary points are not counted, so `U` is ideally a [`Float`]. | |
261 | #[inline] | |
262 | pub fn intersects(&self, other : &Cube<U, N>) -> bool { | |
263 | self.iter_coords().zip(other.iter_coords()).all(|([a1, b1], [a2, b2])| { | |
264 | a1 < b2 && a2 < b1 | |
265 | }) | |
266 | } | |
267 | ||
268 | /// Checks whether the cube contains some `other` cube. | |
269 | pub fn contains_set(&self, other : &Cube<U, N>) -> bool { | |
270 | self.iter_coords().zip(other.iter_coords()).all(|([a1, b1], [a2, b2])| { | |
271 | a1 <= a2 && b1 >= b2 | |
272 | }) | |
273 | } | |
274 | ||
275 | /// Produces the point of minimum $ℓ^p$-norm within the cube `self` for any $p$-norm. | |
276 | /// This is the point where each coordinate is closest to zero. | |
277 | #[inline] | |
278 | pub fn minnorm_point(&self) -> Loc<U, N> { | |
279 | let z = U::ZERO; | |
280 | // As always, we assume that a ≤ b. | |
281 | self.map(|a, b| { | |
282 | debug_assert!(a <= b); | |
283 | match (a < z, z < b) { | |
284 | (false, _) => a, | |
285 | (_, false) => b, | |
286 | (true, true) => z | |
287 | } | |
288 | }).into() | |
289 | } | |
290 | ||
291 | /// Produces the point of maximum $ℓ^p$-norm within the cube `self` for any $p$-norm. | |
292 | /// This is the point where each coordinate is furthest from zero. | |
293 | #[inline] | |
294 | pub fn maxnorm_point(&self) -> Loc<U, N> { | |
295 | let z = U::ZERO; | |
296 | // As always, we assume that a ≤ b. | |
297 | self.map(|a, b| { | |
298 | debug_assert!(a <= b); | |
299 | match (a < z, z < b) { | |
300 | (false, _) => b, | |
301 | (_, false) => a, | |
302 | // A this stage we must have a < 0 (so U must be signed), and want to check | |
303 | // whether |a| > |b|. We can do this without assuming U to actually implement | |
304 | // `Neg` by comparing whether 0 > a + b. | |
305 | (true, true) => if z > a + b { a } else { b } | |
306 | } | |
307 | }).into() | |
308 | } | |
309 | } | |
310 | ||
311 | macro_rules! impl_common { | |
312 | ($($t:ty)*, $min:ident, $max:ident) => { $( | |
313 | impl<const N : usize> SetOrd for Cube<$t, N> { | |
314 | #[inline] | |
315 | fn common(&self, other : &Self) -> Self { | |
316 | map2(self, other, |&[a1, b1], &[a2, b2]| { | |
317 | debug_assert!(a1 <= b1 && a2 <= b2); | |
318 | [a1.$min(a2), b1.$max(b2)] | |
319 | }).into() | |
320 | } | |
321 | ||
322 | #[inline] | |
323 | fn intersect(&self, other : &Self) -> Option<Self> { | |
324 | let arr = map2(self, other, |&[a1, b1], &[a2, b2]| { | |
325 | debug_assert!(a1 <= b1 && a2 <= b2); | |
326 | [a1.$max(a2), b1.$min(b2)] | |
327 | }); | |
328 | arr.iter().all(|&[a, b]| a >= b).then(|| arr.into()) | |
329 | } | |
330 | } | |
331 | )* } | |
332 | } | |
333 | ||
334 | impl_common!(u8 u16 u32 u64 u128 usize | |
335 | i8 i16 i32 i64 i128 isize, min, max); | |
336 | // Any NaN yields NaN | |
337 | impl_common!(f32 f64, minimum, maximum); | |
338 | ||
339 | impl<U : Num, const N : usize> std::ops::Index<usize> for Cube<U, N> { | |
340 | type Output = [U; 2]; | |
341 | #[inline] | |
342 | fn index(&self, index: usize) -> &Self::Output { | |
343 | &self.0[index] | |
344 | } | |
345 | } | |
346 | ||
347 | impl<U : Num, const N : usize> std::ops::IndexMut<usize> for Cube<U, N> { | |
348 | #[inline] | |
349 | fn index_mut(&mut self, index: usize) -> &mut Self::Output { | |
350 | &mut self.0[index] | |
351 | } | |
352 | } |