refprop-rs 0.3.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
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
//! Parallel REFPROP computation via isolated DLL instances.
//!
//! Available when the **`parallel`** Cargo feature is enabled.
//!
//! # How it works
//!
//! REFPROP (the Fortran DLL) maintains global internal state, which
//! makes it impossible to call from multiple threads simultaneously.
//! This module works around the limitation by **copying the shared
//! library N times** (one per CPU core by default) into a temporary
//! directory.  Each copy is loaded independently, giving it its own
//! Fortran global state.  A [`rayon`] thread pool then distributes
//! work across these isolated instances for true data-parallelism.
//!
//! Temporary DLL copies are cleaned up automatically when the
//! [`ParallelFluid`] is dropped.
//!
//! # Quick example
//!
//! ```no_run
//! use refprop::{ParallelFluid, UnitSystem};
//!
//! let pool = ParallelFluid::with_units("R134A", UnitSystem::engineering())?;
//!
//! // 10 000 (T, P) points computed in parallel across all CPU cores
//! let temps:  Vec<f64> = (0..10_000).map(|i| -20.0 + i as f64 * 0.01).collect();
//! let press:  Vec<f64> = vec![10.0; 10_000];
//! let densities = pool.par_get("D", "T", &temps, "P", &press)?;
//! # Ok::<(), refprop::RefpropError>(())
//! ```

use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};

use rayon::prelude::*;

use crate::backend::refprop::RefpropBackend;
use crate::converter::{Converter, UnitSystem};
use crate::error::*;
use crate::fluid::Fluid;
use crate::properties::*;
use crate::sys::find_dll_in_dir;
use crate::traits::FluidApi;

// ── Helper: copy the shared library with a unique name ──────────────

fn copy_dll(original: &Path, dest_dir: &Path, index: usize) -> Result<PathBuf> {
    let stem = original
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("refprop");
    let ext = original
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("");

    let new_name = if ext.is_empty() {
        format!("{stem}_{index}")
    } else {
        format!("{stem}_{index}.{ext}")
    };

    let dest = dest_dir.join(new_name);
    fs::copy(original, &dest).map_err(|e| {
        RefpropError::CalculationFailed(format!(
            "Failed to copy REFPROP library to {}: {e}",
            dest.display()
        ))
    })?;
    Ok(dest)
}

// ── ParallelFluid ───────────────────────────────────────────────────

/// A pool of **isolated REFPROP DLL instances** for parallel
/// thermodynamic computations.
///
/// Each worker owns a private copy of the shared library with
/// independent Fortran global state, enabling lock-free parallel
/// execution via [`rayon`].
///
/// # Platform support
///
/// | OS      | Library names tried                              |
/// |---------|--------------------------------------------------|
/// | Windows | `REFPRP64.DLL`, `REFPROP.DLL`, `refprop.dll`    |
/// | Linux   | `librefprop.so`, `libREFPROP.so`                 |
/// | macOS   | `librefprop.dylib`, `libREFPROP.dylib`           |
///
/// The number of copies defaults to [`num_cpus::get()`] but can be
/// overridden with [`with_units_and_workers`](Self::with_units_and_workers).
pub struct ParallelFluid {
    workers: Vec<Mutex<RefpropBackend>>,
    conv: Converter,
    temp_dir: PathBuf,
    n_workers: usize,
}

impl ParallelFluid {
    // ================================================================
    //  Constructors
    // ================================================================

    /// Create a parallel pool for a **pure fluid or predefined mixture**
    /// using **REFPROP-native units** (K, kPa, mol/L, J/mol).
    ///
    /// The number of workers equals the number of logical CPU cores.
    pub fn new(fluid_name: &str) -> Result<Self> {
        Self::with_units(fluid_name, UnitSystem::refprop())
    }

