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
use std::collections::HashMap;
use super::Pure;
use crate::{
fluid::backend::DefaultBackend, io::FluidTrivialParam::MolarMass, native::AbstractState,
};
/// `CoolProp` custom mixture.
///
/// # See Also
///
/// - [Custom Mixtures](https://coolprop.org/fluid_properties/Mixtures.html)
#[derive(Clone, Debug, PartialEq)]
pub enum CustomMix {
/// Mole-based mixture _(with mole fractions)_.
#[non_exhaustive]
MoleBased(HashMap<Pure, f64>),
/// Mass-based mixture _(with mass fractions)_.
#[non_exhaustive]
MassBased(HashMap<Pure, f64>),
}
impl CustomMix {
/// Creates and returns a new [`CustomMix::MoleBased`] instance.
///
/// # Arguments
///
/// - `components` -- any type convertible into a hash map of components and their _mole_
/// fractions **\[dimensionless, from 0 to 1\]**
///
/// # Errors
///
/// Returns a [`CustomMixError`] for invalid inputs.
///
/// # Examples
///
/// ```
/// use rfluids::prelude::*;
///
/// let mole_based = CustomMix::mole_based([(Pure::Water, 0.8), (Pure::Ethanol, 0.2)]);
/// assert!(mole_based.is_ok());
/// ```
pub fn mole_based(components: impl Into<HashMap<Pure, f64>>) -> Result<Self, CustomMixError> {
let components = components.into();
Self::validate(&components)?;
Ok(Self::MoleBased(components))
}
/// Creates and returns a new [`CustomMix::MassBased`] instance.
///
/// # Arguments
///
/// - `components` -- any type convertible into a hash map of components and their _mass_
/// fractions **\[dimensionless, from 0 to 1\]**
///
/// # Errors
///
/// Returns a [`CustomMixError`] for invalid inputs.
///
/// # Examples
///
/// ```
/// use rfluids::prelude::*;
///
/// let mass_based = CustomMix::mass_based([(Pure::Water, 0.6), (Pure::Ethanol, 0.4)]);
/// assert!(mass_based.is_ok());
/// ```
pub fn mass_based(components: impl Into<HashMap<Pure, f64>>) -> Result<Self, CustomMixError> {
let components = components.into();
Self::validate(&components)?;
Ok(Self::MassBased(components))
}
/// Convert to [`CustomMix::MoleBased`] _(mass fractions will be converted to mole fractions)_.
///
/// # Examples
///
/// ```
/// use rfluids::prelude::*;
///
/// let mole_based = CustomMix::mole_based([(Pure::Water, 0.8), (Pure::Ethanol, 0.2)])?;
/// assert_eq!(mole_based.clone().into_mole_based(), mole_based);
///
/// let mass_based = CustomMix::mass_based([(Pure::R32, 0.5), (Pure::R125, 0.5)])?;
/// assert_ne!(mass_based.clone().into_mole_based(), mass_based);
/// # Ok::<(), rfluids::Error>(())
/// ```
#[must_use]
pub fn into_mole_based(self) -> Self {
match self {
CustomMix::MassBased(c) => {
let mut components = c;
let mut sum = 0.0;
for component in &mut components {
*component.1 /= Self::molar_mass(*component.0);
sum += *component.1;
}
for component in &mut components {
*component.1 /= sum;
}
Self::MoleBased(HashMap::from_iter(components))
}
CustomMix::MoleBased(_) => self,
}
}
/// Specified components and their fractions.
#[must_use]
pub fn components(&self) -> &HashMap<Pure, f64> {
match self {
CustomMix::MoleBased(components) | CustomMix::MassBased(components) => components,
}
}
fn validate(components: &HashMap<Pure, f64>) -> Result<(), CustomMixError> {
if components.len() < 2 {
return Err(CustomMixError::NotEnoughComponents);
}
if components.values().any(|f| !(0.0..=1.0).contains(f)) {
return Err(CustomMixError::InvalidFraction);
}
if (components.values().sum::<f64>() - 1.0).abs() > 1e-6 {
return Err(CustomMixError::InvalidFractionsSum);
}
Ok(())
}
fn molar_mass(component: Pure) -> f64 {
AbstractState::new(component.default_backend().name(), component.as_ref())
.unwrap()
.keyed_output(MolarMass)
.unwrap()
}
}
/// Error during creation of [`CustomMix`].
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum CustomMixError {
/// The specified components are not enough.
#[error("At least 2 unique components must be provided!")]
NotEnoughComponents,
/// Some of the specified fractions are invalid.
#[error("All of the specified fractions must be exclusive between 0 and 1!")]
InvalidFraction,
/// The sum of the specified fractions is invalid.
#[error("The sum of the specified fractions must be equal to 1!")]
InvalidFractionsSum,
}
#[cfg(test)]
mod tests {
use approx::relative_eq;
use rstest::*;
use super::*;
#[rstest]
#[case([(Pure::Water, 0.6), (Pure::Ethanol, 0.4)])]
#[case([(Pure::R32, 0.5), (Pure::R125, 0.5)])]
fn new_valid_components(#[case] components: impl Into<HashMap<Pure, f64>> + Clone) {
// When
let res1 = CustomMix::mole_based(components.clone());
let res2 = CustomMix::mass_based(components);
// Then
assert!(res1.is_ok());
assert!(res2.is_ok());
}
#[rstest]
#[case([(Pure::Water, 0.6)], CustomMixError::NotEnoughComponents)]
#[case(
[(Pure::Water, 0.5), (Pure::Water, 0.5)],
CustomMixError::NotEnoughComponents
)]
#[case(
[(Pure::R32, -0.5), (Pure::R125, 0.5)],
CustomMixError::InvalidFraction
)]
#[case(
[(Pure::R32, 1.5), (Pure::R125, 0.5)],
CustomMixError::InvalidFraction
)]
#[case(
[(Pure::R32, 0.4), (Pure::R125, 0.4)],
CustomMixError::InvalidFractionsSum
)]
fn new_invalid_components(
#[case] components: impl Into<HashMap<Pure, f64>> + Clone,
#[case] expected: CustomMixError,
) {
// When
let res1 = CustomMix::mole_based(components.clone());
let res2 = CustomMix::mass_based(components);
// Then
assert_eq!(res1, Err(expected.clone()));
assert_eq!(res2, Err(expected));
}
#[test]
fn into_mole_based_from_mole_based() {
// Given
let sut = CustomMix::mole_based([(Pure::Water, 0.8), (Pure::Ethanol, 0.2)]).unwrap();
// When
let res = sut.clone().into_mole_based();
// Then
assert_eq!(res, sut);
assert!(matches(&res, [("Water", 0.8), ("Ethanol", 0.2)]));
}
#[test]
fn into_mole_based_from_mass_based() {
// Given
let sut = CustomMix::mass_based([(Pure::R32, 0.5), (Pure::R125, 0.5)]).unwrap();
// When
let res = sut.clone().into_mole_based();
// Then
assert_ne!(res, sut);
assert!(matches(&sut, [("R32", 0.5), ("R125", 0.5)]));
assert!(matches(
&res,
[("R32", 0.697_614_699_375_862_4), ("R125", 0.302_385_300_624_137_54)]
));
}
fn matches(mix: &CustomMix, expected: [(&str, f64); 2]) -> bool {
mix.components().len() == expected.len()
&& mix
.components()
.iter()
.filter(|component| {
expected.iter().any(|exp| {
component.0.as_ref() == exp.0 && relative_eq!(*component.1, exp.1)
})
})
.count()
== expected.len()
}
}