thales 0.4.2

A comprehensive Computer Algebra System (CAS) library for symbolic mathematics, equation solving, calculus, and linear algebra
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
//! Unit and dimension handling for physical quantities.
//!
//! This module provides comprehensive dimensional analysis and unit conversion capabilities
//! for equations involving physical quantities. It implements a type-safe system based on
//! the International System of Units (SI) with support for derived units and unit conversions.
//!
//! # Dimensional Analysis
//!
//! Dimensional analysis is a method to check the consistency of equations and perform
//! unit conversions by tracking the fundamental physical dimensions (length, mass, time, etc.)
//! through calculations. Each physical quantity has an associated dimension that can be
//! expressed as a product of powers of base dimensions.
//!
//! # Core Concepts
//!
//! - **BaseDimension**: The seven SI base dimensions (length, mass, time, current, temperature,
//!   amount of substance, luminous intensity)
//! - **Dimension**: A composite dimension expressed as a product of base dimensions with exponents
//!   (e.g., velocity = Length¹ × Time⁻¹)
//! - **Unit**: A specific measurement standard with a dimension and conversion factor to SI base units
//! - **Quantity**: A numeric value paired with its unit of measurement
//! - **UnitRegistry**: A collection of units for lookup and conversion
//!
//! # Examples
//!
//! ## Creating and Using Units
//!
//! ```
//! use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
//!
//! // Create a velocity dimension: Length / Time
//! let length_dim = Dimension::from_base(BaseDimension::Length, 1);
//! let time_dim = Dimension::from_base(BaseDimension::Time, -1);
//! let velocity_dim = length_dim.multiply(&time_dim);
//!
//! // Create meter per second unit
//! let mps = Unit::new("meter per second", "m/s", velocity_dim.clone(), 1.0);
//!
//! // Create a quantity
//! let speed = Quantity::new(10.0, mps.clone());
//! println!("{}", speed); // "10 m/s"
//! ```
//!
//! ## Unit Conversion
//!
//! ```
//! use thales::dimensions::{BaseDimension, Dimension, Unit};
//!
//! // Create length dimension and units
//! let length_dim = Dimension::from_base(BaseDimension::Length, 1);
//! let meter = Unit::new("meter", "m", length_dim.clone(), 1.0);
//! let kilometer = Unit::new("kilometer", "km", length_dim.clone(), 1000.0);
//!
//! // Convert 5 km to meters
//! let meters = kilometer.convert_to(5.0, &meter).unwrap();
//! assert_eq!(meters, 5000.0);
//! ```
//!
//! ## Temperature with Offset (Affine Units)
//!
//! ```
//! use thales::dimensions::{BaseDimension, Dimension, Unit};
//!
//! // Create temperature dimension
//! let temp_dim = Dimension::from_base(BaseDimension::Temperature, 1);
//!
//! // Kelvin (SI base unit)
//! let kelvin = Unit::new("kelvin", "K", temp_dim.clone(), 1.0);
//!
//! // Celsius with offset: K = °C + 273.15
//! let celsius = Unit::with_offset("celsius", "°C", temp_dim.clone(), 1.0, 273.15);
//!
//! // Convert 0°C to Kelvin
//! let k = celsius.convert_to(0.0, &kelvin).unwrap();
//! assert_eq!(k, 273.15);
//! ```
//!
//! ## Derived Units (Force)
//!
//! ```
//! use thales::dimensions::{BaseDimension, Dimension, Unit};
//!
//! // Force dimension: Mass × Length × Time⁻²
//! let mass_dim = Dimension::from_base(BaseDimension::Mass, 1);
//! let length_dim = Dimension::from_base(BaseDimension::Length, 1);
//! let time_dim = Dimension::from_base(BaseDimension::Time, -2);
//! let force_dim = mass_dim.multiply(&length_dim).multiply(&time_dim);
//!
//! // Newton: kg⋅m/s²
//! let newton = Unit::new("newton", "N", force_dim.clone(), 1.0);
//!
//! // Dyne: g⋅cm/s² = 10⁻⁵ N
//! let dyne = Unit::new("dyne", "dyn", force_dim.clone(), 1e-5);
//!
//! let force_in_dynes = newton.convert_to(1.0, &dyne).unwrap();
//! assert!((force_in_dynes - 100000.0).abs() < 0.01);
//! ```
//!
//! ## Using UnitRegistry
//!
//! ```
//! use thales::dimensions::{BaseDimension, Dimension, Unit, UnitRegistry};
//!
//! let mut registry = UnitRegistry::new();
//!
//! // Add length units
//! let length_dim = Dimension::from_base(BaseDimension::Length, 1);
//! registry.add_unit(Unit::new("meter", "m", length_dim.clone(), 1.0));
//! registry.add_unit(Unit::new("foot", "ft", length_dim.clone(), 0.3048));
//!
//! // Convert using registry
//! let meters = registry.convert(100.0, "ft", "m").unwrap();
//! assert!((meters - 30.48).abs() < 0.001);
//! ```
//!
//! # TODO Items
//!
//! The following features are planned for future implementation:
//!
//! - Compound unit parsing and formatting (e.g., "m/s", "kg⋅m/s²")
//! - Unit prefix support (kilo-, mega-, milli-, micro-, etc.)
//! - Parsing quantities from strings (e.g., "5.2 m/s")
//! - Unit system conversions (SI, Imperial, CGS)
//! - Automatic dimensional analysis validation for equations
//! - Currency units with exchange rates
//! - Enhanced temperature conversion handling (absolute vs relative)

