twine-models 0.4.0

Domain-specific models and model-building tools for Twine
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
//! CoolProp-backed fluid property model.

// CoolProp uses C++ exceptions which require Emscripten's runtime.
// The `wasm32-unknown-unknown` target cannot provide this.
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
compile_error!(
    "CoolProp requires Emscripten for WASM builds. \
     Use target `wasm32-unknown-emscripten`, not `wasm32-unknown-unknown`."
);

mod error;
mod ffi;
mod wrapper;

use std::{
    marker::PhantomData,
    sync::{Mutex, MutexGuard},
};

use uom::si::{
    available_energy::joule_per_kilogram,
    f64::{MassDensity, MolarMass, Pressure, SpecificHeatCapacity, ThermodynamicTemperature},
    mass_density::kilogram_per_cubic_meter,
    molar_mass::kilogram_per_mole,
    pressure::pascal,
    specific_heat_capacity::joule_per_kilogram_kelvin,
    thermodynamic_temperature::kelvin,
};

use crate::support::thermo::{
    PropertyError, State,
    capability::{
        HasCp, HasCv, HasEnthalpy, HasEntropy, HasInternalEnergy, HasPressure, StateFrom,
        ThermoModel,
    },
};
use crate::support::units::{SpecificEnthalpy, SpecificEntropy, SpecificInternalEnergy};

use ffi::{InputPair, OutputParam};
use wrapper::AbstractState;

pub use error::CoolPropError;

/// Trait used to mark fluids as usable with the [`CoolProp`] model.
///
/// Implementors provide the backend and fluid identifiers needed to construct a
/// `CoolProp` `AbstractState`.
pub trait CoolPropFluid: Default + Send + Sync + 'static {
    const BACKEND: &'static str;
    const NAME: &'static str;
}

/// A fluid property model backed by `CoolProp`.
pub struct CoolProp<F: CoolPropFluid> {
    state: Mutex<AbstractState>,
    _f: PhantomData<F>,
}

impl<F: CoolPropFluid> ThermoModel for CoolProp<F> {
    type Fluid = F;
}

impl<F: CoolPropFluid> CoolProp<F> {
    /// Construct a new CoolProp-backed model instance.
    ///
    /// # Errors
    ///
    /// Returns [`CoolPropError`] if the underlying `AbstractState` cannot be
    /// created for the given `F::BACKEND` and `F::NAME`.
    pub fn new() -> Result<Self, CoolPropError> {
        let state = AbstractState::new(F::BACKEND, F::NAME)?;
        Ok(Self {
            state: Mutex::new(state),
            _f: PhantomData,
        })
    }

    /// Returns the molar mass of the fluid.
    ///
    /// # Errors
    ///
    /// Returns [`CoolPropError`] if the call fails.
    pub fn molar_mass(&self) -> Result<MolarMass, CoolPropError> {
        let abstract_state = self.state.lock()?;
        let molar_mass = abstract_state.keyed_output(OutputParam::MOLAR_MASS)?;
        Ok(MolarMass::new::<kilogram_per_mole>(molar_mass))
    }

    /// Locks the underlying `AbstractState` and updates it from `state`.
    fn lock_with_state(
        &self,
        state: &State<F>,
    ) -> Result<MutexGuard<'_, AbstractState>, CoolPropError> {
        let mut abstract_state = self.state.lock()?;
        abstract_state.update(
            InputPair::DMASS_T,
            state.density.get::<kilogram_per_cubic_meter>(),
            state.temperature.get::<kelvin>(),
        )?;
        Ok(abstract_state)
    }
}

impl<F: CoolPropFluid> HasPressure for CoolProp<F> {
    fn pressure(&self, state: &State<Self::Fluid>) -> Result<Pressure, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let pressure = abstract_state
            .keyed_output(OutputParam::P)
            .map_err(CoolPropError::from)?;
        Ok(Pressure::new::<pascal>(pressure))
    }
}

impl<F: CoolPropFluid> HasInternalEnergy for CoolProp<F> {
    fn internal_energy(
        &self,
        state: &State<Self::Fluid>,
    ) -> Result<SpecificInternalEnergy, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let internal_energy = abstract_state
            .keyed_output(OutputParam::UMASS)
            .map_err(CoolPropError::from)?;
        Ok(SpecificInternalEnergy::new::<joule_per_kilogram>(
            internal_energy,
        ))
    }
}

impl<F: CoolPropFluid> HasEnthalpy for CoolProp<F> {
    fn enthalpy(&self, state: &State<Self::Fluid>) -> Result<SpecificEnthalpy, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let enthalpy = abstract_state
            .keyed_output(OutputParam::HMASS)
            .map_err(CoolPropError::from)?;
        Ok(SpecificEnthalpy::new::<joule_per_kilogram>(enthalpy))
    }
}

