force-electric 0.1.0

Typed DC electricity, resistance-network, and energy calculations
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
//! Typed calculations for ideal scalar DC electricity.
//!
//! [`DcOperatingPoint`] applies Ohm's law and DC power relationships, while
//! [`series_resistance`], [`parallel_resistance`], and [`Energy`] connect the
//! same validated quantities to resistance networks and usage over time.

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::error::Error;
use std::fmt;

/// A finite, non-negative electric potential in volts.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Voltage(f64);

impl Voltage {
    /// Creates a voltage magnitude in volts.
    pub fn volts(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "voltage")?;
        Ok(Self(value))
    }

    /// Returns the voltage magnitude in volts.
    pub const fn as_volts(self) -> f64 {
        self.0
    }
}

/// A finite, non-negative electric current in amperes.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Current(f64);

impl Current {
    /// Creates a current magnitude in amperes.
    pub fn amperes(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "current")?;
        Ok(Self(value))
    }

    /// Returns the current magnitude in amperes.
    pub const fn as_amperes(self) -> f64 {
        self.0
    }
}

/// A finite, positive electrical resistance in ohms.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Resistance(f64);

impl Resistance {
    /// Creates a positive resistance in ohms.
    pub fn ohms(value: f64) -> Result<Self, ElectricError> {
        validate_positive_finite(value, "resistance")?;
        Ok(Self(value))
    }

    /// Returns resistance in ohms.
    pub const fn as_ohms(self) -> f64 {
        self.0
    }
}

/// A finite, non-negative power in watts.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Power(f64);

impl Power {
    /// Creates a power magnitude in watts.
    pub fn watts(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "power")?;
        Ok(Self(value))
    }

    /// Calculates ideal DC power as voltage multiplied by current.
    pub fn from_voltage_and_current(
        voltage: Voltage,
        current: Current,
    ) -> Result<Self, ElectricError> {
        let watts = voltage.0 * current.0;
        ensure_finite(watts)?;
        Ok(Self(watts))
    }

    /// Returns power in watts.
    pub const fn as_watts(self) -> f64 {
        self.0
    }
}

/// A finite, non-negative duration stored in seconds.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Duration(f64);

impl Duration {
    /// Creates a duration in seconds.
    pub fn seconds(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "duration")?;
        Ok(Self(value))
    }

    /// Creates a duration in hours.
    pub fn hours(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "duration")?;
        let seconds = value * 3_600.0;
        ensure_finite(seconds)?;
        Ok(Self(seconds))
    }

    /// Returns the duration in seconds.
    pub const fn as_seconds(self) -> f64 {
        self.0
    }

    /// Returns the duration in hours.
    pub fn as_hours(self) -> f64 {
        self.0 / 3_600.0
    }
}

/// A finite, non-negative amount of energy stored in joules.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Energy(f64);

impl Energy {
    /// Creates an energy amount in joules.
    pub fn joules(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "energy")?;
        Ok(Self(value))
    }

    /// Creates an energy amount in watt-hours.
    pub fn watt_hours(value: f64) -> Result<Self, ElectricError> {
        validate_non_negative_finite(value, "energy")?;
        let joules = value * 3_600.0;
        ensure_finite(joules)?;
        Ok(Self(joules))
    }

    /// Calculates energy consumed by constant power over a duration.
    pub fn from_power_over(power: Power, duration: Duration) -> Result<Self, ElectricError> {
        let joules = power.0 * duration.0;
        ensure_finite(joules)?;
        Ok(Self(joules))
    }

    /// Returns energy in joules.
    pub const fn as_joules(self) -> f64 {
        self.0
    }

    /// Returns energy in watt-hours.
    pub fn as_watt_hours(self) -> f64 {
        self.0 / 3_600.0
    }

    /// Calculates how long this energy can supply constant, positive power.
    pub fn runtime_at(self, power: Power) -> Result<Duration, ElectricError> {
        if power.0 == 0.0 {
            return Err(ElectricError::ZeroPower);
        }
        let seconds = self.0 / power.0;
        ensure_finite(seconds)?;
        Ok(Duration(seconds))
    }
}

/// A complete ideal DC operating point satisfying Ohm's law.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DcOperatingPoint {
    voltage: Voltage,
    current: Current,
    resistance: Resistance,
    power: Power,
}

