-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathpython.rs
More file actions
717 lines (683 loc) · 26.4 KB
/
python.rs
File metadata and controls
717 lines (683 loc) · 26.4 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
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
use super::EstimatorError;
use pyo3::exceptions::PyRuntimeError;
use pyo3::PyErr;
impl From<EstimatorError> for PyErr {
fn from(e: EstimatorError) -> PyErr {
PyRuntimeError::new_err(e.to_string())
}
}
#[macro_export]
macro_rules! impl_estimator {
($eos:ty, $py_eos:ty) => {
/// Collection of loss functions that can be applied to residuals
/// to handle outliers.
#[pyclass(name = "Loss")]
#[derive(Clone)]
pub struct PyLoss(Loss);
#[pymethods]
impl PyLoss {
/// Create a linear loss function.
///
/// `loss = s**2 * rho(f**2 / s**2)`
/// where `rho(z) = z` and `s = 1`.
///
/// Returns
/// -------
/// Loss
#[staticmethod]
pub fn linear() -> Self {
Self(Loss::Linear)
}
/// Create a loss function according to SoftL1's method.
///
/// `loss = s**2 * rho(f**2 / s**2)`
/// where `rho(z) = 2 * ((1 + z)**0.5 - 1)`.
/// `s` is the scaling factor.
///
/// Parameters
/// ----------
/// scaling_factor : f64
/// Scaling factor for SoftL1 loss function.
///
/// Returns
/// -------
/// Loss
#[staticmethod]
#[pyo3(text_signature = "(scaling_factor)")]
pub fn softl1(scaling_factor: f64) -> Self {
Self(Loss::SoftL1(scaling_factor))
}
/// Create a loss function according to Huber's method.
///
/// `loss = s**2 * rho(f**2 / s**2)`
/// where `rho(z) = z if z <= 1 else 2*z**0.5 - 1`.
/// `s` is the scaling factor.
///
/// Parameters
/// ----------
/// scaling_factor : f64
/// Scaling factor for Huber loss function.
///
/// Returns
/// -------
/// Loss
#[staticmethod]
#[pyo3(text_signature = "(scaling_factor)")]
pub fn huber(scaling_factor: f64) -> Self {
Self(Loss::Huber(scaling_factor))
}
/// Create a loss function according to Cauchy's method.
///
/// `loss = s**2 * rho(f**2 / s**2)`
/// where `rho(z) = ln(1 + z)`.
/// `s` is the scaling factor.
///
/// Parameters
/// ----------
/// scaling_factor : f64
/// Scaling factor for SoftL1 loss function.
///
/// Returns
/// -------
/// Loss
#[staticmethod]
#[pyo3(text_signature = "(scaling_factor)")]
pub fn cauchy(scaling_factor: f64) -> Self {
Self(Loss::Cauchy(scaling_factor))
}
/// Create a loss function according to Arctan's method.
///
/// `loss = s**2 * rho(f**2 / s**2)`
/// where `rho(z) = arctan(z)`.
/// `s` is the scaling factor.
///
/// Parameters
/// ----------
/// scaling_factor : f64
/// Scaling factor for SoftL1 loss function.
///
/// Returns
/// -------
/// Loss
#[staticmethod]
#[pyo3(text_signature = "(scaling_factor)")]
pub fn arctan(scaling_factor: f64) -> Self {
Self(Loss::Arctan(scaling_factor))
}
}
/// A collection of experimental data that can be used to compute
/// cost functions and make predictions using an equation of state.
#[pyclass(name = "DataSet")]
#[derive(Clone)]
pub struct PyDataSet(Arc<dyn DataSet<$eos>>);
#[pymethods]
impl PyDataSet {
/// Compute the cost function for each input value.
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
/// loss : Loss
/// The loss function that is applied to residuals
/// to handle outliers.
///
/// Returns
/// -------
/// numpy.ndarray[Float]
/// The cost function evaluated for each experimental data point.
///
/// Note
/// ----
/// The cost function that is used depends on the
/// property. For most properties it is the absolute relative difference.
/// See the constructors of the respective properties
/// to learn about the cost functions that are used.
#[pyo3(text_signature = "($self, eos, loss)")]
fn cost<'py>(
&self,
eos: &$py_eos,
loss: PyLoss,
py: Python<'py>,
) -> PyResult<&'py PyArray1<f64>> {
Ok(self.0.cost(&eos.0, loss.0)?.view().to_pyarray(py))
}
/// Return the property of interest for each data point
/// of the input as computed by the equation of state.
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// SIArray1
#[pyo3(text_signature = "($self, eos)")]
fn predict(&self, eos: &$py_eos) -> PyResult<PySIArray1> {
Ok(self.0.predict(&eos.0)?.into())
}
/// Return the relative difference between experimental data
/// and prediction of the equation of state.
///
/// The relative difference is computed as:
///
/// .. math:: \text{Relative Difference} = \frac{x_i^\text{prediction} - x_i^\text{experiment}}{x_i^\text{experiment}}
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// numpy.ndarray[Float]
#[pyo3(text_signature = "($self, eos)")]
fn relative_difference<'py>(
&self,
eos: &$py_eos,
py: Python<'py>,
) -> PyResult<&'py PyArray1<f64>> {
Ok(self.0.relative_difference(&eos.0)?.view().to_pyarray(py))
}
/// Return the mean absolute relative difference.
///
/// The mean absolute relative difference is computed as:
///
/// .. math:: \text{MARD} = \frac{1}{N}\sum_{i=1}^{N} \left|\frac{x_i^\text{prediction} - x_i^\text{experiment}}{x_i^\text{experiment}} \right|
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// Float
#[pyo3(text_signature = "($self, eos)")]
fn mean_absolute_relative_difference(&self, eos: &$py_eos) -> PyResult<f64> {
Ok(self.0.mean_absolute_relative_difference(&eos.0)?)
}
/// Create a DataSet with experimental data for vapor pressure.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for vapor pressure.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// extrapolate : bool, optional
/// Use Antoine type equation to extrapolate vapor
/// pressure if experimental data is above critial
/// point of model. Defaults to False.
/// critical_temperature : SINumber, optional
/// Estimate of the critical temperature used as initial
/// value for critical point calculation. Defaults to None.
/// For additional information, see note.
/// max_iter : int, optional
/// The maximum number of iterations for critical point
/// and VLE algorithms.
/// tol: float, optional
/// Solution tolerance for critical point
/// and VLE algorithms.
/// verbosity : Verbosity, optional
/// Verbosity for critical point
/// and VLE algorithms.
///
/// Returns
/// -------
/// ``DataSet``
///
/// Note
/// ----
/// If no critical temperature is provided, the maximum of the `temperature` input
/// is used. If that fails, the default temperatures of the critical point routine
/// are used.
#[staticmethod]
#[pyo3(text_signature = "(target, temperature, extrapolate, critical_temperature=None, max_iter=None, verbosity=None)")]
fn vapor_pressure(
target: &PySIArray1,
temperature: &PySIArray1,
extrapolate: Option<bool>,
critical_temperature: Option<&PySINumber>,
max_iter: Option<usize>,
tol: Option<f64>,
verbosity: Option<Verbosity>,
) -> PyResult<Self> {
Ok(Self(Arc::new(VaporPressure::new(
target.clone().into(),
temperature.clone().into(),
extrapolate.unwrap_or(false),
critical_temperature.and_then(|tc| Some(tc.clone().into())),
Some((max_iter, tol, verbosity).into()),
)?)))
}
/// Create a DataSet with experimental data for liquid density.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for liquid density.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// pressure : SIArray1
/// Pressure for experimental data points.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(target, temperature, pressure)")]
fn liquid_density(
target: &PySIArray1,
temperature: &PySIArray1,
pressure: &PySIArray1,
) -> PyResult<Self> {
Ok(Self(Arc::new(LiquidDensity::new(
target.clone().into(),
temperature.clone().into(),
pressure.clone().into(),
)?)))
}
/// Create a DataSet with experimental data for liquid density
/// for a vapor liquid equilibrium.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for liquid density.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// max_iter : int, optional
/// The maximum number of iterations for critical point
/// and VLE algorithms.
/// tol: float, optional
/// Solution tolerance for critical point
/// and VLE algorithms.
/// verbosity : Verbosity, optional
/// Verbosity for critical point
/// and VLE algorithms.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(target, temperature)")]
fn equilibrium_liquid_density(
target: &PySIArray1,
temperature: &PySIArray1,
max_iter: Option<usize>,
tol: Option<f64>,
verbosity: Option<Verbosity>,
) -> PyResult<Self> {
Ok(Self(Arc::new(EquilibriumLiquidDensity::new(
target.clone().into(),
temperature.clone().into(),
Some((max_iter, tol, verbosity).into()),
)?)))
}
/// Create a DataSet with experimental data for binary
/// phase equilibria using the chemical potential residual.
///
/// Parameters
/// ----------
/// temperature : SIArray1
/// Temperature of the experimental data points.
/// pressure : SIArray1
/// Pressure of the experimental data points.
/// liquid_molefracs : np.array[float]
/// Molar composition of component 1 in the liquid phase.
/// vapor_molefracs : np.array[float]
/// Molar composition of component 1 in the vapor phase.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(temperature, pressure, liquid_molefracs, vapor_molefracs)")]
fn binary_vle_chemical_potential(
temperature: &PySIArray1,
pressure: &PySIArray1,
liquid_molefracs: &PyArray1<f64>,
vapor_molefracs: &PyArray1<f64>,
) -> Self {
Self(Arc::new(BinaryVleChemicalPotential::new(
temperature.clone().into(),
pressure.clone().into(),
liquid_molefracs.to_owned_array(),
vapor_molefracs.to_owned_array(),
)))
}
/// Create a DataSet with experimental data for binary
/// phase equilibria using the pressure residual.
///
/// Parameters
/// ----------
/// temperature : SIArray1
/// Temperature of the experimental data points.
/// pressure : SIArray1
/// Pressure of the experimental data points.
/// molefracs : np.array[float]
/// Molar composition of component 1 in the considered phase.
/// phase : Phase
/// The phase of the experimental data points.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(temperature, pressure, molefracs, phase)")]
fn binary_vle_pressure(
temperature: &PySIArray1,
pressure: &PySIArray1,
molefracs: &PyArray1<f64>,
phase: Phase,
) -> Self {
Self(Arc::new(BinaryVlePressure::new(
temperature.clone().into(),
pressure.clone().into(),
molefracs.to_owned_array(),
phase,
)))
}
/// Create a DataSet with experimental data for binary
/// phase diagrams using the distance residual.
///
/// Parameters
/// ----------
/// specification : SINumber
/// The constant temperature/pressure of the isotherm/isobar.
/// temperature_or_pressure : SIArray1
/// The temperature (isobar) or pressure (isotherm) of the
/// experimental data points.
/// liquid_molefracs : np.array[float], optional
/// Molar composition of component 1 in the liquid phase.
/// vapor_molefracs : np.array[float], optional
/// Molar composition of component 1 in the vapor phase.
/// npoints : int, optional
/// The resolution of the phase diagram used to calculate
/// the distance residual.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(specification, temperature_or_pressure, liquid_molefracs=None, vapor_molefracs=None, npoints=None)")]
fn binary_phase_diagram(
specification: PySINumber,
temperature_or_pressure: &PySIArray1,
liquid_molefracs: Option<&PyArray1<f64>>,
vapor_molefracs: Option<&PyArray1<f64>>,
npoints: Option<usize>,
) -> Self {
Self(Arc::new(BinaryPhaseDiagram::new(
specification.into(),
temperature_or_pressure.clone().into(),
liquid_molefracs.map(|x| x.to_owned_array()),
vapor_molefracs.map(|x| x.to_owned_array()),
npoints,
)))
}
/// Return `input` as ``Dict[str, SIArray1]``.
#[getter]
fn get_input(&self) -> HashMap<String, PySIArray1> {
let mut m = HashMap::with_capacity(2);
self.0.get_input().drain().for_each(|(k, v)| {
m.insert(k, PySIArray1::from(v));
});
m
}
/// Return `target` as ``SIArray1``.
#[getter]
fn get_target(&self) -> PySIArray1 {
PySIArray1::from(self.0.target().clone())
}
/// Return number of stored data points.
#[getter]
fn get_datapoints(&self) -> usize {
self.0.datapoints()
}
fn __repr__(&self) -> PyResult<String> {
Ok(self.0.to_string())
}
}
/// A collection of `DataSet`s that can be used to compute metrics for experimental data.
///
/// Parameters
/// ----------
/// data : List[DataSet]
/// The properties and experimental data points to add to
/// the estimator.
/// weights : List[float]
/// The weight of each property. When computing the cost function,
/// the weights are normalized (sum of weights equals unity).
/// losses : List[Loss]
/// The loss functions for each property.
///
/// Returns
/// -------
/// Estimator
#[pyclass(name = "Estimator")]
#[pyo3(text_signature = "(data, weights, losses)")]
pub struct PyEstimator(Estimator<$eos>);
#[pymethods]
impl PyEstimator {
#[new]
fn new(data: Vec<PyDataSet>, weights: Vec<f64>, losses: Vec<PyLoss>) -> Self {
Self(Estimator::new(
data.iter().map(|d| d.0.clone()).collect(),
weights,
losses.iter().map(|l| l.0.clone()).collect(),
))
}
/// Compute the cost function for each ``DataSet``.
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// numpy.ndarray[Float]
/// The cost function evaluated for each experimental data point
/// of each ``DataSet``.
///
/// Note
/// ----
/// The cost function is:
///
/// - The relative difference between prediction and target value,
/// - to which a loss function is applied,
/// - and which is weighted according to the number of datapoints,
/// - and the relative weights as defined in the Estimator object.
#[pyo3(text_signature = "($self, eos)")]
fn cost<'py>(&self, eos: &$py_eos, py: Python<'py>) -> PyResult<&'py PyArray1<f64>> {
Ok(self.0.cost(&eos.0)?.view().to_pyarray(py))
}
/// Return the properties as computed by the
/// equation of state for each `DataSet`.
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// List[SIArray1]
#[pyo3(text_signature = "($self, eos)")]
fn predict(&self, eos: &$py_eos) -> PyResult<Vec<PySIArray1>> {
Ok(self
.0
.predict(&eos.0)?
.iter()
.map(|d| PySIArray1::from(d.clone()))
.collect())
}
/// Return the relative difference between experimental data
/// and prediction of the equation of state for each ``DataSet``.
///
/// The relative difference is computed as:
///
/// .. math:: \text{Relative Difference} = \frac{x_i^\text{prediction} - x_i^\text{experiment}}{x_i^\text{experiment}}
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// List[numpy.ndarray[Float]]
#[pyo3(text_signature = "($self, eos)")]
fn relative_difference<'py>(
&self,
eos: &$py_eos,
py: Python<'py>,
) -> PyResult<Vec<&'py PyArray1<f64>>> {
Ok(self
.0
.relative_difference(&eos.0)?
.iter()
.map(|d| d.view().to_pyarray(py))
.collect())
}
/// Return the mean absolute relative difference for each ``DataSet``.
///
/// The mean absolute relative difference is computed as:
///
/// .. math:: \text{MARD} = \frac{1}{N}\sum_{i=1}^{N} \left|\frac{x_i^\text{prediction} - x_i^\text{experiment}}{x_i^\text{experiment}} \right|
///
/// Parameters
/// ----------
/// eos : EquationOfState
/// The equation of state that is used.
///
/// Returns
/// -------
/// numpy.ndarray[Float]
#[pyo3(text_signature = "($self, eos)")]
fn mean_absolute_relative_difference<'py>(
&self,
eos: &$py_eos,
py: Python<'py>,
) -> PyResult<&'py PyArray1<f64>> {
Ok(self
.0
.mean_absolute_relative_difference(&eos.0)?
.view()
.to_pyarray(py))
}
/// Return the stored ``DataSet``s.
///
/// Returns
/// -------
/// List[DataSet]
#[getter]
fn get_datasets(&self) -> Vec<PyDataSet> {
self.0
.datasets()
.iter()
.cloned()
.map(|ds| PyDataSet(ds))
.collect()
}
fn _repr_markdown_(&self) -> String {
self.0._repr_markdownn_()
}
fn __repr__(&self) -> PyResult<String> {
Ok(self.0.to_string())
}
}
};
}
#[macro_export]
macro_rules! impl_estimator_entropy_scaling {
($eos:ty, $py_eos:ty) => {
#[pymethods]
impl PyDataSet {
/// Create a DataSet with experimental data for viscosity.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for viscosity.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// pressure : SIArray1
/// Pressure for experimental data points.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(target, temperature, pressure)")]
fn viscosity(
target: &PySIArray1,
temperature: &PySIArray1,
pressure: &PySIArray1,
) -> PyResult<Self> {
Ok(Self(Arc::new(Viscosity::new(
target.clone().into(),
temperature.clone().into(),
pressure.clone().into(),
)?)))
}
/// Create a DataSet with experimental data for thermal conductivity.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for thermal conductivity.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// pressure : SIArray1
/// Pressure for experimental data points.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(target, temperature, pressure)")]
fn thermal_conductivity(
target: &PySIArray1,
temperature: &PySIArray1,
pressure: &PySIArray1,
) -> PyResult<Self> {
Ok(Self(Arc::new(ThermalConductivity::new(
target.clone().into(),
temperature.clone().into(),
pressure.clone().into(),
)?)))
}
/// Create a DataSet with experimental data for diffusion coefficient.
///
/// Parameters
/// ----------
/// target : SIArray1
/// Experimental data for diffusion coefficient.
/// temperature : SIArray1
/// Temperature for experimental data points.
/// pressure : SIArray1
/// Pressure for experimental data points.
///
/// Returns
/// -------
/// DataSet
#[staticmethod]
#[pyo3(text_signature = "(target, temperature, pressure)")]
fn diffusion(
target: &PySIArray1,
temperature: &PySIArray1,
pressure: &PySIArray1,
) -> PyResult<Self> {
Ok(Self(Arc::new(Diffusion::new(
target.clone().into(),
temperature.clone().into(),
pressure.clone().into(),
)?)))
}
}
};
}