KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
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
//! # Thermodynamic Calculation API Module
//!
//! ## Aim
//! This module provides a unified trait-based API for thermodynamic property calculations
//! across different data sources (NASA, NIST, etc.). It implements the strategy pattern
//! using enum_dispatch for zero-cost abstractions and provides factory methods for
//! creating appropriate calculators based on database type.
//!
//! ## Main Data Structures and Logic
//! - `ThermoCalculator` trait: Unified interface for all thermodynamic calculation implementations
//! - `ThermoEnum`: Enum dispatch wrapper providing zero-cost polymorphism
//! - `ThermoError`: Comprehensive error handling with automatic conversion from specific errors
//! - `EnergyUnit` enum: Standardized energy unit handling (Joules vs Calories)
//! - Factory pattern implementation for creating calculators by type or name
//!
//! ## Key Methods
//! - `extract_model_coefficients()`: Extract appropriate coefficients for given temperature
//! - `calculate_Cp_dH_dS()`: Compute thermodynamic properties at specified conditions
//! - `create_closures_Cp_dH_dS()`: Generate efficient closure functions for repeated calculations
//! - `create_sym_Cp_dH_dS()`: Create symbolic expressions for analytical work
//! - `Taylor_series_cp_dh_ds()`: Generate Taylor series expansions around operating points
//! - `renew_base()`: Update calculator with new substance data (for NIST web scraping)
//!
//! ## Usage
//! ```rust, ignore
//! let mut calc = create_thermal_by_name("NASA_gas");
//! calc.from_serde(database_entry)?;
//! calc.extract_model_coefficients(400.0)?;
//! calc.calculate_Cp_dH_dS(400.0)?;
//! let cp = calc.get_Cp()?;
//! let symbolic_cp = calc.get_Cp_sym()?;
//! ```
//!
//! ## Interesting Features
//! - Zero-cost abstractions using enum_dispatch for runtime polymorphism without vtables
//! - Automatic error conversion between different calculator error types
//! - Factory methods supporting both enum-based and string-based calculator creation
//! - Unified interface hiding implementation details of different thermodynamic databases
//! - Support for both numerical and symbolic computation modes
//! - Comprehensive getter methods for accessing calculated properties and functions
//! - Integration with web scraping for real-time NIST data access

use crate::Thermodynamics::DBhandlers::NIST_parser::{
    NistError as NistParserError, Phase, SearchType,
};
use crate::Thermodynamics::DBhandlers::NISTdata::NISTFitError;
use RustedSciThe::numerical::optimization::sym_fitting::FittingError as RstFittingError;
use RustedSciThe::symbolic::symbolic_engine::Expr;
use enum_dispatch::enum_dispatch;
use serde_json::Value;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub enum ThermoError {
    NoCoefficientsFound {
        temperature: f64,
        range: String,
    },
    InvalidTemperatureRange,
    UnsupportedUnit(String),
    ParserError(NistParserError),
    ParserSetupError(NistParserError),
    NISTSchema(String),
    SerdeError(serde_json::Error),
    SymbolicError(String),
    CalculationError(String),
    FittingError(String),
    FittingAttemptsFailed {
        primary: Box<ThermoError>,
        fallback: Box<ThermoError>,
    },
    NISTFit(NISTFitError),
    FittingBackend {
        stage: &'static str,
        source: RstFittingError,
    },
    NoFitSamples {
        minimum_temperature: f64,
        maximum_temperature: f64,
    },
}

impl fmt::Display for ThermoError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ThermoError::NoCoefficientsFound { temperature, range } => {
                write!(
                    f,
                    "No coefficients found for temperature {} K. Valid range: {}",
                    temperature, range
                )
            }
            ThermoError::InvalidTemperatureRange => {
                write!(f, "Invalid temperature range in coefficient data")
            }
            ThermoError::ParserError(err) => write!(f, "Failed to retrieve NIST data: {}", err),
            ThermoError::ParserSetupError(err) => {
                write!(f, "Failed to initialize NIST parser: {err}")
            }
            ThermoError::NISTSchema(msg) => write!(f, "Invalid NIST data schema: {msg}"),
            ThermoError::SerdeError(msg) => {
                write!(f, "Failed to deserialize thermodynamic data: {}", msg)
            }
            ThermoError::UnsupportedUnit(unit) => {
                write!(
                    f,
                    "Unsupported unit: {}. Only 'J' and 'cal' are supported",
                    unit
                )
            }
            ThermoError::SymbolicError(msg) => {
                write!(f, "Symbolic error: {}", msg)
            }
            ThermoError::CalculationError(msg) => {
                write!(f, "Calculation error: {}", msg)
            }
            ThermoError::FittingError(msg) => {
                write!(f, "Fitting error: {}", msg)
            }
            ThermoError::FittingAttemptsFailed { primary, fallback } => write!(
                f,
                "Thermodynamic fitting routes failed; primary: {primary}; fallback: {fallback}"
            ),
            ThermoError::NISTFit(err) => write!(f, "NIST fit error: {}", err),
            ThermoError::FittingBackend { stage, source } => {
                write!(f, "Thermodynamic {stage} fitting backend failed: {source}")
            }
            ThermoError::NoFitSamples {
                minimum_temperature,
                maximum_temperature,
            } => write!(
                f,
                "No fitting samples overlap the requested range {minimum_temperature}..{maximum_temperature} K"
            ),
        }
    }
}