impl<F: CoolPropFluid> HasEntropy for CoolProp<F> {
    fn entropy(&self, state: &State<Self::Fluid>) -> Result<SpecificEntropy, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let entropy = abstract_state
            .keyed_output(OutputParam::SMASS)
            .map_err(CoolPropError::from)?;
        Ok(SpecificEntropy::new::<joule_per_kilogram_kelvin>(entropy))
    }
}

impl<F: CoolPropFluid> HasCp for CoolProp<F> {
    fn cp(&self, state: &State<Self::Fluid>) -> Result<SpecificHeatCapacity, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let cp = abstract_state
            .keyed_output(OutputParam::CP_MASS)
            .map_err(CoolPropError::from)?;
        Ok(SpecificHeatCapacity::new::<joule_per_kilogram_kelvin>(cp))
    }
}

impl<F: CoolPropFluid> HasCv for CoolProp<F> {
    fn cv(&self, state: &State<Self::Fluid>) -> Result<SpecificHeatCapacity, PropertyError> {
        let abstract_state = self.lock_with_state(state)?;
        let cv = abstract_state
            .keyed_output(OutputParam::CV_MASS)
            .map_err(CoolPropError::from)?;
        Ok(SpecificHeatCapacity::new::<joule_per_kilogram_kelvin>(cv))
    }
}

impl<F: CoolPropFluid> StateFrom<(F, ThermodynamicTemperature, MassDensity)> for CoolProp<F> {
    type Error = CoolPropError;

    fn state_from(
        &self,
        (fluid, temperature, density): (F, ThermodynamicTemperature, MassDensity),
    ) -> Result<State<F>, Self::Error> {
        let mut abstract_state = self.state.lock()?;
        // Update CoolProp to validate the T-D state and surface invalid inputs early.
        abstract_state.update(
            InputPair::DMASS_T,
            density.get::<kilogram_per_cubic_meter>(),
            temperature.get::<kelvin>(),
        )?;

        Ok(State {
            temperature,
            density,
            fluid,
        })
    }
}

impl<F: CoolPropFluid> StateFrom<(F, ThermodynamicTemperature, Pressure)> for CoolProp<F> {
    type Error = CoolPropError;

    fn state_from(
        &self,
        (fluid, temperature, pressure): (F, ThermodynamicTemperature, Pressure),
    ) -> Result<State<F>, Self::Error> {
        let mut abstract_state = self.state.lock()?;
        abstract_state.update(
            InputPair::PT,
            pressure.get::<pascal>(),
            temperature.get::<kelvin>(),
        )?;

        let density = abstract_state.keyed_output(OutputParam::DMASS)?;

        Ok(State {
            temperature,
            density: MassDensity::new::<kilogram_per_cubic_meter>(density),
            fluid,
        })
    }
}

impl<F: CoolPropFluid> StateFrom<(F, Pressure, SpecificEnthalpy)> for CoolProp<F> {
    type Error = CoolPropError;

    fn state_from(
        &self,
        (fluid, pressure, enthalpy): (F, Pressure, SpecificEnthalpy),
    ) -> Result<State<F>, Self::Error> {
        let mut abstract_state = self.state.lock()?;
        abstract_state.update(
            InputPair::HMASS_P,
            enthalpy.get::<joule_per_kilogram>(),
            pressure.get::<pascal>(),
        )?;

        let temperature = abstract_state.keyed_output(OutputParam::T)?;
        let density = abstract_state.keyed_output(OutputParam::DMASS)?;

        Ok(State {
            temperature: ThermodynamicTemperature::new::<kelvin>(temperature),
            density: MassDensity::new::<kilogram_per_cubic_meter>(density),
            fluid,
        })
    }
}

impl<F: CoolPropFluid> StateFrom<(F, Pressure, SpecificEntropy)> for CoolProp<F> {
    type Error = CoolPropError;

    fn state_from(
        &self,
        (fluid, pressure, entropy): (F, Pressure, SpecificEntropy),
    ) -> Result<State<F>, Self::Error> {
        let mut abstract_state = self.state.lock()?;
        abstract_state.update(
            InputPair::PS_MASS,
            pressure.get::<pascal>(),
            entropy.get::<joule_per_kilogram_kelvin>(),
        )?;

        let temperature = abstract_state.keyed_output(OutputParam::T)?;
        let density = abstract_state.keyed_output(OutputParam::DMASS)?;

        Ok(State {
            temperature: ThermodynamicTemperature::new::<kelvin>(temperature),
            density: MassDensity::new::<kilogram_per_cubic_meter>(density),
            fluid,
        })
    }
}

impl<F: CoolPropFluid> StateFrom<(F, SpecificEnthalpy, SpecificEntropy)> for CoolProp<F> {
    type Error = CoolPropError;

