nsys-math-utils 0.1.0

Math types and traits
Documentation
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Abstract traits

use either::Either;
#[cfg(feature = "derive_serdes")]
use serde;

use crate::num_traits as num;
use crate::types::{Affinity, Projectivity, Sign};

/// Projective completion (homogeneous coordinates)
pub trait ProjectiveSpace <S, V> : VectorSpace <S> where
  V : VectorSpace <S> + std::fmt::Display,
  S : Field + std::fmt::Display
{
  /// Construct an augmented matrix for the affinity
  fn homography <A> (
    affinity : Affinity <S, A, A, <A::Vector as Module <S>>::LinearEndo>
  ) -> Projectivity <S, V, V, Self, Self, Self::LinearEndo> where
    A : AffineSpace <S, Vector=V>;
  /// Return the projective completion (homogeneous coordinates) of the affine
  /// point or vector
  fn homogeneous <A> (point_or_vector : Either <A::Point, A::Vector>)
    -> Self
  where
    A : AffineSpace <S, Vector=V>,
    V : GroupAction <A::Point>;
}

/// `AffineSpace` with translations in a (Euclidean) real inner product space
pub trait EuclideanSpace <S : Real> : AffineSpace <S> where
  Self::Vector : InnerProductSpace <S>
{
  fn origin() -> Self::Point {
    use num::Zero;
    Self::Point::from_vector (Self::Vector::zero())
  }
}

/// Space of `Point` and `Vector` (translations)
pub trait AffineSpace <S : Field> {
  type Point  : Point <Self::Vector>;
  type Vector : VectorSpace <S> + GroupAction <Self::Point>;
}

impl <S, V> AffineSpace <S> for V where
  S : Field,
  V : VectorSpace <S> + GroupAction <V> + Point <V>
{
  type Point  = Self;
  type Vector = Self;
}

/// Point types convertible to and from a vector type, with difference function
/// that follows from the free and transitive group action
pub trait Point <V> : Sized + std::ops::Sub <Self, Output=V> where
  V : AdditiveGroup + GroupAction <Self>
{
  fn to_vector (self) -> V;
  fn from_vector (vector : V) -> Self;
  fn origin() -> Self {
    Self::from_vector (V::zero())
  }
}

/// (Right) action of a group on a set
pub trait GroupAction <X> : Group {
  fn action (self, x : X) -> X;
}

impl <G> GroupAction <G> for G where G : Group {
  fn action (self, g : Self) -> Self {
    Self::operation (g, self)
  }
}

/// Bilinear form on a `VectorSpace`
pub trait InnerProductSpace <S : Field> : VectorSpace <S> + Dot <S> {
  fn inner_product (self, other : Self) -> S {
    self.dot (other)
  }
}

impl <V, S> NormedVectorSpace <S> for V where
  V : InnerProductSpace <S>,
  S : Field
{
  fn norm_squared (self) -> S {
    self.self_dot()
  }
}

/// Scalar product (bilinear form) on a `Module`
pub trait Dot <S : Ring> : Module <S> {
  fn dot (self, other : Self) -> S;
  /// Self dot product
  fn self_dot (self) -> S {
    self.dot (self)
  }
}

/// `VectorSpace` with vector length/magnitude function
pub trait NormedVectorSpace <S : Field> : VectorSpace <S> {
  fn norm_squared (self) -> S;
  fn norm (self) -> S where S : Sqrt {
    self.norm_squared().sqrt()
  }
  fn normalize (self) -> Self where S : Sqrt {
    self / self.norm()
  }
  fn unit_sigvec (self) -> Self where S : SignedExt + Sqrt {
    let v = self.sigvec();
    if v.is_zero() {
      v
    } else {
      v.normalize()
    }
  }
}

impl <V, S> MetricSpace <S> for V where
  V : NormedVectorSpace <S>,
  S : Field
{
  fn distance_squared (self, other : Self) -> S {
    (self - other).norm_squared()
  }
}

