refprop-rs 0.2.1

Safe Rust bindings for NIST REFPROP – thermodynamic & transport properties of refrigerants, pure fluids, and mixtures
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
//! Configurable unit conversion for REFPROP values.
//!
//! REFPROP internally uses: **K, kPa, mol/L, J/mol, J/(mol·K), µPa·s,
//! W/(m·K), m/s**.  This module lets you work in whatever units you
//! prefer (°C, bar, kg/m³, kJ/kg, …) and handles the conversion
//! transparently.
//!
//! # Presets
//!
//! | Preset          | T   | P   | D     | H      | S         |
//! |-----------------|-----|-----|-------|--------|-----------|
//! | `refprop()`     | K   | kPa | mol/L | J/mol  | J/(mol·K) |
//! | `engineering()` | °C  | bar | kg/m³ | kJ/kg  | kJ/(kg·K) |
//! | `si()`          | K   | Pa  | kg/m³ | J/kg   | J/(kg·K)  |
//!
//! # Builder
//!
//! ```
//! use refprop::{UnitSystem, TempUnit, PressUnit};
//!
//! let units = UnitSystem::new()
//!     .temperature(TempUnit::Celsius)
//!     .pressure(PressUnit::Bar);
//! ```

use serde::{Deserialize, Serialize};

use crate::error::{RefpropError, Result};

// ────────────────────────────────────────────────────────────────────
//  Unit enums
// ────────────────────────────────────────────────────────────────────

/// Temperature unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TempUnit {
    /// Kelvin (REFPROP native)
    Kelvin,
    /// Degrees Celsius
    Celsius,
    /// Degrees Fahrenheit
    Fahrenheit,
}

/// Pressure unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PressUnit {
    /// Kilopascal (REFPROP native)
    KPa,
    /// Bar (1 bar = 100 kPa)
    Bar,
    /// Megapascal
    MPa,
    /// Pascal
    Pa,
    /// Standard atmosphere (101.325 kPa)
    Atm,
    /// Pounds per square inch
    Psi,
}

/// Density unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DensityUnit {
    /// mol/L (REFPROP native)
    MolPerL,
    /// kg/m³ (requires molar mass)
    KgPerM3,
}

/// Energy / enthalpy unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EnergyUnit {
    /// J/mol (REFPROP native)
    JPerMol,
    /// kJ/kg (requires molar mass)
    KJPerKg,
    /// J/kg (requires molar mass)
    JPerKg,
}

/// Entropy / heat-capacity unit (energy per temperature).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EntropyUnit {
    /// J/(mol·K) (REFPROP native)
    JPerMolK,
    /// kJ/(kg·K) (requires molar mass)
    KJPerKgK,
    /// J/(kg·K) (requires molar mass)
    JPerKgK,
}

/// Dynamic viscosity unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ViscosityUnit {
    /// µPa·s (REFPROP native)
    MicroPaS,
    /// mPa·s (= centipoise)
    MilliPaS,
    /// Pa·s
    PaS,
}

/// Thermal conductivity unit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConductivityUnit {
    /// W/(m·K) (REFPROP native)
    WPerMK,
    /// mW/(m·K)
    MilliWPerMK,
}

// ────────────────────────────────────────────────────────────────────
//  UnitSystem — user configuration (no molar mass needed yet)
// ────────────────────────────────────────────────────────────────────

/// Describes the set of units the user wants to work in.
///
/// Create one with a preset (`refprop()`, `engineering()`, `si()`) or
/// customise individual properties with the builder methods.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnitSystem {
    pub temperature: TempUnit,
    pub pressure: PressUnit,
    pub density: DensityUnit,
    pub energy: EnergyUnit,
    pub entropy: EntropyUnit,
    pub viscosity: ViscosityUnit,
    pub conductivity: ConductivityUnit,
}

impl UnitSystem {
    /// Start from REFPROP-native units.  Use the builder methods to
    /// change individual properties.
    pub fn new() -> Self {
        Self::refprop()
    }