    /// Create a parallel pool with a **custom unit system**.
    ///
    /// Workers = logical CPU cores.
    pub fn with_units(fluid_name: &str, units: UnitSystem) -> Result<Self> {
        let n = num_cpus::get().max(1);
        Self::with_units_and_workers(fluid_name, units, n)
    }

    /// Create a parallel pool with an explicit worker count.
    pub fn with_workers(fluid_name: &str, n_workers: usize) -> Result<Self> {
        Self::with_units_and_workers(fluid_name, UnitSystem::refprop(), n_workers)
    }

    /// Create a parallel pool with a **custom unit system** and an
    /// explicit number of workers.
    pub fn with_units_and_workers(
        fluid_name: &str,
        units: UnitSystem,
        n_workers: usize,
    ) -> Result<Self> {
        let n_workers = n_workers.max(1);
        Fluid::load_dotenv();
        let refprop_path = Fluid::find_refprop_path()?;
        let data_dir = Path::new(&refprop_path);

        let original_dll = find_dll_in_dir(data_dir).ok_or_else(|| {
            RefpropError::LibraryNotFound(format!(
                "No REFPROP shared library found in {}",
                data_dir.display()
            ))
        })?;

        let temp_dir = Self::create_temp_dir()?;
        let mut workers = Vec::with_capacity(n_workers);

        for i in 0..n_workers {
            let dll_copy = copy_dll(&original_dll, &temp_dir, i)?;
            let backend =
                RefpropBackend::new_isolated(fluid_name, &refprop_path, &dll_copy)?;
            workers.push(Mutex::new(backend));
        }

        let mm = workers[0]
            .lock()
            .map_err(|_| {
                RefpropError::CalculationFailed("Worker lock poisoned during init".into())
            })?
            .molar_mass_mix_direct();

        let conv = Converter::new(units, mm);

        Ok(Self {
            workers,
            conv,
            temp_dir,
            n_workers,
        })
    }

    /// Create a parallel pool for a **custom mixture**.
    pub fn mixture(components: &[(&str, f64)]) -> Result<Self> {
        Self::mixture_with_units(components, UnitSystem::refprop())
    }

    /// Create a parallel pool for a **custom mixture** with a custom
    /// unit system.  Workers = logical CPU cores.
    pub fn mixture_with_units(
        components: &[(&str, f64)],
        units: UnitSystem,
    ) -> Result<Self> {
        let n = num_cpus::get().max(1);
        Self::mixture_with_units_and_workers(components, units, n)
    }

    /// Create a parallel pool for a **custom mixture** with explicit
    /// unit system and worker count.
    pub fn mixture_with_units_and_workers(
        components: &[(&str, f64)],
        units: UnitSystem,
        n_workers: usize,
    ) -> Result<Self> {
        let n_workers = n_workers.max(1);
        Fluid::load_dotenv();
        let refprop_path = Fluid::find_refprop_path()?;
        let data_dir = Path::new(&refprop_path);

        let original_dll = find_dll_in_dir(data_dir).ok_or_else(|| {
            RefpropError::LibraryNotFound(format!(
                "No REFPROP shared library found in {}",
                data_dir.display()
            ))
        })?;

        let temp_dir = Self::create_temp_dir()?;
        let mut workers = Vec::with_capacity(n_workers);

        for i in 0..n_workers {
            let dll_copy = copy_dll(&original_dll, &temp_dir, i)?;
            let backend = RefpropBackend::new_mixture_isolated(
                components,
                &refprop_path,
                &dll_copy,
            )?;
            workers.push(Mutex::new(backend));
        }

        let mm = workers[0]
            .lock()
            .map_err(|_| {
                RefpropError::CalculationFailed("Worker lock poisoned during init".into())
            })?
            .molar_mass_mix_direct();

        let conv = Converter::new(units, mm);

        Ok(Self {
            workers,
            conv,
            temp_dir,
            n_workers,
        })
    }

    // ================================================================
    //  Info
    // ================================================================