use std::collections::HashMap;
use std::fmt;

/// The seven fundamental SI base dimensions.
///
/// These dimensions form the foundation of the International System of Units (SI).
/// All other physical quantities can be expressed as combinations of these base dimensions.
///
/// # SI Base Dimensions
///
/// | Dimension | SI Base Unit | Symbol |
/// |-----------|--------------|--------|
/// | Length | meter | m |
/// | Mass | kilogram | kg |
/// | Time | second | s |
/// | Current | ampere | A |
/// | Temperature | kelvin | K |
/// | Amount | mole | mol |
/// | Luminosity | candela | cd |
///
/// # Examples
///
/// ```
/// use thales::dimensions::BaseDimension;
///
/// // Each base dimension represents a fundamental physical property
/// let length = BaseDimension::Length;
/// let mass = BaseDimension::Mass;
/// let time = BaseDimension::Time;
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BaseDimension {
    /// Length dimension - fundamental measure of spatial extent.
    ///
    /// SI base unit: meter (m)
    Length,

    /// Mass dimension - fundamental measure of matter quantity.
    ///
    /// SI base unit: kilogram (kg)
    Mass,

    /// Time dimension - fundamental measure of temporal duration.
    ///
    /// SI base unit: second (s)
    Time,

    /// Electric current dimension - fundamental measure of charge flow.
    ///
    /// SI base unit: ampere (A)
    Current,

    /// Thermodynamic temperature dimension - fundamental measure of thermal energy.
    ///
    /// SI base unit: kelvin (K)
    Temperature,

    /// Amount of substance dimension - fundamental measure of particle count.
    ///
    /// SI base unit: mole (mol)
    Amount,

    /// Luminous intensity dimension - fundamental measure of perceived light power.
    ///
    /// SI base unit: candela (cd)
    Luminosity,
}

/// Composite dimension expressed as a product of base dimensions with integer exponents.
///
/// A `Dimension` represents the dimensional formula of a physical quantity using the
/// exponent-based representation: L^a × M^b × T^c × ... where L=Length, M=Mass, T=Time, etc.
///
/// # Mathematical Representation
///
/// Each dimension is stored as a mapping from base dimensions to their exponents:
/// - Velocity: Length¹ × Time⁻¹ → {Length: 1, Time: -1}
/// - Force: Mass¹ × Length¹ × Time⁻² → {Mass: 1, Length: 1, Time: -2}
/// - Energy: Mass¹ × Length² × Time⁻² → {Mass: 1, Length: 2, Time: -2}
///
/// # Examples
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension};
///
/// // Create velocity dimension: Length / Time = Length¹ × Time⁻¹
/// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
/// let time_dim = Dimension::from_base(BaseDimension::Time, -1);
/// let velocity_dim = length_dim.multiply(&time_dim);
///
/// // Create dimensionless quantity (pure number)
/// let dimensionless = Dimension::dimensionless();
/// assert!(dimensionless.is_dimensionless());
/// ```
///
/// ## Derived Dimensions
///
/// Common derived dimensions:
/// - **Velocity**: L¹T⁻¹ (meters per second)
/// - **Acceleration**: L¹T⁻² (meters per second squared)
/// - **Force**: M¹L¹T⁻² (newtons = kg⋅m/s²)
/// - **Energy**: M¹L²T⁻² (joules = kg⋅m²/s²)
/// - **Power**: M¹L²T⁻³ (watts = kg⋅m²/s³)
/// - **Pressure**: M¹L⁻¹T⁻² (pascals = kg/(m⋅s²))
/// - **Frequency**: T⁻¹ (hertz = 1/s)
#[derive(Debug, Clone, PartialEq)]
pub struct Dimension {
    exponents: HashMap<BaseDimension, i32>,
}

impl Dimension {
    /// Create a dimensionless quantity.
    ///
    /// Dimensionless quantities are pure numbers with no associated physical dimension.
    /// Examples include ratios, angles (in radians), and mathematical constants.
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::Dimension;
    ///
    /// let dimensionless = Dimension::dimensionless();
    /// assert!(dimensionless.is_dimensionless());
    /// ```
    pub fn dimensionless() -> Self {
        Self {
            exponents: HashMap::new(),
        }
    }