    // ── Presets ──────────────────────────────────────────────────────

    /// REFPROP native: K, kPa, mol/L, J/mol, J/(mol·K), µPa·s, W/(m·K).
    pub fn refprop() -> Self {
        Self {
            temperature: TempUnit::Kelvin,
            pressure: PressUnit::KPa,
            density: DensityUnit::MolPerL,
            energy: EnergyUnit::JPerMol,
            entropy: EntropyUnit::JPerMolK,
            viscosity: ViscosityUnit::MicroPaS,
            conductivity: ConductivityUnit::WPerMK,
        }
    }

    /// Engineering / HVAC: °C, bar, kg/m³, kJ/kg, kJ/(kg·K).
    pub fn engineering() -> Self {
        Self {
            temperature: TempUnit::Celsius,
            pressure: PressUnit::Bar,
            density: DensityUnit::KgPerM3,
            energy: EnergyUnit::KJPerKg,
            entropy: EntropyUnit::KJPerKgK,
            viscosity: ViscosityUnit::MicroPaS,
            conductivity: ConductivityUnit::WPerMK,
        }
    }

    /// Strict SI: K, Pa, kg/m³, J/kg, J/(kg·K), Pa·s.
    pub fn si() -> Self {
        Self {
            temperature: TempUnit::Kelvin,
            pressure: PressUnit::Pa,
            density: DensityUnit::KgPerM3,
            energy: EnergyUnit::JPerKg,
            entropy: EntropyUnit::JPerKgK,
            viscosity: ViscosityUnit::PaS,
            conductivity: ConductivityUnit::WPerMK,
        }
    }

    // ── Builder methods ─────────────────────────────────────────────

    pub fn temperature(mut self, u: TempUnit) -> Self {
        self.temperature = u;
        self
    }
    pub fn pressure(mut self, u: PressUnit) -> Self {
        self.pressure = u;
        self
    }
    pub fn density(mut self, u: DensityUnit) -> Self {
        self.density = u;
        self
    }
    pub fn energy(mut self, u: EnergyUnit) -> Self {
        self.energy = u;
        self
    }
    pub fn entropy(mut self, u: EntropyUnit) -> Self {
        self.entropy = u;
        self
    }
    pub fn viscosity(mut self, u: ViscosityUnit) -> Self {
        self.viscosity = u;
        self
    }
    pub fn conductivity(mut self, u: ConductivityUnit) -> Self {
        self.conductivity = u;
        self
    }
}

impl Default for UnitSystem {
    fn default() -> Self {
        Self::refprop()
    }
}

// ────────────────────────────────────────────────────────────────────
//  Converter — UnitSystem + molar mass → ready to convert
// ────────────────────────────────────────────────────────────────────

/// Performs conversions between user units and REFPROP internal units.
///
/// Created by combining a [`UnitSystem`] with the fluid's molar mass
/// (needed for mol ↔ kg conversions).
#[derive(Debug, Clone)]
pub struct Converter {
    pub units: UnitSystem,
    /// Molar mass in g/mol (mixture-averaged for mixtures).
    pub molar_mass: f64,
}

impl Converter {
    pub fn new(units: UnitSystem, molar_mass: f64) -> Self {
        Self { units, molar_mass }
    }

    /// Identity converter — no conversion at all (REFPROP native units,
    /// molar mass = 1 so mass-based formulas still work formally).
    pub fn identity() -> Self {
        Self {
            units: UnitSystem::refprop(),
            molar_mass: 1.0,
        }
    }

    // ── Temperature ─────────────────────────────────────────────────

    /// User → REFPROP (K)
    pub fn t_to_rp(&self, t: f64) -> f64 {
        match self.units.temperature {
            TempUnit::Kelvin => t,
            TempUnit::Celsius => t + 273.15,
            TempUnit::Fahrenheit => (t - 32.0) * 5.0 / 9.0 + 273.15,
        }
    }