impl DcOperatingPoint {
    /// Derives current and power from voltage and resistance.
    pub fn from_voltage_and_resistance(
        voltage: Voltage,
        resistance: Resistance,
    ) -> Result<Self, ElectricError> {
        let current = Current(voltage.0 / resistance.0);
        ensure_finite(current.0)?;
        Self::assemble(voltage, current, resistance)
    }

    /// Derives voltage and power from current and resistance.
    pub fn from_current_and_resistance(
        current: Current,
        resistance: Resistance,
    ) -> Result<Self, ElectricError> {
        let voltage = Voltage(current.0 * resistance.0);
        ensure_finite(voltage.0)?;
        Self::assemble(voltage, current, resistance)
    }

    /// Derives resistance and power from positive voltage and current.
    pub fn from_voltage_and_current(
        voltage: Voltage,
        current: Current,
    ) -> Result<Self, ElectricError> {
        if voltage.0 == 0.0 || current.0 == 0.0 {
            return Err(ElectricError::UnderdeterminedResistance);
        }
        let resistance = Resistance(voltage.0 / current.0);
        ensure_finite(resistance.0)?;
        Self::assemble(voltage, current, resistance)
    }

    fn assemble(
        voltage: Voltage,
        current: Current,
        resistance: Resistance,
    ) -> Result<Self, ElectricError> {
        let power = Power::from_voltage_and_current(voltage, current)?;
        Ok(Self {
            voltage,
            current,
            resistance,
            power,
        })
    }

    /// Returns voltage.
    pub const fn voltage(self) -> Voltage {
        self.voltage
    }

    /// Returns current.
    pub const fn current(self) -> Current {
        self.current
    }

    /// Returns resistance.
    pub const fn resistance(self) -> Resistance {
        self.resistance
    }

    /// Returns ideal DC power.
    pub const fn power(self) -> Power {
        self.power
    }
}

/// Calculates the equivalent resistance of a non-empty series network.
pub fn series_resistance(resistors: &[Resistance]) -> Result<Resistance, ElectricError> {
    if resistors.is_empty() {
        return Err(ElectricError::EmptyResistanceNetwork);
    }
    let mut total = 0.0;
    for resistor in resistors {
        total += resistor.0;
        ensure_finite(total)?;
    }
    Ok(Resistance(total))
}

/// Calculates the equivalent resistance of a non-empty parallel network.
pub fn parallel_resistance(resistors: &[Resistance]) -> Result<Resistance, ElectricError> {
    if resistors.is_empty() {
        return Err(ElectricError::EmptyResistanceNetwork);
    }
    let mut reciprocal_sum = 0.0;
    for resistor in resistors {
        reciprocal_sum += 1.0 / resistor.0;
        ensure_finite(reciprocal_sum)?;
    }
    let equivalent = 1.0 / reciprocal_sum;
    ensure_finite(equivalent)?;
    if equivalent == 0.0 {
        return Err(ElectricError::CalculationOutOfRange);
    }
    Ok(Resistance(equivalent))
}

/// Invalid electrical input or a calculation outside finite numeric range.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ElectricError {
    /// A named input was not finite.
    NonFinite(&'static str),
    /// A named input was negative.
    Negative(&'static str),
    /// A named input had to be positive but was zero.
    Zero(&'static str),
    /// Zero voltage or current could not determine a finite positive resistance.
    UnderdeterminedResistance,
    /// Runtime cannot be calculated at zero power.
    ZeroPower,
    /// An equivalent resistance was requested for no resistors.
    EmptyResistanceNetwork,
    /// Arithmetic produced a non-finite or unrepresentable result.
    CalculationOutOfRange,
}

impl fmt::Display for ElectricError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NonFinite(name) => write!(formatter, "{name} must be finite"),
            Self::Negative(name) => write!(formatter, "{name} must not be negative"),
            Self::Zero(name) => write!(formatter, "{name} must be greater than zero"),
            Self::UnderdeterminedResistance => formatter
                .write_str("voltage and current must both be positive to derive resistance"),
            Self::ZeroPower => formatter.write_str("runtime at zero power is undefined"),
            Self::EmptyResistanceNetwork => {
                formatter.write_str("resistance network must not be empty")
            }
            Self::CalculationOutOfRange => {
                formatter.write_str("calculation exceeded representable finite range")
            }
        }
    }
}