    /// Create a dimension from a single base dimension with an exponent.
    ///
    /// # Arguments
    ///
    /// * `base` - The base dimension (Length, Mass, Time, etc.)
    /// * `exponent` - The power to which the base dimension is raised
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// // Create area dimension: Length²
    /// let area = Dimension::from_base(BaseDimension::Length, 2);
    ///
    /// // Create frequency dimension: Time⁻¹
    /// let frequency = Dimension::from_base(BaseDimension::Time, -1);
    ///
    /// // Zero exponent creates dimensionless
    /// let none = Dimension::from_base(BaseDimension::Mass, 0);
    /// assert!(none.is_dimensionless());
    /// ```
    pub fn from_base(base: BaseDimension, exponent: i32) -> Self {
        let mut exponents = HashMap::new();
        if exponent != 0 {
            exponents.insert(base, exponent);
        }
        Self { exponents }
    }

    /// Check if this dimension is dimensionless.
    ///
    /// Returns `true` if the dimension has no base dimension components
    /// (i.e., it represents a pure number).
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// let dimensionless = Dimension::dimensionless();
    /// assert!(dimensionless.is_dimensionless());
    ///
    /// let length = Dimension::from_base(BaseDimension::Length, 1);
    /// assert!(!length.is_dimensionless());
    /// ```
    pub fn is_dimensionless(&self) -> bool {
        self.exponents.is_empty()
    }

    /// Multiply two dimensions by adding their exponents.
    ///
    /// Dimension multiplication corresponds to physical quantity multiplication:
    /// - Distance × Distance = Area (L¹ × L¹ = L²)
    /// - Force × Distance = Energy (ML¹T⁻² × L¹ = ML²T⁻²)
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// // Velocity × Time = Distance
    /// let velocity = Dimension::from_base(BaseDimension::Length, 1)
    ///     .multiply(&Dimension::from_base(BaseDimension::Time, -1));
    /// let time = Dimension::from_base(BaseDimension::Time, 1);
    /// let distance = velocity.multiply(&time);
    /// // Result: Length¹ × Time⁻¹ × Time¹ = Length¹
    /// ```
    ///
    pub fn multiply(&self, other: &Dimension) -> Dimension {
        let mut exponents = self.exponents.clone();
        for (&base, &exp) in &other.exponents {
            let entry = exponents.entry(base).or_insert(0);
            *entry += exp;
            if *entry == 0 {
                exponents.remove(&base);
            }
        }
        Self { exponents }
    }

    /// Divide two dimensions by subtracting their exponents.
    ///
    /// Dimension division corresponds to physical quantity division:
    /// - Distance / Time = Velocity (L¹ / T¹ = L¹T⁻¹)
    /// - Force / Mass = Acceleration (ML¹T⁻² / M¹ = L¹T⁻²)
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// // Distance / Time = Velocity
    /// let distance = Dimension::from_base(BaseDimension::Length, 1);
    /// let time = Dimension::from_base(BaseDimension::Time, 1);
    /// let velocity = distance.divide(&time);
    /// // Result: Length¹T⁻¹
    /// ```
    ///
    pub fn divide(&self, other: &Dimension) -> Dimension {
        let mut exponents = self.exponents.clone();
        for (&base, &exp) in &other.exponents {
            let entry = exponents.entry(base).or_insert(0);
            *entry -= exp;
            if *entry == 0 {
                exponents.remove(&base);
            }
        }
        Self { exponents }
    }

    /// Raise a dimension to a power by multiplying all exponents.
    ///
    /// Dimension exponentiation corresponds to physical quantity exponentiation:
    /// - (Length)² = Area (L¹ → L²)
    /// - (Velocity)² = (L¹T⁻¹)² = L²T⁻²
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// // Square a velocity to get (m/s)²
    /// let velocity = Dimension::from_base(BaseDimension::Length, 1)
    ///     .multiply(&Dimension::from_base(BaseDimension::Time, -1));
    /// let velocity_squared = velocity.power(2);
    /// // Result: Length²T⁻²
    /// ```
    ///
    pub fn power(&self, exponent: i32) -> Dimension {
        if exponent == 0 {
            return Self::dimensionless();
        }
        let exponents = self
            .exponents
            .iter()
            .map(|(&base, &exp)| (base, exp * exponent))
            .collect();
        Self { exponents }
    }

