KiThe 0.1.5

A collection of structures and functions useful for chemical kinetics, chemical thermodynamics, combustion, heat and mass transfer, shock tubes and so on and so far. 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
#![allow(warnings)]
pub mod kinetics;
mod mechfinder;

use log::{error, info, warn};
//v 0.1.1
/// ru
/// Модуль снабжен библиотекой кинетических параметров химических реакций, полученной в результате парсинга общедоступныхбаз данных
/// Модуль берет на вход название библиотеки и вектор веществ а затем выдает следующие данные:
/// 1) все реакции исходных веществ между собой, и всех их возможных продуктов между собой.
/// 2) HashMap с кинетическими данными всех найденных реакций
/// ----------------------------------------------------------------
/// eng
/// The module is equipped with a library of kinetic parameters of chemical reactions obtained as a result of parsing publicly available databases
/// The module takes as input the name of the library and the vector of substances and then produces the following data:
/// 1) all reactions of starting substances with each other, and all their possible products with each other.
/// 2) HashMap with kinetic data of all found reactions
use kinetics::{ElementaryStruct, FalloffStruct, PressureStruct, ThreeBodyStruct};

use serde::{Deserialize, Serialize};
use serde::de::{self, Deserializer, MapAccess, Visitor};
use std::fmt;
use serde_json::{Map, Number, Value};
use std::collections::{HashMap, HashSet};
use std::f64;
/// enum for types of chemical kinetics rate contant functions 
#[derive(Debug, PartialEq, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum ReactionType {
    Elem,
    Falloff,
    #[serde(rename = "pres")]
    Pressure,
   #[serde(rename = "three-body")]
    ThreeBody,
    Empirical,
}
impl<'de> Deserialize<'de> for ReactionType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "elem" => Ok(ReactionType::Elem),
            "falloff" => Ok(ReactionType::Falloff),
            "pressure"|"pres" => Ok(ReactionType::Pressure),
            "three-body" | "threebody" => Ok(ReactionType::ThreeBody),
            "empirical" => Ok(ReactionType::Empirical),
            _ => Err(serde::de::Error::custom(format!(
                "Unknown reaction type: {}",
                s
            ))),
        }
    }
}
/// struct for reaction data 
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ReactionData {
    #[serde(rename = "type")]
  pub  reaction_type: ReactionType,
  pub eq: String,
  pub react: Option<HashMap<String, f64>>,
    #[serde(flatten)]
  pub data: ReactionKinetics,
}
/// enum for structs of different types of kinetics
#[derive(Debug, Serialize,  Deserialize,  Clone)]
#[serde(untagged)]
pub enum ReactionKinetics {
  
    Falloff(FalloffStruct),
    Pressure(PressureStruct),
    ThreeBody(ThreeBodyStruct),
    Elementary(ElementaryStruct),
}
// Implement custom Deserialize for ReactionKinetics
/* 
impl<'de> Deserialize<'de> for ReactionKinetics {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ReactionKineticsVisitor;

        impl<'de> Visitor<'de> for ReactionKineticsVisitor {
            type Value = ReactionKinetics;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a map containing reaction kinetics data")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut reaction_type: Option<ReactionType> = None;

                // First, find the "type" field to determine the reaction type
                while let Some((key, value)) = map.next_entry::<String, Value>()? {
                    if key == "type" {
                        reaction_type = Some(ReactionType::deserialize(value)?);
                        break;
                    }
                }

                // Now that we know the reaction type, deserialize the appropriate struct
                match reaction_type {
                    Some(ReactionType::Falloff) => Ok(ReactionKinetics::Falloff(FalloffStruct::deserialize(de::value::MapAccessDeserializer::new(map))?)),
                    Some(ReactionType::Pressure) => Ok(ReactionKinetics::Pressure(PressureStruct::deserialize(de::value::MapAccessDeserializer::new(map))?)),
                    Some(ReactionType::ThreeBody) => Ok(ReactionKinetics::ThreeBody(ThreeBodyStruct::deserialize(de::value::MapAccessDeserializer::new(map))?)),
                    Some(ReactionType::Elem) => Ok(ReactionKinetics::Elementary(ElementaryStruct::deserialize(de::value::MapAccessDeserializer::new(map))?)),
                    _ => Err(de::Error::custom("Unknown or missing reaction type")),
                }
            }
        }

        deserializer.deserialize_map(ReactionKineticsVisitor)
    }
}
*/


