oxirs-physics 0.2.4

Physics-informed digital twin simulation bridge for OxiRS
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
//! Dimensional Analysis and Unit Checking
//!
//! Validates dimensional consistency and unit compatibility using fundamental SI dimensions

use crate::error::{PhysicsError, PhysicsResult};
use std::collections::HashMap;

/// Fundamental SI dimensions (L, M, T, I, Θ, N, J)
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Dimensions {
    /// Length (m)
    pub length: i8,
    /// Mass (kg)
    pub mass: i8,
    /// Time (s)
    pub time: i8,
    /// Electric current (A)
    pub current: i8,
    /// Temperature (K)
    pub temperature: i8,
    /// Amount of substance (mol)
    pub amount: i8,
    /// Luminous intensity (cd)
    pub luminosity: i8,
}

impl Dimensions {
    /// Dimensionless quantity
    pub const fn dimensionless() -> Self {
        Self {
            length: 0,
            mass: 0,
            time: 0,
            current: 0,
            temperature: 0,
            amount: 0,
            luminosity: 0,
        }
    }

    /// Check if dimensions are equal
    pub fn equals(&self, other: &Self) -> bool {
        self.length == other.length
            && self.mass == other.mass
            && self.time == other.time
            && self.current == other.current
            && self.temperature == other.temperature
            && self.amount == other.amount
            && self.luminosity == other.luminosity
    }

    /// Check if dimensionless
    pub fn is_dimensionless(&self) -> bool {
        self.equals(&Self::dimensionless())
    }
}

/// Dimensional Analyzer
pub struct DimensionalAnalyzer {
    /// Known unit dimensions
    unit_dimensions: HashMap<String, Dimensions>,
}

impl DimensionalAnalyzer {
    pub fn new() -> Self {
        let mut analyzer = Self {
            unit_dimensions: HashMap::new(),
        };
        analyzer.initialize_si_units();
        analyzer
    }

