-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathuser_defined.rs
More file actions
254 lines (231 loc) · 8.24 KB
/
user_defined.rs
File metadata and controls
254 lines (231 loc) · 8.24 KB
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
use crate::{EquationOfState, HelmholtzEnergy, HelmholtzEnergyDual, MolarWeight, StateHD};
use ndarray::Array1;
use num_dual::*;
use numpy::convert::IntoPyArray;
use numpy::{PyReadonlyArrayDyn, PyArray};
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use quantity::python::PySIArray1;
use quantity::si::{SIArray1};
use std::fmt;
struct PyHelmholtzEnergy(Py<PyAny>);
/// Struct containing pointer to Python Class that implements Helmholtz energy.
pub struct PyEoSObj {
obj: Py<PyAny>,
contributions: Vec<Box<dyn HelmholtzEnergy>>,
}
impl PyEoSObj {
pub fn new(obj: Py<PyAny>) -> PyResult<Self> {
Python::with_gil(|py| {
let attr = obj.as_ref(py).hasattr("components")?;
if !attr {
panic!("Python Class has to have a method 'components' with signature:\n\tdef signature(self) -> int")
}
let attr = obj.as_ref(py).hasattr("subset")?;
if !attr {
panic!("Python Class has to have a method 'subset' with signature:\n\tdef subset(self, component_list: List[int]) -> Self")
}
let attr = obj.as_ref(py).hasattr("molar_weight")?;
if !attr {
panic!("Python Class has to have a method 'molar_weight' with signature:\n\tdef molar_weight(self) -> SIArray1\nwhere the size of the returned array has to be 'components'.")
}
let attr = obj.as_ref(py).hasattr("max_density")?;
if !attr {
panic!("Python Class has to have a method 'max_density' with signature:\n\tdef max_density(self, moles: numpy.ndarray[float]) -> float\nwhere the size of the input array has to be 'components'.")
}
let attr = obj.as_ref(py).hasattr("helmholtz_energy")?;
if !attr {
panic!("{}", "Python Class has to have a method 'helmholtz_energy' with signature:\n\tdef helmholtz_energy(self, state: StateHD) -> HD\nwhere 'HD' has to be any of {{float, Dual64, HyperDual64, HyperDualDual64, Dual3Dual64, Dual3_64}}.")
}
Ok(Self {
obj: obj.clone(),
contributions: vec![Box::new(PyHelmholtzEnergy(obj))],
})
})
}
}
impl MolarWeight for PyEoSObj {
fn molar_weight(&self) -> SIArray1 {
Python::with_gil(|py| {
let py_result = self.obj.as_ref(py).call_method0("molar_weight").unwrap();
if py_result.get_type().name().unwrap() != "SIArray1" {
panic!(
"Expected an 'SIArray1' for the 'molar_weight' method return type, got {}",
py_result.get_type().name().unwrap()
);
}
py_result.extract::<PySIArray1>().unwrap().into()
})
}
}
impl EquationOfState for PyEoSObj {
fn components(&self) -> usize {
Python::with_gil(|py| {
let py_result = self.obj.as_ref(py).call_method0("components").unwrap();
if py_result.get_type().name().unwrap() != "int" {
panic!(
"Expected an integer for the components() method signature, got {}",
py_result.get_type().name().unwrap()
);
}
py_result.extract().unwrap()
})
}
fn subset(&self, component_list: &[usize]) -> Self {
Python::with_gil(|py| {
let py_result = self
.obj
.as_ref(py)
.call_method1("subset", (component_list.to_vec(),))
.unwrap();
Self::new(py_result.extract().unwrap()).unwrap()
})
}
fn compute_max_density(&self, moles: &Array1<f64>) -> f64 {
Python::with_gil(|py| {
let py_result = self
.obj
.as_ref(py)
.call_method1("max_density", (moles.to_owned().into_pyarray(py),))
.unwrap();
py_result.extract().unwrap()
})
}
fn residual(&self) -> &[Box<dyn HelmholtzEnergy>] {
&self.contributions
}
}
impl fmt::Display for PyHelmholtzEnergy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Custom")
}
}
macro_rules! state {
($py_state_id:ident, $py_hd_id:ident, $hd_ty:ty) => {
#[pyclass]
#[derive(Clone)]
pub struct $py_state_id(StateHD<$hd_ty>);
impl From<StateHD<$hd_ty>> for $py_state_id {
fn from(s: StateHD<$hd_ty>) -> Self {
Self(s)
}
}
#[pymethods]
impl $py_state_id {
#[new]
pub fn new(temperature: $py_hd_id, volume: $py_hd_id, moles: Vec<$py_hd_id>) -> Self {
let m = Array1::from(moles).mapv(<$hd_ty>::from);
Self(StateHD::<$hd_ty>::new(temperature.into(), volume.into(), m))
}
#[getter]
pub fn get_temperature(&self) -> $py_hd_id {
<$py_hd_id>::from(self.0.temperature)
}
#[getter]
pub fn get_volume(&self) -> $py_hd_id {
<$py_hd_id>::from(self.0.volume)
}
#[getter]
pub fn get_moles(&self) -> Vec<$py_hd_id> {
self.0.moles.mapv(<$py_hd_id>::from).into_raw_vec()
}
#[getter]
pub fn get_partial_density(&self) -> Vec<$py_hd_id> {
self.0
.partial_density
.mapv(<$py_hd_id>::from)
.into_raw_vec()
}
#[getter]
pub fn get_molefracs(&self) -> Vec<$py_hd_id> {
self.0.molefracs.mapv(<$py_hd_id>::from).into_raw_vec()
}
#[getter]
pub fn get_density(&self) -> $py_hd_id {
<$py_hd_id>::from(self.0.partial_density.sum())
}
}
};
}
macro_rules! dual_number {
($py_hd_id:ident, $hd_ty:ty, $py_field_ty:ty) => {
#[pyclass]
#[derive(Clone)]
pub struct $py_hd_id($hd_ty);
impl_dual_num!($py_hd_id, $hd_ty, $py_field_ty);
};
}
macro_rules! helmholtz_energy {
($py_state_id:ident, $py_hd_id:ident, $hd_ty:ty) => {
impl HelmholtzEnergyDual<$hd_ty> for PyHelmholtzEnergy {
fn helmholtz_energy(&self, state: &StateHD<$hd_ty>) -> $hd_ty {
Python::with_gil(|py| {
let py_result = self
.0
.as_ref(py)
.call_method1("helmholtz_energy", (<$py_state_id>::from(state.clone()),))
.unwrap();
<$hd_ty>::from(py_result.extract::<$py_hd_id>().unwrap())
})
}
}
};
}
macro_rules! impl_dual_state_helmholtz_energy {
($py_state_id:ident, $py_hd_id:ident, $hd_ty:ty, $py_field_ty:ty) => {
dual_number!($py_hd_id, $hd_ty, $py_field_ty);
state!($py_state_id, $py_hd_id, $hd_ty);
helmholtz_energy!($py_state_id, $py_hd_id, $hd_ty);
};
}
// No definition of dual number necessary for f64
state!(PyStateF, f64, f64);
helmholtz_energy!(PyStateF, f64, f64);
impl_dual_state_helmholtz_energy!(PyStateD, PyDual64, Dual64, f64);
dual_number!(PyDualVec3, DualVec64<3>, f64);
impl_dual_state_helmholtz_energy!(
PyStateDualDualVec3,
PyDualDualVec3,
Dual<DualVec64<3>, f64>,
PyDualVec3
);
impl_dual_state_helmholtz_energy!(
PyStateHD,
PyHyperDual64,
HyperDual64,
f64
);
impl_dual_state_helmholtz_energy!(PyStateD2, PyDual2_64, Dual2_64, f64);
impl_dual_state_helmholtz_energy!(PyStateD3, PyDual3_64, Dual3_64, f64);
impl_dual_state_helmholtz_energy!(PyStateHDD, PyHyperDualDual64, HyperDual<Dual64, f64>, PyDual64);
dual_number!(PyDualVec2, DualVec64<2>, f64);
impl_dual_state_helmholtz_energy!(
PyStateHDDVec2,
PyHyperDualVec2,
HyperDual<DualVec64<2>, f64>,
PyDualVec2
);
impl_dual_state_helmholtz_energy!(
PyStateHDDVec3,
PyHyperDualVec3,
HyperDual<DualVec64<3>, f64>,
PyDualVec3
);
impl_dual_state_helmholtz_energy!(
PyStateD3D,
PyDual3Dual64,
Dual3<Dual64, f64>,
PyDual64
);
impl_dual_state_helmholtz_energy!(
PyStateD3DVec2,
PyDual3DualVec2,
Dual3<DualVec64<2>, f64>,
PyDualVec2
);
impl_dual_state_helmholtz_energy!(
PyStateD3DVec3,
PyDual3DualVec3,
Dual3<DualVec64<3>, f64>,
PyDualVec3
);