    /// Number of parallel workers (DLL instances).
    pub fn worker_count(&self) -> usize {
        self.n_workers
    }

    /// Access the active unit converter.
    pub fn converter(&self) -> &Converter {
        &self.conv
    }

    // ================================================================
    //  Single-point API (convenience, uses worker 0)
    // ================================================================

    /// Generic single-point property lookup.
    pub fn get(
        &self,
        output: &str,
        key1: &str,
        val1: f64,
        key2: &str,
        val2: f64,
    ) -> Result<f64> {
        let v1 = self.conv.input_to_rp(key1, val1)?;
        let v2 = self.conv.input_to_rp(key2, val2)?;
        let guard = self.lock_worker(0)?;
        let raw = guard.get_direct(output, key1, v1, key2, v2)?;
        Ok(self.conv.output_from_rp(output, raw))
    }

    /// Single-point T-P flash.
    pub fn props_tp(&self, t: f64, p: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_tp_direct(self.conv.t_to_rp(t), self.conv.p_to_rp(p))?;
        Ok(self.convert_thermo(raw))
    }

    /// Single-point P-H flash.
    pub fn props_ph(&self, p: f64, h: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_ph_direct(self.conv.p_to_rp(p), self.conv.h_to_rp(h))?;
        Ok(self.convert_thermo(raw))
    }

    /// Single-point P-S flash.
    pub fn props_ps(&self, p: f64, s: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_ps_direct(self.conv.p_to_rp(p), self.conv.s_to_rp(s))?;
        Ok(self.convert_thermo(raw))
    }

    /// Single-point T-Q flash.
    pub fn props_tq(&self, t: f64, q: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_tq_direct(self.conv.t_to_rp(t), self.conv.q_to_rp(q)?)?;
        Ok(self.convert_thermo(raw))
    }

    /// Single-point P-Q flash.
    pub fn props_pq(&self, p: f64, q: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_pq_direct(self.conv.p_to_rp(p), self.conv.q_to_rp(q)?)?;
        Ok(self.convert_thermo(raw))
    }

    /// Temperature–density flash.
    pub fn props_td(&self, t: f64, d: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_td_direct(self.conv.t_to_rp(t), self.conv.d_to_rp(d))?;
        Ok(self.convert_thermo(raw))
    }

    /// Temperature–enthalpy flash.
    pub fn props_th(&self, t: f64, h: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_th_direct(self.conv.t_to_rp(t), self.conv.h_to_rp(h))?;
        Ok(self.convert_thermo(raw))
    }

    /// Temperature–entropy flash.
    pub fn props_ts(&self, t: f64, s: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_ts_direct(self.conv.t_to_rp(t), self.conv.s_to_rp(s))?;
        Ok(self.convert_thermo(raw))
    }

    /// Pressure–density flash.
    pub fn props_pd(&self, p: f64, d: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_pd_direct(self.conv.p_to_rp(p), self.conv.d_to_rp(d))?;
        Ok(self.convert_thermo(raw))
    }

    /// Density–enthalpy flash.
    pub fn props_dh(&self, d: f64, h: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_dh_direct(self.conv.d_to_rp(d), self.conv.h_to_rp(h))?;
        Ok(self.convert_thermo(raw))
    }

    /// Density–entropy flash.
    pub fn props_ds(&self, d: f64, s: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_ds_direct(self.conv.d_to_rp(d), self.conv.s_to_rp(s))?;
        Ok(self.convert_thermo(raw))
    }

    /// Enthalpy–entropy flash.
    pub fn props_hs(&self, h: f64, s: f64) -> Result<ThermoProp> {
        let guard = self.lock_worker(0)?;
        let raw = guard.props_hs_direct(self.conv.h_to_rp(h), self.conv.s_to_rp(s))?;
        Ok(self.convert_thermo(raw))
    }