/// Set of points with distance function
pub trait MetricSpace <S> : Sized {
  fn distance_squared (self, other : Self) -> S;
  fn distance (self, other : Self) -> S where S : Sqrt {
    self.distance_squared (other).sqrt()
  }
}

/// Module with scalars taken from a `Field`
pub trait VectorSpace <S : Field> :
  Module <S> + std::ops::Div <S, Output=Self> + Copy
{
  // required
  fn map <F> (self, f : F) -> Self where F : FnMut (S) -> S;
  // provided
  /// Map `signum_or_zero` over each element of the given vector
  fn sigvec (self) -> Self where S : SignedExt {
    self.map (|x| x.signum_or_zero())
  }
}

/// Additive group combined with scalar multiplication
pub trait Module <S : Ring> :
  AdditiveGroup + std::ops::Mul <S, Output=Self> + Copy
{
  /// Linear endomorphism represented by a square matrix type
  type LinearEndo : LinearMap <S, Self, Self> + MultiplicativeMonoid;
}

/// Module homomorphism
pub trait LinearMap <S, V, W> : std::ops::Mul <V, Output=W> + Copy where
  S : Ring,
  V : Module <S>,
  W : Module <S>
{
  fn determinant (self) -> S;
  fn transpose   (self) -> Self;
}

/// `Field` with special functions and partial ordering
pub trait Real : Field + SignedExt + Exp + Sqrt + Trig + MinMax {
  // TODO: more constants
  fn pi() -> Self;
  fn frac_pi_3() -> Self;
  fn sqrt_3() -> Self;
  fn frac_1_sqrt_3() -> Self;
  fn floor (self) -> Self;
  fn ceil (self) -> Self;
  fn trunc (self) -> Self;
  fn fract (self) -> Self;
}

/// A (commutative) `Ring` where $1 \neq 0$ and all non-zero elements are
/// invertible
pub trait Field : Ring + MultiplicativeGroup + Powi + Powf {
  // some generic constants
  fn half() -> Self {
    Self::one() / Self::two()
  }
  fn two() -> Self {
    Self::one() + Self::one()
  }
  fn three() -> Self {
    Self::one() + Self::one() + Self::one()
  }
  fn four() -> Self {
    Self::two() * Self::two()
  }
  fn five() -> Self {
    Self::two() + Self::three()
  }
  fn six() -> Self {
    Self::two() * Self::three()
  }
  fn seven() -> Self {
    Self::three() + Self::four()
  }
  fn eight() -> Self {
    Self::two() * Self::two() * Self::two()
  }
  fn nine() -> Self {
    Self::three() * Self::three()
  }
  fn ten() -> Self {
    Self::two() * Self::five()
  }
}

/// Interface for a group with identity represented by `one`, operation
/// defined by `*` and `/`
pub trait MultiplicativeGroup : MultiplicativeMonoid +
  std::ops::Div <Self, Output=Self> + std::ops::DivAssign +
  num::Inv <Output=Self>
{ }

/// Ring of integers
pub trait Integer : Ring + num::PrimInt + num::Signed { }

/// Interface for a (partially ordered) ring as a combination of an additive
/// group and a distributive multiplication operation
pub trait Ring : Copy + PartialOrd + MinMax + AdditiveGroup +
  std::ops::Mul <Self, Output=Self> + std::ops::MulAssign + num::Signed +
  num::MulAdd <Self, Self, Output=Self> + num::MulAddAssign <Self, Self>
{
  fn squared (self) -> Self {
    self * self
  }
  fn cubed (self) -> Self {
    self * self * self
  }
}

/// Interface for a group with identity represented by `zero`, and operation
/// defined by `+` and `-`
pub trait AdditiveGroup : AdditiveMonoid +
  std::ops::Sub <Self, Output=Self> + std::ops::SubAssign +
  std::ops::Neg <Output=Self>
{ }

/// Set with identity, inverses, and (associative) binary operation
pub trait Group : PartialEq + std::ops::Neg <Output=Self> {
  fn identity() -> Self;
  fn operation (a : Self, b : Self) -> Self;
}

