astronomy 0.1.5

A library for astronomical calculations in Rust
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use ndarray::Array1;
use thiserror::Error;

// Define the base dimensions of physical quantities
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Dimension {
    Length,              // L - e.g., metres (m), centimetres (cm), kilometres (km)
    Mass,                // M - e.g., kilograms (kg), grams (g)
    Time,                // T - e.g., seconds (s), milliseconds (ms)
    ElectricCurrent,     // I - e.g., amperes (A), milliamperes (mA)
    AbsoluteTemperature, // Theta - e.g., kelvin (K), celsius (C)
    AmountOfSubstance,   // N - e.g., moles (mol)
    LuminousIntensity,   // J - e.g., candela (cd)
}

// Implement Unit Multiplication/Division
#[derive(Debug, Clone, PartialEq)]
pub struct UnitProduct {
    // (Dimension, exponent)
    // e.g., [(Dimension::Length, 1), (Dimension::Time, -1)] for velocity
    components: [(Dimension, i32); 7],
}
// Implement methods for UnitProduct
impl UnitProduct {
    pub const fn new(dimension: Dimension) -> Self {
        // Initialize an array with all exponents as 0
        let mut components = [
            (Dimension::Length, 0),
            (Dimension::Mass, 0),
            (Dimension::Time, 0),
            (Dimension::ElectricCurrent, 0),
            (Dimension::AbsoluteTemperature, 0),
            (Dimension::AmountOfSubstance, 0),
            (Dimension::LuminousIntensity, 0),
        ];
        let mut i = 0;
        while i < components.len() {
            if components[i].0 as usize == dimension as usize {
                components[i].1 += 1; // Increment the exponent for the specified dimension
                break;
            }
            i += 1;
        }
        UnitProduct { components }
    }
    pub const fn zero() -> Self {
        // Initialize an array with all exponents as 0
        UnitProduct {
            components: [
                (Dimension::Length, 0),
                (Dimension::Mass, 0),
                (Dimension::Time, 0),
                (Dimension::ElectricCurrent, 0),
                (Dimension::AbsoluteTemperature, 0),
                (Dimension::AmountOfSubstance, 0),
                (Dimension::LuminousIntensity, 0),
            ],
        }
    }
    pub const fn from_components(dims: &[(Dimension, i32)]) -> Self {
        let mut components = [
            (Dimension::Length, 0),
            (Dimension::Mass, 0),
            (Dimension::Time, 0),
            (Dimension::ElectricCurrent, 0),
            (Dimension::AbsoluteTemperature, 0),
            (Dimension::AmountOfSubstance, 0),
            (Dimension::LuminousIntensity, 0),
        ];
        let mut i = 0;
        while i < dims.len() {
            let (dim, exp) = dims[i];
            let mut j = 0;
            while j < components.len() {
                if components[j].0 as usize == dim as usize {
                    components[j].1 = exp;
                    break;
                }
                j += 1;
            }
            i += 1;
        }
        UnitProduct { components }
    }
    pub fn multiply(&self, other: &Self) -> Self {
        let mut result_components = self.components;
        for (other_dim, other_exp) in &other.components {
            for (dim, exp) in result_components.iter_mut() {
                if dim == other_dim {
                    *exp += other_exp; // Add the exponent if dimension matches
                    break;
                }
            }
        }
        UnitProduct {
            components: result_components,
        }
    }

    // Helper for division (or negative exponents) in a constant context
    pub const fn inverse(mut self) -> Self {
        let mut i = 0;
        while i < self.components.len() {
            self.components[i].1 *= -1;
            i += 1;
        }
        self
    }
}

// Define a unit of measurement
#[derive(Debug, Clone, PartialEq)]
pub struct Unit {
    // Simplified representation (e.g. "metre", "second")
    pub name: &'static str,
    // Scale factor relative to SI (e.g., 0.01 for "centimetre")
    pub scale: f64,
    // Dimension of the unit (e.g., Length, Time, Mass)
    pub dimensions: UnitProduct,
}

