KiThe 0.3.0

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical engeneering. Work in progress. Advices and contributions will be appreciated
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
use crate::Thermodynamics::DBhandlers::thermo_api::ThermoCalculator;
use crate::Thermodynamics::User_substances::{
    CalculatorType, DataType, Phases, SearchResult, SubsData, WhatIsFound,
};
use RustedSciThe::symbolic::symbolic_engine::Expr;
use std::collections::HashMap;
use std::f64;
const R: f64 = 8.314;
#[allow(non_upper_case_globals)]
const R_sym: Expr = Expr::Const(R);

///////////////////////////////////////////////////////////////////dG///////////////////////////////////
impl SubsData {
    pub fn calc_dG_for_one_phase(
        &mut self,
        P: f64,

        T: f64,
        n: Option<Vec<f64>>,
        Np: Option<f64>,
    ) -> HashMap<String, f64> {
        let phases_map = self.map_of_phases.clone();

        let mut map_to_insert = HashMap::new();
        let Np = Np.unwrap_or(1.0);
        for (i, substance) in self.substances.iter().enumerate() {
            let map_property_values = self.therm_map_of_properties_values.get(substance).unwrap();

            let dh = map_property_values.get(&DataType::dH).unwrap().unwrap();
            let ds = map_property_values.get(&DataType::dS).unwrap().unwrap();
            let dG = dh - T * ds;
            println!(
                "substance:{}: dh {}, ds {}, dG {} \n",
                substance, dh, ds, dG
            );
            // gas_correrction = 0 if w = None or if Phase is not Gas, else gas_correrction = R*T*ln(P/101325) + R*T*ln(w[i])
            // if Phase is Gas or Phase is None
            let gas_correrction: f64 = if let Some(ref n) = n {
                let correction: f64 = R * T * f64::ln(P / 101325.0) + R * T * f64::ln(n[i] / Np);

                if let Some(phase) = phases_map.get(substance).unwrap() {
                    match phase {
                        Phases::Gas => correction,
                        _ => 0.0,
                    }
                } else {
                    correction
                }
            } else {
                0.0
            };
            let dG = dG + gas_correrction;
            map_to_insert.insert(substance.clone(), dG);
        } // for (i, substance) in self.substances.iter().enumerate()
        map_to_insert
    }

    pub fn calculate_Gibbs_sym_one_phase(
        &mut self,
        _T: f64,
        n: Option<Vec<Expr>>,
        Np: Option<Expr>,
    ) -> HashMap<String, Expr> {
        let phases_map = self.map_of_phases.clone();

        //let _ = self.extract_all_thermal_coeffs(T);
        // let _ = self.calculate_therm_map_of_sym();
        let T = Expr::Var("T".to_owned());
        let P = Expr::Var("P".to_owned());
        let Np = Np.unwrap_or(Expr::Const(1.0));
        let mut map_to_insert = HashMap::new();
        for (i, substance) in self.substances.iter().enumerate() {
            let map_sym = self
                .clone()
                .therm_map_of_sym
                .get(&substance.clone())
                .unwrap()
                .clone();
            let dh_sym = *map_sym.get(&DataType::dH_sym).unwrap().clone().unwrap();
            let ds_sym = *map_sym.get(&DataType::dS_sym).unwrap().clone().unwrap();
            let dG_sym = dh_sym - T.clone() * ds_sym;
            let gas_correrction: Expr = if let Some(ref n) = n {
                let correction: Expr =
                    R_sym * T.clone() * Expr::ln(P.clone() / Expr::Const(101325.0))
                        + R_sym * T.clone() * Expr::ln(n[i].clone() / Np.clone());
                let gas_correrction: Expr = if let Some(phase) = phases_map.get(substance).unwrap()
                {
                    match phase {
                        Phases::Gas => correction,
                        _ => Expr::Const(0.0),
                    }
                } else {
                    correction
                };
                gas_correrction
            } else {
                Expr::Const(0.0)
            };

            let dG_sym = dG_sym.simplify() + gas_correrction.simplify();
            map_to_insert.insert(substance.clone(), dG_sym.clone());
        }
        map_to_insert
    }

