oxirs-samm 0.2.4

Semantic Aspect Meta Model (SAMM) implementation 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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/// SAMM physical unit conversion engine.
///
/// Converts measurements between physical units using a linear model:
/// `si_value = measurement_value * si_factor + si_offset`.
/// Inverse: `measurement_value = (si_value - si_offset) / si_factor`.
use std::collections::HashMap;

/// A physical unit with an affine mapping to SI.
#[derive(Debug, Clone)]
pub struct Unit {
    /// IRI identifier for the unit (e.g. `unit:degreeCelsius`).
    pub iri: String,
    /// Short symbol (e.g. "°C", "m", "kg").
    pub symbol: String,
    /// Quantity kind (e.g. "temperature", "length", "mass").
    pub quantity_kind: String,
    /// Multiplier to convert this unit to SI: `si = value * si_factor + si_offset`.
    pub si_factor: f64,
    /// Offset term for affine conversions (non-zero for Celsius/Fahrenheit).
    pub si_offset: f64,
}

/// Errors from unit conversion operations.
#[derive(Debug)]
pub enum ConversionError {
    /// The unit IRI is not registered.
    UnknownUnit(String),
    /// The two units have incompatible quantity kinds.
    IncompatibleUnits(String, String),
    /// Division by zero during inverse conversion.
    DivisionByZero,
}

impl std::fmt::Display for ConversionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::UnknownUnit(u) => write!(f, "Unknown unit: {u}"),
            Self::IncompatibleUnits(a, b) => {
                write!(f, "Incompatible units: {a} and {b}")
            }
            Self::DivisionByZero => write!(f, "Division by zero in unit conversion"),
        }
    }
}

impl std::error::Error for ConversionError {}

/// A successful conversion result with provenance information.
#[derive(Debug, Clone)]
pub struct ConversionResult {
    /// The converted value in the target unit.
    pub value: f64,
    /// Source unit IRI.
    pub from_unit: String,
    /// Target unit IRI.
    pub to_unit: String,
    /// Human-readable conversion formula applied.
    pub formula: String,
}

/// Engine for converting between registered physical units.
#[derive(Debug, Default)]
pub struct UnitConverter {
    units: HashMap<String, Unit>,
}

impl UnitConverter {
    /// Create an empty converter.
    pub fn new() -> Self {
        Self {
            units: HashMap::new(),
        }
    }

    /// Create a converter pre-loaded with SI and common units.
    pub fn with_defaults() -> Self {
        let mut uc = Self::new();
        // --- Length ---
        uc.register(Unit {
            iri: "unit:metre".to_string(),
            symbol: "m".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 1.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:kilometre".to_string(),
            symbol: "km".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 1000.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:mile".to_string(),
            symbol: "mi".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 1609.344,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:centimetre".to_string(),
            symbol: "cm".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 0.01,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:inch".to_string(),
            symbol: "in".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 0.0254,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:foot".to_string(),
            symbol: "ft".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 0.3048,
            si_offset: 0.0,
        });
        // --- Mass ---
        uc.register(Unit {
            iri: "unit:kilogram".to_string(),
            symbol: "kg".to_string(),
            quantity_kind: "mass".to_string(),
            si_factor: 1.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:gram".to_string(),
            symbol: "g".to_string(),
            quantity_kind: "mass".to_string(),
            si_factor: 0.001,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:pound".to_string(),
            symbol: "lb".to_string(),
            quantity_kind: "mass".to_string(),
            si_factor: 0.453592,
            si_offset: 0.0,
        });
        // --- Time ---
        uc.register(Unit {
            iri: "unit:second".to_string(),
            symbol: "s".to_string(),
            quantity_kind: "time".to_string(),
            si_factor: 1.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:minute".to_string(),
            symbol: "min".to_string(),
            quantity_kind: "time".to_string(),
            si_factor: 60.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:hour".to_string(),
            symbol: "h".to_string(),
            quantity_kind: "time".to_string(),
            si_factor: 3600.0,
            si_offset: 0.0,
        });
        // --- Temperature ---
        uc.register(Unit {
            iri: "unit:kelvin".to_string(),
            symbol: "K".to_string(),
            quantity_kind: "temperature".to_string(),
            si_factor: 1.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:degreeCelsius".to_string(),
            symbol: "°C".to_string(),
            quantity_kind: "temperature".to_string(),
            si_factor: 1.0,
            si_offset: 273.15,
        });
        uc.register(Unit {
            iri: "unit:degreeFahrenheit".to_string(),
            symbol: "°F".to_string(),
            quantity_kind: "temperature".to_string(),
            si_factor: 5.0 / 9.0,
            si_offset: 273.15 - (32.0 * 5.0 / 9.0),
        });
        // --- Volume ---
        uc.register(Unit {
            iri: "unit:cubicMetre".to_string(),
            symbol: "".to_string(),
            quantity_kind: "volume".to_string(),
            si_factor: 1.0,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:litre".to_string(),
            symbol: "L".to_string(),
            quantity_kind: "volume".to_string(),
            si_factor: 0.001,
            si_offset: 0.0,
        });
        uc.register(Unit {
            iri: "unit:gallon".to_string(),
            symbol: "gal".to_string(),
            quantity_kind: "volume".to_string(),
            si_factor: 0.003785411784,
            si_offset: 0.0,
        });
        uc
    }