    fn state_from(
        &self,
        (fluid, enthalpy, entropy): (F, SpecificEnthalpy, SpecificEntropy),
    ) -> Result<State<F>, Self::Error> {
        let mut abstract_state = self.state.lock()?;
        abstract_state.update(
            InputPair::HMASS_SMASS,
            enthalpy.get::<joule_per_kilogram>(),
            entropy.get::<joule_per_kilogram_kelvin>(),
        )?;

        let temperature = abstract_state.keyed_output(OutputParam::T)?;
        let density = abstract_state.keyed_output(OutputParam::DMASS)?;

        Ok(State {
            temperature: ThermodynamicTemperature::new::<kelvin>(temperature),
            density: MassDensity::new::<kilogram_per_cubic_meter>(density),
            fluid,
        })
    }
}

// Static assertion: `CoolProp<F>` must be `Send + Sync` for any `CoolPropFluid`.
// Thread safety is provided by `COOLPROP_LOCK` in `wrapper.rs`, which serializes
// all CoolProp FFI calls. The local `Mutex<AbstractState>` provides interior
// mutability and keeps update/query call pairs atomic.
// TODO: remove when CoolProp<F> gains a public method that exercises the
// Send + Sync bound (e.g., a parallel property evaluation API).
#[allow(dead_code)]
const _: () = {
    fn assert_send_sync<T: Send + Sync>() {}
    fn check<F: CoolPropFluid>() {
        assert_send_sync::<CoolProp<F>>();
    }
};

// Exact `assert_eq!` on f64 is intentional in the spot-check tests —
// they verify bit-for-bit reproducibility across CoolProp builds.
#[allow(clippy::float_cmp)]
#[cfg(test)]
mod tests {
    use super::*;

    use approx::assert_relative_eq;
    use uom::si::{
        available_energy::kilojoule_per_kilogram,
        f64::{MassDensity, ThermodynamicTemperature},
        mass_density::kilogram_per_cubic_meter,
        molar_mass::gram_per_mole,
        pressure::megapascal,
        specific_heat_capacity::{joule_per_kilogram_kelvin, kilojoule_per_kilogram_kelvin},
        thermodynamic_temperature::{degree_celsius, kelvin},
    };

    use crate::support::thermo::fluid::{CarbonDioxide, Water};

    fn co2_model() -> CoolProp<CarbonDioxide> {
        CoolProp::<CarbonDioxide>::new().unwrap()
    }

    fn co2_state() -> State<CarbonDioxide> {
        State::new(
            ThermodynamicTemperature::new::<degree_celsius>(42.0),
            MassDensity::new::<kilogram_per_cubic_meter>(670.0),
            CarbonDioxide,
        )
    }

    fn water_model() -> CoolProp<Water> {
        CoolProp::<Water>::new().unwrap()
    }

    fn water_state() -> State<Water> {
        State::new(
            ThermodynamicTemperature::new::<degree_celsius>(25.0),
            MassDensity::new::<kilogram_per_cubic_meter>(1000.0),
            Water,
        )
    }

    // ── Spot-check tests ──────────────────────────────────────────────
    //
    // Assert exact `f64` values for CO₂ at 42 °C / 670 kg/m³.
    // Running with both `coolprop-static` and `coolprop-dylib` verifies
    // the from-source build matches the prebuilt shared library at full
    // precision (not just within an epsilon).
    //
    // Reference values captured from CoolProp v7.2.0 (official macOS
    // AArch64 shared library via `coolprop-sys-macos-aarch64`).

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_pressure() {
        let model = co2_model();
        let state = co2_state();
        let value = model.pressure(&state).unwrap().get::<pascal>();
        assert_eq!(value, 1.133_616_265_282_128_8e7);
    }

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_internal_energy() {
        let model = co2_model();
        let state = co2_state();
        let value = model
            .internal_energy(&state)
            .unwrap()
            .get::<joule_per_kilogram>();
        assert_eq!(value, 2.909_564_765_862_165e5);
    }

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_enthalpy() {
        let model = co2_model();
        let state = co2_state();
        let value = model.enthalpy(&state).unwrap().get::<joule_per_kilogram>();
        assert_eq!(value, 3.078_761_223_366_96e5);
    }

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_entropy() {
        let model = co2_model();
        let state = co2_state();
        let value = model
            .entropy(&state)
            .unwrap()
            .get::<joule_per_kilogram_kelvin>();
        assert_eq!(value, 1.333_274_008_373_242_2e3);
    }

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_cp() {
        let model = co2_model();
        let state = co2_state();
        let value = model.cp(&state).unwrap().get::<joule_per_kilogram_kelvin>();
        assert_eq!(value, 4.125_049_199_079_285e3);
    }