impl Unit {
    pub fn new(name: &'static str, scale: f64, dimensions: UnitProduct) -> Self {
        Unit {
            name,
            scale,
            dimensions,
        }
    }
    // Check if two units are equivalent based on their dimensions
    pub fn is_equivalent(&self, other: &Unit) -> bool {
        self.dimensions == other.dimensions
    }
}
// Predefine some common units
pub const SECOND: Unit = Unit {
    name: "s",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::Time),
};
pub const METRE: Unit = Unit {
    name: "m",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::Length),
};
pub const KILOGRAM: Unit = Unit {
    name: "kg",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::Mass),
};
pub const AMPERE: Unit = Unit {
    name: "A",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::ElectricCurrent),
};
pub const KELVIN: Unit = Unit {
    name: "K",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::AbsoluteTemperature),
};
pub const MOLE: Unit = Unit {
    name: "mol",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::AmountOfSubstance),
};
pub const CANDELA: Unit = Unit {
    name: "cd",
    scale: 1.0,
    dimensions: UnitProduct::new(Dimension::LuminousIntensity),
};
pub const CENTIMETRE: Unit = Unit {
    name: "cm",
    scale: 0.01,
    dimensions: UnitProduct::new(Dimension::Length),
};

// Derived units can be created by combining base units
pub const METRE_PER_SECOND: Unit = Unit {
    name: "m/s",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[(Dimension::Length, 1), (Dimension::Time, -1)]),
};

pub const NEWTON: Unit = Unit {
    name: "N",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, 1),
        (Dimension::Length, 1),
        (Dimension::Time, -2),
    ]),
};

pub const JOULE: Unit = Unit {
    name: "J",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, 1),
        (Dimension::Length, 2),
        (Dimension::Time, -2),
    ]),
};

pub const WATT: Unit = Unit {
    name: "W",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, 1),
        (Dimension::Length, 2),
        (Dimension::Time, -3),
    ]),
};

pub const COULOMB: Unit = Unit {
    name: "C",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::ElectricCurrent, 1),
        (Dimension::Time, 1),
    ]),
};

pub const VOLT: Unit = Unit {
    name: "V",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, 1),
        (Dimension::Length, 2),
        (Dimension::Time, -3),
        (Dimension::ElectricCurrent, -1),
    ]),
};

pub const OHM: Unit = Unit {
    name: "Ω",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, 1),
        (Dimension::Length, 2),
        (Dimension::Time, -3),
        (Dimension::ElectricCurrent, -2),
    ]),
};

pub const FARAD: Unit = Unit {
    name: "F",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[
        (Dimension::Mass, -1),
        (Dimension::Length, -2),
        (Dimension::Time, 4),
        (Dimension::ElectricCurrent, 2),
    ]),
};

pub const HERTZ: Unit = Unit {
    name: "Hz",
    scale: 1.0,
    dimensions: UnitProduct::from_components(&[(Dimension::Time, -1)]),
};

// --- Quantities ---

#[derive(Debug, Error)]
pub enum QuantityError {
    #[error("Incompatible units: Cannot convert '{from}' to '{to}'. Dimensions differ.")]
    IncompatibleUnits { from: String, to: String },
    #[error("Incompatible units: Cannot add '{lhs}' and '{rhs}'. Units are not identical.")]
    IncompatibleAddition { lhs: String, rhs: String },
    #[error("Incompatible units: Cannot subtract '{lhs}' and '{rhs}'. Units are not identical.")]
    IncompatibleSubtraction { lhs: String, rhs: String },
    #[error("Incompatible units: Cannot multiply '{lhs}' and '{rhs}'. Units are not compatible.")]
    IncompatibleMultiplication { lhs: String, rhs: String },
    #[error("Incompatible units: Cannot divide '{lhs}' by '{rhs}'. Units are not compatible.")]
    IncompatibleDivision { lhs: String, rhs: String },
    #[error("Invalid unit: '{0}'")]
    InvalidUnit(String),
    #[error("Invalid quantity: '{0}'")]
    InvalidQuantity(String),
    #[error("Invalid operation: Cannot divide by zero.")]
    DivideByZero,
    #[error("Mismatched quantity: {0}")]
    MismatchError(String),
}

// Define Quantity type to represent physical quantities with units
#[derive(Debug, Clone, PartialEq)]
pub struct Quantity {
    pub value: Array1<f64>,
    pub unit: Unit,
}

impl Quantity {
    pub fn new(value: Array1<f64>, unit: Unit) -> Self {
        Quantity { value, unit }
    }

    // Convert the Quantity to a target unit if dimensions match
    pub fn to(&self, target_unit: &Unit) -> Result<Self, QuantityError> {
        // Use the is_equivalent method to check if units are compatible
        if !self.unit.is_equivalent(target_unit) {
            return Err(QuantityError::IncompatibleUnits {
                from: self.unit.name.to_string(),
                to: target_unit.name.to_string(),
            });
        }
        let scale_factor = self.unit.scale / target_unit.scale;
        let new_value = &self.value * scale_factor;
        Ok(Quantity::new(new_value, target_unit.clone()))
    }