    /// Register a unit in the converter.
    pub fn register(&mut self, unit: Unit) {
        self.units.insert(unit.iri.clone(), unit);
    }

    /// Convert a value from one unit to another.
    pub fn convert(
        &self,
        value: f64,
        from_iri: &str,
        to_iri: &str,
    ) -> Result<ConversionResult, ConversionError> {
        let from = self
            .units
            .get(from_iri)
            .ok_or_else(|| ConversionError::UnknownUnit(from_iri.to_string()))?;
        let to = self
            .units
            .get(to_iri)
            .ok_or_else(|| ConversionError::UnknownUnit(to_iri.to_string()))?;

        if from.quantity_kind != to.quantity_kind {
            return Err(ConversionError::IncompatibleUnits(
                from.quantity_kind.clone(),
                to.quantity_kind.clone(),
            ));
        }

        // Convert to SI then to target
        let si_value = value * from.si_factor + from.si_offset;
        let result_value = self.convert_from_si_unit(si_value, to)?;

        let formula = format!("{value} {} = {} {}", from.symbol, result_value, to.symbol);

        Ok(ConversionResult {
            value: result_value,
            from_unit: from_iri.to_string(),
            to_unit: to_iri.to_string(),
            formula,
        })
    }

    /// Convert a value to its SI equivalent.
    pub fn to_si(&self, value: f64, unit_iri: &str) -> Result<f64, ConversionError> {
        let unit = self
            .units
            .get(unit_iri)
            .ok_or_else(|| ConversionError::UnknownUnit(unit_iri.to_string()))?;
        Ok(value * unit.si_factor + unit.si_offset)
    }

    /// Convert a SI value to the specified unit.
    pub fn from_si(&self, si_value: f64, unit_iri: &str) -> Result<f64, ConversionError> {
        let unit = self
            .units
            .get(unit_iri)
            .ok_or_else(|| ConversionError::UnknownUnit(unit_iri.to_string()))?;
        self.convert_from_si_unit(si_value, unit)
    }

    fn convert_from_si_unit(&self, si_value: f64, unit: &Unit) -> Result<f64, ConversionError> {
        if unit.si_factor == 0.0 {
            return Err(ConversionError::DivisionByZero);
        }
        Ok((si_value - unit.si_offset) / unit.si_factor)
    }

    /// Return all units belonging to a given quantity kind.
    pub fn units_for_quantity(&self, quantity_kind: &str) -> Vec<&Unit> {
        self.units
            .values()
            .filter(|u| u.quantity_kind == quantity_kind)
            .collect()
    }

    /// Return the total number of registered units.
    pub fn unit_count(&self) -> usize {
        self.units.len()
    }