    /// Saturation properties at a given pressure.
    pub fn saturation_p(&self, p: f64) -> Result<SaturationProps> {
        let guard = self.lock_worker(0)?;
        let raw = guard.saturation_p_direct(self.conv.p_to_rp(p))?;
        Ok(self.convert_sat(raw))
    }

    /// Saturation properties at a given temperature.
    pub fn saturation_t(&self, t: f64) -> Result<SaturationProps> {
        let guard = self.lock_worker(0)?;
        let raw = guard.saturation_t_direct(self.conv.t_to_rp(t))?;
        Ok(self.convert_sat(raw))
    }

    /// Transport properties at (T, D) — density must be in user units.
    pub fn transport(&self, t: f64, d: f64) -> Result<TransportProps> {
        let guard = self.lock_worker(0)?;
        let raw = guard.transport_direct(self.conv.t_to_rp(t), self.conv.d_to_rp(d))?;
        Ok(TransportProps {
            viscosity: self.conv.eta_from_rp(raw.viscosity),
            thermal_conductivity: self.conv.tcx_from_rp(raw.thermal_conductivity),
        })
    }

    /// Static fluid information (molar mass, triple point, …).
    ///
    /// **Note:** values in this struct are always in REFPROP-native
    /// units regardless of the configured `UnitSystem`, because they
    /// describe intrinsic fluid constants.
    pub fn info(&self) -> Result<FluidInfo> {
        let guard = self.lock_worker(0)?;
        Ok(guard.fluid_info_direct())
    }

    /// Critical point in user units.
    pub fn critical_point(&self) -> Result<CriticalProps> {
        let guard = self.lock_worker(0)?;
        let raw = guard.critical_point_direct()?;
        Ok(CriticalProps {
            temperature: self.conv.t_from_rp(raw.temperature),
            pressure: self.conv.p_from_rp(raw.pressure),
            density: self.conv.d_from_rp(raw.density),
        })
    }

    // ================================================================
    //  Parallel batch API
    // ================================================================

    /// Compute a single output property for many (key1, key2) input
    /// pairs **in parallel**.
    ///
    /// `vals1` and `vals2` must have the same length.  Each element
    /// pair is dispatched to a worker; results are returned in the
    /// same order as the inputs.
    ///
    /// ```no_run
    /// # use refprop::{ParallelFluid, UnitSystem};
    /// # let pool = ParallelFluid::with_units("R134A", UnitSystem::engineering())?;
    /// let temps  = vec![-20.0, -10.0, 0.0, 10.0, 20.0];
    /// let press  = vec![1.0;  5];
    /// let rho = pool.par_get("D", "T", &temps, "P", &press)?;
    /// # Ok::<(), refprop::RefpropError>(())
    /// ```
    pub fn par_get(
        &self,
        output: &str,
        key1: &str,
        vals1: &[f64],
        key2: &str,
        vals2: &[f64],
    ) -> Result<Vec<f64>> {
        if vals1.len() != vals2.len() {
            return Err(RefpropError::InvalidInput(format!(
                "vals1.len() ({}) != vals2.len() ({})",
                vals1.len(),
                vals2.len()
            )));
        }
        if vals1.is_empty() {
            return Ok(vec![]);
        }

        let inputs: Vec<(f64, f64)> = vals1.iter().copied().zip(vals2.iter().copied()).collect();
        let chunk_size = (inputs.len() + self.n_workers - 1) / self.n_workers;

        let results: Vec<Vec<Result<f64>>> = inputs
            .chunks(chunk_size)
            .enumerate()
            .collect::<Vec<_>>()
            .into_par_iter()
            .map(|(worker_idx, chunk)| {
                let guard = self.workers[worker_idx].lock().unwrap();
                chunk
                    .iter()
                    .map(|(v1, v2)| {
                        let v1_rp = self.conv.input_to_rp(key1, *v1)?;
                        let v2_rp = self.conv.input_to_rp(key2, *v2)?;
                        let raw = guard.get_direct(output, key1, v1_rp, key2, v2_rp)?;
                        Ok(self.conv.output_from_rp(output, raw))
                    })
                    .collect()
            })
            .collect();

        results.into_iter().flatten().collect()
    }