    // Implement basic arithmetic operations for Quantity
    // Multiply the Quantity by a scalar
    pub fn multiply_scalar(&self, scalar: f64) -> Result<Self, QuantityError> {
        Ok(Quantity::new(&self.value * scalar, self.unit.clone()))
    }
    pub fn divide_scalar(&self, scalar: f64) -> Result<Self, QuantityError> {
        if scalar == 0.0 {
            return Err(QuantityError::DivideByZero);
        }
        Ok(Quantity::new(&self.value / scalar, self.unit.clone()))
    }
}

// Implement basic arithmetic operations for Quantity
use std::ops::{Add, Div, Mul, Sub};

// Implement addition for Quantity
impl Add for Quantity {
    type Output = Result<Self, QuantityError>;
    fn add(self, rhs: Self) -> Self::Output {
        if self.unit != rhs.unit {
            return Err(QuantityError::IncompatibleAddition {
                lhs: self.unit.name.to_string(),
                rhs: rhs.unit.name.to_string(),
            });
        }
        Ok(Quantity::new(&self.value + &rhs.value, self.unit))
    }
}

// Implement subtraction for Quantity
impl Sub for Quantity {
    type Output = Result<Self, QuantityError>;
    fn sub(self, rhs: Self) -> Self::Output {
        if self.unit != rhs.unit {
            return Err(QuantityError::IncompatibleSubtraction {
                lhs: self.unit.name.to_string(),
                rhs: rhs.unit.name.to_string(),
            });
        }
        Ok(Quantity::new(&self.value - &rhs.value, self.unit))
    }
}

// Implement multiplication for Quantity
impl Mul for Quantity {
    type Output = Self; // Multiplication of two quantities results in a new quantity with a new unit
    fn mul(self, rhs: Self) -> Self::Output {
        let new_value = &self.value * &rhs.value;
        let new_unit_dimensions = self.unit.dimensions.multiply(&rhs.unit.dimensions);
        let new_unit_name = format!("{}*{}", self.unit.name, rhs.unit.name);
        let new_unit_scale = self.unit.scale * rhs.unit.scale;

        Quantity::new(
            new_value,
            Unit {
                name: new_unit_name.leak(), // Convert to static str
                scale: new_unit_scale,
                dimensions: new_unit_dimensions,
            },
        )
    }
}

