rssn 0.2.9

A comprehensive scientific computing library for Rust, aiming for feature parity with NumPy and SymPy.
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
//! # Unit Unification and Dimensional Analysis
//!
//! This module provides functionality for handling physical units and performing
//! dimensional analysis within symbolic expressions. It supports parsing unit strings,
//! unifying expressions involving quantities with units, and performing arithmetic
//! operations while respecting dimensional consistency.
//!
//! # Supported Units
//! Currently, the module supports basic SI units and some common derivatives:
//! - **Length**: meter (m), centimeter (cm)
//! - **Mass**: kilogram (kg), gram (g)
//! - **Time**: second (s), minute (min)
//! - **Area**: square meter (m², sqm)
//! - **Velocity**: meter per second (m/s, mps)
//!
//! # Examples
//! ```
//! use std::sync::Arc;
//!
//! use rssn::symbolic::core::Expr;
//! use rssn::symbolic::unit_unification::unify_expression;
//!
//! // Define quantities: 5m and 3m
//! let q1 = Expr::QuantityWithValue(Arc::new(Expr::new_constant(5.0)), "m".to_string());
//!
//! let q2 = Expr::QuantityWithValue(Arc::new(Expr::new_constant(3.0)), "m".to_string());
//!
//! // Add them: 5m + 3m
//! let sum_expr = Expr::new_add(q1, q2);
//!
//! // Unify to get the result: 8m
//! let result = unify_expression(&sum_expr).unwrap();
//! ```

use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;
use std::ops::Add;
use std::ops::Div;
use std::ops::Mul;
use std::ops::Neg;
use std::ops::Sub;
use std::sync::Arc;

use ordered_float;
use uom::si::area;
use uom::si::f64::Area;
use uom::si::f64::Length;
use uom::si::f64::Mass;
use uom::si::f64::Time;
use uom::si::f64::Velocity;
use uom::si::length;
use uom::si::mass;
use uom::si::time;
use uom::si::velocity;

use crate::symbolic::core::Expr;

/// Represents a physical quantity with a specific dimension.
///
/// This enum wraps the `uom` crate's types to provide a unified interface for
/// different physical dimensions.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[repr(C)]
pub enum SupportedQuantity {
    /// Represents a length quantity.
    Length(Length),
    /// Represents a mass quantity.
    Mass(Mass),
    /// Represents a time quantity.
    Time(Time),
    /// Represents an area quantity.
    Area(Area),
    /// Represents a velocity quantity.
    Velocity(Velocity),
}

#[allow(clippy::arithmetic_side_effects)]
impl Add for SupportedQuantity {
    type Output = Result<Self, String>;