    /// REFPROP (K) → User
    pub fn t_from_rp(&self, t: f64) -> f64 {
        match self.units.temperature {
            TempUnit::Kelvin => t,
            TempUnit::Celsius => t - 273.15,
            TempUnit::Fahrenheit => (t - 273.15) * 9.0 / 5.0 + 32.0,
        }
    }

    // ── Pressure ────────────────────────────────────────────────────

    /// User → REFPROP (kPa)
    pub fn p_to_rp(&self, p: f64) -> f64 {
        match self.units.pressure {
            PressUnit::KPa => p,
            PressUnit::Bar => p * 100.0,
            PressUnit::MPa => p * 1000.0,
            PressUnit::Pa => p / 1000.0,
            PressUnit::Atm => p * 101.325,
            PressUnit::Psi => p * 6.894_757,
        }
    }

    /// REFPROP (kPa) → User
    pub fn p_from_rp(&self, p: f64) -> f64 {
        match self.units.pressure {
            PressUnit::KPa => p,
            PressUnit::Bar => p / 100.0,
            PressUnit::MPa => p / 1000.0,
            PressUnit::Pa => p * 1000.0,
            PressUnit::Atm => p / 101.325,
            PressUnit::Psi => p / 6.894_757,
        }
    }

    // ── Density ─────────────────────────────────────────────────────

    /// User → REFPROP (mol/L)
    pub fn d_to_rp(&self, d: f64) -> f64 {
        match self.units.density {
            DensityUnit::MolPerL => d,
            DensityUnit::KgPerM3 => d / self.molar_mass,
        }
    }

    /// REFPROP (mol/L) → User
    pub fn d_from_rp(&self, d: f64) -> f64 {
        match self.units.density {
            DensityUnit::MolPerL => d,
            DensityUnit::KgPerM3 => d * self.molar_mass,
        }
    }

    // ── Energy / Enthalpy / Internal energy ─────────────────────────

    /// User → REFPROP (J/mol)
    pub fn h_to_rp(&self, h: f64) -> f64 {
        match self.units.energy {
            EnergyUnit::JPerMol => h,
            EnergyUnit::KJPerKg => h * self.molar_mass,
            EnergyUnit::JPerKg => h * self.molar_mass / 1000.0,
        }
    }

    /// REFPROP (J/mol) → User
    pub fn h_from_rp(&self, h: f64) -> f64 {
        match self.units.energy {
            EnergyUnit::JPerMol => h,
            EnergyUnit::KJPerKg => h / self.molar_mass,
            EnergyUnit::JPerKg => h * 1000.0 / self.molar_mass,
        }
    }

    // ── Entropy / Cv / Cp ───────────────────────────────────────────

    /// User → REFPROP (J/(mol·K))
    pub fn s_to_rp(&self, s: f64) -> f64 {
        match self.units.entropy {
            EntropyUnit::JPerMolK => s,
            EntropyUnit::KJPerKgK => s * self.molar_mass,
            EntropyUnit::JPerKgK => s * self.molar_mass / 1000.0,
        }
    }

    /// REFPROP (J/(mol·K)) → User
    pub fn s_from_rp(&self, s: f64) -> f64 {
        match self.units.entropy {
            EntropyUnit::JPerMolK => s,
            EntropyUnit::KJPerKgK => s / self.molar_mass,
            EntropyUnit::JPerKgK => s * 1000.0 / self.molar_mass,
        }
    }

    // ── Viscosity ───────────────────────────────────────────────────

    /// REFPROP (µPa·s) → User
    pub fn eta_from_rp(&self, eta: f64) -> f64 {
        match self.units.viscosity {
            ViscosityUnit::MicroPaS => eta,
            ViscosityUnit::MilliPaS => eta / 1000.0,
            ViscosityUnit::PaS => eta / 1_000_000.0,
        }
    }