    /// Check if two dimensions are compatible (can be converted between).
    ///
    /// Two dimensions are compatible if they have identical exponents for all
    /// base dimensions. Only compatible dimensions can be added, subtracted,
    /// or converted between.
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension};
    ///
    /// let length1 = Dimension::from_base(BaseDimension::Length, 1);
    /// let length2 = Dimension::from_base(BaseDimension::Length, 1);
    /// let area = Dimension::from_base(BaseDimension::Length, 2);
    ///
    /// assert!(length1.is_compatible(&length2)); // meters ↔ feet
    /// assert!(!length1.is_compatible(&area));   // meters ↮ square meters
    /// ```
    pub fn is_compatible(&self, other: &Dimension) -> bool {
        self == other
    }
}

/// Return the SI symbol string for a base dimension.
fn base_dimension_symbol(base: BaseDimension) -> &'static str {
    match base {
        BaseDimension::Length => "m",
        BaseDimension::Mass => "kg",
        BaseDimension::Time => "s",
        BaseDimension::Current => "A",
        BaseDimension::Temperature => "K",
        BaseDimension::Amount => "mol",
        BaseDimension::Luminosity => "cd",
    }
}

/// Format an integer exponent as Unicode superscript characters.
///
/// Returns an empty string for exponent 1 (conventional omission).
fn format_superscript(exp: i32) -> String {
    if exp == 1 {
        return String::new();
    }
    let digits: &[char] = &['', '¹', '²', '³', '', '', '', '', '', ''];
    let minus = '';
    let (sign, abs_exp) = if exp < 0 {
        (true, (-exp) as u32)
    } else {
        (false, exp as u32)
    };
    let mut result = String::new();
    if sign {
        result.push(minus);
    }
    for ch in abs_exp.to_string().chars() {
        let digit = ch.to_digit(10).expect("digit") as usize;
        result.push(digits[digit]);
    }
    result
}

/// Canonical ordering for display: Length, Mass, Time, Current, Temperature, Amount, Luminosity.
fn base_dimension_order(base: &BaseDimension) -> u8 {
    match base {
        BaseDimension::Length => 0,
        BaseDimension::Mass => 1,
        BaseDimension::Time => 2,
        BaseDimension::Current => 3,
        BaseDimension::Temperature => 4,
        BaseDimension::Amount => 5,
        BaseDimension::Luminosity => 6,
    }
}

impl fmt::Display for Dimension {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.exponents.is_empty() {
            return write!(f, "1");
        }
        let mut pairs: Vec<(BaseDimension, i32)> =
            self.exponents.iter().map(|(&b, &e)| (b, e)).collect();
        pairs.sort_by_key(|(b, _)| base_dimension_order(b));
        let mut parts = pairs.iter().map(|(base, exp)| {
            format!(
                "{}{}",
                base_dimension_symbol(*base),
                format_superscript(*exp)
            )
        });
        write!(f, "{}", parts.next().unwrap_or_default())?;
        for part in parts {
            write!(f, "·{}", part)?;
        }
        Ok(())
    }
}

/// Unit of measurement with dimension and conversion factor.
///
/// A `Unit` represents a specific measurement standard for a physical quantity.
/// It includes the unit's name, symbol, dimension, and conversion factors to the
/// SI base unit system.
///
/// # Conversion Formula
///
/// Conversion to SI base units uses the formula:
/// ```text
/// SI_value = value * to_si_factor + offset
/// ```
///
/// For most units, `offset = 0` (linear/multiplicative conversion).
/// For affine units like temperature, `offset ≠ 0` (affine/additive conversion).
///
/// # Examples
///
/// ## Linear Units (Length)
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension, Unit};
///
/// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
///
/// // Meter (SI base unit)
/// let meter = Unit::new("meter", "m", length_dim.clone(), 1.0);
///
/// // Kilometer (1 km = 1000 m)
/// let kilometer = Unit::new("kilometer", "km", length_dim.clone(), 1000.0);
///
/// // Inch (1 in = 0.0254 m)
/// let inch = Unit::new("inch", "in", length_dim.clone(), 0.0254);
/// ```
///
/// ## Affine Units (Temperature)
///
/// Temperature units require an offset for absolute temperature scales:
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension, Unit};
///
/// let temp_dim = Dimension::from_base(BaseDimension::Temperature, 1);
///
/// // Kelvin (SI base unit)
/// let kelvin = Unit::new("kelvin", "K", temp_dim.clone(), 1.0);
///
/// // Celsius: K = °C + 273.15
/// let celsius = Unit::with_offset("celsius", "°C", temp_dim.clone(), 1.0, 273.15);
///
/// // Fahrenheit: K = (°F + 459.67) * 5/9
/// let fahrenheit = Unit::with_offset(
///     "fahrenheit", "°F", temp_dim.clone(), 5.0/9.0, 459.67 * 5.0/9.0
/// );
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Unit {
    /// Unit name (e.g., "meter", "kilogram").
    ///
    /// Full descriptive name of the unit in singular form.
    pub name: String,

    /// Unit symbol (e.g., "m", "kg").
    ///
    /// Standard abbreviated symbol for the unit, following international conventions.
    pub symbol: String,

    /// Physical dimension of this unit.
    ///
    /// Defines what physical quantity this unit measures (length, mass, etc.)
    pub dimension: Dimension,

    /// Conversion factor to SI base unit.
    ///
    /// Multiplier used in conversion: `SI_value = value * to_si_factor + offset`
    pub to_si_factor: f64,

    /// Offset for affine units (e.g., Celsius, Fahrenheit).
    ///
    /// Additive offset used in conversion: `SI_value = value * to_si_factor + offset`
    /// - For linear units (meters, kilograms): `offset = 0`
    /// - For affine units (Celsius, Fahrenheit): `offset ≠ 0`
    pub offset: f64,
}

