Skip to content
This repository was archived by the owner on Jun 14, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 27 additions & 40 deletions src/cubic.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
use crate::equation_of_state::{EquationOfState, HelmholtzEnergy, HelmholtzEnergyDual};
use crate::joback::JobackRecord;
use crate::parameter::{BinaryRecord, Identifier, Parameter, ParameterError, PureRecord};
use crate::parameter::{Identifier, Parameter, ParameterError, PureRecord};
use crate::si::{GRAM, MOL};
use crate::state::StateHD;
use crate::MolarWeight;
use ndarray::{Array, Array1, Array2};
use ndarray::{Array1, Array2};
use num_dual::DualNum;
use quantity::si::{SIArray1, SIUnit};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::f64::consts::SQRT_2;
use std::rc::Rc;

const KB_A3: f64 = 13806490.0;

Expand All @@ -33,7 +34,6 @@ impl std::fmt::Display for PengRobinsonRecord {
}

/// Peng-Robinson parameters for one ore more substances.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct PengRobinsonParameters {
tc: Array1<f64>,
a: Array1<f64>,
Expand All @@ -43,17 +43,6 @@ pub struct PengRobinsonParameters {
molarweight: Array1<f64>,
pure_records: Vec<PureRecord<PengRobinsonRecord, JobackRecord>>,
joback_records: Option<Vec<JobackRecord>>,
binary_records: Option<Vec<BinaryRecord<Identifier, f64>>>,
}

impl PengRobinsonParameters {
pub fn subset(&self, component_list: &[usize]) -> Self {
let pure_records = component_list
.iter()
.map(|&i| self.pure_records[i].clone())
.collect();
Self::from_records(pure_records, self.binary_records.clone()).unwrap()
}
}

impl PengRobinsonParameters {
Expand Down Expand Up @@ -83,7 +72,10 @@ impl PengRobinsonParameters {
PureRecord::new(id, molarweight[i], None, Some(record), None)
})
.collect();
PengRobinsonParameters::from_records(records, None)
Ok(PengRobinsonParameters::from_records(
records,
Array2::zeros([pc.len(); 2]),
))
}
}

Expand All @@ -94,8 +86,8 @@ impl Parameter for PengRobinsonParameters {

fn from_records(
pure_records: Vec<PureRecord<Self::Pure, Self::IdealGas>>,
binary_records: Option<Vec<crate::parameter::BinaryRecord<Identifier, Self::Binary>>>,
) -> Result<Self, crate::parameter::ParameterError> {
binary_records: Array2<Self::Binary>,
) -> Self {
let n = pure_records.len();

let mut tc = Array1::zeros(n);
Expand Down Expand Up @@ -123,44 +115,39 @@ impl Parameter for PengRobinsonParameters {
};
}

let mut k_ij = Array::zeros([n, n]);
match &binary_records {
Some(bs) => bs.iter().for_each(|record| {
let i = component_index.get(&record.id1);
let j = component_index.get(&record.id2);
if let (Some(i), Some(j)) = (i, j) {
k_ij[[*i, *j]] = record.model_record;
k_ij[[*j, *i]] = record.model_record
}
}),
None => (),
}

let joback_records = pure_records
.iter()
.map(|r| r.ideal_gas_record.clone())
.collect();

Ok(Self {
Self {
tc,
a,
b,
k_ij,
k_ij: binary_records,
kappa,
molarweight,
pure_records,
joback_records,
binary_records,
})
}
}

fn records(
&self,
) -> (
&[PureRecord<PengRobinsonRecord, JobackRecord>],
&Array2<f64>,
) {
(&self.pure_records, &self.k_ij)
}
}

pub struct PengRobinson {
parameters: PengRobinsonParameters,
parameters: Rc<PengRobinsonParameters>,
}