/*
impl<'de> Deserialize<'de> for ReactionKinetics {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct ReactionKineticsVisitor;

        impl<'de> Visitor<'de> for ReactionKineticsVisitor {
            type Value = ReactionKinetics;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a map with reaction type and data")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut reaction_type = None;
                let mut data = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => {
                            reaction_type = Some(map.next_value::<ReactionType>()?);
                        }
                        _ => {
                            // Collect all other fields into a Value
                            data = Some(map.next_value::<serde_json::Value>()?);
                        }
                    }
                }

                let reaction_type = reaction_type.ok_or_else(|| de::Error::missing_field("type"))?;
                let data = data.ok_or_else(|| de::Error::missing_field("data"))?;

                match reaction_type {
                    ReactionType::Elem => Ok(ReactionKinetics::Elementary(
                        serde_json::from_value(data).map_err(de::Error::custom)?,
                    )),
                    ReactionType::Falloff => Ok(ReactionKinetics::Falloff(
                        serde_json::from_value(data).map_err(de::Error::custom)?,
                    )),
                    ReactionType::Pressure => Ok(ReactionKinetics::Pressure(
                        serde_json::from_value(data).map_err(de::Error::custom)?,
                    )),
                    ReactionType::ThreeBody => Ok(ReactionKinetics::ThreeBody(
                        serde_json::from_value(data).map_err(de::Error::custom)?,
                    )),
                    ReactionType::Empirical => Err(de::Error::custom("Empirical reactions not supported")),
                }
            }
        }

        deserializer.deserialize_map(ReactionKineticsVisitor)
    }
}
*/

pub fn parse_kinetic_data(
    big_mech: &str,
    vec_of_reactions: &[String],
    vec_of_reaction_value: Vec<Value>,
) -> (Map<String, Value>, Vec<String>) {
    let mut reaction_data_hash = Map::new();
    let mut equations = Vec::new();
    info!("______________PARCING REACTION DATA INTO STRUCTS________");
    for (reaction_record, reaction_id) in vec_of_reaction_value.iter().zip(vec_of_reactions) {
        info!("reaction_record {:#?} \n \n ", reaction_record);
        let react_code = format!("{}_{}", big_mech, reaction_id);
        if let Ok(mut reactiondata) =
            serde_json::from_value::<ReactionData>(reaction_record.clone())
        {
            equations.push(reactiondata.eq.clone());
            // let reacttype =  &reactiondata.reaction_type;

            // Initialize any additional fields based on reaction type
            match &mut reactiondata.data {
                ReactionKinetics::Elementary(elem_data) => {}
                ReactionKinetics::ThreeBody(threebody_data) => {}
                ReactionKinetics::Falloff(falloff_data) => {}
                _ => {}
            }

            let value = serde_json::to_value(&reactiondata).unwrap();
            reaction_data_hash.insert(react_code, value);
        } else {
            error!("Error parsing reaction: {}", reaction_record);
            panic!("Error parsing reaction: {}", reaction_record);
        }
    }
    info!("______________PARCING REACTION DATA INTO STRUCTS ENDED________");
    (reaction_data_hash, equations)
}
/// parse Vec of serde Values with reaction data 
pub fn parse_kinetic_data_vec(

    vec_of_reaction_value: Vec<Value>,
) -> (Vec<ReactionData>, Vec<String>) {
    println!("\n \n______________PARCING REACTION DATA INTO STRUCTS________");
    let mut reaction_dat = Vec::new();
    let mut equations = Vec::new();

    for reaction_record in vec_of_reaction_value.iter() {
        println!("reaction_record {:#?} \n \n ", reaction_record);
        if let Ok(mut reactiondata) =
            serde_json::from_value::<ReactionData>(reaction_record.clone())
        {
            equations.push(reactiondata.eq.clone());
            println!("parsed into {:#?} \n", reactiondata);
            reaction_dat.push(reactiondata);
        } else {

            info!("Error parsing reaction: {}", reaction_record);
            panic!("Error parsing reaction: {}", reaction_record);
        }
    }
    info!("______________PARCING REACTION DATA INTO STRUCTS ENDED________");
    (reaction_dat, equations)
}
/// struct for chemical mechanism construction
#[derive(Debug)]
pub struct Mechanism_search {
    pub task_substances: Vec<String>,
    pub task_library: String,
    pub mechanism: Vec<String>,
    pub reactants: Vec<String>,
    pub vec_of_reactions: Vec<String>,
    pub reactdata:Vec<ReactionData>,
}
//
impl Mechanism_search {
    pub fn new(
        task_substances: Vec<String>,
        task_library: String,

    ) -> Self {
        Self {
           task_substances: task_substances,
            task_library: task_library,
             mechanism: Vec::new(),
             reactants: Vec::new(),
             vec_of_reactions: Vec::new(),
             reactdata: Vec::new(),
        }
    }