impl Unit {
    /// Create a new linear unit (without offset).
    ///
    /// Use this for units with purely multiplicative conversion to SI base units.
    /// Most units are linear: length, mass, velocity, force, energy, etc.
    ///
    /// # Arguments
    ///
    /// * `name` - Full name of the unit (e.g., "meter", "kilogram")
    /// * `symbol` - Standard symbol (e.g., "m", "kg")
    /// * `dimension` - Physical dimension of the unit
    /// * `to_si_factor` - Multiplier to convert to SI base unit
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit};
    ///
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    ///
    /// // SI base unit
    /// let meter = Unit::new("meter", "m", length_dim.clone(), 1.0);
    ///
    /// // 1 mile = 1609.344 meters
    /// let mile = Unit::new("mile", "mi", length_dim.clone(), 1609.344);
    ///
    /// let meters = mile.to_si(5.0);
    /// assert_eq!(meters, 8046.72);
    /// ```
    pub fn new(
        name: impl Into<String>,
        symbol: impl Into<String>,
        dimension: Dimension,
        to_si_factor: f64,
    ) -> Self {
        Self {
            name: name.into(),
            symbol: symbol.into(),
            dimension,
            to_si_factor,
            offset: 0.0,
        }
    }

    /// Create an affine unit with offset.
    ///
    /// Use this for units with both multiplicative and additive conversion to SI base units.
    /// This is primarily needed for temperature scales (Celsius, Fahrenheit).
    ///
    /// # Arguments
    ///
    /// * `name` - Full name of the unit
    /// * `symbol` - Standard symbol
    /// * `dimension` - Physical dimension
    /// * `to_si_factor` - Multiplier in conversion formula
    /// * `offset` - Additive offset in conversion formula
    ///
    /// # Conversion Formula
    ///
    /// `SI_value = value * to_si_factor + offset`
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit};
    ///
    /// let temp_dim = Dimension::from_base(BaseDimension::Temperature, 1);
    ///
    /// // Celsius: K = °C + 273.15
    /// let celsius = Unit::with_offset("celsius", "°C", temp_dim.clone(), 1.0, 273.15);
    ///
    /// let kelvin_value = celsius.to_si(0.0);
    /// assert_eq!(kelvin_value, 273.15); // 0°C = 273.15 K
    ///
    /// let celsius_value = celsius.from_si(373.15);
    /// assert_eq!(celsius_value, 100.0); // 373.15 K = 100°C
    /// ```
    pub fn with_offset(
        name: impl Into<String>,
        symbol: impl Into<String>,
        dimension: Dimension,
        to_si_factor: f64,
        offset: f64,
    ) -> Self {
        Self {
            name: name.into(),
            symbol: symbol.into(),
            dimension,
            to_si_factor,
            offset,
        }
    }

    /// Convert a value from this unit to SI base unit.
    ///
    /// Applies the conversion formula: `SI_value = value * to_si_factor + offset`
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit};
    ///
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// let kilometer = Unit::new("kilometer", "km", length_dim, 1000.0);
    ///
    /// let meters = kilometer.to_si(5.0);
    /// assert_eq!(meters, 5000.0);
    /// ```
    pub fn to_si(&self, value: f64) -> f64 {
        value * self.to_si_factor + self.offset
    }

    /// Convert a value from SI base unit to this unit.
    ///
    /// Applies the inverse conversion formula: `value = (SI_value - offset) / to_si_factor`
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit};
    ///
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// let foot = Unit::new("foot", "ft", length_dim, 0.3048);
    ///
    /// let feet = foot.from_si(100.0);
    /// assert!((feet - 328.084).abs() < 0.001);
    /// ```
    pub fn from_si(&self, value: f64) -> f64 {
        (value - self.offset) / self.to_si_factor
    }

    /// Convert a value from this unit to another unit.
    ///
    /// Performs two-step conversion: source → SI base → target unit.
    /// Returns an error if the dimensions are incompatible.
    ///
    /// # Arguments
    ///
    /// * `value` - Value in the source unit
    /// * `target` - Target unit to convert to
    ///
    /// # Returns
    ///
    /// * `Ok(f64)` - Converted value if dimensions are compatible
    /// * `Err(String)` - Error message if dimensions are incompatible
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit};
    ///
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// let mile = Unit::new("mile", "mi", length_dim.clone(), 1609.344);
    /// let kilometer = Unit::new("kilometer", "km", length_dim.clone(), 1000.0);
    ///
    /// let km = mile.convert_to(10.0, &kilometer).unwrap();
    /// assert!((km - 16.09344).abs() < 0.0001);
    ///
    /// // Incompatible dimensions produce error
    /// let time_dim = Dimension::from_base(BaseDimension::Time, 1);
    /// let second = Unit::new("second", "s", time_dim, 1.0);
    /// assert!(mile.convert_to(10.0, &second).is_err());
    /// ```
    pub fn convert_to(&self, value: f64, target: &Unit) -> Result<f64, String> {
        if !self.dimension.is_compatible(&target.dimension) {
            return Err(format!(
                "Incompatible dimensions: {} vs {}",
                self.dimension, target.dimension
            ));
        }
        let si_value = self.to_si(value);
        Ok(target.from_si(si_value))
    }
}