impl Error for ThermoError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            ThermoError::SerdeError(err) => Some(err),
            ThermoError::ParserError(err) => Some(err),
            ThermoError::ParserSetupError(err) => Some(err),
            ThermoError::FittingBackend { source, .. } => Some(source),
            ThermoError::NISTFit(err) => Some(err),
            ThermoError::FittingAttemptsFailed { fallback, .. } => Some(fallback.as_ref()),
            _ => None,
        }
    }
}

impl From<super::NISTdata::NISTError> for ThermoError {
    fn from(err: super::NISTdata::NISTError) -> Self {
        match err {
            super::NISTdata::NISTError::NoCoefficientsFound { temperature, range } => {
                ThermoError::NoCoefficientsFound { temperature, range }
            }
            super::NISTdata::NISTError::InvalidTemperatureRange => {
                ThermoError::InvalidTemperatureRange
            }
            super::NISTdata::NISTError::SchemaError(msg) => ThermoError::NISTSchema(msg),
            super::NISTdata::NISTError::ParserSetupError(err) => ThermoError::ParserSetupError(err),
            super::NISTdata::NISTError::ParserError(err) => ThermoError::ParserError(err),
            super::NISTdata::NISTError::SerdeError(msg) => ThermoError::SerdeError(msg),
            super::NISTdata::NISTError::UnsupportedUnit(unit) => ThermoError::UnsupportedUnit(unit),
            super::NISTdata::NISTError::SymbolicError(msg) => ThermoError::SymbolicError(msg),
            super::NISTdata::NISTError::FittingError(msg) => ThermoError::FittingError(msg),
            super::NISTdata::NISTError::Fit(err) => ThermoError::NISTFit(err),
            super::NISTdata::NISTError::FittingBackend { stage, source } => {
                ThermoError::FittingBackend { stage, source }
            }
            super::NISTdata::NISTError::NoFitSamples {
                minimum_temperature,
                maximum_temperature,
            } => ThermoError::NoFitSamples {
                minimum_temperature,
                maximum_temperature,
            },
            //    super::NISTdata::NISTError::SerdeError(err) => ThermoError::SerdeError(err),
        }
    }
}