    pub fn default() -> Self {
        Self {
            task_substances: Vec::new(),
            task_library: String::new(),
            mechanism: Vec::new(),
            reactants: Vec::new(),
            vec_of_reactions: Vec::new(),
            reactdata: Vec::new(),
        }
    }
    pub fn mechfinder_api(&mut self) -> (Vec<String>, Vec<String>, Vec<String>) {
        /*
        let tuple = [ "O", "NH3", "NO", "O2", "N2", "N2O", "CO", "C"];
        O,NH3,NO,O2,N2,N2O,CO,C
        let big_mech = "NUIG".to_string();
            let vec: Vec<&str> =  tuple.into_iter().collect();
        */

        let vec: Vec<&str> = self.task_substances.iter().map(|s| s.as_str()).collect();
        let big_mech = self.task_library.clone();
        info!("задание {:?}, библиотека {:?}", &big_mech, &vec);
        let (mechanism, reactants, vec_of_reactions, vec_of_reaction_value) =
            mechfinder::mechfinder(&big_mech, vec);
        // info!("mechanism {:?}", &mechanism);
        let (mut reactdata, vec_of_equations) =
            parse_kinetic_data_vec(vec_of_reaction_value.clone()); // парсим данные о реакциях
        self.mechanism = mechanism;
        self.reactants = reactants;
        self.vec_of_reactions = vec_of_reactions;
        self.reactdata = reactdata.clone();
        return (
            self.mechanism.to_owned(),
            self.reactants.to_owned(),
            self.vec_of_reactions.to_owned(),
        );
    }
}

//tests
const ELEM_TESTING_JSON: &str = r#"{"type": "elem",
                 "eq": "NAPH+C2H3<=>NAPHV+C2H4",
                  "Arrenius": [0.408, 4.02, 36822.949]}"#;
const FALOFF_TESTING_JSON: &str = r#" {"type": "falloff",
                 "eq": "C4H71-3+CH3(+M)<=>C5H10-2(+M)",
                 "low_rate": [3.91e+60, -12.81, 26143.75],
                "high_rate": [100000000000000.0, -0.32, -1097.2009],
                 "eff": {"H2": 2.0, "H2O": 6.0, "CH4": 2.0, "CO": 1.5, "CO2": 2.0, "C2H6": 3.0, "AR": 0.7},
                 "troe": [0.104, 1606.0, 60000.0, 6118.0]} "#;
const PRES_TESTING_JSON: &str =  r#"{"type": "pres", "eq": "SC4H9<=>C3H6+CH3",
               'Arrenius': {"0.001": [2.89e+40, -9.76, 140552.983],
                             "0.01": [1.8e+44, -10.5, 154800.281],
                             "0.1": [2.51e+46, -10.73, 168311.37099999998],
                             "1.0": [4.74e+44, -9.85, 175020.903], 
                             "10.0": [3.79e+37, -7.44, 169846.532],
                             "100.0": [4.79e+26, -4.01, 154344.334] }}"#;