/// Registry of standard units for lookup and conversion.
///
/// `UnitRegistry` provides a centralized collection of units that can be accessed by
/// their symbols. It simplifies unit conversions by managing unit instances and providing
/// string-based conversion methods.
///
/// # Examples
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension, Unit, UnitRegistry};
///
/// let mut registry = UnitRegistry::new();
///
/// // Add length units
/// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
/// registry.add_unit(Unit::new("meter", "m", length_dim.clone(), 1.0));
/// registry.add_unit(Unit::new("kilometer", "km", length_dim.clone(), 1000.0));
/// registry.add_unit(Unit::new("mile", "mi", length_dim.clone(), 1609.344));
///
/// // Convert using symbols
/// let km = registry.convert(10.0, "mi", "km").unwrap();
/// assert!((km - 16.09344).abs() < 0.0001);
/// ```
#[derive(Debug, Clone)]
pub struct UnitRegistry {
    units: HashMap<String, Unit>,
}

impl UnitRegistry {
    /// Create a new empty registry.
    ///
    /// Use this when you want to build a custom registry with only specific units.
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::UnitRegistry;
    ///
    /// let registry = UnitRegistry::new();
    /// // Registry is empty, ready for custom units
    /// ```
    pub fn new() -> Self {
        Self {
            units: HashMap::new(),
        }
    }

    /// Create a registry pre-populated with SI base units.
    ///
    /// # SI Base Units
    ///
    /// The following units will be added (when implemented):
    /// - meter (m) - length
    /// - kilogram (kg) - mass
    /// - second (s) - time
    /// - ampere (A) - electric current
    /// - kelvin (K) - temperature
    /// - mole (mol) - amount of substance
    /// - candela (cd) - luminous intensity
    ///
    /// # TODO
    ///
    /// Currently returns an empty registry. Implementation pending.
    pub fn with_si_base() -> Self {
        let registry = Self::new();
        // TODO: Add SI base units
        // meter, kilogram, second, ampere, kelvin, mole, candela
        registry
    }

    /// Create a registry with common derived units.
    ///
    /// Includes SI base units plus common derived units such as:
    /// - newton (N) - force
    /// - joule (J) - energy
    /// - watt (W) - power
    /// - pascal (Pa) - pressure
    /// - volt (V) - electric potential
    /// - ohm (Ω) - electric resistance
    /// - hertz (Hz) - frequency
    ///
    /// # TODO
    ///
    /// Currently returns a registry with only base units. Derived units pending.
    pub fn with_common_units() -> Self {
        let registry = Self::with_si_base();
        // TODO: Add common derived units
        // newton, joule, watt, pascal, etc.
        registry
    }