impl From<super::NASAdata::NASAError> for ThermoError {
    fn from(err: super::NASAdata::NASAError) -> Self {
        match err {
            super::NASAdata::NASAError::NoCoefficientsFound { temperature, range } => {
                ThermoError::NoCoefficientsFound { temperature, range }
            }
            super::NASAdata::NASAError::InvalidTemperatureRange => {
                ThermoError::InvalidTemperatureRange
            }
            super::NASAdata::NASAError::SerdeError(msg) => ThermoError::SerdeError(msg),
            super::NASAdata::NASAError::UnsupportedUnit(unit) => ThermoError::UnsupportedUnit(unit),
            super::NASAdata::NASAError::SymbolicError(msg) => ThermoError::SymbolicError(msg),
            super::NASAdata::NASAError::FittingError(msg) => ThermoError::FittingError(msg),
            super::NASAdata::NASAError::FittingBackend { stage, source } => {
                ThermoError::FittingBackend { stage, source }
            }
            super::NASAdata::NASAError::FittingAttemptsFailed { primary, fallback } => {
                ThermoError::FittingAttemptsFailed {
                    primary: Box::new((*primary).into()),
                    fallback: Box::new((*fallback).into()),
                }
            }
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
pub enum EnergyUnit {
    J,
    Cal,
}
#[enum_dispatch]
pub trait ThermoCalculator {
    fn newinstance(&mut self) -> Result<(), ThermoError>;
    fn set_unit(&mut self, unit: Option<EnergyUnit>) -> Result<(), ThermoError>;
    fn from_serde(&mut self, serde: Value) -> Result<(), ThermoError>;
    fn extract_model_coefficients(&mut self, t: f64) -> Result<(), ThermoError>;
    fn parse_coefficients(&mut self) -> Result<(), ThermoError>;
    fn calculate_Cp_dH_dS(&mut self, t: f64) -> Result<(), ThermoError>;
    fn create_closures_Cp_dH_dS(&mut self) -> Result<(), ThermoError>;
    fn create_sym_Cp_dH_dS(&mut self) -> Result<(), ThermoError>;
    fn Taylor_series_cp_dh_ds(
        &mut self,
        temperature: f64,
        order: usize,
    ) -> Result<(Expr, Expr, Expr), ThermoError>;
    fn pretty_print_data(&self) -> Result<(), ThermoError>;
    fn renew_base(
        &mut self,
        sub_name: String,
        search_type: SearchType,
        phase: Phase,
    ) -> Result<(), ThermoError>;
    fn get_coefficients(&self) -> Result<Vec<f64>, ThermoError>;

    // Add getter methods for thermodynamic properties
    fn print_instance(&self) -> Result<(), ThermoError>;
    fn get_Cp(&self) -> Result<f64, ThermoError>;
    fn get_dh(&self) -> Result<f64, ThermoError>;
    fn get_ds(&self) -> Result<f64, ThermoError>;
    fn get_C_fun(&self) -> Result<Box<dyn Fn(f64) -> f64 + Send + Sync>, ThermoError>;
    fn get_dh_fun(&self) -> Result<Box<dyn Fn(f64) -> f64 + Send + Sync>, ThermoError>;
    fn get_ds_fun(&self) -> Result<Box<dyn Fn(f64) -> f64 + Send + Sync>, ThermoError>;
    fn get_Cp_sym(&self) -> Result<Expr, ThermoError>;
    fn get_dh_sym(&self) -> Result<Expr, ThermoError>;
    fn get_ds_sym(&self) -> Result<Expr, ThermoError>;
    fn get_composition(&self) -> Result<Option<HashMap<String, f64>>, ThermoError>;
    fn fitting_coeffs_for_T_interval(&mut self) -> Result<(), ThermoError>;
    fn integr_mean(&mut self) -> Result<(), ThermoError>;
    fn set_T_interval(&mut self, T_min: f64, T_max: f64) -> Result<(), ThermoError>;
    fn calculate_Cp_dH_dS_with_T_range(&mut self, T: f64) -> Result<(), ThermoError>;
    fn create_closures_Cp_dH_dS_with_T_range(&mut self, T: f64) -> Result<(), ThermoError>;
    fn create_sym_Cp_dH_dS_with_T_range(&mut self, T: f64) -> Result<(), ThermoError>;
    fn is_coeffs_valid_for_T(&self, T: f64) -> Result<bool, ThermoError>;
    /// Returns the currently selected native coefficient interval, if any.
    fn current_coeffs_temperature_interval(&self) -> Result<Option<(f64, f64)>, ThermoError>;
    /// Returns the inclusive temperature domain represented by the parsed
    /// source record.  This is metadata about the record, not a user-selected
    /// fitting interval.
    fn valid_temperature_interval(&self) -> Result<(f64, f64), ThermoError>;
    /// Returns each native coefficient interval without merging gaps.
    fn valid_temperature_intervals(&self) -> Result<Vec<(f64, f64)>, ThermoError>;
}

/// Returns whether a union of native coefficient intervals continuously covers
/// a requested temperature range.
///
/// Endpoints are inclusive, so adjacent intervals such as `[200, 1000]` and
/// `[1000, 6000]` cover `[900, 1500]`. Any gap, malformed interval, invalid
/// requested bound, or empty interval set returns `false`. The check accepts
/// intervals in any order and does not allocate or modify the input slice.
pub fn temperature_intervals_cover_range(
    intervals: &[(f64, f64)],
    requested_lower: f64,
    requested_upper: f64,
) -> bool {
    if !requested_lower.is_finite()
        || !requested_upper.is_finite()
        || requested_lower <= 0.0
        || requested_lower > requested_upper
        || intervals.is_empty()
        || intervals.iter().any(|(lower, upper)| {
            !lower.is_finite() || !upper.is_finite() || *lower <= 0.0 || lower > upper
        })
    {
        return false;
    }
    if requested_lower == requested_upper {
        return intervals
            .iter()
            .any(|(lower, upper)| *lower <= requested_lower && *upper >= requested_upper);
    }

    let mut covered_until = requested_lower;
    loop {
        if covered_until >= requested_upper {
            return true;
        }
        let furthest = intervals
            .iter()
            .filter(|(lower, upper)| *lower <= covered_until && *upper >= covered_until)
            .map(|(_, upper)| *upper)
            .fold(covered_until, f64::max);
        if furthest <= covered_until {
            return false;
        }
        covered_until = furthest;
    }
}

#[derive(Clone, Debug)]
#[enum_dispatch(ThermoCalculator)]
pub enum ThermoEnum {
    NIST(super::NISTdata::NISTdata),
    NASA(super::NASAdata::NASAdata),
}

pub enum ThermoType {
    NIST,
    NASA,
}

pub fn create_thermal(calc_type: ThermoType) -> ThermoEnum {
    match calc_type {
        ThermoType::NIST => ThermoEnum::NIST(super::NISTdata::NISTdata::new()),
        ThermoType::NASA => ThermoEnum::NASA(super::NASAdata::NASAdata::new()),
    }
}

pub fn create_thermal_by_name(calc_name: &str) -> ThermoEnum {
    match calc_name {
        "Cantera_nasa_base_gas"
        | "NASA_gas"
        | "NASA_cond"
        | "Cantera_nasa_base_cond"
        | "nuig_thermo"
        | "NASA"
        | "NASA7" => ThermoEnum::NASA(super::NASAdata::NASAdata::new()),
        "NIST" | "NIST9" => ThermoEnum::NIST(super::NISTdata::NISTdata::new()),
        _ => panic!("no such library!"),
    }
}
pub fn energy_dimension(unit: EnergyUnit) -> String {
    match unit {
        EnergyUnit::J => "J".to_owned(),
        EnergyUnit::Cal => "cal".to_owned(),
    }
}

#[cfg(test)]
mod error_conversion_tests {
    use super::{NistParserError, ThermoError};
    use crate::Thermodynamics::DBhandlers::NISTdata::NISTError;
    use std::error::Error;

    #[test]
    fn nist_facade_conversion_preserves_schema_and_parser_setup_categories() {
        let schema: ThermoError = NISTError::SchemaError("missing Cp rows".into()).into();
        assert!(matches!(schema, ThermoError::NISTSchema(message) if message == "missing Cp rows"));

        let setup: ThermoError = NISTError::ParserSetupError(NistParserError::ConfigurationError(
            "invalid client timeout".into(),
        ))
        .into();
        assert!(matches!(&setup, ThermoError::ParserSetupError(_)));
        assert!(setup.source().is_some());
    }
}

#[cfg(test)]
mod temperature_interval_tests {
    use super::temperature_intervals_cover_range;

    #[test]
    fn coverage_accepts_single_adjacent_overlapping_and_unsorted_intervals() {
        assert!(temperature_intervals_cover_range(
            &[(200.0, 1000.0)],
            200.0,
            1000.0
        ));
        assert!(temperature_intervals_cover_range(
            &[(200.0, 1000.0), (1000.0, 6000.0)],
            900.0,
            1500.0
        ));
        assert!(temperature_intervals_cover_range(
            &[(600.0, 1600.0), (200.0, 1000.0)],
            300.0,
            1500.0
        ));
        assert!(temperature_intervals_cover_range(
            &[(200.0, 300.0), (400.0, 2000.0)],
            500.0,
            1500.0
        ));
    }

    #[test]
    fn coverage_rejects_gaps_out_of_domain_and_malformed_inputs() {
        assert!(!temperature_intervals_cover_range(
            &[(200.0, 900.0), (1000.0, 6000.0)],
            300.0,
            1500.0
        ));
        assert!(!temperature_intervals_cover_range(
            &[(200.0, 300.0), (400.0, 2000.0)],
            350.0,
            1500.0
        ));
        assert!(!temperature_intervals_cover_range(
            &[(200.0, 1000.0)],
            1000.1,
            1500.0
        ));
        assert!(!temperature_intervals_cover_range(
            &[(0.0, 1000.0)],
            100.0,
            500.0
        ));
        assert!(!temperature_intervals_cover_range(
            &[(800.0, 200.0)],
            100.0,
            500.0
        ));
        assert!(!temperature_intervals_cover_range(&[], 100.0, 500.0));
        assert!(!temperature_intervals_cover_range(
            &[(200.0, 1000.0)],
            0.0,
            500.0
        ));
        assert!(!temperature_intervals_cover_range(
            &[(200.0, 1000.0)],
            700.0,
            600.0
        ));
    }

    #[test]
    fn inclusive_single_temperature_at_a_shared_endpoint_is_covered() {
        assert!(temperature_intervals_cover_range(
            &[(200.0, 1000.0), (1000.0, 6000.0)],
            1000.0,
            1000.0
        ));
    }
}