    /// Parallel T-P flash for many (T, P) pairs.
    pub fn par_props_tp(&self, inputs: &[(f64, f64)]) -> Vec<Result<ThermoProp>> {
        self.par_flash(inputs, |guard, t, p| {
            guard
                .props_tp_direct(self.conv.t_to_rp(t), self.conv.p_to_rp(p))
                .map(|raw| self.convert_thermo(raw))
        })
    }

    /// Parallel P-H flash for many (P, H) pairs.
    pub fn par_props_ph(&self, inputs: &[(f64, f64)]) -> Vec<Result<ThermoProp>> {
        self.par_flash(inputs, |guard, p, h| {
            guard
                .props_ph_direct(self.conv.p_to_rp(p), self.conv.h_to_rp(h))
                .map(|raw| self.convert_thermo(raw))
        })
    }

    /// Parallel P-S flash for many (P, S) pairs.
    pub fn par_props_ps(&self, inputs: &[(f64, f64)]) -> Vec<Result<ThermoProp>> {
        self.par_flash(inputs, |guard, p, s| {
            guard
                .props_ps_direct(self.conv.p_to_rp(p), self.conv.s_to_rp(s))
                .map(|raw| self.convert_thermo(raw))
        })
    }

    /// Parallel T-Q flash for many (T, Q) pairs.
    pub fn par_props_tq(&self, inputs: &[(f64, f64)]) -> Vec<Result<ThermoProp>> {
        self.par_flash(inputs, |guard, t, q| {
            let q_rp = self.conv.q_to_rp(q)?;
            guard
                .props_tq_direct(self.conv.t_to_rp(t), q_rp)
                .map(|raw| self.convert_thermo(raw))
        })
    }

    /// Parallel P-Q flash for many (P, Q) pairs.
    pub fn par_props_pq(&self, inputs: &[(f64, f64)]) -> Vec<Result<ThermoProp>> {
        self.par_flash(inputs, |guard, p, q| {
            let q_rp = self.conv.q_to_rp(q)?;
            guard
                .props_pq_direct(self.conv.p_to_rp(p), q_rp)
                .map(|raw| self.convert_thermo(raw))
        })
    }

    // ================================================================
    //  Internal helpers
    // ================================================================