impl Error for ElectricError {}

fn validate_non_negative_finite(value: f64, name: &'static str) -> Result<(), ElectricError> {
    if !value.is_finite() {
        return Err(ElectricError::NonFinite(name));
    }
    if value < 0.0 {
        return Err(ElectricError::Negative(name));
    }
    Ok(())
}

fn validate_positive_finite(value: f64, name: &'static str) -> Result<(), ElectricError> {
    validate_non_negative_finite(value, name)?;
    if value == 0.0 {
        return Err(ElectricError::Zero(name));
    }
    Ok(())
}

fn ensure_finite(value: f64) -> Result<(), ElectricError> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(ElectricError::CalculationOutOfRange)
    }
}

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

    #[test]
    fn voltage_and_resistance_derive_current_and_power() {
        let point = DcOperatingPoint::from_voltage_and_resistance(
            Voltage::volts(12.0).unwrap(),
            Resistance::ohms(6.0).unwrap(),
        )
        .unwrap();
        assert_eq!(point.current().as_amperes(), 2.0);
        assert_eq!(point.power().as_watts(), 24.0);
    }

    #[test]
    fn current_and_resistance_derive_voltage() {
        let point = DcOperatingPoint::from_current_and_resistance(
            Current::amperes(0.5).unwrap(),
            Resistance::ohms(20.0).unwrap(),
        )
        .unwrap();
        assert_eq!(point.voltage().as_volts(), 10.0);
        assert_eq!(point.power().as_watts(), 5.0);
    }

    #[test]
    fn voltage_and_current_derive_resistance() {
        let point = DcOperatingPoint::from_voltage_and_current(
            Voltage::volts(9.0).unwrap(),
            Current::amperes(0.3).unwrap(),
        )
        .unwrap();
        assert_eq!(point.resistance().as_ohms(), 30.0);
    }

    #[test]
    fn equivalent_resistances_are_calculated() {
        let resistors = [
            Resistance::ohms(100.0).unwrap(),
            Resistance::ohms(100.0).unwrap(),
        ];
        assert_eq!(series_resistance(&resistors).unwrap().as_ohms(), 200.0);
        assert!((parallel_resistance(&resistors).unwrap().as_ohms() - 50.0).abs() < 1e-12);
    }

    #[test]
    fn power_over_time_produces_energy_and_runtime() {
        let energy =
            Energy::from_power_over(Power::watts(24.0).unwrap(), Duration::hours(3.0).unwrap())
                .unwrap();
        assert_eq!(energy.as_watt_hours(), 72.0);
        assert_eq!(
            energy
                .runtime_at(Power::watts(36.0).unwrap())
                .unwrap()
                .as_hours(),
            2.0
        );
    }

    #[test]
    fn invalid_inputs_are_rejected() {
        assert_eq!(
            Voltage::volts(f64::NAN),
            Err(ElectricError::NonFinite("voltage"))
        );
        assert_eq!(
            Current::amperes(-1.0),
            Err(ElectricError::Negative("current"))
        );
        assert_eq!(
            Resistance::ohms(0.0),
            Err(ElectricError::Zero("resistance"))
        );
        assert_eq!(
            parallel_resistance(&[]),
            Err(ElectricError::EmptyResistanceNetwork)
        );
        assert_eq!(
            Energy::joules(10.0)
                .unwrap()
                .runtime_at(Power::watts(0.0).unwrap()),
            Err(ElectricError::ZeroPower)
        );
    }

    #[test]
    fn zero_pair_cannot_derive_resistance() {
        assert_eq!(
            DcOperatingPoint::from_voltage_and_current(
                Voltage::volts(0.0).unwrap(),
                Current::amperes(0.0).unwrap()
            ),
            Err(ElectricError::UnderdeterminedResistance)
        );
    }

    #[test]
    fn calculation_overflow_is_reported() {
        assert_eq!(
            Power::from_voltage_and_current(
                Voltage::volts(f64::MAX).unwrap(),
                Current::amperes(2.0).unwrap()
            ),
            Err(ElectricError::CalculationOutOfRange)
        );
    }
}