ndarray_unit/
array_unit.rs

1use std::fmt::{Display, Formatter, Result};
2use std::ops::{Add, Div, Mul, Sub};
3
4extern crate ndarray;
5use ndarray::{ArrayBase, Data, Dimension};
6
7use crate::unit::Unit;
8
9pub struct ArrayUnit<T, D>
10where
11    T: Data,
12    D: Dimension,
13{
14    unit: Unit,
15    array: ArrayBase<T, D>,
16}
17
18impl<T, D> ArrayUnit<T, D>
19where
20    T: Data,
21    D: Dimension,
22{
23    /// Create an ArrayUnit from a ndarray::ArrayBase and an Unit
24    pub fn new(arr: ArrayBase<T, D>, u: Unit) -> ArrayUnit<T, D> {
25        ArrayUnit {
26            unit: u,
27            array: arr,
28        }
29    }
30
31    /// Return a reference to the underlying ndarray::ArrayBase
32    pub fn array(&self) -> &ArrayBase<T, D> {
33        &self.array
34    }
35}
36
37impl<T, D> Mul for &ArrayUnit<T, D>
38where
39    T: Data,
40    D: Dimension,
41    for<'a> &'a ArrayBase<T, D>: Mul<Output = ArrayBase<T, D>>,
42{
43    type Output = ArrayUnit<T, D>;
44
45    fn mul(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
46        ArrayUnit {
47            unit: &self.unit * &other.unit,
48            array: &self.array * &other.array,
49        }
50    }
51}
52
53impl<T, D> Div for &ArrayUnit<T, D>
54where
55    T: Data,
56    D: Dimension,
57    for<'a> &'a ArrayBase<T, D>: Div<Output = ArrayBase<T, D>>,
58{
59    type Output = ArrayUnit<T, D>;
60
61    fn div(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
62        ArrayUnit {
63            unit: &self.unit / &other.unit,
64            array: &self.array / &other.array,
65        }
66    }
67}
68
69impl<T, D> Sub for &ArrayUnit<T, D>
70where
71    T: Data,
72    D: Dimension,
73    for<'a> &'a ArrayBase<T, D>: Sub<Output = ArrayBase<T, D>>,
74{
75    type Output = ArrayUnit<T, D>;
76
77    fn sub(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
78        if self.unit != other.unit {
79            panic!();
80        }
81        ArrayUnit {
82            unit: self.unit.clone(),
83            array: &self.array - &other.array,
84        }
85    }
86}
87
88impl<T, D> Add for &ArrayUnit<T, D>
89where
90    T: Data,
91    D: Dimension,
92    for<'a> &'a ArrayBase<T, D>: Add<Output = ArrayBase<T, D>>,
93{
94    type Output = ArrayUnit<T, D>;
95
96    fn add(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
97        if self.unit != other.unit {
98            panic!();
99        }
100        ArrayUnit {
101            unit: self.unit.clone(),
102            array: &self.array + &other.array,
103        }
104    }
105}
106
107impl<A: Display, T, D> Display for ArrayUnit<T, D>
108where
109    T: Data<Elem = A>,
110    D: Dimension,
111{
112    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
113        write!(f, "{} {}", &self.array, &self.unit)
114    }
115}