// Implement division for Quantity
impl Div for Quantity {
    type Output = Result<Self, QuantityError>;
    fn div(self, rhs: Self) -> Self::Output {
        // Check for division by zero values in the rhs Array1
        if rhs.value.iter().any(|&x| x == 0.0) {
            return Err(QuantityError::DivideByZero);
        }

        let new_value = &self.value / &rhs.value;
        let new_unit_dimensions = self
            .unit
            .dimensions
            .multiply(&rhs.unit.dimensions.inverse());
        let new_unit_name = format!("{}/{}", self.unit.name, rhs.unit.name);
        let new_unit_scale = self.unit.scale / rhs.unit.scale;

        Ok(Quantity::new(
            new_value,
            Unit {
                name: new_unit_name.leak(), // Convert to static str
                scale: new_unit_scale,
                dimensions: new_unit_dimensions,
            },
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::array;
    #[test]
    fn test_quantity_new() {
        let q = Quantity::new(array![1.0], METRE.clone());
        assert_eq!(q.value, array![1.0]);
        assert_eq!(q.unit.name, "m");
        assert_eq!(q.unit, METRE);
    }

    #[test]
    fn test_quantity_to() {
        let m = METRE.clone();
        let cm = CENTIMETRE.clone();
        let q = Quantity::new(array![1.0, 2.0, 3.0], m);
        let q_cm = q.to(&cm).unwrap();
        assert_eq!(q_cm.value, array![100.0, 200.0, 300.0]);
        assert_eq!(q_cm.unit.name, "cm");
    }

    #[test]
    fn test_quantity_multiply_scalar() {
        let q = Quantity::new(array![1.0, 2.0], METRE.clone());
        let result = q.multiply_scalar(2.0).unwrap();
        assert_eq!(result.value, array![2.0, 4.0]);
        assert_eq!(result.unit.name, "m");
    }
    #[test]
    fn test_quantity_divide_scalar() {
        let q = Quantity::new(array![2.0, 4.0], METRE.clone());
        let result = q.divide_scalar(2.0).unwrap();
        assert_eq!(result.value, array![1.0, 2.0]);
        assert_eq!(result.unit.name, "m");
    }
    #[test]
    fn test_quantity_divide_scalar_by_zero() {
        let q = Quantity::new(array![2.0, 4.0], METRE.clone());
        let result = q.divide_scalar(0.0);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Invalid operation: Cannot divide by zero."
        );
    }
    #[test]
    fn test_quantity_addition() {
        let unit = METRE.clone();
        let q1 = Quantity::new(array![1.0, 2.0], unit.clone());
        let q2 = Quantity::new(array![3.0, 4.0], unit);
        let sum = (q1 + q2).unwrap();
        assert_eq!(sum.value, array![4.0, 6.0]);
        assert_eq!(sum.unit.name, "m");
    }
    #[test]
    fn test_quantity_subtraction() {
        let unit = METRE.clone();
        let q1 = Quantity::new(array![5.0, 6.0], unit.clone());
        let q2 = Quantity::new(array![3.0, 4.0], unit);
        let difference = (q1 - q2).unwrap();
        assert_eq!(difference.value, array![2.0, 2.0]);
        assert_eq!(difference.unit.name, "m");
    }
    #[test]
    fn test_quantity_multiplication() {
        let q1 = Quantity::new(array![1.0, 2.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], SECOND.clone());
        let product = q1 * q2;
        assert_eq!(product.value, array![3.0, 8.0]);
        assert_eq!(product.unit.name, "m*s");
    }
    #[test]
    fn test_quantity_division() {
        let q1 = Quantity::new(array![6.0, 8.0], METRE.clone());
        let q2 = Quantity::new(array![2.0, 4.0], SECOND.clone());
        let quotient = q1 / q2;
        assert!(quotient.is_ok());
        let quotient = quotient.unwrap();
        assert_eq!(quotient.value, array![3.0, 2.0]);
        assert_eq!(quotient.unit.name, "m/s");
    }
    #[test]
    fn test_quantity_divide_by_zero() {
        let q1 = Quantity::new(array![6.0, 8.0], METRE.clone());
        let q2 = Quantity::new(array![0.0, 4.0], SECOND.clone());
        let result = q1 / q2;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Invalid operation: Cannot divide by zero."
        );
    }

    #[test]
    fn test_quantity_addition_incompatible_units() {
        let q1 = Quantity::new(array![1.0, 2.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], SECOND.clone());
        let result = q1 + q2;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Incompatible units: Cannot add 'm' and 's'. Units are not identical."
        );
    }
    #[test]
    fn test_quantity_subtraction_incompatible_units() {
        let q1 = Quantity::new(array![5.0, 6.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], SECOND.clone());
        let result = q1 - q2;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err().to_string(),
            "Incompatible units: Cannot subtract 'm' and 's'. Units are not identical."
        );
    }
    #[test]
    fn test_quantity_multiplication_incompatible_units() {
        let q1 = Quantity::new(array![1.0, 2.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], SECOND.clone());
        let result = q1 * q2;
        assert_eq!(result.value, array![3.0, 8.0]);
        assert_eq!(result.unit.name, "m*s");
    }
    #[test]
    fn test_quantity_division_incompatible_units() {
        let q1 = Quantity::new(array![6.0, 8.0], METRE.clone());
        let q2 = Quantity::new(array![2.0, 4.0], SECOND.clone());
        let result = q1 / q2;
        assert!(result.is_ok());
        let quotient = result.unwrap();
        assert_eq!(quotient.value, array![3.0, 2.0]);
        assert_eq!(quotient.unit.name, "m/s");
    }
    #[test]
    fn test_quantity_addition_compatible_units() {
        let q1 = Quantity::new(array![1.0, 2.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], CENTIMETRE.clone());
        let result = q1.to(&CENTIMETRE).unwrap() + q2;
        assert!(result.is_ok());
        let sum = result.unwrap();
        assert_eq!(sum.value, array![103.0, 204.0]);
        assert_eq!(sum.unit.name, "cm");
    }
    #[test]
    fn test_quantity_subtraction_compatible_units() {
        let q1 = Quantity::new(array![5.0, 6.0], METRE.clone());
        let q2 = Quantity::new(array![3.0, 4.0], CENTIMETRE.clone());
        let result = q1.to(&CENTIMETRE).unwrap() - q2;
        assert!(result.is_ok());
        let difference = result.unwrap();
        assert_eq!(difference.value, array![497.0, 596.0]);
        assert_eq!(difference.unit.name, "cm");
    }
}