Skip to main content

dualis_units/
lib.rs

1//! Dimensional analysis: physical quantities that refuse to be added wrongly.
2//!
3//! ```
4//! use dualis_units::{Area, Energy, Length, Mass, Power, SpecificHeat, Temperature, Time};
5//!
6//! // A unit-bearing constructor is the only place a factor of a thousand may appear.
7//! let side = Length::mm(10.0);
8//! let area: Area = side * side;                       // the dimension follows the product
9//! assert!((area.to_si() - 1e-4).abs() < 1e-18);
10//!
11//! // Absorbed power over a time is an energy, and the type says so without being told.
12//! let absorbed = Power::mw(96.0);
13//! let heat: Energy = absorbed * Time::s(1.0);
14//!
15//! // Divide it by a heat capacity and a temperature comes out.
16//! let capacity = Mass::g(2.0) * SpecificHeat::j_per_kg_k(858.0);
17//! let rise: Temperature = heat / capacity;
18//! assert!((rise.to_si() - 0.05594).abs() < 1e-4);
19//! ```
20//!
21//! And the mistake the whole crate exists to prevent does not compile:
22//!
23//! ```compile_fail
24//! use dualis_units::{Length, Time};
25//! let nonsense = Length::mm(3.0) + Time::s(1.0);
26//! ```
27//!
28//! One domain can get away with a convention. `dualis-core` began as optics and
29//! said "millimetres, nanometres and seconds, everywhere" in a doc comment, and
30//! that held because every number in the crate was a length, a wavelength or a
31//! fraction. It stops holding the moment a second domain arrives: a kelvin, a
32//! newton and a watt are all `f64`, they all add, and the compiler and the tests
33//! both stay green while the physics goes wrong.
34//!
35//! So dimension lives in the type. [`Qty`] carries the seven SI base exponents as
36//! const generic parameters, which makes `Length + Time` a compile error and
37//! `Force * Length` an [`Energy`] — and costs nothing at runtime, since a `Qty`
38//! is an `f64` and every operation on it is the `f64` operation.
39//!
40//! # Storage is always SI base units
41//!
42//! A `Qty` holds metres, kilograms, seconds, amperes, kelvin, moles, candela —
43//! never millimetres, never nanometres. Those are *entry and exit* forms:
44//!
45//! ```
46//! use dualis_units::{Length, Time, Velocity};
47//!
48//! let d = Length::mm(120.0);
49//! let t = Time::ms(4.0);
50//! let v: Velocity = d / t;
51//! assert!((v.to_si() - 30.0).abs() < 1e-12);   // 30 m/s
52//! assert!((d.in_nm() - 1.2e8).abs() < 1.0);
53//! ```
54//!
55//! That way there is exactly one representation to reason about, and the
56//! unit-bearing constructors are the only place a factor of 1000 can hide.
57//!
58//! # What this cannot do
59//!
60//! **Angles are dimensionless**, so [`Frequency`] and an angular velocity are the
61//! same type — SI says radians are m/m, and no dimensional system can separate
62//! them. Same for torque and energy. Where that distinction matters, it has to be
63//! carried by a newtype in the domain crate, not here.
64//!
65//! **Only declared products compose.** `Length * Length` is an [`Area`] because
66//! that pair is written down below. Deriving arbitrary products would need
67//! arithmetic on const generic parameters, which is unstable, so the alternative
68//! to a declared list is a dependency on `uom`. The list is cheap to extend, and
69//! anything undeclared can always go through [`Qty::from_si`].
70
71// Every public item carries a doc comment. Denied rather than warned: a public physics API
72// whose `Length::mm` shows a blank summary in rustdoc is documented in the sense that a
73// paragraph exists somewhere, and not in the sense a reader needs.
74#![deny(missing_docs)]
75#![forbid(unsafe_code)]
76
77use core::fmt;
78use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
79
80use serde::{Deserialize, Deserializer, Serialize, Serializer};
81
82pub mod vector;
83pub use vector::{AccelerationVec, ForceVec, LengthVec, MomentumVec, QVec3, VelocityVec};
84
85/// A quantity, with the seven SI base dimensions in its type.
86///
87/// The parameters are the exponents of metre, kilogram, second, ampere, kelvin,
88/// mole and candela, in that order, so a velocity (m·s⁻¹) is `Qty<1,0,-1,0,0,0,0>`
89/// — which is what [`Velocity`] names.
90///
91/// Addition, subtraction, negation, comparison and scaling by a plain `f64` work
92/// for every dimension. Multiplication and division between two quantities work
93/// for the pairs declared in this module.
94#[derive(Clone, Copy, PartialEq, PartialOrd, Default)]
95pub struct Qty<
96    const L: i8,
97    const M: i8,
98    const T: i8,
99    const I: i8,
100    const K: i8,
101    const N: i8,
102    const J: i8,
103>(f64);
104
105impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
106    Qty<L, M, T, I, K, N, J>
107{
108    /// Zero, which is the one value every dimension shares.
109    pub const ZERO: Self = Qty(0.0);
110
111    /// Wrap a number already in SI base units. The escape hatch: use it when a
112    /// dimension has no name here, and name it if you use it twice.
113    ///
114    /// `const`, so a dimensioned constant can be written without a lazy static.
115    pub const fn from_si(value: f64) -> Self {
116        Qty(value)
117    }
118
119    /// The value in SI base units.
120    pub const fn to_si(self) -> f64 {
121        self.0
122    }
123
124    /// The seven exponents, for diagnostics and for a runtime dimension check at
125    /// a boundary the type system does not cross (deserialisation, FFI).
126    pub const fn dimension() -> [i8; 7] {
127        [L, M, T, I, K, N, J]
128    }
129
130    /// Magnitude without its sign, in the same dimension.
131    pub fn abs(self) -> Self {
132        Qty(self.0.abs())
133    }
134
135    /// The smaller of two quantities of the same dimension.
136    pub fn min(self, other: Self) -> Self {
137        Qty(self.0.min(other.0))
138    }
139
140    /// The larger of two quantities of the same dimension.
141    pub fn max(self, other: Self) -> Self {
142        Qty(self.0.max(other.0))
143    }
144
145    /// Whether the magnitude is neither infinite nor NaN.
146    ///
147    /// Worth checking where a limit is reported rather than computed: several methods here
148    /// return an infinity to mean "no limit", which is honest but arithmetic on it is not.
149    pub fn is_finite(self) -> bool {
150        self.0.is_finite()
151    }
152
153    /// Sign of the magnitude, as a plain number — a sign has no dimension.
154    pub fn signum(self) -> f64 {
155        self.0.signum()
156    }
157
158    /// Linear interpolation, which stays within the dimension.
159    pub fn lerp(self, other: Self, t: f64) -> Self {
160        Qty(self.0 + (other.0 - self.0) * t)
161    }
162}
163
164// ---------------------------------------------------------------------------
165// Dimension-preserving arithmetic: works for every dimension at once, because
166// none of it changes the exponents.
167// ---------------------------------------------------------------------------
168
169macro_rules! generic_op {
170    ($trait:ident, $method:ident, $op:tt) => {
171        impl<
172                const L: i8,
173                const M: i8,
174                const T: i8,
175                const I: i8,
176                const K: i8,
177                const N: i8,
178                const J: i8,
179            > $trait for Qty<L, M, T, I, K, N, J>
180        {
181            type Output = Self;
182            fn $method(self, rhs: Self) -> Self {
183                Qty(self.0 $op rhs.0)
184            }
185        }
186    };
187}
188
189generic_op!(Add, add, +);
190generic_op!(Sub, sub, -);
191
192impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
193    AddAssign for Qty<L, M, T, I, K, N, J>
194{
195    fn add_assign(&mut self, rhs: Self) {
196        self.0 += rhs.0;
197    }
198}
199
200impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
201    SubAssign for Qty<L, M, T, I, K, N, J>
202{
203    fn sub_assign(&mut self, rhs: Self) {
204        self.0 -= rhs.0;
205    }
206}
207
208impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8> Neg
209    for Qty<L, M, T, I, K, N, J>
210{
211    type Output = Self;
212    fn neg(self) -> Self {
213        Qty(-self.0)
214    }
215}
216
217impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
218    Mul<f64> for Qty<L, M, T, I, K, N, J>
219{
220    type Output = Self;
221    fn mul(self, k: f64) -> Self {
222        Qty(self.0 * k)
223    }
224}
225
226impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
227    Div<f64> for Qty<L, M, T, I, K, N, J>
228{
229    type Output = Self;
230    fn div(self, k: f64) -> Self {
231        Qty(self.0 / k)
232    }
233}
234
235impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
236    Mul<Qty<L, M, T, I, K, N, J>> for f64
237{
238    type Output = Qty<L, M, T, I, K, N, J>;
239    fn mul(self, q: Qty<L, M, T, I, K, N, J>) -> Qty<L, M, T, I, K, N, J> {
240        Qty(self * q.0)
241    }
242}
243
244/// Dividing two quantities of the *same* dimension gives a plain number — which
245/// is the one product rule that needs no exponent arithmetic, and the one every
246/// tolerance check uses.
247impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8> Div
248    for Qty<L, M, T, I, K, N, J>
249{
250    type Output = f64;
251    fn div(self, rhs: Self) -> f64 {
252        self.0 / rhs.0
253    }
254}
255
256impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
257    fmt::Debug for Qty<L, M, T, I, K, N, J>
258{
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        write!(f, "{}", self.0)?;
261        for (symbol, exponent) in [
262            ("m", L),
263            ("kg", M),
264            ("s", T),
265            ("A", I),
266            ("K", K),
267            ("mol", N),
268            ("cd", J),
269        ] {
270            match exponent {
271                0 => {}
272                1 => write!(f, "·{symbol}")?,
273                e => write!(f, "·{symbol}^{e}")?,
274            }
275        }
276        Ok(())
277    }
278}
279
280impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
281    fmt::Display for Qty<L, M, T, I, K, N, J>
282{
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        fmt::Debug::fmt(self, f)
285    }
286}
287
288// Serialised as the bare SI number: a scene file stays readable, and the
289// dimension is carried by the field's type rather than repeated in the data.
290impl<const L: i8, const M: i8, const T: i8, const I: i8, const K: i8, const N: i8, const J: i8>
291    Serialize for Qty<L, M, T, I, K, N, J>
292{
293    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
294        self.0.serialize(s)
295    }
296}
297
298impl<
299        'de,
300        const L: i8,
301        const M: i8,
302        const T: i8,
303        const I: i8,
304        const K: i8,
305        const N: i8,
306        const J: i8,
307    > Deserialize<'de> for Qty<L, M, T, I, K, N, J>
308{
309    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
310        f64::deserialize(d).map(Qty)
311    }
312}
313
314// ---------------------------------------------------------------------------
315// The dimensions themselves.
316// ---------------------------------------------------------------------------
317
318/// A pure ratio: reflectance, duty cycle, refractive index, Strehl.
319pub type Dimensionless = Qty<0, 0, 0, 0, 0, 0, 0>;
320
321/// Metres.
322pub type Length = Qty<1, 0, 0, 0, 0, 0, 0>;
323/// Kilograms.
324pub type Mass = Qty<0, 1, 0, 0, 0, 0, 0>;
325/// Seconds.
326pub type Time = Qty<0, 0, 1, 0, 0, 0, 0>;
327/// Amperes.
328pub type Current = Qty<0, 0, 0, 1, 0, 0, 0>;
329/// Absolute temperature. Kelvin only — see [`Temperature::celsius`].
330pub type Temperature = Qty<0, 0, 0, 0, 1, 0, 0>;
331/// Moles.
332pub type Amount = Qty<0, 0, 0, 0, 0, 1, 0>;
333/// Candelas.
334pub type LuminousIntensity = Qty<0, 0, 0, 0, 0, 0, 1>;
335
336/// Square metres.
337pub type Area = Qty<2, 0, 0, 0, 0, 0, 0>;
338/// Cubic metres.
339pub type Volume = Qty<3, 0, 0, 0, 0, 0, 0>;
340/// Metres per second.
341pub type Velocity = Qty<1, 0, -1, 0, 0, 0, 0>;
342/// Metres per second squared.
343pub type Acceleration = Qty<1, 0, -2, 0, 0, 0, 0>;
344/// kg·m·s⁻¹ — mass times velocity, and the thing a closed system conserves
345/// exactly rather than nearly.
346pub type Momentum = Qty<1, 1, -1, 0, 0, 0, 0>;
347/// Newtons.
348pub type Force = Qty<1, 1, -2, 0, 0, 0, 0>;
349/// Pascals. Also the unit of an energy density and of a stress, which are the same
350/// dimension and not a coincidence.
351pub type Pressure = Qty<-1, 1, -2, 0, 0, 0, 0>;
352/// Joules.
353pub type Energy = Qty<2, 1, -2, 0, 0, 0, 0>;
354/// Watts.
355pub type Power = Qty<2, 1, -3, 0, 0, 0, 0>;
356/// kg·m⁻³. Note that a glass catalogue quotes g/cm³, a factor of a thousand away —
357/// see [`Density::g_per_cm3`].
358pub type Density = Qty<-3, 1, 0, 0, 0, 0, 0>;
359/// Cycles per second. Dimensionally identical to an angular velocity, since a
360/// radian is m/m — the type system cannot and should not pretend otherwise.
361pub type Frequency = Qty<0, 0, -1, 0, 0, 0, 0>;
362/// Power per unit area, W·m⁻². What a detector face actually receives.
363pub type Irradiance = Qty<0, 1, -3, 0, 0, 0, 0>;
364/// W·m⁻¹·K⁻¹ — the `k` of Fourier's law.
365pub type ThermalConductivity = Qty<1, 1, -3, 0, -1, 0, 0>;
366/// W·K⁻¹ — how fast heat crosses a joint, `UA`.
367///
368/// Dimensionally [`Power`] per [`Temperature`], and equivalently [`ThermalConductivity`] times
369/// a [`Length`], which is the physically meaningful reading: `kA/L`. It is what a *contact*
370/// resistance is measured in — a bolted joint, a winding pressed into a stator — and those have
371/// no bulk conductivity to be derived from, which is why the quantity exists in its own right.
372pub type Conductance = Qty<2, 1, -3, 0, -1, 0, 0>;
373/// J·kg⁻¹·K⁻¹ — the `c_p` that says how much heat a gram of glass can hide.
374pub type SpecificHeat = Qty<2, 0, -2, 0, -1, 0, 0>;
375/// m²·s⁻¹ — thermal diffusivity `α = k/(ρ c_p)`, and also mass diffusivity.
376pub type Diffusivity = Qty<2, 0, -1, 0, 0, 0, 0>;
377/// K⁻¹ — the coefficient that turns absorbed light into a focus shift.
378pub type ThermalExpansion = Qty<0, 0, 0, 0, -1, 0, 0>;
379/// kg·m² — how hard a body is to spin up about an axis.
380///
381/// The rotational counterpart of mass, and unlike mass it depends on the axis: a
382/// pencil is trivial to spin about its length and awkward about its middle. That
383/// direction-dependence is why it is a tensor and why a free body's rotation is
384/// interesting rather than uniform.
385pub type MomentOfInertia = Qty<2, 1, 0, 0, 0, 0, 0>;
386/// kg·m²·s⁻¹ — the rotational counterpart of momentum, and conserved for the same
387/// reason.
388pub type AngularMomentum = Qty<2, 1, -1, 0, 0, 0, 0>;
389/// N·m⁻¹ — a spring's `k`, and the penalty stiffness a contact is modelled with.
390///
391/// This is what sets a mechanical solver's stability limit: a mass on a spring
392/// oscillates with period `2π√(m/k)`, and an explicit integrator has to resolve that
393/// period whether or not anyone cares about it. Stiff contact is expensive for
394/// exactly this reason.
395pub type Stiffness = Qty<0, 1, -2, 0, 0, 0, 0>;
396/// N·s·m⁻¹ — a dashpot's `c`. Force proportional to velocity, and the only place a
397/// mechanical simulation loses energy on purpose.
398pub type Damping = Qty<0, 1, -1, 0, 0, 0, 0>;
399/// Coulombs.
400pub type Charge = Qty<0, 0, 1, 1, 0, 0, 0>;
401/// Volts.
402pub type Voltage = Qty<2, 1, -3, -1, 0, 0, 0>;
403/// Ohms — volts per ampere.
404pub type Resistance = Qty<2, 1, -3, -2, 0, 0, 0>;
405/// Ω·m — resistance times length. The property of a *material*, where [`Resistance`] is the
406/// property of a particular piece of one.
407///
408/// The distinction is the whole point of a field formulation of current: `R = ρL/A` is a
409/// statement about a uniform bar, and a shape that is not a uniform bar does not have one.
410pub type Resistivity = Qty<3, 1, -3, -2, 0, 0, 0>;
411/// S/m — the reciprocal of [`Resistivity`], and what a finite-volume solve actually wants,
412/// because conductances in parallel add where resistances do not.
413pub type Conductivity = Qty<-3, -1, 3, 2, 0, 0, 0>;
414/// V/m — the gradient of a potential.
415pub type ElectricField = Qty<1, 1, -3, -1, 0, 0, 0>;
416/// A/m² — current per unit area. What actually flows, and the thing `I` is an integral of.
417pub type CurrentDensity = Qty<-2, 0, 0, 1, 0, 0, 0>;
418/// J·K⁻¹ — mass times specific heat. How much heat a thing can hide before it
419/// shows up as a temperature.
420pub type HeatCapacity = Qty<2, 1, -2, 0, -1, 0, 0>;
421
422// ---------------------------------------------------------------------------
423// Declared products. Each line also gives the two divisions that undo it.
424// ---------------------------------------------------------------------------
425
426macro_rules! product {
427    ($a:ty, $b:ty => $c:ty) => {
428        impl Mul<$b> for $a {
429            type Output = $c;
430            fn mul(self, rhs: $b) -> $c {
431                Qty(self.0 * rhs.0)
432            }
433        }
434        impl Mul<$a> for $b {
435            type Output = $c;
436            fn mul(self, rhs: $a) -> $c {
437                Qty(self.0 * rhs.0)
438            }
439        }
440        impl Div<$b> for $c {
441            type Output = $a;
442            fn div(self, rhs: $b) -> $a {
443                Qty(self.0 / rhs.0)
444            }
445        }
446        impl Div<$a> for $c {
447            type Output = $b;
448            fn div(self, rhs: $a) -> $b {
449                Qty(self.0 / rhs.0)
450            }
451        }
452    };
453}
454
455macro_rules! square {
456    ($a:ty => $c:ty) => {
457        impl Mul<$a> for $a {
458            type Output = $c;
459            fn mul(self, rhs: $a) -> $c {
460                Qty(self.0 * rhs.0)
461            }
462        }
463        impl Div<$a> for $c {
464            type Output = $a;
465            fn div(self, rhs: $a) -> $a {
466                Qty(self.0 / rhs.0)
467            }
468        }
469    };
470}
471
472square!(Length => Area);
473product!(Area, Length => Volume);
474product!(Velocity, Time => Length);
475product!(Acceleration, Time => Velocity);
476product!(Mass, Acceleration => Force);
477product!(Mass, Velocity => Momentum);
478product!(Force, Length => Energy);
479product!(Force, Time => Momentum);
480product!(Pressure, Area => Force);
481product!(Power, Time => Energy);
482product!(Irradiance, Area => Power);
483product!(Density, Volume => Mass);
484product!(Current, Time => Charge);
485product!(Voltage, Current => Power);
486// Ohm's law, declared rather than asserted: this line compiling is the check that ohms times
487// amperes are volts, and with the line above it that `I²R` comes out in watts.
488product!(Resistance, Current => Voltage);
489// The field form of Ohm's law: J = sigma E. These lines compiling is the check that
490// (S/m)*(V/m) is A/m^2, and that resistivity really is the reciprocal of conductivity.
491product!(Conductivity, ElectricField => CurrentDensity);
492product!(Resistivity, CurrentDensity => ElectricField);
493product!(Resistance, Length => Resistivity);
494product!(CurrentDensity, Area => Current);
495product!(ElectricField, Length => Voltage);
496product!(Mass, Area => MomentOfInertia);
497product!(MomentOfInertia, Frequency => AngularMomentum);
498product!(Stiffness, Length => Force);
499product!(Damping, Velocity => Force);
500product!(Mass, SpecificHeat => HeatCapacity);
501// UA·ΔT is watts, and C/UA is a time — the two identities a thermal network is built out of,
502// so the type system checks them rather than a comment claiming them.
503product!(Conductance, Temperature => Power);
504product!(Conductance, Time => HeatCapacity);
505product!(HeatCapacity, Temperature => Energy);
506product!(Frequency, Time => Dimensionless);
507
508impl Volume {
509    /// Cubic metres.
510    pub fn m3(v: f64) -> Volume {
511        Qty(v)
512    }
513    /// Cubic centimetres — the unit a person actually has for a part.
514    pub fn cm3(v: f64) -> Volume {
515        Qty(v * 1e-6)
516    }
517    /// Cubic millimetres.
518    pub fn mm3(v: f64) -> Volume {
519        Qty(v * 1e-9)
520    }
521    /// Litres.
522    pub fn litres(v: f64) -> Volume {
523        Qty(v * 1e-3)
524    }
525}
526
527impl Area {
528    /// Square metres.
529    pub fn m2(v: f64) -> Area {
530        Qty(v)
531    }
532    /// Square centimetres.
533    pub fn cm2(v: f64) -> Area {
534        Qty(v * 1e-4)
535    }
536    /// Square millimetres — wire cross-sections live here.
537    pub fn mm2(v: f64) -> Area {
538        Qty(v * 1e-6)
539    }
540}
541
542impl Area {
543    /// The side of a square of this area. The one root worth naming, because it
544    /// is how a beam radius comes back out of a spot area.
545    pub fn sqrt(self) -> Length {
546        Qty(self.0.sqrt())
547    }
548}
549
550// ---------------------------------------------------------------------------
551// Unit-bearing entry and exit. The only place a factor of 1000 may appear.
552// ---------------------------------------------------------------------------
553
554impl Resistivity {
555    /// Ohm-metres. Copper is 1.724e-8 at 20 °C, aluminium 2.65e-8, and a resistor's ceramic
556    /// substrate is fourteen orders of magnitude up from either.
557    pub fn ohm_m(v: f64) -> Resistivity {
558        Qty(v)
559    }
560    /// µΩ·cm, which is what a materials datasheet quotes: copper is 1.724.
561    pub fn micro_ohm_cm(v: f64) -> Resistivity {
562        Qty(v * 1e-8)
563    }
564    /// The conductivity that is its reciprocal. Zero resistivity gives an infinite
565    /// conductivity, which is the honest answer and not a panic.
566    pub fn conductivity(self) -> Conductivity {
567        Qty(1.0 / self.0)
568    }
569}
570
571impl Conductivity {
572    /// Siemens per metre.
573    pub fn s_per_m(v: f64) -> Conductivity {
574        Qty(v)
575    }
576    /// The resistivity that is its reciprocal.
577    pub fn resistivity(self) -> Resistivity {
578        Qty(1.0 / self.0)
579    }
580}
581
582impl ElectricField {
583    /// Volts per metre.
584    pub fn v_per_m(v: f64) -> ElectricField {
585        Qty(v)
586    }
587}
588
589impl CurrentDensity {
590    /// Amperes per square metre.
591    pub fn a_per_m2(v: f64) -> CurrentDensity {
592        Qty(v)
593    }
594    /// A/mm², which is how a cable's rating is quoted — 5 A/mm² is a normal continuous
595    /// figure for insulated copper in air.
596    pub fn a_per_mm2(v: f64) -> CurrentDensity {
597        Qty(v * 1e6)
598    }
599}
600
601impl Resistance {
602    /// Ohms.
603    pub fn ohm(v: f64) -> Resistance {
604        Qty(v)
605    }
606    /// Milliohms — the range a motor winding or a shunt actually lives in.
607    pub fn milliohm(v: f64) -> Resistance {
608        Qty(v * 1e-3)
609    }
610}
611
612impl Current {
613    /// Amperes.
614    pub fn a(v: f64) -> Current {
615        Qty(v)
616    }
617    /// Milliamperes.
618    pub fn ma(v: f64) -> Current {
619        Qty(v * 1e-3)
620    }
621}
622
623impl Voltage {
624    /// Volts.
625    pub fn v(v: f64) -> Voltage {
626        Qty(v)
627    }
628    /// Millivolts.
629    pub fn mv(v: f64) -> Voltage {
630        Qty(v * 1e-3)
631    }
632}
633
634impl Length {
635    /// Metres.
636    pub fn m(v: f64) -> Length {
637        Qty(v)
638    }
639    /// Millimetres.
640    pub fn mm(v: f64) -> Length {
641        Qty(v * 1e-3)
642    }
643    /// Micrometres.
644    pub fn um(v: f64) -> Length {
645        Qty(v * 1e-6)
646    }
647    /// Nanometres. The wavelength unit, and why every `Spectrum` field is named `_nm`.
648    pub fn nm(v: f64) -> Length {
649        Qty(v * 1e-9)
650    }
651    /// As millimetres.
652    pub fn in_mm(self) -> f64 {
653        self.0 * 1e3
654    }
655    /// As micrometres.
656    pub fn in_um(self) -> f64 {
657        self.0 * 1e6
658    }
659    /// As nanometres.
660    pub fn in_nm(self) -> f64 {
661        self.0 * 1e9
662    }
663}
664
665impl Time {
666    /// Seconds.
667    pub fn s(v: f64) -> Time {
668        Qty(v)
669    }
670    /// Milliseconds.
671    pub fn ms(v: f64) -> Time {
672        Qty(v * 1e-3)
673    }
674    /// Microseconds.
675    pub fn us(v: f64) -> Time {
676        Qty(v * 1e-6)
677    }
678    /// Nanoseconds.
679    pub fn ns(v: f64) -> Time {
680        Qty(v * 1e-9)
681    }
682    /// As milliseconds.
683    pub fn in_ms(self) -> f64 {
684        self.0 * 1e3
685    }
686    /// As microseconds.
687    pub fn in_us(self) -> f64 {
688        self.0 * 1e6
689    }
690}
691
692impl Temperature {
693    /// Kelvin, which is what is stored.
694    pub fn kelvin(v: f64) -> Temperature {
695        Qty(v)
696    }
697    /// Celsius is an *offset* scale, not a scaled one, which is why it gets a
698    /// named constructor rather than a factor: 20 °C is 293.15 K, and a
699    /// temperature *difference* of 20 K is a different thing entirely.
700    pub fn celsius(v: f64) -> Temperature {
701        Qty(v + 273.15)
702    }
703    /// As degrees Celsius. Subtracts the offset; see [`Temperature::celsius`].
704    pub fn in_celsius(self) -> f64 {
705        self.0 - 273.15
706    }
707}
708
709impl Mass {
710    /// Kilograms.
711    pub fn kg(v: f64) -> Mass {
712        Qty(v)
713    }
714    /// Grams.
715    pub fn g(v: f64) -> Mass {
716        Qty(v * 1e-3)
717    }
718}
719
720impl Density {
721    /// The way a glass catalogue quotes it: N-BK7 is 2.51 g/cm³.
722    pub fn g_per_cm3(v: f64) -> Density {
723        Qty(v * 1e3)
724    }
725    /// Kilograms per cubic metre, which is what is stored.
726    pub fn kg_per_m3(v: f64) -> Density {
727        Qty(v)
728    }
729}
730
731impl Power {
732    /// Watts.
733    pub fn w(v: f64) -> Power {
734        Qty(v)
735    }
736    /// Milliwatts.
737    pub fn mw(v: f64) -> Power {
738        Qty(v * 1e-3)
739    }
740    /// Microwatts.
741    pub fn uw(v: f64) -> Power {
742        Qty(v * 1e-6)
743    }
744    /// As milliwatts.
745    pub fn in_mw(self) -> f64 {
746        self.0 * 1e3
747    }
748}
749
750impl Energy {
751    /// Joules.
752    pub fn j(v: f64) -> Energy {
753        Qty(v)
754    }
755    /// Millijoules.
756    pub fn mj(v: f64) -> Energy {
757        Qty(v * 1e-3)
758    }
759}
760
761impl Frequency {
762    /// Hertz.
763    pub fn hz(v: f64) -> Frequency {
764        Qty(v)
765    }
766    /// Kilohertz.
767    pub fn khz(v: f64) -> Frequency {
768        Qty(v * 1e3)
769    }
770    /// Megahertz.
771    pub fn mhz(v: f64) -> Frequency {
772        Qty(v * 1e6)
773    }
774    /// Period: one over the frequency. Named because `1.0 / f` cannot typecheck.
775    pub fn period(self) -> Time {
776        Qty(1.0 / self.0)
777    }
778}
779
780impl Velocity {
781    /// Metres per second.
782    pub fn m_per_s(v: f64) -> Velocity {
783        Qty(v)
784    }
785    /// Millimetres per second.
786    pub fn mm_per_s(v: f64) -> Velocity {
787        Qty(v * 1e-3)
788    }
789}
790
791impl Irradiance {
792    /// Watts per square metre, which is what is stored.
793    pub fn w_per_m2(v: f64) -> Irradiance {
794        Qty(v)
795    }
796    /// How an illumination spec is usually written: mW/cm².
797    pub fn mw_per_cm2(v: f64) -> Irradiance {
798        Qty(v * 10.0)
799    }
800}
801
802impl ThermalConductivity {
803    /// W·m⁻¹·K⁻¹, the unit a materials table uses.
804    pub fn w_per_m_k(v: f64) -> ThermalConductivity {
805        Qty(v)
806    }
807}
808
809impl SpecificHeat {
810    /// J·kg⁻¹·K⁻¹, the unit a materials table uses.
811    pub fn j_per_kg_k(v: f64) -> SpecificHeat {
812        Qty(v)
813    }
814}
815
816impl Conductance {
817    /// Watts per kelvin.
818    pub fn w_per_k(v: f64) -> Conductance {
819        Qty(v)
820    }
821}
822
823impl HeatCapacity {
824    /// Joules per kelvin. The companion to [`Conductance::w_per_k`]: their ratio is a time
825    /// constant, and the type system says so.
826    pub fn j_per_k(v: f64) -> HeatCapacity {
827        Qty(v)
828    }
829}
830
831impl ThermalExpansion {
832    /// Catalogues quote it in parts per million per kelvin: N-BK7 is 7.1.
833    pub fn ppm_per_k(v: f64) -> ThermalExpansion {
834        Qty(v * 1e-6)
835    }
836}
837
838impl Dimensionless {
839    /// A bare ratio, for the one case where a number genuinely has no dimension:
840    /// a reflectance, a duty cycle, a refractive index.
841    pub fn ratio(v: f64) -> Dimensionless {
842        Qty(v)
843    }
844}
845
846// ---------------------------------------------------------------------------
847// Physical constants, in SI base units, so that a formula written with them
848// carries its own dimensional proof.
849// ---------------------------------------------------------------------------
850
851/// Speed of light in vacuum, m·s⁻¹ (exact by definition).
852pub const C: Velocity = Qty(299_792_458.0);
853/// Planck constant, J·s (exact by definition).
854pub const PLANCK: Qty<2, 1, -1, 0, 0, 0, 0> = Qty(6.626_070_15e-34);
855/// Boltzmann constant, J·K⁻¹ (exact by definition).
856pub const BOLTZMANN: HeatCapacity = Qty(1.380_649e-23);
857/// Stefan-Boltzmann constant, W·m⁻²·K⁻⁴ — radiative exchange lives on this.
858pub const STEFAN_BOLTZMANN: Qty<0, 1, -3, 0, -4, 0, 0> = Qty(5.670_374_419e-8);
859/// Standard gravity, m·s⁻².
860pub const G0: Acceleration = Qty(9.806_65);
861
862/// Energy of one photon at a vacuum wavelength: `E = hc/λ`.
863///
864/// The bridge between a spectrum and a photon count, and the reason a detector's
865/// response is not the same shape as a lamp's output.
866pub fn photon_energy(wavelength: Length) -> Energy {
867    Qty(PLANCK.0 * C.0 / wavelength.0)
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873
874    /// The point of the crate: a product of dimensions lands on the type that
875    /// names it, whichever route it took there.
876    #[test]
877    fn products_land_on_the_named_dimension() {
878        let m = Mass::kg(2.0);
879        let a = Acceleration::from_si(3.0);
880        let f: Force = m * a;
881        assert!((f.to_si() - 6.0).abs() < 1e-12);
882
883        // Two different routes to the same energy, and they unify.
884        let by_work: Energy = f * Length::m(4.0);
885        let by_power: Energy = Power::w(24.0) * Time::s(1.0);
886        assert!((by_work - by_power).abs().to_si() < 1e-12);
887
888        // And multiplication commutes, as it must.
889        let swapped: Force = a * m;
890        assert_eq!(f, swapped);
891    }
892
893    /// Millimetres and nanometres are entry forms only; storage is metres. A
894    /// wavelength and a lens diameter therefore compare correctly without anyone
895    /// remembering which convention each was written in.
896    #[test]
897    fn unit_prefixes_are_only_a_doorway() {
898        let lens = Length::mm(25.4);
899        let green = Length::nm(550.0);
900        assert!(lens > green);
901        assert!((lens.to_si() - 0.0254).abs() < 1e-15);
902        assert!((green.in_nm() - 550.0).abs() < 1e-9);
903        // 25.4 mm is 46181.8... wavelengths of green light.
904        let waves = lens / green;
905        assert!((waves - 46_181.8).abs() < 0.1, "got {waves}");
906    }
907
908    /// Dividing like by like gives a plain number, which is what every
909    /// tolerance and every reflectance is.
910    #[test]
911    fn like_over_like_is_a_bare_number() {
912        let reflected = Power::mw(0.42);
913        let incident = Power::mw(10.0);
914        let r: f64 = reflected / incident;
915        assert!((r - 0.042).abs() < 1e-12);
916    }
917
918    /// Celsius offsets rather than scales, and getting that wrong is a 273 K
919    /// error that no dimensional check would ever catch.
920    #[test]
921    fn celsius_is_an_offset_not_a_factor() {
922        assert!((Temperature::celsius(20.0).to_si() - 293.15).abs() < 1e-12);
923        assert!((Temperature::kelvin(293.15).in_celsius() - 20.0).abs() < 1e-12);
924        // A *difference* of 20 K is not 293.15 K, and only one of these is a
925        // temperature you can put in Stefan-Boltzmann.
926        let rise = Temperature::kelvin(313.15) - Temperature::kelvin(293.15);
927        assert!((rise.to_si() - 20.0).abs() < 1e-12);
928    }
929
930    /// The optics-to-thermal chain this whole crate exists to make safe: a
931    /// surface absorbs a fraction of an irradiance over an area, and the watts
932    /// that result heat a mass with a known specific heat.
933    #[test]
934    fn absorbed_light_becomes_a_temperature_rise() {
935        let irradiance = Irradiance::mw_per_cm2(50.0); // 500 W/m²
936        let area: Area = Length::mm(10.0) * Length::mm(10.0); // 1e-4 m²
937        let absorptance = 0.02; // what SurfaceOptics::absorptance returns
938        let absorbed: Power = irradiance * area * absorptance;
939        assert!((absorbed.to_si() - 0.001).abs() < 1e-12, "{absorbed:?}");
940
941        // 1 mW into a 2 g piece of glass for 1 s.
942        let glass = Mass::g(2.0);
943        let c_p = SpecificHeat::j_per_kg_k(858.0); // N-BK7
944        let capacity: HeatCapacity = glass * c_p;
945        let heat: Energy = absorbed * Time::s(1.0);
946        let rise: Temperature = heat / capacity;
947        assert!(
948            (rise.to_si() - 0.000_582_7).abs() < 1e-7,
949            "expected about 0.58 mK, got {rise:?}"
950        );
951    }
952
953    /// A photon at 550 nm carries 3.6e-19 J, and the count per watt follows.
954    /// This is the number that separates radiometry from photon counting.
955    #[test]
956    fn photon_energy_matches_the_textbook_figure() {
957        let e = photon_energy(Length::nm(550.0));
958        assert!((e.to_si() - 3.612e-19).abs() < 1e-21, "{e:?}");
959        // 2.26 eV, and about 2.77e18 photons in a joule.
960        let per_joule = Energy::j(1.0) / e;
961        assert!((per_joule - 2.768e18).abs() < 1e15, "got {per_joule:e}");
962    }
963
964    /// Debug prints the dimension, so a mismatch found at a boundary can be
965    /// reported in a form a human recognises.
966    #[test]
967    fn debug_shows_the_dimension() {
968        assert_eq!(format!("{:?}", Force::from_si(6.0)), "6·m·kg·s^-2");
969        assert_eq!(format!("{:?}", Dimensionless::ratio(0.5)), "0.5");
970        assert_eq!(Force::dimension(), [1, 1, -2, 0, 0, 0, 0]);
971    }
972
973    /// Serialised as the bare SI number: the dimension is in the field's type,
974    /// not repeated in every scene file.
975    #[test]
976    fn serialises_as_a_bare_si_number() {
977        let json = serde_json::to_string(&Length::mm(25.4)).unwrap();
978        assert_eq!(json, "0.0254");
979        let back: Length = serde_json::from_str(&json).unwrap();
980        assert_eq!(back, Length::mm(25.4));
981    }
982}