/// Set with identity represented by `one` and (associative) binary operation
/// defined by `*`
pub trait MultiplicativeMonoid : Sized + PartialEq +
  std::ops::Mul <Self, Output=Self> + std::ops::MulAssign + num::One
{ }

/// Set with identity represented by `zero` and (associative) binary operation
/// defined by `+`
pub trait AdditiveMonoid : Sized + PartialEq +
  std::ops::Add <Self, Output=Self> + std::ops::AddAssign + num::Zero
{ }

/// Interface for angle units
pub trait Angle <S : Real> : Clone + Copy + PartialEq + PartialOrd + Sized +
  AdditiveGroup + std::ops::Div <Self, Output=S> +
  std::ops::Mul <S, Output=Self> + std::ops::Div <S, Output=Self> +
  std::ops::Rem <Self, Output=Self>
{
  // required
  /// Full rotation
  fn full_turn() -> Self;
  // provided
  /// Half rotation
  fn half_turn() -> Self {
    Self::full_turn() / S::two()
  }
  /// Restrict to (-half_turn, half_turn]
  fn wrap_signed (self) -> Self {
    let out = (self + Self::half_turn()).wrap_unsigned() - Self::half_turn();
    if out == -Self::half_turn() {
        Self::half_turn()
    } else {
        out
    }
  }
  /// Restrict to [0, full_turn)
  fn wrap_unsigned (self) -> Self {
    if self >= Self::full_turn() {
        self % Self::full_turn()
    } else if self < Self::zero() {
        self + Self::full_turn() *
          ((self / Self::full_turn()).trunc().abs() + S::one())
    } else {
        self
    }
  }
}

/// Unsigned integer power function
pub trait Pow {
  fn pow (self, exp : u32) -> Self;
}
/// Signed integer power function
pub trait Powi {
  fn powi (self, n : i32) -> Self;
}
/// Fractional power function
pub trait Powf {
  fn powf (self, n : Self) -> Self;
}
/// Exponential function
pub trait Exp {
  fn exp (self) -> Self;
}
/// Square root function
pub trait Sqrt {
  fn sqrt (self) -> Self;
}
/// Trigonometric functions
pub trait Trig : Sized {
  fn sin      (self) -> Self;
  fn sin_cos  (self) -> (Self, Self);
  fn cos      (self) -> Self;
  fn tan      (self) -> Self;
  fn asin     (self) -> Self;
  fn acos     (self) -> Self;
  fn atan     (self) -> Self;
  fn atan2    (self, other : Self) -> Self;
}

/// Provides `min`, `max`, and `clamp` that are not necessarily consistent with
/// those from `Ord`. This is provided because `f32` and `f64` do not implement
/// `Ord`, so this trait is defined to give a uniform interface with `Ord`
/// types.
pub trait MinMax {
  fn min   (self, other : Self) -> Self;
  fn max   (self, other : Self) -> Self;
  fn clamp (self, min : Self, max : Self) -> Self;
}

/// Function returning number representing sign of self
pub trait SignedExt : num::Signed {
  #[inline]
  fn sign (self) -> Sign {
    if self.is_zero() {
      Sign::Zero
    } else if self.is_positive() {
      Sign::Positive
    } else {
      debug_assert!(self.is_negative());
      Sign::Negative
    }
  }
  /// Maps `0.0` to `0.0`, otherwise equal to `S::signum` (which would otherwise
  /// map `+0.0 -> 1.0` and `-0.0 -> -1.0`)
  #[inline]
  fn signum_or_zero (self) -> Self where Self : num::Zero {
    if self.is_zero() {
      Self::zero()
    } else {
      self.signum()
    }
  }
}

/// Adds serde Serialize and DeserializeOwned constraints.
///
/// This makes it easier to conditionally add these constraints to type
/// definitions when `derive_serdes` feature is enabled.
#[cfg(not(feature = "derive_serdes"))]
pub trait MaybeSerDes { }
#[cfg(feature = "derive_serdes")]
pub trait MaybeSerDes : serde::Serialize + serde::de::DeserializeOwned { }