    pub fn calculate_dG0_sym_one_phase(&mut self) -> HashMap<String, Expr> {
        let T = Expr::Var("T".to_owned());

        let mut map_to_insert = HashMap::new();
        for (_, substance) in self.substances.iter().enumerate() {
            let map_sym = self
                .clone()
                .therm_map_of_sym
                .get(&substance.clone())
                .unwrap()
                .clone();
            let dh_sym = *map_sym.get(&DataType::dH_sym).unwrap().clone().unwrap();
            let ds_sym = *map_sym.get(&DataType::dS_sym).unwrap().clone().unwrap();
            let dG_sym = dh_sym - T.clone() * ds_sym;
            let dG_sym = dG_sym.simplify();
            map_to_insert.insert(substance.clone(), dG_sym.clone());
        }
        map_to_insert
    }
    /// Function for calculating Gibbs free energy of a given mixure of substances ( at given T, P, concentration)
    pub fn calculate_Gibbs_fun_one_phase(
        &mut self,
        P: f64,
        T: f64,
    ) -> HashMap<String, Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64 + 'static>> {
        let phases_map = self.map_of_phases.clone();

        let mut map_to_insert = HashMap::new();
        let (_Cp, mut dh_vec, mut ds_vec) = self.calculate_therm_map_of_fun_local().unwrap();
        for (i, substance) in self.substances.iter().enumerate() {
            let dh = dh_vec[i].take().unwrap();
            let ds = ds_vec[i].take().unwrap();
            let phases = phases_map.clone();

            let gas_correction = {
                let substance = substance.clone();

                move |T: f64, n: Option<Vec<f64>>, Np: Option<f64>| -> f64 {
                    if let Some(n) = n {
                        let Np = Np.unwrap_or(1.0);
                        let correction = R * T * f64::ln(P / 101325.0) + R * T * f64::ln(n[i] / Np);
                        match phases.get(&substance) {
                            Some(Some(Phases::Gas)) => correction,
                            _ => 0.0,
                        }
                    } else {
                        0.0
                    }
                }
            };
            let dG = Box::new(move |t: f64, n: Option<Vec<f64>>, Np: Option<f64>| {
                dh(t) - t * ds(t) + gas_correction(t, n, Np)
            });
            let dG: Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64 + 'static> = dG;
            map_to_insert.insert(substance.clone(), dG);
        }
        map_to_insert
    }

    /// Function for calculating Gibbs free energy of a given mixure of substances ( at given T, P, concentration)
    pub fn calculate_dG0_fun_one_phase(
        &mut self,
    ) -> HashMap<String, Box<dyn Fn(f64) -> f64 + Send + Sync>> {
        let mut map_to_insert = HashMap::new();
        let (_Cp, mut dh_vec, mut ds_vec) = self.calculate_therm_map_of_fun_local().unwrap();
        for (i, substance) in self.substances.iter().enumerate() {
            let dh = dh_vec[i].take().unwrap();
            let ds = ds_vec[i].take().unwrap();

            let dG = Box::new(move |t: f64| dh(t) - t * ds(t));
            let dG: Box<dyn Fn(f64) -> f64 + Send + Sync> = dG;
            map_to_insert.insert(substance.clone(), dG);
        }
        map_to_insert
    }
    /// Creates closures for the thermodynamic properties of the substances
    pub fn calculate_therm_map_of_fun_local(
        &mut self,
    ) -> Result<
        (
            Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>>,
            Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>>,
            Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>>,
        ),
        String,
    > {
        let mut vec_of_cp: Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>> = Vec::new();
        let mut vec_of_dh: Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>> = Vec::new();
        let mut vec_of_ds: Vec<Option<Box<dyn Fn(f64) -> f64 + Send + Sync>>> = Vec::new();
        for substance in &self.substances.clone() {
            match self
                .search_results
                .get_mut(substance)
                .unwrap()
                .get_mut(&WhatIsFound::Thermo)
                .unwrap()
            {
                Some(SearchResult {
                    calculator: Some(CalculatorType::Thermo(thermo)),
                    ..
                }) => {
                    let mut thermo = thermo.clone();

                    // Create closures for thermodynamic functions
                    if let Err(e) = thermo.create_closures_Cp_dH_dS() {
                        println!(
                            "Warning: Failed to create closures for {}: {}",
                            substance, e
                        );
                        continue;
                    }

                    match thermo.get_C_fun() {
                        Ok(cp_fun) => {
                            vec_of_cp.push(Some(cp_fun));
                        }
                        Err(e) => {
                            println!(
                                "Warning: Failed to get Cp function for {}: {}",
                                substance, e
                            );
                        }
                    };

                    match thermo.get_dh_fun() {
                        Ok(dh_fun) => {
                            vec_of_dh.push(Some(dh_fun));
                        }
                        Err(e) => {
                            println!(
                                "Warning: Failed to get dH function for {}: {}",
                                substance, e
                            );
                        }
                    };

                    match thermo.get_ds_fun() {
                        Ok(ds_fun) => {
                            vec_of_ds.push(Some(ds_fun));
                        }
                        Err(e) => {
                            println!(
                                "Warning: Failed to get dS function for {}: {}",
                                substance, e
                            );
                        }
                    };
                }
                _ => {
                    continue;
                }
            }
        }
        Ok((vec_of_cp, vec_of_dh, vec_of_ds))
    }
    ////////////////////////////////////////////S - ENTHROPY///////////////////////////////////////////////////////////
    /// Function for calculating enthropy of a given mixure of substances (numerical result at given T, P, concentration)
    pub fn calculate_S_for_one_phase(
        &mut self,
        P: f64,

        T: f64,
        n: Option<Vec<f64>>,
        Np: Option<f64>,
    ) -> HashMap<String, f64> {
        let phases_map = self.map_of_phases.clone();

        let mut map_to_insert = HashMap::new();

        for (i, substance) in self.substances.iter().enumerate() {
            let map_property_values = self.therm_map_of_properties_values.get(substance).unwrap();

            let dS = map_property_values.get(&DataType::dS).unwrap().unwrap();

            // gas_correrction = 0 if w = None or if Phase is not Gas, else gas_correrction = R*T*ln(P/101325) + R*T*ln(w[i])
            // if Phase is Gas or Phase is None
            let gas_correrction: f64 = if let Some(ref n) = n {
                let Np = Np.unwrap_or(1.0);
                let correction: f64 = R * f64::ln(P / 101325.0) + R * f64::ln(n[i] / Np);

                if let Some(phase) = phases_map.get(substance).unwrap() {
                    match phase {
                        Phases::Gas => correction,
                        _ => 0.0,
                    }
                } else {
                    correction
                }
            } else {
                0.0
            };
            let dS = dS - gas_correrction;
            map_to_insert.insert(substance.clone(), dS);
        } // for (i, substance) in self.substances.iter().enumerate()
        map_to_insert
    }

    pub fn calculate_S_sym_for_one_phase(
        &mut self,
        T: f64,
        n: Option<Vec<Expr>>,
        Np: Option<Expr>,
    ) -> HashMap<String, Expr> {
        let phases_map = self.map_of_phases.clone();

        let P = Expr::Var("P".to_owned());
        let Np = Np.unwrap_or(Expr::Const(1.0));
        let mut map_to_insert = HashMap::new();
        for (i, substance) in self.substances.iter().enumerate() {
            let map_sym = self
                .clone()
                .therm_map_of_sym
                .get(&substance.clone())
                .unwrap()
                .clone();

            let ds_sym = *map_sym.get(&DataType::dS_sym).unwrap().clone().unwrap();

            let gas_correrction: Expr = if let Some(ref n) = n {
                let correction: Expr = R_sym * Expr::ln(P.clone() / Expr::Const(101325.0))
                    + R_sym * Expr::ln(n[i].clone() / Np.clone());
                let gas_correrction: Expr = if let Some(phase) = phases_map.get(substance).unwrap()
                {
                    match phase {
                        Phases::Gas => correction,
                        _ => Expr::Const(0.0),
                    }
                } else {
                    correction
                };
                gas_correrction
            } else {
                Expr::Const(0.0)
            };

            let dS_sym = ds_sym.simplify() - gas_correrction.simplify();
            map_to_insert.insert(substance.clone(), dS_sym.clone());
        }
        map_to_insert
    }

    pub fn calculate_S_fun_for_one_phase(
        &mut self,
        P: f64,
        T: f64,
    ) -> HashMap<String, Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64>> {
        let phases_map = self.map_of_phases.clone();

        let mut map_to_insert = HashMap::new();
        let (_Cp, _dh_vec, mut ds_vec) = self.calculate_therm_map_of_fun_local().unwrap();
        for (i, substance) in self.substances.iter().enumerate() {
            let ds = ds_vec[i].take().unwrap();
            let phases = phases_map.clone();

            let gas_correction = {
                let substance = substance.clone();

                move |n: Option<Vec<f64>>, Np: Option<f64>| -> f64 {
                    if let Some(n) = n {
                        let Np = Np.unwrap_or(1.0);
                        let correction = R * f64::ln(P / 101325.0) + R * f64::ln(n[i] / Np);
                        match phases.get(&substance) {
                            Some(Some(Phases::Gas)) => correction,
                            _ => 0.0,
                        }
                    } else {
                        0.0
                    }
                }
            };
            let dS = Box::new(move |t: f64, n: Option<Vec<f64>>, Np: Option<f64>| {
                ds(t) - gas_correction(n, Np)
            });
            let dS: Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64> = dS;
            map_to_insert.insert(substance.clone(), dS);
        }
        map_to_insert
    }

    ///////////////////////////////////////////////////////////////////dA - HELMHOLTZ ENERGY///////////////////////////////////
    pub fn calc_dA_for_one_phase(
        &mut self,
        P: f64,

        T: f64,
        n: Option<Vec<f64>>,
        Np: Option<f64>,
    ) -> HashMap<String, f64> {
        let phases_map = self.map_of_phases.clone();

        let _ = self.extract_all_thermal_coeffs(T);
        let _ = self.calculate_therm_map_of_properties(T);
        let mut map_to_insert = HashMap::new();
        let Np = Np.unwrap_or(1.0);

        for (i, substance) in self.substances.iter().enumerate() {
            let map_property_values = self.therm_map_of_properties_values.get(substance).unwrap();
            let dh = map_property_values.get(&DataType::dH).unwrap().unwrap();
            let ds = map_property_values.get(&DataType::dS).unwrap().unwrap();

            // dA = dU - T*dS, where dU = dH - P*V (for ideal gas: P*V = R*T)
            let du = dh - R * T; // For ideal gas
            let dA = du - T * ds;

            let gas_correction: f64 = if let Some(ref n) = n {
                let correction: f64 = R * T * f64::ln(n[i] / Np);
                if let Some(phase) = phases_map.get(substance).unwrap() {
                    match phase {
                        Phases::Gas => correction,
                        _ => 0.0,
                    }
                } else {
                    correction
                }
            } else {
                0.0
            };

            let dA = dA + gas_correction;
            map_to_insert.insert(substance.clone(), dA);
        }
        map_to_insert
    }

    pub fn calculate_Helmholtz_sym_one_phase(
        &mut self,
        T: f64,
        n: Option<Vec<Expr>>,
        Np: Option<Expr>,
    ) -> HashMap<String, Expr> {
        let phases_map = self.map_of_phases.clone();

        let _ = self.extract_all_thermal_coeffs(T);
        let _ = self.calculate_therm_map_of_sym();
        let T = Expr::Var("T".to_owned());
        let Np = Np.unwrap_or(Expr::Const(1.0));
        let mut map_to_insert = HashMap::new();

        for (i, substance) in self.substances.iter().enumerate() {
            let map_sym = self
                .clone()
                .therm_map_of_sym
                .get(&substance.clone())
                .unwrap()
                .clone();
            let dh_sym = *map_sym.get(&DataType::dH_sym).unwrap().clone().unwrap();
            let ds_sym = *map_sym.get(&DataType::dS_sym).unwrap().clone().unwrap();

            // dA = dU - T*dS, where dU = dH - R*T for ideal gas
            let du_sym = dh_sym - R_sym * T.clone();
            let dA_sym = du_sym - T.clone() * ds_sym;

            let gas_correction: Expr = if let Some(ref n) = n {
                let correction: Expr = R_sym * T.clone() * Expr::ln(n[i].clone() / Np.clone());
                if let Some(phase) = phases_map.get(substance).unwrap() {
                    match phase {
                        Phases::Gas => correction,
                        _ => Expr::Const(0.0),
                    }
                } else {
                    correction
                }
            } else {
                Expr::Const(0.0)
            };

            let dA_sym = dA_sym.simplify() + gas_correction.simplify();
            map_to_insert.insert(substance.clone(), dA_sym.clone());
        }
        map_to_insert
    }

    pub fn calculate_Helmholtz_fun_one_phase(
        &mut self,
        P: f64,
        T: f64,
    ) -> HashMap<String, Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64>> {
        let phases_map = self.map_of_phases.clone();

        let _ = self.extract_all_thermal_coeffs(T);
        let mut map_to_insert = HashMap::new();
        let (_Cp, mut dh_vec, mut ds_vec) = self.calculate_therm_map_of_fun_local().unwrap();

        for (i, substance) in self.substances.iter().enumerate() {
            let dh = dh_vec[i].take().unwrap();
            let ds = ds_vec[i].take().unwrap();
            let phases = phases_map.clone();

            let gas_correction = {
                let substance = substance.clone();
                move |T: f64, n: Option<Vec<f64>>, Np: Option<f64>| -> f64 {
                    if let Some(n) = n {
                        let Np = Np.unwrap_or(1.0);
                        let correction = R * T * f64::ln(n[i] / Np);
                        match phases.get(&substance) {
                            Some(Some(Phases::Gas)) => correction,
                            _ => 0.0,
                        }
                    } else {
                        0.0
                    }
                }
            };

            let dA = Box::new(move |t: f64, n: Option<Vec<f64>>, Np: Option<f64>| {
                let du = dh(t) - R * t; // dU = dH - R*T for ideal gas
                du - t * ds(t) + gas_correction(t, n, Np)
            });
            let dA: Box<dyn Fn(f64, Option<Vec<f64>>, Option<f64>) -> f64> = dA;
            map_to_insert.insert(substance.clone(), dA);
        }
        map_to_insert
    }
}