    /// User → REFPROP (µPa·s)
    pub fn eta_to_rp(&self, eta: f64) -> f64 {
        match self.units.viscosity {
            ViscosityUnit::MicroPaS => eta,
            ViscosityUnit::MilliPaS => eta * 1000.0,
            ViscosityUnit::PaS => eta * 1_000_000.0,
        }
    }

    // ── Thermal conductivity ────────────────────────────────────────

    /// REFPROP (W/(m·K)) → User
    pub fn tcx_from_rp(&self, tcx: f64) -> f64 {
        match self.units.conductivity {
            ConductivityUnit::WPerMK => tcx,
            ConductivityUnit::MilliWPerMK => tcx * 1000.0,
        }
    }

    /// User → REFPROP (W/(m·K))
    pub fn tcx_to_rp(&self, tcx: f64) -> f64 {
        match self.units.conductivity {
            ConductivityUnit::WPerMK => tcx,
            ConductivityUnit::MilliWPerMK => tcx / 1000.0,
        }
    }

    // ── Quality (vapour fraction) ────────────────────────────────────

    /// User (0–100 %) → REFPROP (0–1 molar fraction).
    ///
    /// Returns [`InvalidInput`](RefpropError::InvalidInput) when `q`
    /// is outside the 0–100 range.
    pub fn q_to_rp(&self, q: f64) -> Result<f64> {
        if q < 0.0 || q > 100.0 {
            return Err(RefpropError::InvalidInput(format!(
                "Quality Q must be between 0 and 100 (got {q})"
            )));
        }
        Ok(q / 100.0)
    }

    /// REFPROP (0–1 molar fraction) → User (0–100 %).
    pub fn q_from_rp(&self, q: f64) -> f64 {
        q * 100.0
    }

    // ── Generic key-based conversion ────────────────────────────────

    /// Convert a user-provided input value to REFPROP units, choosing
    /// the right conversion based on the property key (e.g. `"T"`,
    /// `"P"`, `"H"`, …).
    ///
    /// Quality `"Q"` is expected in **percent** (0–100) and is converted
    /// to the REFPROP molar fraction (0–1).  Values outside 0–100 yield
    /// an [`InvalidInput`](RefpropError::InvalidInput) error.
    pub fn input_to_rp(&self, key: &str, val: f64) -> Result<f64> {
        match key.to_uppercase().as_str() {
            "T" => Ok(self.t_to_rp(val)),
            "P" => Ok(self.p_to_rp(val)),
            "D" | "RHO" => Ok(self.d_to_rp(val)),
            "H" => Ok(self.h_to_rp(val)),
            "S" => Ok(self.s_to_rp(val)),
            "E" | "U" => Ok(self.h_to_rp(val)),
            "CV" | "CP" => Ok(self.s_to_rp(val)),
            "ETA" | "V" | "VIS" => Ok(self.eta_to_rp(val)),
            "TCX" | "L" | "LAMBDA" => Ok(self.tcx_to_rp(val)),
            "Q" => self.q_to_rp(val),
            _ => Ok(val), // W, etc.
        }
    }

    /// Convert a REFPROP output value to user units.
    ///
    /// Quality `"Q"` is returned in **percent** (0–100), converted from
    /// the REFPROP molar fraction (0–1).
    pub fn output_from_rp(&self, key: &str, val: f64) -> f64 {
        match key.to_uppercase().as_str() {
            "T" => self.t_from_rp(val),
            "P" => self.p_from_rp(val),
            "D" | "RHO" => self.d_from_rp(val),
            "H" => self.h_from_rp(val),
            "S" => self.s_from_rp(val),
            "E" | "U" => self.h_from_rp(val),
            "CV" | "CP" => self.s_from_rp(val),
            "ETA" | "V" | "VIS" => self.eta_from_rp(val),
            "TCX" | "L" | "LAMBDA" => self.tcx_from_rp(val),
            "Q" => self.q_from_rp(val),
            _ => val, // W, etc.
        }
    }
}