    /// Add a unit to the registry.
    ///
    /// The unit is indexed by its symbol. If a unit with the same symbol already
    /// exists, it will be replaced.
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, UnitRegistry};
    ///
    /// let mut registry = UnitRegistry::new();
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// let meter = Unit::new("meter", "m", length_dim, 1.0);
    ///
    /// registry.add_unit(meter);
    /// assert!(registry.get("m").is_some());
    /// ```
    pub fn add_unit(&mut self, unit: Unit) {
        self.units.insert(unit.symbol.clone(), unit);
    }

    /// Get a unit by its symbol.
    ///
    /// # Arguments
    ///
    /// * `symbol` - The unit symbol to look up (e.g., "m", "kg", "s")
    ///
    /// # Returns
    ///
    /// * `Some(&Unit)` - Reference to the unit if found
    /// * `None` - If no unit with that symbol exists
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, UnitRegistry};
    ///
    /// let mut registry = UnitRegistry::new();
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// registry.add_unit(Unit::new("meter", "m", length_dim, 1.0));
    ///
    /// let meter = registry.get("m");
    /// assert!(meter.is_some());
    /// assert_eq!(meter.unwrap().name, "meter");
    ///
    /// let unknown = registry.get("xyz");
    /// assert!(unknown.is_none());
    /// ```
    pub fn get(&self, symbol: &str) -> Option<&Unit> {
        self.units.get(symbol)
    }

    /// Convert a value between two units using their symbols.
    ///
    /// This is a convenience method that looks up both units and performs the conversion.
    ///
    /// # Arguments
    ///
    /// * `value` - Value to convert
    /// * `from` - Symbol of the source unit
    /// * `to` - Symbol of the target unit
    ///
    /// # Returns
    ///
    /// * `Ok(f64)` - Converted value if both units exist and are compatible
    /// * `Err(String)` - Error if units don't exist or are incompatible
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, UnitRegistry};
    ///
    /// let mut registry = UnitRegistry::new();
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// registry.add_unit(Unit::new("meter", "m", length_dim.clone(), 1.0));
    /// registry.add_unit(Unit::new("kilometer", "km", length_dim.clone(), 1000.0));
    ///
    /// let meters = registry.convert(5.0, "km", "m").unwrap();
    /// assert_eq!(meters, 5000.0);
    ///
    /// // Error cases
    /// assert!(registry.convert(5.0, "unknown", "m").is_err());
    /// ```
    pub fn convert(&self, value: f64, from: &str, to: &str) -> Result<f64, String> {
        let from_unit = self
            .get(from)
            .ok_or_else(|| format!("Unknown unit: {}", from))?;
        let to_unit = self
            .get(to)
            .ok_or_else(|| format!("Unknown unit: {}", to))?;
        from_unit.convert_to(value, to_unit)
    }
}

impl Default for UnitRegistry {
    fn default() -> Self {
        Self::with_common_units()
    }
}

/// Physical quantity combining a numeric value with its unit of measurement.
///
/// A `Quantity` represents a measured or calculated physical value with explicit units,
/// enabling type-safe dimensional analysis and unit conversions.
///
/// # Examples
///
/// ## Creating Quantities
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
///
/// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
/// let meter = Unit::new("meter", "m", length_dim, 1.0);
///
/// let distance = Quantity::new(100.0, meter);
/// println!("{}", distance); // "100 m"
/// ```
///
/// ## Converting Quantities
///
/// ```
/// use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
///
/// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
/// let meter = Unit::new("meter", "m", length_dim.clone(), 1.0);
/// let kilometer = Unit::new("kilometer", "km", length_dim.clone(), 1000.0);
///
/// let distance_m = Quantity::new(5000.0, meter);
/// let distance_km = distance_m.convert_to(&kilometer).unwrap();
///
/// assert_eq!(distance_km.value, 5.0);
/// assert_eq!(distance_km.unit.symbol, "km");
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Quantity {
    /// The numeric value of the quantity.
    pub value: f64,

    /// The unit of measurement for this quantity.
    pub unit: Unit,
}

impl Quantity {
    /// Create a new quantity from a value and unit.
    ///
    /// # Arguments
    ///
    /// * `value` - The numeric magnitude
    /// * `unit` - The unit of measurement
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
    ///
    /// let mass_dim = Dimension::from_base(BaseDimension::Mass, 1);
    /// let kilogram = Unit::new("kilogram", "kg", mass_dim, 1.0);
    ///
    /// let mass = Quantity::new(75.5, kilogram);
    /// assert_eq!(mass.value, 75.5);
    /// ```
    pub fn new(value: f64, unit: Unit) -> Self {
        Self { value, unit }
    }

    /// Convert this quantity to another unit.
    ///
    /// Creates a new `Quantity` with the value converted to the target unit.
    /// Returns an error if the units have incompatible dimensions.
    ///
    /// # Arguments
    ///
    /// * `target_unit` - The unit to convert to
    ///
    /// # Returns
    ///
    /// * `Ok(Quantity)` - New quantity in target units if compatible
    /// * `Err(String)` - Error message if dimensions are incompatible
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
    ///
    /// let time_dim = Dimension::from_base(BaseDimension::Time, 1);
    /// let second = Unit::new("second", "s", time_dim.clone(), 1.0);
    /// let minute = Unit::new("minute", "min", time_dim.clone(), 60.0);
    ///
    /// let duration_s = Quantity::new(300.0, second);
    /// let duration_min = duration_s.convert_to(&minute).unwrap();
    ///
    /// assert_eq!(duration_min.value, 5.0);
    /// assert_eq!(duration_min.unit.symbol, "min");
    /// ```
    pub fn convert_to(&self, target_unit: &Unit) -> Result<Quantity, String> {
        let converted_value = self.unit.convert_to(self.value, target_unit)?;
        Ok(Quantity::new(converted_value, target_unit.clone()))
    }