impl <
  #[cfg(not(feature = "derive_serdes"))]
  T,
  #[cfg(feature = "derive_serdes")]
  T : serde::Serialize + serde::de::DeserializeOwned
> MaybeSerDes for T { }

macro impl_integer ($type:ty) {
  impl Integer        for $type { }
  impl Ring           for $type { }
  impl AdditiveGroup  for $type { }
  impl AdditiveMonoid for $type { }
  impl SignedExt      for $type { }
  impl MinMax         for $type {
    fn min (self, other : Self) -> Self {
      Ord::min (self, other)
    }
    fn max (self, other : Self) -> Self {
      Ord::max (self, other)
    }
    fn clamp (self, min : Self, max : Self) -> Self {
      Ord::clamp (self, min, max)
    }
  }
  impl Pow for $type {
    fn pow (self, exp : u32) -> Self {
      self.pow (exp)
    }
  }
}
impl_integer!(i8);
impl_integer!(i16);
impl_integer!(i32);
impl_integer!(i64);

macro impl_real_float ($type:ident) {
  impl VectorSpace <Self> for $type {
    fn map <F> (self, mut f : F) -> Self where F : FnMut (Self) -> Self {
      f (self)
    }
  }
  impl Module <Self> for $type {
    type LinearEndo = Self;
  }
  impl LinearMap <Self, Self, Self> for $type {
    fn determinant (self) -> Self {
      self
    }
    fn transpose (self) -> Self {
      self
    }
  }
  impl Real for $type {
    fn pi() -> Self {
      std::$type::consts::PI
    }
    fn frac_pi_3() -> Self {
      std::$type::consts::FRAC_PI_3
    }
    #[allow(clippy::excessive_precision)]
    fn sqrt_3() -> Self {
      1.732050807568877293527446341505872366942805253810380628055f64 as $type
    }
    #[allow(clippy::excessive_precision)]
    fn frac_1_sqrt_3() -> Self {
      (1.0f64 / 1.732050807568877293527446341505872366942805253810380628055f64) as $type
    }
    fn floor (self) -> Self {
      self.floor()
    }
    fn ceil (self) -> Self {
      self.ceil()
    }
    fn trunc (self) -> Self {
      self.trunc()
    }
    fn fract (self) -> Self {
      self.fract()
    }
  }
  impl Field                for $type { }
  impl MultiplicativeGroup  for $type { }
  impl MultiplicativeMonoid for $type { }
  impl Ring                 for $type { }
  impl AdditiveGroup        for $type { }
  impl AdditiveMonoid       for $type { }
  impl SignedExt            for $type { }
  impl MinMax               for $type {
    fn min (self, other : Self) -> Self {
      self.min (other)
    }
    fn max (self, other : Self) -> Self {
      self.max (other)
    }
    fn clamp (self, min : Self, max : Self) -> Self {
      self.clamp (min, max)
    }
  }
  impl Powi for $type {
    fn powi (self, n : i32) -> Self {
      self.powi (n as i32)
    }
  }
  impl Powf for $type {
    fn powf (self, n : Self) -> Self {
      self.powf (n)
    }
  }
  impl Exp for $type {
    fn exp (self) -> Self {
      self.exp()
    }
  }
  impl Sqrt for $type {
    fn sqrt (self) -> Self {
      self.sqrt()
    }
  }
  impl Trig for $type {
    fn sin (self) -> Self {
      self.sin()
    }
    fn sin_cos (self) -> (Self, Self) {
      self.sin_cos()
    }
    fn cos (self) -> Self {
      self.cos()
    }
    fn tan (self) -> Self {
      self.tan()
    }
    fn asin (self) -> Self {
      self.asin()
    }
    fn acos (self) -> Self {
      self.acos()
    }
    fn atan (self) -> Self {
      self.atan()
    }
    fn atan2 (self, other : Self) -> Self {
      self.atan2 (other)
    }
  }
}

impl_real_float!(f32);
impl_real_float!(f64);