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
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::ops::{AddAssign, MulAssign, SubAssign};

use bytemuck::Pod;
use nalgebra::{RealField, SMatrix};
use num_integer::Integer;
use num_traits::{
    Bounded, CheckedAdd, CheckedMul, CheckedSub, FromPrimitive, NumCast, SaturatingSub, ToPrimitive,
};

/// Convenience trait that combines `Send` and `Sync`
pub trait ThreadSafe: Sync + Send {}
impl<T> ThreadSafe for T where T: Sync + Send {}

pub struct IndexRange<I: Index> {
    start: I,
    end: I,
}

impl<I: Index> IndexRange<I> {
    fn new(start: I, end: I) -> Self {
        assert!(start <= end, "start must be less or equal to end");
        Self { start, end }
    }

    pub fn iter(self) -> impl Iterator<Item = I> {
        let end = self.end;
        let mut counter = self.start;
        std::iter::from_fn(move || {
            let current = counter;
            if current < end {
                counter += I::one();
                Some(current)
            } else {
                None
            }
        })
    }
}

/// Trait that has to be implemented for types to be used as background grid cell indices in the context of the library
pub trait Index:
    Copy
    + Hash
    + Integer
    + Bounded
    + CheckedAdd
    + CheckedSub
    + CheckedMul
    + SaturatingSub
    + AddAssign
    + SubAssign
    + MulAssign
    + FromPrimitive
    + ToPrimitive
    + NumCast
    + Default
    + Debug
    + Display
    + Pod
    + ThreadSafe
    + 'static
{
    fn range(start: Self, end: Self) -> IndexRange<Self> {
        IndexRange::new(start, end)
    }

    fn two() -> Self {
        Self::one() + Self::one()
    }

    /// Converts this value to the specified [`Real`] type `T` by converting first to `f64` followed by `T::from_f64`. If the value cannot be represented by the target type, `None` is returned.
    fn to_real<R: Real>(self) -> Option<R> {
        R::from_f64(self.to_f64()?)
    }

    /// Converts this value to the specified [`Real`] type, panics if the value cannot be represented by the target type.
    fn to_real_unchecked<R: Real>(self) -> R {
        R::from_f64(self.to_f64().unwrap()).unwrap()
    }

    /// Multiplies this value by the specified `i32` coefficient. Panics if the coefficient cannot be converted into the target type.
    fn times(self, n: i32) -> Self {
        self.mul(Self::from_i32(n).unwrap())
    }

    /// Returns the squared value of this value.
    fn squared(self) -> Self {
        self * self
    }

    /// Returns the cubed value of this value.
    fn cubed(self) -> Self {
        self * self * self
    }

    fn checked_cubed(self) -> Option<Self> {
        self.checked_mul(&self)
            .and_then(|val| val.checked_mul(&self))
    }
}

/// Trait that has to be implemented for types to be used as floating points values in the context of the library (e.g. for coordinates, density values)
pub trait Real:
RealField
// Required by RStar and not part of RealFied anymore
+ Bounded
// Not part of RealField anymore
+ Copy
+ FromPrimitive
+ ToPrimitive
+ NumCast
+ Debug
+ Default
+ Pod
+ ThreadSafe
{
    /// Converts this value to the specified [`Index`] type. If the value cannot be represented by the target type, `None` is returned.
    fn to_index<I: Index>(self) -> Option<I> {
        I::from_f64(self.to_f64()?)
    }

    /// Converts this value to the specified [`Index`] type, panics if the value cannot be represented by the target type.
    fn to_index_unchecked<I: Index>(self) -> I {
        I::from_f64(self.to_f64().unwrap()).unwrap()
    }

    /// Multiplies this value by the specified `i32` coefficient. Panics if the coefficient cannot be converted into the target type.
    fn times(self, n: i32) -> Self {
        self.mul(Self::from_i32(n).unwrap())
    }

    /// Multiplies this value by the specified `f64` coefficient. Panics if the coefficient cannot be converted into the target type.
    fn times_f64(self, x: f64) -> Self {
        self.mul(Self::from_f64(x).unwrap())
    }
}

impl<T> Index for T where
    T: Copy
        + Hash
        + Integer
        + Bounded
        + CheckedAdd
        + CheckedSub
        + CheckedMul
        + SaturatingSub
        + AddAssign
        + SubAssign
        + MulAssign
        + FromPrimitive
        + ToPrimitive
        + NumCast
        + Debug
        + Default
        + Display
        + Pod
        + ThreadSafe
        + 'static
{
}

impl<
        T: RealField
            + Bounded
            + Copy
            + FromPrimitive
            + ToPrimitive
            + NumCast
            + Debug
            + Default
            + Pod
            + ThreadSafe
            + 'static,
    > Real for T
{
}

/// Trait for converting values, matrices, etc. from one `Real` type to another.
pub trait RealConvert: Sized {
    type Out<To>
    where
        To: Real;

    /// Tries to convert this value to the target type, returns `None` if value cannot be represented by the target type
    fn try_convert<To: Real>(self) -> Option<Self::Out<To>>;
    /// Converts this value to the target type, panics if value cannot be represented by the target type
    fn convert<To: Real>(self) -> Self::Out<To> {
        self.try_convert().expect("failed to convert")
    }
}

impl<From: Real> RealConvert for &From {
    type Out<To> = To where To: Real;

    fn try_convert<To: Real>(self) -> Option<To> {
        <To as NumCast>::from(*self)
    }
}

impl<From: Real, const R: usize, const C: usize> RealConvert for SMatrix<From, R, C> {
    type Out<To> = SMatrix<To, R, C> where To: Real;

    fn try_convert<To: Real>(self) -> Option<SMatrix<To, R, C>> {
        let mut m_out: SMatrix<To, R, C> = SMatrix::zeros();
        m_out
            .iter_mut()
            .zip(self.iter())
            .try_for_each(|(x_out, x_in)| {
                *x_out = <To as NumCast>::from(*x_in)?;
                Some(())
            })?;
        Some(m_out)
    }
}