    #[test]
    #[ignore = "offline verification — run manually when updating CoolProp"]
    fn co2_spot_check_cv() {
        let model = co2_model();
        let state = co2_state();
        let value = model.cv(&state).unwrap().get::<joule_per_kilogram_kelvin>();
        assert_eq!(value, 9.805_326_153_531_056e2);
    }

    #[test]
    fn co2_molar_mass_matches_expected() {
        let model = co2_model();
        let molar_mass = model.molar_mass().unwrap();
        assert_relative_eq!(molar_mass.get::<gram_per_mole>(), 44.0098);
    }

    #[test]
    fn co2_pressure_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let pressure = model.pressure(&state).unwrap();
        assert_relative_eq!(pressure.get::<megapascal>(), 11.3362, epsilon = 1e-4);
    }

    #[test]
    fn co2_internal_energy_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let internal_energy = model.internal_energy(&state).unwrap();
        assert_relative_eq!(
            internal_energy.get::<kilojoule_per_kilogram>(),
            290.9565,
            epsilon = 1e-4
        );
    }

    #[test]
    fn co2_enthalpy_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let enthalpy = model.enthalpy(&state).unwrap();
        assert_relative_eq!(
            enthalpy.get::<kilojoule_per_kilogram>(),
            307.8761,
            epsilon = 1e-4
        );
    }

    #[test]
    fn co2_entropy_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let entropy = model.entropy(&state).unwrap();
        assert_relative_eq!(
            entropy.get::<kilojoule_per_kilogram_kelvin>(),
            1.3333,
            epsilon = 1e-4
        );
    }

    #[test]
    fn co2_cp_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let cp = model.cp(&state).unwrap();
        assert_relative_eq!(
            cp.get::<kilojoule_per_kilogram_kelvin>(),
            4.125,
            epsilon = 1e-4
        );
    }

    #[test]
    fn co2_cv_matches_expected() {
        let model = co2_model();
        let state = co2_state();
        let cv = model.cv(&state).unwrap();
        assert_relative_eq!(
            cv.get::<joule_per_kilogram_kelvin>(),
            980.5326,
            epsilon = 1e-4
        );
    }

    #[test]
    fn co2_state_from_temperature_pressure_roundtrips_from_temperature_density() {
        let model = co2_model();

        let state = co2_state();
        let pressure = model.pressure(&state).unwrap();
        let roundtrip = model
            .state_from((CarbonDioxide, state.temperature, pressure))
            .unwrap();

        assert_relative_eq!(
            roundtrip.density.get::<kilogram_per_cubic_meter>(),
            state.density.get::<kilogram_per_cubic_meter>(),
            max_relative = 1e-9
        );
    }

    #[test]
    fn water_state_from_pressure_enthalpy_roundtrips_from_temperature_density() {
        let model = water_model();

        let state = water_state();
        let pressure = model.pressure(&state).unwrap();
        let enthalpy = model.enthalpy(&state).unwrap();
        let roundtrip = model.state_from((Water, pressure, enthalpy)).unwrap();

        assert_relative_eq!(
            roundtrip.temperature.get::<kelvin>(),
            state.temperature.get::<kelvin>(),
            max_relative = 1e-9
        );
        assert_relative_eq!(
            roundtrip.density.get::<kilogram_per_cubic_meter>(),
            state.density.get::<kilogram_per_cubic_meter>(),
            max_relative = 1e-9
        );
    }

    #[test]
    fn water_state_from_pressure_entropy_roundtrips_from_temperature_density() {
        let model = water_model();

        let state = water_state();
        let pressure = model.pressure(&state).unwrap();
        let entropy = model.entropy(&state).unwrap();
        let roundtrip = model.state_from((Water, pressure, entropy)).unwrap();

        assert_relative_eq!(
            roundtrip.temperature.get::<kelvin>(),
            state.temperature.get::<kelvin>(),
            max_relative = 1e-9
        );
        assert_relative_eq!(
            roundtrip.density.get::<kilogram_per_cubic_meter>(),
            state.density.get::<kilogram_per_cubic_meter>(),
            max_relative = 1e-9
        );
    }

    #[test]
    fn water_state_from_enthalpy_entropy_roundtrips_from_temperature_density() {
        let model = water_model();

        let state = water_state();
        let enthalpy = model.enthalpy(&state).unwrap();
        let entropy = model.entropy(&state).unwrap();
        let roundtrip = model.state_from((Water, enthalpy, entropy)).unwrap();

        assert_relative_eq!(
            roundtrip.temperature.get::<kelvin>(),
            state.temperature.get::<kelvin>(),
            max_relative = 1e-9
        );
        assert_relative_eq!(
            roundtrip.density.get::<kilogram_per_cubic_meter>(),
            state.density.get::<kilogram_per_cubic_meter>(),
            max_relative = 1e-9
        );
    }
}