KiThe 0.3.6

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical engeneering. Work in progress. Advices and contributions will be appreciated
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
//! Compatibility facade over single- and multi-phase thermodynamic systems.
//!
//! `CustomSubstance` deliberately owns no calculation state. It normalizes
//! read-only access across `OnePhase` and `PhaseOrSolution` while the shared
//! `PhaseSystem` remains the engine beneath both variants.

use std::collections::HashMap;

use RustedSciThe::symbolic::symbolic_engine::Expr;
use enum_dispatch::enum_dispatch;
use nalgebra::DMatrix;

use crate::Thermodynamics::User_PhaseOrSolution2::OnePhase;
use crate::Thermodynamics::User_substances_error::{SubsDataError, SubsDataResult};
use crate::Thermodynamics::phase_layout::SystemLayout;

use super::{
    MoleNumberSnapshot, NestedPhaseCacheView, PhaseDataPreparation, PhaseEquilibriumAssembly,
    PhaseLagrangeFunction, PhaseLayoutAccess, PhaseOrSolution, PhaseSymbolicPropertyBuilder,
    ResolvedPhaseSystemReport, SubstancesContainer, ThermoCacheSnapshot, ThermoResultSnapshot,
    ThermoStateSnapshot, ThermodynamicsCalculatorTrait, build_cache_snapshot,
};

/// Unified compatibility interface for single- and multi-phase systems.
///
/// New code should prefer the narrow phase traits; this enum preserves one
/// read-only facade for existing consumers that must accept either shape.
#[derive(Debug, Clone)]
#[enum_dispatch(ThermodynamicsCalculatorTrait)]
pub enum CustomSubstance {
    OnePhase(OnePhase),
    PhaseOrSolution(PhaseOrSolution),
}

impl CustomSubstance {
    pub fn system_layout(&self) -> SystemLayout {
        match self {
            Self::OnePhase(one_phase) => one_phase.system_layout(),
            Self::PhaseOrSolution(phase_or_solution) => phase_or_solution.system_layout(),
        }
    }

    pub fn layout_revision(&self) -> usize {
        match self {
            Self::OnePhase(one_phase) => one_phase.layout_revision(),
            Self::PhaseOrSolution(phase_or_solution) => phase_or_solution.layout_revision(),
        }
    }