    /// Get the value in SI base units.
    ///
    /// Converts this quantity to its equivalent value in the SI base unit system.
    /// This is useful for calculations that need to be performed in a consistent
    /// unit system.
    ///
    /// # Examples
    ///
    /// ```
    /// use thales::dimensions::{BaseDimension, Dimension, Unit, Quantity};
    ///
    /// let length_dim = Dimension::from_base(BaseDimension::Length, 1);
    /// let kilometer = Unit::new("kilometer", "km", length_dim, 1000.0);
    ///
    /// let distance = Quantity::new(5.0, kilometer);
    /// let si_value = distance.to_si();
    ///
    /// assert_eq!(si_value, 5000.0); // 5 km = 5000 m
    /// ```
    pub fn to_si(&self) -> f64 {
        self.unit.to_si(self.value)
    }
}

impl fmt::Display for Quantity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.value, self.unit.symbol)
    }
}

// TODO: Add support for compound units (m/s, kg*m/s^2)
// TODO: Add unit parsing from strings ("5.2 m/s")
// TODO: Add unit system conversions (SI, Imperial, CGS)
// TODO: Add unit prefix support (kilo, mega, milli, micro)
// TODO: Add dimensional analysis validation for equations
// TODO: Add automatic unit inference
// TODO: Add support for currency units with exchange rates
// TODO: Add temperature conversion with proper handling of absolute vs relative

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

    fn length() -> Dimension {
        Dimension::from_base(BaseDimension::Length, 1)
    }

    fn time() -> Dimension {
        Dimension::from_base(BaseDimension::Time, 1)
    }

    fn mass() -> Dimension {
        Dimension::from_base(BaseDimension::Mass, 1)
    }

    #[test]
    fn multiply_adds_exponents() {
        // Length × Length = Length²
        let area = length().multiply(&length());
        assert_eq!(area.exponents[&BaseDimension::Length], 2);
        assert_eq!(area.exponents.len(), 1);
    }

    #[test]
    fn multiply_velocity_is_length_per_time() {
        // velocity = Length / Time = Length × Time⁻¹
        let inv_time = Dimension::from_base(BaseDimension::Time, -1);
        let velocity = length().multiply(&inv_time);
        assert_eq!(velocity.exponents[&BaseDimension::Length], 1);
        assert_eq!(velocity.exponents[&BaseDimension::Time], -1);
    }

    #[test]
    fn divide_velocity() {
        // velocity = length / time
        let velocity = length().divide(&time());
        assert_eq!(velocity.exponents[&BaseDimension::Length], 1);
        assert_eq!(velocity.exponents[&BaseDimension::Time], -1);
    }

    #[test]
    fn divide_acceleration() {
        // acceleration = velocity / time = length / time²
        let velocity = length().divide(&time());
        let acceleration = velocity.divide(&time());
        assert_eq!(acceleration.exponents[&BaseDimension::Length], 1);
        assert_eq!(acceleration.exponents[&BaseDimension::Time], -2);
    }

    #[test]
    fn divide_dimensionless_cancellation() {
        // length / length = dimensionless
        let result = length().divide(&length());
        assert!(result.is_dimensionless());
    }

    #[test]
    fn power_velocity_squared() {
        // velocity² = Length²·Time⁻²
        let velocity = length().divide(&time());
        let v2 = velocity.power(2);
        assert_eq!(v2.exponents[&BaseDimension::Length], 2);
        assert_eq!(v2.exponents[&BaseDimension::Time], -2);
    }

    #[test]
    fn power_zero_is_dimensionless() {
        assert!(length().power(0).is_dimensionless());
    }

    #[test]
    fn energy_is_mass_times_velocity_squared() {
        // E = m·v² = Mass × Length²·Time⁻²
        let velocity = length().divide(&time());
        let energy = mass().multiply(&velocity.power(2));
        assert_eq!(energy.exponents[&BaseDimension::Mass], 1);
        assert_eq!(energy.exponents[&BaseDimension::Length], 2);
        assert_eq!(energy.exponents[&BaseDimension::Time], -2);
    }

    #[test]
    fn display_dimensionless() {
        assert_eq!(Dimension::dimensionless().to_string(), "1");
    }

    #[test]
    fn display_length() {
        assert_eq!(length().to_string(), "m");
    }

    #[test]
    fn display_velocity() {
        let velocity = length().divide(&time());
        assert_eq!(velocity.to_string(), "m·s⁻¹");
    }

    #[test]
    fn display_acceleration() {
        let accel = length().divide(&time().multiply(&time()));
        assert_eq!(accel.to_string(), "m·s⁻²");
    }

    #[test]
    fn display_energy() {
        let velocity = length().divide(&time());
        let energy = mass().multiply(&velocity.power(2));
        assert_eq!(energy.to_string(), "m²·kg·s⁻²");
    }
}