    /// Retrieve a unit by IRI.
    pub fn get_unit(&self, iri: &str) -> Option<&Unit> {
        self.units.get(iri)
    }
}

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

    const EPSILON: f64 = 1e-6;

    fn approx_eq(a: f64, b: f64) -> bool {
        (a - b).abs() < EPSILON
    }

    // --- metres / kilometres ---

    #[test]
    fn test_metres_to_kilometres() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1000.0, "unit:metre", "unit:kilometre")
            .expect("should succeed");
        assert!(approx_eq(r.value, 1.0));
    }

    #[test]
    fn test_kilometres_to_metres() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:kilometre", "unit:metre")
            .expect("should succeed");
        assert!(approx_eq(r.value, 1000.0));
    }

    #[test]
    fn test_same_unit_identity() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(42.0, "unit:metre", "unit:metre")
            .expect("should succeed");
        assert!(approx_eq(r.value, 42.0));
    }

    // --- temperature (offset conversions) ---

    #[test]
    fn test_celsius_to_fahrenheit() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(0.0, "unit:degreeCelsius", "unit:degreeFahrenheit")
            .expect("should succeed");
        // 0°C = 32°F
        assert!((r.value - 32.0).abs() < 0.001);
    }

    #[test]
    fn test_celsius_100_to_fahrenheit() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(100.0, "unit:degreeCelsius", "unit:degreeFahrenheit")
            .expect("should succeed");
        // 100°C = 212°F
        assert!((r.value - 212.0).abs() < 0.001);
    }

    #[test]
    fn test_fahrenheit_to_celsius() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(32.0, "unit:degreeFahrenheit", "unit:degreeCelsius")
            .expect("should succeed");
        // 32°F = 0°C
        assert!(r.value.abs() < 0.001);
    }

    #[test]
    fn test_celsius_to_kelvin() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(0.0, "unit:degreeCelsius", "unit:kelvin")
            .expect("should succeed");
        assert!((r.value - 273.15).abs() < 0.001);
    }

    // --- distance ---

    #[test]
    fn test_miles_to_metres() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:mile", "unit:metre")
            .expect("should succeed");
        assert!((r.value - 1609.344).abs() < 0.01);
    }

    #[test]
    fn test_inches_to_centimetres() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:inch", "unit:centimetre")
            .expect("should succeed");
        assert!((r.value - 2.54).abs() < 0.001);
    }

    // --- volume ---

    #[test]
    fn test_litres_to_gallons() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:litre", "unit:gallon")
            .expect("should succeed");
        // 1 L ≈ 0.264172 gal
        assert!((r.value - 0.264172).abs() < 0.0001);
    }

    #[test]
    fn test_gallons_to_litres() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:gallon", "unit:litre")
            .expect("should succeed");
        assert!((r.value - 3.785411784).abs() < 0.0001);
    }

    // --- error cases ---

    #[test]
    fn test_unknown_from_unit() {
        let uc = UnitConverter::with_defaults();
        let err = uc.convert(1.0, "unit:unknown", "unit:metre");
        assert!(matches!(err, Err(ConversionError::UnknownUnit(_))));
    }

    #[test]
    fn test_unknown_to_unit() {
        let uc = UnitConverter::with_defaults();
        let err = uc.convert(1.0, "unit:metre", "unit:unknown");
        assert!(matches!(err, Err(ConversionError::UnknownUnit(_))));
    }

    #[test]
    fn test_incompatible_units() {
        let uc = UnitConverter::with_defaults();
        let err = uc.convert(1.0, "unit:metre", "unit:kilogram");
        assert!(matches!(err, Err(ConversionError::IncompatibleUnits(_, _))));
    }

    // --- to_si / from_si ---

    #[test]
    fn test_to_si_metre() {
        let uc = UnitConverter::with_defaults();
        let si = uc.to_si(5.0, "unit:metre").expect("should succeed");
        assert!(approx_eq(si, 5.0));
    }

    #[test]
    fn test_to_si_kilometre() {
        let uc = UnitConverter::with_defaults();
        let si = uc.to_si(3.0, "unit:kilometre").expect("should succeed");
        assert!(approx_eq(si, 3000.0));
    }

    #[test]
    fn test_from_si_metre_roundtrip() {
        let uc = UnitConverter::with_defaults();
        let si = uc.to_si(7.5, "unit:kilometre").expect("should succeed");
        let back = uc.from_si(si, "unit:kilometre").expect("should succeed");
        assert!((back - 7.5).abs() < EPSILON);
    }

    #[test]
    fn test_celsius_to_si_round_trip() {
        let uc = UnitConverter::with_defaults();
        let si = uc
            .to_si(25.0, "unit:degreeCelsius")
            .expect("should succeed");
        let back = uc
            .from_si(si, "unit:degreeCelsius")
            .expect("should succeed");
        assert!((back - 25.0).abs() < 0.001);
    }

    #[test]
    fn test_to_si_unknown() {
        let uc = UnitConverter::with_defaults();
        assert!(uc.to_si(1.0, "unit:xyz").is_err());
    }

    #[test]
    fn test_from_si_unknown() {
        let uc = UnitConverter::with_defaults();
        assert!(uc.from_si(1.0, "unit:xyz").is_err());
    }

    // --- units_for_quantity ---

    #[test]
    fn test_units_for_length() {
        let uc = UnitConverter::with_defaults();
        let units = uc.units_for_quantity("length");
        assert!(!units.is_empty());
        assert!(units.iter().any(|u| u.iri == "unit:metre"));
        assert!(units.iter().any(|u| u.iri == "unit:kilometre"));
    }

    #[test]
    fn test_units_for_temperature() {
        let uc = UnitConverter::with_defaults();
        let units = uc.units_for_quantity("temperature");
        assert!(units.iter().any(|u| u.iri == "unit:degreeCelsius"));
        assert!(units.iter().any(|u| u.iri == "unit:kelvin"));
    }

    #[test]
    fn test_units_for_unknown_quantity() {
        let uc = UnitConverter::with_defaults();
        let units = uc.units_for_quantity("luminosity");
        assert!(units.is_empty());
    }

    // --- unit_count / get_unit ---

    #[test]
    fn test_unit_count_with_defaults() {
        let uc = UnitConverter::with_defaults();
        assert!(uc.unit_count() >= 10);
    }

    #[test]
    fn test_get_unit_present() {
        let uc = UnitConverter::with_defaults();
        let u = uc.get_unit("unit:metre");
        assert!(u.is_some());
        assert_eq!(u.expect("should succeed").symbol, "m");
    }

    #[test]
    fn test_get_unit_absent() {
        let uc = UnitConverter::new();
        assert!(uc.get_unit("unit:metre").is_none());
    }

    // --- custom unit registration ---

    #[test]
    fn test_register_custom_unit() {
        let mut uc = UnitConverter::new();
        uc.register(Unit {
            iri: "unit:parsec".to_string(),
            symbol: "pc".to_string(),
            quantity_kind: "length".to_string(),
            si_factor: 3.085677581e16,
            si_offset: 0.0,
        });
        assert_eq!(uc.unit_count(), 1);
        assert!(uc.get_unit("unit:parsec").is_some());
    }

    // --- formula string ---

    #[test]
    fn test_conversion_result_formula_populated() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1000.0, "unit:metre", "unit:kilometre")
            .expect("should succeed");
        assert!(!r.formula.is_empty());
        assert!(r.formula.contains("km"));
    }

    // --- error display ---

    #[test]
    fn test_unknown_unit_error_display() {
        let err = ConversionError::UnknownUnit("unit:xyz".to_string());
        assert!(format!("{err}").contains("unit:xyz"));
    }

    #[test]
    fn test_incompatible_units_display() {
        let err = ConversionError::IncompatibleUnits("length".to_string(), "mass".to_string());
        let msg = format!("{err}");
        assert!(msg.contains("length") && msg.contains("mass"));
    }

    #[test]
    fn test_division_by_zero_display() {
        let err = ConversionError::DivisionByZero;
        assert!(format!("{err}").contains("zero"));
    }

    // --- mass conversions ---

    #[test]
    fn test_grams_to_kilograms() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1000.0, "unit:gram", "unit:kilogram")
            .expect("should succeed");
        assert!((r.value - 1.0).abs() < EPSILON);
    }

    #[test]
    fn test_pounds_to_kilograms() {
        let uc = UnitConverter::with_defaults();
        let r = uc
            .convert(1.0, "unit:pound", "unit:kilogram")
            .expect("should succeed");
        assert!((r.value - 0.453592).abs() < 0.0001);
    }
}