    /// Initialize common SI units and derived units
    fn initialize_si_units(&mut self) {
        // Base SI units
        self.register_unit(
            "m",
            Dimensions {
                length: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "kg",
            Dimensions {
                mass: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "s",
            Dimensions {
                time: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "A",
            Dimensions {
                current: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "K",
            Dimensions {
                temperature: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "mol",
            Dimensions {
                amount: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "cd",
            Dimensions {
                luminosity: 1,
                ..Dimensions::dimensionless()
            },
        );

        // Derived units - Mechanical
        self.register_unit(
            "N",
            Dimensions {
                length: 1,
                mass: 1,
                time: -2,
                ..Dimensions::dimensionless()
            },
        ); // Newton
        self.register_unit(
            "Pa",
            Dimensions {
                length: -1,
                mass: 1,
                time: -2,
                ..Dimensions::dimensionless()
            },
        ); // Pascal
        self.register_unit(
            "J",
            Dimensions {
                length: 2,
                mass: 1,
                time: -2,
                ..Dimensions::dimensionless()
            },
        ); // Joule
        self.register_unit(
            "W",
            Dimensions {
                length: 2,
                mass: 1,
                time: -3,
                ..Dimensions::dimensionless()
            },
        ); // Watt

        // Derived units - Electrical
        self.register_unit(
            "V",
            Dimensions {
                length: 2,
                mass: 1,
                time: -3,
                current: -1,
                ..Dimensions::dimensionless()
            },
        ); // Volt
        self.register_unit(
            "Ω",
            Dimensions {
                length: 2,
                mass: 1,
                time: -3,
                current: -2,
                ..Dimensions::dimensionless()
            },
        ); // Ohm
        self.register_unit(
            "C",
            Dimensions {
                time: 1,
                current: 1,
                ..Dimensions::dimensionless()
            },
        ); // Coulomb

        // Thermal units
        self.register_unit(
            "°C",
            Dimensions {
                temperature: 1,
                ..Dimensions::dimensionless()
            },
        );
        self.register_unit(
            "W/(m*K)",
            Dimensions {
                length: 1,
                mass: 1,
                time: -3,
                temperature: -1,
                ..Dimensions::dimensionless()
            },
        ); // Thermal conductivity
        self.register_unit(
            "J/(kg*K)",
            Dimensions {
                length: 2,
                time: -2,
                temperature: -1,
                ..Dimensions::dimensionless()
            },
        ); // Specific heat
        self.register_unit(
            "kg/m^3",
            Dimensions {
                length: -3,
                mass: 1,
                ..Dimensions::dimensionless()
            },
        ); // Density

        // Dimensionless
        self.register_unit("dimensionless", Dimensions::dimensionless());
        self.register_unit("1", Dimensions::dimensionless());
    }

    /// Register a unit with its dimensions
    pub fn register_unit(&mut self, unit: &str, dimensions: Dimensions) {
        self.unit_dimensions.insert(unit.to_string(), dimensions);
    }

    /// Get dimensions for a unit
    pub fn get_dimensions(&self, unit: &str) -> Option<&Dimensions> {
        self.unit_dimensions.get(unit)
    }

    /// Check dimensional consistency between two quantities
    pub fn check_consistency(&self, unit1: &str, unit2: &str) -> PhysicsResult<bool> {
        let dim1 = self
            .get_dimensions(unit1)
            .ok_or_else(|| PhysicsError::UnitConversion(format!("Unknown unit: {}", unit1)))?;

        let dim2 = self
            .get_dimensions(unit2)
            .ok_or_else(|| PhysicsError::UnitConversion(format!("Unknown unit: {}", unit2)))?;

        Ok(dim1.equals(dim2))
    }

    /// Check if a unit is dimensionless
    pub fn is_dimensionless(&self, unit: &str) -> PhysicsResult<bool> {
        let dim = self
            .get_dimensions(unit)
            .ok_or_else(|| PhysicsError::UnitConversion(format!("Unknown unit: {}", unit)))?;

        Ok(dim.is_dimensionless())
    }
}

impl Default for DimensionalAnalyzer {
    fn default() -> Self {
        Self::new()
    }
}

/// Unit Checker - validates unit compatibility and conversions
pub struct UnitChecker {
    analyzer: DimensionalAnalyzer,
}

impl UnitChecker {
    pub fn new() -> Self {
        Self {
            analyzer: DimensionalAnalyzer::new(),
        }
    }

    /// Validate unit compatibility (same dimensions)
    pub fn check_compatibility(&self, unit1: &str, unit2: &str) -> PhysicsResult<bool> {
        self.analyzer.check_consistency(unit1, unit2)
    }

    /// Validate that a unit exists
    pub fn validate_unit(&self, unit: &str) -> PhysicsResult<()> {
        if self.analyzer.get_dimensions(unit).is_none() {
            return Err(PhysicsError::UnitConversion(format!(
                "Unknown or unsupported unit: {}",
                unit
            )));
        }
        Ok(())
    }

    /// Get canonical form of a unit (if available)
    pub fn canonical_form(&self, unit: &str) -> PhysicsResult<String> {
        // Validate unit exists
        self.validate_unit(unit)?;

        // For now, return the unit as-is
        // Future: Convert to canonical SI form (e.g., N -> kg·m/s²)
        Ok(unit.to_string())
    }

    /// Check if conversion is possible between units
    pub fn can_convert(&self, from: &str, to: &str) -> PhysicsResult<bool> {
        self.check_compatibility(from, to)
    }
}

impl Default for UnitChecker {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dimensional_consistency() {
        let analyzer = DimensionalAnalyzer::new();

        // Same units should be consistent
        assert!(analyzer
            .check_consistency("m", "m")
            .expect("should succeed"));
        assert!(analyzer
            .check_consistency("kg", "kg")
            .expect("should succeed"));

        // Different units with same dimensions
        // Note: m and km have different prefixes but same dimensions
        // This would require prefix handling (future work)

        // Different dimensions should not be consistent
        assert!(!analyzer
            .check_consistency("m", "kg")
            .expect("should succeed"));
        assert!(!analyzer
            .check_consistency("J", "Pa")
            .expect("should succeed"));
    }

    #[test]
    fn test_derived_units() {
        let analyzer = DimensionalAnalyzer::new();

        // Force (N) = mass * length / time^2
        let newton = analyzer.get_dimensions("N").expect("should succeed");
        assert_eq!(newton.mass, 1);
        assert_eq!(newton.length, 1);
        assert_eq!(newton.time, -2);

        // Energy (J) = mass * length^2 / time^2
        let joule = analyzer.get_dimensions("J").expect("should succeed");
        assert_eq!(joule.mass, 1);
        assert_eq!(joule.length, 2);
        assert_eq!(joule.time, -2);

        // Power (W) = energy / time
        let watt = analyzer.get_dimensions("W").expect("should succeed");
        assert_eq!(watt.mass, 1);
        assert_eq!(watt.length, 2);
        assert_eq!(watt.time, -3);
    }

    #[test]
    fn test_dimensionless() {
        let analyzer = DimensionalAnalyzer::new();

        assert!(analyzer
            .is_dimensionless("dimensionless")
            .expect("should succeed"));
        assert!(analyzer.is_dimensionless("1").expect("should succeed"));
        assert!(!analyzer.is_dimensionless("m").expect("should succeed"));
    }

    #[test]
    fn test_unit_checker() {
        let checker = UnitChecker::new();

        // Valid units
        assert!(checker.validate_unit("m").is_ok());
        assert!(checker.validate_unit("kg").is_ok());
        assert!(checker.validate_unit("N").is_ok());

        // Invalid unit
        assert!(checker.validate_unit("invalid_unit").is_err());

        // Compatibility
        assert!(checker
            .check_compatibility("m", "m")
            .expect("should succeed"));
        assert!(!checker
            .check_compatibility("m", "kg")
            .expect("should succeed"));
    }

    #[test]
    fn test_thermal_units() {
        let analyzer = DimensionalAnalyzer::new();

        // Thermal conductivity: W/(m·K) = kg·m/s³·K
        let k = analyzer.get_dimensions("W/(m*K)").expect("should succeed");
        assert_eq!(k.length, 1);
        assert_eq!(k.mass, 1);
        assert_eq!(k.time, -3);
        assert_eq!(k.temperature, -1);

        // Specific heat: J/(kg·K) = m²/(s²·K)
        let cp = analyzer.get_dimensions("J/(kg*K)").expect("should succeed");
        assert_eq!(cp.length, 2);
        assert_eq!(cp.mass, 0);
        assert_eq!(cp.time, -2);
        assert_eq!(cp.temperature, -1);
    }
}