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
use std::fmt::{Display, Formatter, Result};
use std::ops::{Add, Div, Mul, Sub};

extern crate ndarray;
use ndarray::{ArrayBase, Data, Dimension};

use crate::unit::Unit;

pub struct ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
{
    unit: Unit,
    array: ArrayBase<T, D>,
}

impl<T, D> ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
{
    /// Create an ArrayUnit from a ndarray::ArrayBase and an Unit
    pub fn new(arr: ArrayBase<T, D>, u: Unit) -> ArrayUnit<T, D> {
        ArrayUnit {
            unit: u,
            array: arr,
        }
    }

    /// Return a reference to the underlying ndarray::ArrayBase
    pub fn array(&self) -> &ArrayBase<T, D> {
        &self.array
    }
}

impl<T, D> Mul for &ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
    for<'a> &'a ArrayBase<T, D>: Mul<Output = ArrayBase<T, D>>,
{
    type Output = ArrayUnit<T, D>;

    fn mul(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
        ArrayUnit {
            unit: &self.unit * &other.unit,
            array: &self.array * &other.array,
        }
    }
}

impl<T, D> Div for &ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
    for<'a> &'a ArrayBase<T, D>: Div<Output = ArrayBase<T, D>>,
{
    type Output = ArrayUnit<T, D>;

    fn div(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
        ArrayUnit {
            unit: &self.unit / &other.unit,
            array: &self.array / &other.array,
        }
    }
}

impl<T, D> Sub for &ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
    for<'a> &'a ArrayBase<T, D>: Sub<Output = ArrayBase<T, D>>,
{
    type Output = ArrayUnit<T, D>;

    fn sub(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
        if self.unit != other.unit {
            panic!();
        }
        ArrayUnit {
            unit: self.unit.clone(),
            array: &self.array - &other.array,
        }
    }
}

impl<T, D> Add for &ArrayUnit<T, D>
where
    T: Data,
    D: Dimension,
    for<'a> &'a ArrayBase<T, D>: Add<Output = ArrayBase<T, D>>,
{
    type Output = ArrayUnit<T, D>;

    fn add(self, other: &ArrayUnit<T, D>) -> ArrayUnit<T, D> {
        if self.unit != other.unit {
            panic!();
        }
        ArrayUnit {
            unit: self.unit.clone(),
            array: &self.array + &other.array,
        }
    }
}

impl<A: Display, T, D> Display for ArrayUnit<T, D>
where
    T: Data<Elem = A>,
    D: Dimension,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        write!(f, "{} {}", &self.array, &self.unit)
    }
}