    fn lock_worker(
        &self,
        idx: usize,
    ) -> Result<std::sync::MutexGuard<'_, RefpropBackend>> {
        self.workers[idx].lock().map_err(|_| {
            RefpropError::CalculationFailed("Worker lock poisoned".into())
        })
    }

    fn create_temp_dir() -> Result<PathBuf> {
        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!(
            "refprop_pool_{}_{ts}",
            std::process::id()
        ));
        fs::create_dir_all(&dir).map_err(|e| {
            RefpropError::CalculationFailed(format!(
                "Failed to create temp directory {}: {e}",
                dir.display()
            ))
        })?;
        Ok(dir)
    }

    /// Generic parallel flash dispatcher.
    ///
    /// Partitions `inputs` into chunks (one per worker), then applies
    /// `compute` in parallel via rayon.  Unit conversion is the
    /// responsibility of the caller's closure.
    fn par_flash<F>(&self, inputs: &[(f64, f64)], compute: F) -> Vec<Result<ThermoProp>>
    where
        F: Fn(&RefpropBackend, f64, f64) -> Result<ThermoProp> + Sync,
    {
        if inputs.is_empty() {
            return vec![];
        }

        let chunk_size = (inputs.len() + self.n_workers - 1) / self.n_workers;

        inputs
            .chunks(chunk_size)
            .enumerate()
            .collect::<Vec<_>>()
            .into_par_iter()
            .map(|(worker_idx, chunk)| {
                let guard = self.workers[worker_idx].lock().unwrap();
                chunk
                    .iter()
                    .map(|(a, b)| compute(&guard, *a, *b))
                    .collect::<Vec<_>>()
            })
            .flatten()
            .collect()
    }

    fn convert_sat(&self, raw: SaturationProps) -> SaturationProps {
        SaturationProps {
            temperature: self.conv.t_from_rp(raw.temperature),
            pressure: self.conv.p_from_rp(raw.pressure),
            density_liquid: self.conv.d_from_rp(raw.density_liquid),
            density_vapor: self.conv.d_from_rp(raw.density_vapor),
        }
    }

    fn convert_thermo(&self, raw: ThermoProp) -> ThermoProp {
        ThermoProp {
            temperature: self.conv.t_from_rp(raw.temperature),
            pressure: self.conv.p_from_rp(raw.pressure),
            density: self.conv.d_from_rp(raw.density),
            enthalpy: self.conv.h_from_rp(raw.enthalpy),
            entropy: self.conv.s_from_rp(raw.entropy),
            cv: self.conv.s_from_rp(raw.cv),
            cp: self.conv.s_from_rp(raw.cp),
            sound_speed: raw.sound_speed,
            quality: self.conv.q_from_rp(raw.quality),
            internal_energy: self.conv.h_from_rp(raw.internal_energy),
        }
    }
}

// ── FluidApi trait implementation ────────────────────────────────────

impl FluidApi for ParallelFluid {
    fn get(&self, output: &str, key1: &str, val1: f64, key2: &str, val2: f64) -> Result<f64> {
        self.get(output, key1, val1, key2, val2)
    }

    fn props_tp(&self, t: f64, p: f64) -> Result<ThermoProp> { self.props_tp(t, p) }
    fn props_ph(&self, p: f64, h: f64) -> Result<ThermoProp> { self.props_ph(p, h) }
    fn props_ps(&self, p: f64, s: f64) -> Result<ThermoProp> { self.props_ps(p, s) }
    fn props_td(&self, t: f64, d: f64) -> Result<ThermoProp> { self.props_td(t, d) }
    fn props_th(&self, t: f64, h: f64) -> Result<ThermoProp> { self.props_th(t, h) }
    fn props_ts(&self, t: f64, s: f64) -> Result<ThermoProp> { self.props_ts(t, s) }
    fn props_pd(&self, p: f64, d: f64) -> Result<ThermoProp> { self.props_pd(p, d) }
    fn props_dh(&self, d: f64, h: f64) -> Result<ThermoProp> { self.props_dh(d, h) }
    fn props_ds(&self, d: f64, s: f64) -> Result<ThermoProp> { self.props_ds(d, s) }
    fn props_hs(&self, h: f64, s: f64) -> Result<ThermoProp> { self.props_hs(h, s) }
    fn props_tq(&self, t: f64, q: f64) -> Result<ThermoProp> { self.props_tq(t, q) }
    fn props_pq(&self, p: f64, q: f64) -> Result<ThermoProp> { self.props_pq(p, q) }

    fn saturation_p(&self, p: f64) -> Result<SaturationProps> { self.saturation_p(p) }
    fn saturation_t(&self, t: f64) -> Result<SaturationProps> { self.saturation_t(t) }

    fn transport(&self, t: f64, d: f64) -> Result<TransportProps> { self.transport(t, d) }

    fn critical_point(&self) -> Result<CriticalProps> { self.critical_point() }
    fn info(&self) -> Result<FluidInfo> { self.info() }

    fn converter(&self) -> &Converter { self.converter() }
}

impl Drop for ParallelFluid {
    fn drop(&mut self) {
        // Release all DLL handles before deleting the files.
        self.workers.clear();
        let _ = fs::remove_dir_all(&self.temp_dir);
    }
}