    fn add(
        self,
        rhs: Self,
    ) -> Self::Output {
        match (self, rhs) {
            | (Self::Length(l1), Self::Length(l2)) => Ok(Self::Length(l1 + l2)),
            | (Self::Mass(m1), Self::Mass(m2)) => Ok(Self::Mass(m1 + m2)),
            | (Self::Time(t1), Self::Time(t2)) => Ok(Self::Time(t1 + t2)),
            | (Self::Area(a1), Self::Area(a2)) => Ok(Self::Area(a1 + a2)),
            | (Self::Velocity(v1), Self::Velocity(v2)) => Ok(Self::Velocity(v1 + v2)),
            | _ => {
                Err("Incompatible types \
                 for addition"
                    .to_string())
            },
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Sub for SupportedQuantity {
    type Output = Result<Self, String>;

    fn sub(
        self,
        rhs: Self,
    ) -> Self::Output {
        match (self, rhs) {
            | (Self::Length(l1), Self::Length(l2)) => Ok(Self::Length(l1 - l2)),
            | (Self::Mass(m1), Self::Mass(m2)) => Ok(Self::Mass(m1 - m2)),
            | (Self::Time(t1), Self::Time(t2)) => Ok(Self::Time(t1 - t2)),
            | (Self::Area(a1), Self::Area(a2)) => Ok(Self::Area(a1 - a2)),
            | (Self::Velocity(v1), Self::Velocity(v2)) => Ok(Self::Velocity(v1 - v2)),
            | _ => {
                Err("Incompatible types \
                 for subtraction"
                    .to_string())
            },
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Neg for SupportedQuantity {
    type Output = Self;

    fn neg(self) -> Self::Output {
        match self {
            | Self::Length(l) => Self::Length(-l),
            | Self::Mass(m) => Self::Mass(-m),
            | Self::Time(t) => Self::Time(-t),
            | Self::Area(a) => Self::Area(-a),
            | Self::Velocity(v) => Self::Velocity(-v),
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Mul for SupportedQuantity {
    type Output = Result<Self, String>;

    fn mul(
        self,
        rhs: Self,
    ) -> Self::Output {
        match (self, rhs) {
            | (Self::Length(l1), Self::Length(l2)) => Ok(Self::Area(l1 * l2)),
            | _ => {
                Err("Unsupported or \
                     complex quantity \
                     combination for \
                     multiplication"
                    .to_string())
            },
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Mul<f64> for SupportedQuantity {
    type Output = Self;

    fn mul(
        self,
        rhs: f64,
    ) -> Self::Output {
        match self {
            | Self::Length(l) => Self::Length(l * rhs),
            | Self::Mass(m) => Self::Mass(m * rhs),
            | Self::Time(t) => Self::Time(t * rhs),
            | Self::Area(a) => Self::Area(a * rhs),
            | Self::Velocity(v) => Self::Velocity(v * rhs),
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Div for SupportedQuantity {
    type Output = Result<Self, String>;

    fn div(
        self,
        rhs: Self,
    ) -> Self::Output {
        match (self, rhs) {
            | (Self::Length(l), Self::Time(t)) => Ok(Self::Velocity(l / t)),
            | (Self::Length(_l), Self::Length(_l2)) => {
                Err("Division resulting \
                 in dimensionless \
                 scalar is not yet \
                 supported"
                    .to_string())
            },
            | _ => {
                Err("Unsupported or \
                     complex quantity \
                     combination for \
                     division"
                    .to_string())
            },
        }
    }
}

#[allow(clippy::arithmetic_side_effects)]
impl Div<f64> for SupportedQuantity {
    type Output = Self;

    fn div(
        self,
        rhs: f64,
    ) -> Self::Output {
        match self {
            | Self::Length(l) => Self::Length(l / rhs),
            | Self::Mass(m) => Self::Mass(m / rhs),
            | Self::Time(t) => Self::Time(t / rhs),
            | Self::Area(a) => Self::Area(a / rhs),
            | Self::Velocity(v) => Self::Velocity(v / rhs),
        }
    }
}

/// A wrapper struct for `SupportedQuantity` to be used within `Expr`.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UnitQuantity(pub SupportedQuantity);

#[allow(clippy::arithmetic_side_effects)]
impl Eq for UnitQuantity {}

#[allow(clippy::arithmetic_side_effects)]
impl Hash for UnitQuantity {
    fn hash<H: Hasher>(
        &self,
        state: &mut H,
    ) {
        match &self.0 {
            | SupportedQuantity::Length(l) => {
                ("Length", ordered_float::OrderedFloat(l.value)).hash(state);
            },
            | SupportedQuantity::Mass(m) => {
                ("Mass", ordered_float::OrderedFloat(m.value)).hash(state);
            },
            | SupportedQuantity::Time(t) => {
                ("Time", ordered_float::OrderedFloat(t.value)).hash(state);
            },
            | SupportedQuantity::Area(a) => {
                ("Area", ordered_float::OrderedFloat(a.value)).hash(state);
            },
            | SupportedQuantity::Velocity(v) => {
                ("Velocity", ordered_float::OrderedFloat(v.value)).hash(state);
            },
        }
    }
}

/// Parses a value and a unit string into a `SupportedQuantity` enum.
#[inline]
pub(crate) fn parse_quantity(
    value: f64,
    unit: &str,
) -> Result<SupportedQuantity, String> {
    let unit_lower = unit.to_lowercase();

    match unit_lower.as_str() {
        | "m" | "meter" => {
            Ok(SupportedQuantity::Length(Length::new::<length::meter>(
                value,
            )))
        },
        | "cm" | "centimeter" => {
            Ok(SupportedQuantity::Length(
                Length::new::<length::centimeter>(value),
            ))
        },
        | "kg" | "kilogram" => Ok(SupportedQuantity::Mass(Mass::new::<mass::kilogram>(value))),
        | "g" | "gram" => Ok(SupportedQuantity::Mass(Mass::new::<mass::gram>(value))),
        | "s" | "second" => Ok(SupportedQuantity::Time(Time::new::<time::second>(value))),
        | "min" | "minute" => Ok(SupportedQuantity::Time(Time::new::<time::minute>(value))),
        | "m2" | "sqm" => {
            Ok(SupportedQuantity::Area(Area::new::<area::square_meter>(
                value,
            )))
        },
        | "m/s" | "mps" => {
            Ok(SupportedQuantity::Velocity(Velocity::new::<
                velocity::meter_per_second,
            >(value)))
        },
        | _ => Err(format!("Unknown or unsupported unit: {unit}")),
    }
}

/// Converts a numeric `Expr` variant into an `f64`.
///
/// This function handles `Expr::Constant`, `Expr::BigInt`, `Expr::Rational`, and `Expr::Dag`
/// (by converting it to an AST expression first).
///
/// # Arguments
/// * `expr` - The expression to convert.
///
/// # Returns
/// A `Result` containing the `f64` value or an error string.
#[inline]
pub(crate) fn expr_to_f64(expr: &Expr) -> Result<f64, String> {
    let expr_ast = if let Expr::Dag(node) = expr {
        node.to_expr().map_err(|e| {
            format!(
                "DAG conversion \
                     error: {e}"
            )
        })?
    } else {
        expr.clone()
    };

    expr_ast.to_f64().ok_or_else(|| {
        format!(
            "Expression cannot be \
                 converted to a \
                 numeric value: \
                 {expr:?}"
        )
    })
}

/// Unifies an expression containing quantities with units.
///
/// This function recursively traverses the expression tree, resolving `QuantityWithValue`
/// nodes into `Quantity` nodes with concrete `UnitQuantity` values. It then performs
/// arithmetic operations on these quantities, checking for dimensional consistency.
///
/// # Arguments
/// * `expr` - The expression to unify.
///
/// # Returns
/// A `Result` containing the unified `Expr` or an error string if unification fails
/// (e.g., due to incompatible units).
///
/// # Examples
/// ```
/// use std::sync::Arc;
///
/// use rssn::symbolic::core::Expr;
/// use rssn::symbolic::unit_unification::unify_expression;
///
/// // 10m / 2s
/// let dist = Expr::QuantityWithValue(Arc::new(Expr::new_constant(10.0)), "m".to_string());
///
/// let time = Expr::QuantityWithValue(Arc::new(Expr::new_constant(2.0)), "s".to_string());
///
/// let velocity_expr = Expr::new_div(dist, time);
///
/// let result = unify_expression(&velocity_expr).unwrap();
/// // Result is a Quantity representing 5 m/s
/// ```
///
/// # Panics
///
/// Panics if a `Dag` node cannot be converted to an `Expr`, which indicates an
/// internal inconsistency in the expression representation. This should ideally
/// not happen in a well-formed expression DAG.
///
/// # Errors
///
/// This function will return an error if:
/// - A numerical value cannot be extracted from a quantity expression.
/// - Units cannot be parsed from the provided strings.
/// - Addition, subtraction, multiplication, or division of quantities fails
///   due to incompatible dimensions.
pub fn unify_expression(expr: &Expr) -> Result<Expr, String> {
    match expr {
        | Expr::Dag(node) => unify_expression(&node.to_expr().expect("Dag Unify")),
        | Expr::QuantityWithValue(val_expr, unit_str) => {
            let value = expr_to_f64(val_expr)?;

            let quantity = parse_quantity(value, unit_str)?;

            Ok(Expr::Quantity(Arc::new(UnitQuantity(quantity))))
        },
        | Expr::Add(a, b) => {
            let unified_a = unify_expression(a)?;

            let unified_b = unify_expression(b)?;

            match (unified_a, unified_b) {
                | (Expr::Quantity(qa), Expr::Quantity(qb)) => {
                    let result = qa.0.clone() + qb.0.clone();

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result?))))
                },
                | (a, b) => Ok(Expr::new_add(a, b)),
            }
        },
        | Expr::Sub(a, b) => {
            let unified_a = unify_expression(a)?;

            let unified_b = unify_expression(b)?;

            match (unified_a, unified_b) {
                | (Expr::Quantity(qa), Expr::Quantity(qb)) => {
                    let result = qa.0.clone() - qb.0.clone();

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result?))))
                },
                | (a, b) => Ok(Expr::new_sub(a, b)),
            }
        },
        | Expr::Mul(a, b) => {
            let unified_a = unify_expression(a)?;

            let unified_b = unify_expression(b)?;

            match (unified_a, unified_b) {
                | (Expr::Quantity(qa), Expr::Quantity(qb)) => {
                    let result = (qa.0.clone() * qb.0.clone())?;

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result))))
                },
                | (Expr::Quantity(qa), Expr::Constant(scalar_f64))
                | (Expr::Constant(scalar_f64), Expr::Quantity(qa)) => {
                    let result = qa.0.clone() * scalar_f64;

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result))))
                },
                | (a, b) => Ok(Expr::new_mul(a, b)),
            }
        },
        | Expr::Div(a, b) => {
            let unified_a = unify_expression(a)?;

            let unified_b = unify_expression(b)?;

            match (unified_a, unified_b) {
                | (Expr::Quantity(qa), Expr::Quantity(qb)) => {
                    let result = (qa.0.clone() / qb.0.clone())?;

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result))))
                },
                #[allow(clippy::arithmetic_side_effects)]
                | (Expr::Quantity(qa), Expr::Constant(scalar_f64)) => {
                    if !scalar_f64.is_normal() {
                        return Err(format!(
                            "Error: Division scalar must be a non-zero, finite number. Received: \
                             {scalar_f64}"
                        ));
                    }

                    let result = qa.0.clone() / scalar_f64;

                    Ok(Expr::Quantity(Arc::new(UnitQuantity(result))))
                },
                | (Expr::Constant(_), Expr::Quantity(_)) => {
                    Err("Error: Scalar \
                     divided by \
                     Quantity (S / Q) \
                     is not yet \
                     supported as it \
                     requires new \
                     reciprocal \
                     dimension types \
                     (like Frequency \
                     or Reciprocal \
                     Length)."
                        .to_string())
                },
                | (a, b) => Ok(Expr::new_div(a, b)),
            }
        },
        | Expr::Neg(a) => {
            let unified_a = unify_expression(a)?;

            if let Expr::Quantity(qa) = unified_a {
                Ok(Expr::Quantity(Arc::new(UnitQuantity(qa.0.clone().neg()))))
            } else {
                Ok(Expr::new_neg(unified_a))
            }
        },
        | _ => Ok(expr.clone()),
    }
}