    pub fn state_snapshot(&self) -> ThermoStateSnapshot<'_> {
        match self {
            Self::OnePhase(one_phase) => one_phase.state_snapshot(),
            Self::PhaseOrSolution(phase_or_solution) => phase_or_solution.state_snapshot(),
        }
    }

    pub fn result_snapshot(
        &self,
        temperature: Option<f64>,
        pressure: Option<f64>,
    ) -> ThermoResultSnapshot<'_> {
        match self {
            Self::OnePhase(one_phase) => one_phase.result_snapshot(temperature, pressure),
            Self::PhaseOrSolution(phase_or_solution) => {
                phase_or_solution.result_snapshot(temperature, pressure)
            }
        }
    }

    pub fn dG_snapshot(&self) -> ThermoCacheSnapshot<'_, f64> {
        build_cache_snapshot(self.layout_revision(), self.get_dG_view())
    }

    pub fn dG_sym_snapshot(&self) -> ThermoCacheSnapshot<'_, Expr> {
        build_cache_snapshot(self.layout_revision(), self.get_dG_sym_view())
    }

    pub fn dS_snapshot(&self) -> ThermoCacheSnapshot<'_, f64> {
        build_cache_snapshot(self.layout_revision(), self.get_dS_view())
    }

    pub fn dS_sym_snapshot(&self) -> ThermoCacheSnapshot<'_, Expr> {
        build_cache_snapshot(self.layout_revision(), self.get_dS_sym_view())
    }

    /// Typed lookup provenance for the resolved payloads, if this facade came
    /// from the typed resolution pipeline.
    pub fn resolution_report(&self) -> Option<&ResolvedPhaseSystemReport> {
        match self {
            Self::OnePhase(one_phase) => one_phase.resolution_report(),
            Self::PhaseOrSolution(phase_or_solution) => phase_or_solution.resolution_report(),
        }
    }

    /// Returns legacy structural input without flattening phase identity.
    pub fn extract_SubstancesContainer(&self) -> SubsDataResult<SubstancesContainer> {
        match self {
            Self::OnePhase(subs_data) => Ok(SubstancesContainer::SinglePhase(
                subs_data.subs_data_view().substances.clone(),
            )),
            Self::PhaseOrSolution(phase_or_solution) => {
                let layout = phase_or_solution.system_layout();
                let mut phase_substances = HashMap::new();
                for phase in layout.phases() {
                    let phase_key =
                        phase
                            .as_option()
                            .clone()
                            .ok_or_else(|| SubsDataError::MissingData {
                                field: "phase name".to_string(),
                                substance: "unknown".to_string(),
                            })?;
                    let components = layout.components_for_phase(phase).ok_or_else(|| {
                        SubsDataError::MissingData {
                            field: "phase component layout".to_string(),
                            substance: phase_key.clone(),
                        }
                    })?;
                    phase_substances.insert(
                        phase_key,
                        components
                            .iter()
                            .map(|component| component.substance.clone())
                            .collect(),
                    );
                }
                Ok(SubstancesContainer::MultiPhase(phase_substances))
            }
        }
    }

    pub fn get_ordered_component_labels(&self) -> SubsDataResult<Vec<(Option<String>, String)>> {
        Ok(match self {
            Self::OnePhase(one_phase) => one_phase
                .subs_data_view()
                .substances
                .iter()
                .cloned()
                .map(|substance| (None, substance))
                .collect(),
            Self::PhaseOrSolution(phase_or_solution) => phase_or_solution
                .system_layout()
                .components()
                .iter()
                .map(|component| {
                    let phase_key = component.phase.as_option().clone().ok_or_else(|| {
                        SubsDataError::MissingData {
                            field: "phase name".to_string(),
                            substance: "unknown".to_string(),
                        }
                    })?;
                    Ok((Some(phase_key), component.substance.clone()))
                })
                .collect::<SubsDataResult<Vec<_>>>()?,
        })
    }

    pub fn get_ordered_substances(&self) -> SubsDataResult<Vec<String>> {
        Ok(self
            .get_ordered_component_labels()?
            .into_iter()
            .map(|(_, substance)| substance)
            .collect())
    }

    pub fn get_ordered_result_labels(&self) -> SubsDataResult<Vec<String>> {
        Ok(match self {
            Self::OnePhase(one_phase) => one_phase.subs_data_view().substances.clone(),
            Self::PhaseOrSolution(phase_or_solution) => {
                phase_or_solution.system_layout().component_labels()
            }
        })
    }

    pub fn normalize_mole_numbers(
        &self,
        non_zero_number_of_moles: HashMap<
            Option<String>,
            (Option<f64>, Option<HashMap<String, f64>>),
        >,
    ) -> SubsDataResult<MoleNumberSnapshot> {
        match self {
            Self::OnePhase(one_phase) => one_phase.normalize_mole_numbers(non_zero_number_of_moles),
            Self::PhaseOrSolution(phase_or_solution) => {
                phase_or_solution.normalize_mole_numbers(non_zero_number_of_moles)
            }
        }
    }

    /// Compatibility projection of the typed mole-number snapshot.
    pub fn create_full_map_of_mole_numbers(
        &self,
        non_zero_number_of_moles: HashMap<
            Option<String>,
            (Option<f64>, Option<HashMap<String, f64>>),
        >,
    ) -> SubsDataResult<(
        HashMap<Option<String>, (Option<f64>, Option<HashMap<String, f64>>)>,
        HashMap<Option<String>, (Option<f64>, Option<Vec<f64>>)>,
        HashMap<String, f64>,
    )> {
        match self {
            Self::OnePhase(one_phase) => {
                one_phase.create_full_map_of_mole_numbers(non_zero_number_of_moles)
            }
            Self::PhaseOrSolution(phase_or_solution) => {
                phase_or_solution.create_full_map_of_mole_numbers(non_zero_number_of_moles)
            }
        }
    }

    pub fn get_dG_sym_view(&self) -> NestedPhaseCacheView<'_, Expr> {
        match self {
            Self::OnePhase(one_phase) => NestedPhaseCacheView::Single(one_phase.dG_sym_view()),
            Self::PhaseOrSolution(phase_or_solution) => {
                NestedPhaseCacheView::Multi(phase_or_solution.dG_sym_view())
            }
        }
    }

    pub fn get_dG_sym(&self) -> NestedPhaseCacheView<'_, Expr> {
        self.get_dG_sym_view()
    }

    pub fn get_dG_view(&self) -> NestedPhaseCacheView<'_, f64> {
        match self {
            Self::OnePhase(one_phase) => NestedPhaseCacheView::Single(one_phase.dG_view()),
            Self::PhaseOrSolution(phase_or_solution) => {
                NestedPhaseCacheView::Multi(phase_or_solution.dG_view())
            }
        }
    }

    pub fn get_dG(&self) -> NestedPhaseCacheView<'_, f64> {
        self.get_dG_view()
    }

    pub fn get_dS_sym_view(&self) -> NestedPhaseCacheView<'_, Expr> {
        match self {
            Self::OnePhase(one_phase) => NestedPhaseCacheView::Single(one_phase.dS_sym_view()),
            Self::PhaseOrSolution(phase_or_solution) => {
                NestedPhaseCacheView::Multi(phase_or_solution.dS_sym_view())
            }
        }
    }

    pub fn get_dS_view(&self) -> NestedPhaseCacheView<'_, f64> {
        match self {
            Self::OnePhase(one_phase) => NestedPhaseCacheView::Single(one_phase.dS_view()),
            Self::PhaseOrSolution(phase_or_solution) => {
                NestedPhaseCacheView::Multi(phase_or_solution.dS_view())
            }
        }
    }
}