const THREE_BODY_TESTING_JSON: &str = r#"{"type": "threebody",
              "eq": "H2+M<=>H+H+M",
              "Arrenius": [4.577e+19, -1.4, 436705.19999999995],
             "eff": {"H2": 2.5, "H2O": 12.0, "CO": 1.9, "CO2": 3.8, "HE": 0.83, "CH4": 2.0, "C2H6": 3.0} }"#;
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_mechfinder_api() {
        let mut mech_search = Mechanism_search::new(
            vec!["O".to_string(), "NH3".to_string(), "NO".to_string()],
            "NUIG".to_string(),
          
        );

        let (mechanism, reactants, vec_of_reactions) = mech_search.mechfinder_api();

        assert!(!mechanism.is_empty());
        assert!(!reactants.is_empty());
        assert!(!vec_of_reactions.is_empty());
    }

    #[test]
    fn test_default_values() {
        let mech_search = Mechanism_search::default();

        assert!(mech_search.task_substances.is_empty());
        assert!(mech_search.task_library.is_empty());
        assert!(mech_search.mechanism.is_empty());
        assert!(mech_search.reactants.is_empty());
        assert!(mech_search.vec_of_reactions.is_empty());
    }

    #[test]

    fn test_ELEM_parse_kinetic_data() {
        let big_mech: &str = "NUIG";
        /*
        let test_data = [ELEM_TESTING_JSON, FALOFF_TESTING_JSON, PRES_TESTING_JSON, THREE_BODY_TESTING_JSON];
        let   test_reactions_numbers = vec!("1", "2532", "1736", "5");
        let vec_of_reactions: Vec<String> =  test_reactions_numbers.iter().map(|&s| s.trim().to_string()).collect();
        let vec_of_reaction_value: Vec<Value> = test_data.iter().map(|&s| serde_json::from_str(&s).unwrap()).collect();
        */
        let vec_of_reactions = vec!["1".to_string()];
        let reaction = ELEM_TESTING_JSON;
        let vec_of_reaction_value: Vec<Value> = vec![serde_json::from_str(reaction).unwrap()];
        let (ReactionDataHash, _) =
            parse_kinetic_data(big_mech, &vec_of_reactions, vec_of_reaction_value);

        assert!(!ReactionDataHash.is_empty());
        //   let elem_saved_to_hash = ReactionDataHash[test_reactions_numbers[0]];
        let key = format!("{}_{}", big_mech, &vec_of_reactions[0]);
        let elem_react_testing_instance: ElementaryStruct =
            serde_json::from_value::<ElementaryStruct>(ReactionDataHash[&key].clone()).unwrap();
        println!("K_const {:?}", elem_react_testing_instance.K_const(298.15));
        assert!(elem_react_testing_instance.K_const(298.15) > 0.0);
    }
    #[test]

    fn test_THREEBODY_parse_kinetic_data() {
        let ThreeBodyStruct_test_data: &str = r#"{"Arrenius": [4.577e+19, -1.4, 436705.19999999995],
       "eff": {"H2": 2.5, "H2O": 12.0, "CO": 1.9, "CO2": 3.8, "HE": 0.83, "CH4": 2.0, "C2H6": 3.0} }"#;
        let big_mech: &str = "NUIG";
        let vec_of_reactions = vec!["2".to_string()];
        let reaction = THREE_BODY_TESTING_JSON;
        let vec_of_reaction_value: Vec<Value> = vec![serde_json::from_str(reaction).unwrap()];
        let (ReactionDataHash, _) =
            parse_kinetic_data(big_mech, &vec_of_reactions, vec_of_reaction_value);

        assert!(!ReactionDataHash.is_empty());
        println!("ReactionDataHash: {:?} \n \n", ReactionDataHash);
        let key = format!("{}_{}", big_mech, &vec_of_reactions[0]);

        let threebody_react_testing_instance: ThreeBodyStruct =
            serde_json::from_value::<ThreeBodyStruct>(
                serde_json::from_str(ThreeBodyStruct_test_data).unwrap(),
            )
            .unwrap();
        println!(
            "threebody_react_testing_instance {:?}",
            threebody_react_testing_instance
        );
        let mut Concentrations: HashMap<String, f64> = HashMap::new();
        Concentrations.insert("H".to_string(), 0.5);
        Concentrations.insert("O".to_string(), 0.5);
        assert!(threebody_react_testing_instance.K_const(298.15, Concentrations) > 0.0);
        // assert!(elem_react_testing_instance.K_const(298.15) > 0.0);
    }
    #[test]
    fn test_THREEBODY_from_lib() {
        use crate::Kinetics::User_reactions::KinData;
        let mut kinetics = KinData::new();
        let C1_react = Some(vec!["C1".to_string()]);
        kinetics.shortcut_reactions = C1_react.clone();

        kinetics.get_reactions_from_shortcuts();

        kinetics.reactdata_parsing();
        assert!(kinetics.vec_of_reaction_data.iter().len() > 0);
    }
    #[test]

    fn test_FALOFF_parse_kinetic_data() {
        let big_mech: &str = "NUIG";
        let vec_of_reactions = vec!["3".to_string()];
        let reaction = FALOFF_TESTING_JSON;
        let vec_of_reaction_value: Vec<Value> = vec![serde_json::from_str(reaction).unwrap()];
        let (ReactionDataHash, _) =
            parse_kinetic_data(big_mech, &vec_of_reactions, vec_of_reaction_value);
        println!("ReactionDataHash: {:#?}", ReactionDataHash);
        assert!(!ReactionDataHash.is_empty());
        let key = format!("{}_{}", big_mech, &vec_of_reactions[0]);
        let falloff_react_testing_instance: FalloffStruct =
            serde_json::from_value::<FalloffStruct>(ReactionDataHash[&key].clone()).unwrap();
        let mut Concentrations: HashMap<String, f64> = HashMap::new();
        Concentrations.insert("H".to_string(), 0.5);
        Concentrations.insert("O".to_string(), 0.5);
        assert!(falloff_react_testing_instance.K_const(298.15, Concentrations) > 0.0);
        // assert!(elem_react_testing_instance.K_const(298.15) > 0.0);
    }

    #[test]
    fn test_three_body_deserialization() {
        use serde_json::json;
        let three_body_json = json!({
            "type": "three-body",
            "eq": "H2+M<=>H+H+M",
            "Arrenius": [4.577e+19, -1.4, 436705.19999999995],
            "eff": {
                "H2": 2.5,
                "H2O": 12.0,
                "CO": 1.9,
                "CO2": 3.8,
                "HE": 0.83,
                "CH4": 2.0,
                "C2H6": 3.0
            }
        });

        let reaction_data: ReactionData = serde_json::from_value(three_body_json).unwrap();
        println!("reaction_data: {:#?}", reaction_data);
        assert_eq!(reaction_data.reaction_type, ReactionType::ThreeBody, "wrong reaction type!");
        if let ReactionKinetics::ThreeBody(_) = reaction_data.data {
            // Success
        } else {
            panic!("Expected ThreeBody variant");
        }
    }
    #[test]
    fn test_pres_deserialization() {
  
        let reaction_data: ReactionData = serde_json::from_str(PRES_TESTING_JSON).expect("Error parsing JSON: {err:?}");
        println!("reaction_data: {:#?}", reaction_data);
        assert_eq!(reaction_data.reaction_type, ReactionType::Pressure, "wrong reaction type!");
        if let ReactionKinetics::Pressure(_) = reaction_data.data {
            // Success
        } else {
            panic!("Expected Pressure variant");
        }
    }
    #[test]
    fn test_pres_data_deserialization() {
              const PRES_TESTING_JSON: &str = r#"{
                        "Arrenius":{"0.01": [2.89e+40, -9.76, 140552.983],
                                    "0.1": [1.8e+44, -10.5, 154800.281]
                                    }}"#;

        let pres_val  = serde_json::from_str(PRES_TESTING_JSON).expect("Error parsing JSON: {err:?}"); 
       println!("val: {:#?}", pres_val);
         let pres_data =
        serde_json::from_value::<PressureStruct>(
            pres_val
        );
        if let Ok(pres)= pres_data {
            println!("pres_data: {:#?}", pres);
            // Success
        } else { panic!("Expected Pressure variant");}
        
    }
}