impl PengRobinson {
pub fn new(parameters: PengRobinsonParameters) -> Self {
pub fn new(parameters: Rc<PengRobinsonParameters>) -> Self {
Self { parameters }
}
}
Expand All @@ -171,7 +158,7 @@ impl EquationOfState for PengRobinson {
}

fn subset(&self, component_list: &[usize]) -> Self {
Self::new(self.parameters.subset(component_list))
Self::new(Rc::new(self.parameters.subset(component_list)))
}

fn compute_max_density(&self, moles: &Array1<f64>) -> f64 {
Expand Down Expand Up @@ -280,9 +267,9 @@ mod tests {
let propane = mixture[0].clone();
let tc = propane.model_record.clone().unwrap().tc;
let pc = propane.model_record.clone().unwrap().pc;
let parameters = PengRobinsonParameters::from_records(vec![propane.clone()], None)
.expect("Error reading parameters!");
let pr = Rc::new(PengRobinson::new(parameters));
let parameters =
PengRobinsonParameters::from_records(vec![propane.clone()], Array2::zeros((1, 1)));
let pr = Rc::new(PengRobinson::new(Rc::new(parameters)));
let cp = State::critical_point(&pr, None, None, VLEOptions::default())?;
println!("{} {}", cp.temperature, cp.pressure(Contributions::Total));
assert_relative_eq!(cp.temperature, tc * KELVIN, max_relative = 1e-4);
Expand Down
10 changes: 3 additions & 7 deletions src/joback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,7 @@ impl fmt::Display for JobackRecord {
/// Implementation of the combining rules as described in
/// [Joback and Reid, 1987](https://doi.org/10.1080/00986448708960487).
impl FromSegments for JobackRecord {
type Binary = ();
fn from_segments(
segments: &[(Self, f64)],
_binary_records: Option<&[BinaryRecord<String, Self::Binary>]>,
) -> Result<Self, ParameterError> {
fn from_segments(segments: &[(Self, f64)]) -> Self {
let mut a = -37.93;
let mut b = 0.21;
let mut c = -3.91e-4;
Expand All @@ -63,7 +59,7 @@ impl FromSegments for JobackRecord {
d += s.d * *n;
e += s.e * *n;
});
Ok(Self { a, b, c, d, e })
Self { a, b, c, d, e }
}
}

Expand Down Expand Up @@ -238,7 +234,7 @@ mod tests {
.iter()
.map(|(s, &n)| (s.ideal_gas_record.clone().unwrap(), n))
.collect();
let jr = JobackRecord::from_segments(&joback_segments, None).unwrap();
let jr = JobackRecord::from_segments(&joback_segments);
assert_relative_eq!(
jr.a,
33.3 * 2.0 - 2.14 * 4.0 - 8.25 * 2.0 - 37.93,
Expand Down
26 changes: 13 additions & 13 deletions src/parameter/chemical_record.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,19 @@ impl ChemicalRecord {
Ok(counts)
}

/// Count the number of occurences of each individual segment identifier in the
/// chemical record.
///
/// The map contains the segment identifier as key and the count as (float) value.
pub fn segment_id_count(&self) -> HashMap<String, f64> {
let mut counts = HashMap::with_capacity(self.segments.len());
for si in &self.segments {
let entry = counts.entry(si.clone()).or_insert(0.0);
*entry += 1.0;
}
counts
}

/// Build a HashMap from SegmentRecords for the segments.
///
/// The map contains the segment identifier (String) as key
Expand All @@ -80,19 +93,6 @@ impl ChemicalRecord {
.map(|s| segments.remove_entry(s).unwrap())
.collect())
}

/// Compute the molar weight from SegmentRecords
pub fn molarweight_from_segments<M: Clone, I: Clone>(
&self,
segment_records: &[SegmentRecord<M, I>],
) -> Result<f64, ParameterError> {
let segment_map = self.segment_map(segment_records)?;
Ok(self
.segments
.iter()
.map(|s| segment_map.get(s).unwrap().molarweight)
.sum())
}
}

impl std::fmt::Display for ChemicalRecord {
Expand Down
Loading