// The enum owns no separate state. These implementations are intentionally
// transparent forwarding so callers can use narrow capabilities without
// matching on the compatibility facade themselves.
impl PhaseDataPreparation for CustomSubstance {
    fn prepare_thermal_coefficients(&mut self, temperature: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.prepare_thermal_coefficients(temperature),
            Self::PhaseOrSolution(value) => value.prepare_thermal_coefficients(temperature),
        }
    }

    fn rebuild_numeric_thermodynamic_properties(&mut self, temperature: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.rebuild_numeric_thermodynamic_properties(temperature),
            Self::PhaseOrSolution(value) => {
                value.rebuild_numeric_thermodynamic_properties(temperature)
            }
        }
    }

    fn rebuild_symbolic_thermodynamic_properties(&mut self) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.rebuild_symbolic_thermodynamic_properties(),
            Self::PhaseOrSolution(value) => value.rebuild_symbolic_thermodynamic_properties(),
        }
    }

    fn ensure_coefficients_for_temperature(
        &mut self,
        temperature: f64,
    ) -> SubsDataResult<Vec<String>> {
        match self {
            Self::OnePhase(value) => value.ensure_coefficients_for_temperature(temperature),
            Self::PhaseOrSolution(value) => value.ensure_coefficients_for_temperature(temperature),
        }
    }

    fn configure_phase_properties(
        &mut self,
        pressure: f64,
        pressure_unit: Option<String>,
        molar_masses: HashMap<String, f64>,
        mass_unit: Option<String>,
    ) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => {
                value.configure_phase_properties(pressure, pressure_unit, molar_masses, mass_unit)
            }
            Self::PhaseOrSolution(value) => {
                value.configure_phase_properties(pressure, pressure_unit, molar_masses, mass_unit)
            }
        }
    }

    fn fetch_missing_thermochemistry_from_nist(&mut self) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.fetch_missing_thermochemistry_from_nist(),
            Self::PhaseOrSolution(value) => value.fetch_missing_thermochemistry_from_nist(),
        }
    }
}

impl PhaseSymbolicPropertyBuilder for CustomSubstance {
    fn build_symbolic_gibbs(&mut self, temperature: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.build_symbolic_gibbs(temperature),
            Self::PhaseOrSolution(value) => value.build_symbolic_gibbs(temperature),
        }
    }

    fn build_gibbs_functions(&mut self, temperature: f64, pressure: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.build_gibbs_functions(temperature, pressure),
            Self::PhaseOrSolution(value) => value.build_gibbs_functions(temperature, pressure),
        }
    }

    fn substitute_pressure_in_symbolic_gibbs(&mut self, pressure: f64) {
        match self {
            Self::OnePhase(value) => value.substitute_pressure_in_symbolic_gibbs(pressure),
            Self::PhaseOrSolution(value) => value.substitute_pressure_in_symbolic_gibbs(pressure),
        }
    }

    fn substitute_temperature_in_symbolic_gibbs(&mut self, temperature: f64) {
        match self {
            Self::OnePhase(value) => value.substitute_temperature_in_symbolic_gibbs(temperature),
            Self::PhaseOrSolution(value) => {
                value.substitute_temperature_in_symbolic_gibbs(temperature)
            }
        }
    }

    fn build_symbolic_entropy(&mut self, temperature: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.build_symbolic_entropy(temperature),
            Self::PhaseOrSolution(value) => value.build_symbolic_entropy(temperature),
        }
    }

    fn build_entropy_functions(&mut self, temperature: f64, pressure: f64) -> SubsDataResult<()> {
        match self {
            Self::OnePhase(value) => value.build_entropy_functions(temperature, pressure),
            Self::PhaseOrSolution(value) => value.build_entropy_functions(temperature, pressure),
        }
    }
}

impl PhaseEquilibriumAssembly for CustomSubstance {
    fn build_symbolic_lagrange_equations(
        &mut self,
        element_matrix: DMatrix<f64>,
        reference_temperature: f64,
    ) -> SubsDataResult<Vec<Expr>> {
        match self {
            Self::OnePhase(value) => {
                value.build_symbolic_lagrange_equations(element_matrix, reference_temperature)
            }
            Self::PhaseOrSolution(value) => {
                value.build_symbolic_lagrange_equations(element_matrix, reference_temperature)
            }
        }
    }

    fn build_numeric_lagrange_equations(
        &mut self,
        element_matrix: DMatrix<f64>,
        temperature: f64,
        pressure: f64,
        reference_temperature: f64,
    ) -> SubsDataResult<PhaseLagrangeFunction> {
        match self {
            Self::OnePhase(value) => value.build_numeric_lagrange_equations(
                element_matrix,
                temperature,
                pressure,
                reference_temperature,
            ),
            Self::PhaseOrSolution(value) => value.build_numeric_lagrange_equations(
                element_matrix,
                temperature,
                pressure,
                reference_temperature,
            ),
        }
    }
}