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
//! Typed declarations and resolved records for phase thermodynamics.
//!
//! This module deliberately contains no numeric property evaluation and no
//! cache state. It defines what a phase is before lookup, then validates the
//! layout-aligned payload produced by resolution.
//!
//! ```text
//! HIERARCHY
//!
//!             PhaseSpec
//!       /        |            \               
//! PhaseId PhasePhysicalState PhaseModel
//! ```

use std::collections::{HashMap, HashSet};
use std::fmt;

use crate::Thermodynamics::User_substances::{Phases, SubsData};
use crate::Thermodynamics::User_substances2::SearchSummaryReport;
use crate::Thermodynamics::phase_layout::{PhaseId, SystemLayout};
use crate::Thermodynamics::physical_state::NistFallbackPolicy;
use crate::Thermodynamics::physical_state::PhysicalState;
use tabled::settings::Style;
use tabled::{Table, Tabled};

use super::SubstanceSystemFactoryError;

/// Physical state of a phase. This is deliberately separate from the
/// thermodynamic model: a liquid is not automatically an ideal solution.
/// Backwards-compatible phase-level name for the canonical lookup state.
pub type PhasePhysicalState = PhysicalState;

/// Activity/mixing model actually implemented by the phase-property layer.
/// More elaborate solution models must be added with their standard-state and
/// activity-coefficient contracts; they must not be implied by a phase name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PhaseModel {
    /// One shared ideal-gas assemblage with pressure-normalized activities.
    IdealGas,
    /// Multicomponent ideal mixture in a condensed physical state.
    ///
    /// The numerical law uses component mole fractions. This is intentionally
    /// distinct from `PureCondensed`: the two share the `q = 1` limit only
    /// when an ideal solution contains exactly one component.
    IdealSolution,
    /// A one-component condensed phase with unit activity.
    PureCondensed,
}

/// Declarative definition of one phase before library data is resolved.
/// Components are ordered because that order is part of the numerical solver
/// contract and is preserved by `SystemLayout` after resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PhaseSpec {
    id: PhaseId,
    components: Vec<String>,
    physical_state: PhasePhysicalState,
    model: PhaseModel,
}

impl PhaseSpec {
    pub fn new(
        id: PhaseId,
        components: Vec<String>,
        physical_state: PhasePhysicalState,
        model: PhaseModel,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        let spec = Self {
            id,
            components,
            physical_state,
            model,
        };
        spec.validate()?;
        Ok(spec)
    }

    pub fn ideal_gas(
        id: PhaseId,
        components: Vec<String>,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        Self::new(
            id,
            components,
            PhasePhysicalState::Gas,
            PhaseModel::IdealGas,
        )
    }

    pub fn pure_condensed(
        id: PhaseId,
        components: Vec<String>,
        physical_state: PhasePhysicalState,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        Self::new(id, components, physical_state, PhaseModel::PureCondensed)
    }

    /// Builds a multicomponent ideal condensed solution.
    ///
    /// Physical state and mixing semantics remain explicit: callers must not
    /// infer ideal mixing from a liquid or solid label alone.
    pub fn ideal_solution(
        id: PhaseId,
        components: Vec<String>,
        physical_state: PhasePhysicalState,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        Self::new(id, components, physical_state, PhaseModel::IdealSolution)
    }

    pub fn id(&self) -> &PhaseId {
        &self.id
    }

    pub fn components(&self) -> &[String] {
        &self.components
    }

    pub fn physical_state(&self) -> PhasePhysicalState {
        self.physical_state
    }

    pub fn model(&self) -> PhaseModel {
        self.model
    }

    /// Derives the per-substance lookup-state projection required by `SubsData`.
    ///
    /// `PhaseSpec` remains the canonical owner of physical state. This map is
    /// a compatibility-shaped projection for lower-level record lookup, not
    /// an independent declaration that callers should maintain by hand.
    pub(crate) fn legacy_component_phase_map(&self) -> HashMap<String, Option<Phases>> {
        let state = Some(self.physical_state);
        self.components
            .iter()
            .cloned()
            .map(|component| (component, state))
            .collect()
    }

    pub(crate) fn validate(&self) -> Result<(), SubstanceSystemFactoryError> {
        if let Some(name) = self.id.as_option() {
            if name.trim().is_empty() {
                return Err(SubstanceSystemFactoryError::InvalidSpecification {
                    field: "phase id".to_string(),
                    reason: "named phases must have a non-empty identifier".to_string(),
                });
            }
        }
        if self.components.is_empty() {
            return Err(SubstanceSystemFactoryError::InvalidSpecification {
                field: "phase components".to_string(),
                reason: "each phase must contain at least one substance".to_string(),
            });
        }
        let mut seen = HashSet::with_capacity(self.components.len());
        for component in &self.components {
            if component.trim().is_empty() || !seen.insert(component) {
                return Err(SubstanceSystemFactoryError::InvalidSpecification {
                    field: "phase components".to_string(),
                    reason: format!(
                        "component '{}' is empty or duplicated within phase",
                        component
                    ),
                });
            }
        }
        match (self.physical_state, self.model) {
            (PhasePhysicalState::Gas, PhaseModel::IdealGas) => Ok(()),
            (
                PhasePhysicalState::Liquid
                | PhasePhysicalState::Solid
                | PhasePhysicalState::Condensed,
                PhaseModel::IdealSolution,
            ) => Ok(()),
            (
                PhasePhysicalState::Liquid
                | PhasePhysicalState::Solid
                | PhasePhysicalState::Condensed,
                PhaseModel::PureCondensed,
            ) if self.components.len() == 1 => Ok(()),
            (_, PhaseModel::PureCondensed) => {
                Err(SubstanceSystemFactoryError::InvalidSpecification {
                    field: "phase components".to_string(),
                    reason: "a pure condensed phase must contain exactly one component".to_string(),
                })
            }
            (state, model) => Err(SubstanceSystemFactoryError::InvalidSpecification {
                field: "phase model".to_string(),
                reason: format!(
                    "model {:?} is not implemented for physical state {:?}",
                    model, state
                ),
            }),
        }
    }
}

/// Fully resolved phase-system input. It connects validated declarations to
/// the exact `SubsData` records selected from the thermodynamic libraries and
/// to the solver component order derived from those records.
///
/// This is intentionally distinct from `PhaseSystem`, which owns mutable
/// computed caches. Resolution is a fallible boundary; evaluation is not
/// allowed to silently change what was resolved.
///
/// The accompanying report preserves the lookup provenance selected for each
/// phase, including whether NIST fallback was enabled for this resolution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PhaseResolutionSummary {
    phase: PhaseId,
    search: SearchSummaryReport,
}

impl PhaseResolutionSummary {
    pub fn phase(&self) -> &PhaseId {
        &self.phase
    }

    pub fn search(&self) -> &SearchSummaryReport {
        &self.search
    }
}

/// Immutable lookup provenance paired with a resolved phase-system payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedPhaseSystemReport {
    nist_fallback_policy: NistFallbackPolicy,
    phases: Vec<PhaseResolutionSummary>,
}

impl ResolvedPhaseSystemReport {
    /// Whether unresolved local records were allowed to query NIST.
    pub fn nist_fallback_enabled(&self) -> bool {
        self.nist_fallback_policy.enabled()
    }

    /// Exact policy used when local phase records were missing.
    pub fn nist_fallback_policy(&self) -> NistFallbackPolicy {
        self.nist_fallback_policy
    }

    /// Per-phase lookup summaries in canonical solver phase order.
    pub fn phases(&self) -> &[PhaseResolutionSummary] {
        &self.phases
    }

    /// Finds lookup provenance for one phase identity.
    pub fn phase(&self, phase: &PhaseId) -> Option<&PhaseResolutionSummary> {
        self.phases.iter().find(|summary| summary.phase == *phase)
    }

    /// Renders the resolved source records and property-level lookup states.
    pub fn render_table(&self) -> String {
        #[derive(Tabled)]
        struct Row {
            phase: String,
            substance: String,
            property: String,
            state: String,
            library: String,
            record_key: String,
            priority: String,
            calculator: String,
        }

        let rows = self
            .phases
            .iter()
            .flat_map(|phase| {
                phase.search.rows().iter().map(|search| Row {
                    phase: format!("{:?}", phase.phase),
                    substance: search.substance().to_string(),
                    property: search.property().to_string(),
                    state: search.state().to_string(),
                    library: search.library().to_string(),
                    record_key: search.record_key().to_string(),
                    priority: search.priority().to_string(),
                    calculator: search.calculator().to_string(),
                })
            })
            .collect::<Vec<_>>();
        let fallback = if self.nist_fallback_policy.enabled() {
            format!("enabled ({:?})", self.nist_fallback_policy)
        } else {
            "disabled".to_string()
        };
        format!(
            "Resolved phase thermochemistry; NIST fallback={fallback}\nPending means the property was not queried, not that a record is missing.\n{}",
            Table::new(rows).with(Style::modern_rounded())
        )
    }
}

#[derive(Clone)]
pub struct ResolvedPhaseSystem {
    phase_specs: Vec<PhaseSpec>,
    phase_data: HashMap<Option<String>, SubsData>,
    layout: SystemLayout,
    report: ResolvedPhaseSystemReport,
}

impl ResolvedPhaseSystem {
    pub fn new(
        phase_specs: Vec<PhaseSpec>,
        phase_data: HashMap<Option<String>, SubsData>,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        Self::new_with_nist_fallback_policy(phase_specs, phase_data, NistFallbackPolicy::Disabled)
    }

    /// Creates a resolved system while retaining the lookup policy that
    /// produced the phase payloads.
    pub(crate) fn new_with_nist_fallback_policy(
        mut phase_specs: Vec<PhaseSpec>,
        phase_data: HashMap<Option<String>, SubsData>,
        nist_fallback_policy: NistFallbackPolicy,
    ) -> Result<Self, SubstanceSystemFactoryError> {
        phase_specs.sort_by(|left, right| left.id.cmp(&right.id));
        let expected_keys = phase_specs
            .iter()
            .map(|spec| spec.id.as_option().clone())
            .collect::<HashSet<_>>();
        let resolved_keys = phase_data.keys().cloned().collect::<HashSet<_>>();
        if expected_keys != resolved_keys {
            return Err(SubstanceSystemFactoryError::InvalidSpecification {
                field: "resolved phases".to_string(),
                reason: "resolved phase records do not match the requested phase ids".to_string(),
            });
        }
        for phase in &phase_specs {
            let key = phase.id.as_option();
            let data = phase_data.get(key).ok_or_else(|| {
                SubstanceSystemFactoryError::InvalidSpecification {
                    field: "resolved phases".to_string(),
                    reason: format!("missing resolved record for phase {:?}", phase.id),
                }
            })?;
            if data.substances != phase.components {
                return Err(SubstanceSystemFactoryError::InvalidSpecification {
                    field: "resolved phase components".to_string(),
                    reason: format!(
                        "resolved component order for phase {:?} differs from its specification",
                        phase.id
                    ),
                });
            }
        }
        let layout = SystemLayout::from_phase_map(&phase_data);
        let phase_reports = phase_specs
            .iter()
            .map(|phase| {
                let key = phase.id.as_option();
                let data = phase_data.get(key).ok_or_else(|| {
                    SubstanceSystemFactoryError::InvalidSpecification {
                        field: "resolved phases".to_string(),
                        reason: format!(
                            "missing resolved record while reporting phase {:?}",
                            phase.id
                        ),
                    }
                })?;
                Ok(PhaseResolutionSummary {
                    phase: phase.id.clone(),
                    search: data.search_summary_report(),
                })
            })
            .collect::<Result<Vec<_>, SubstanceSystemFactoryError>>()?;
        let report = ResolvedPhaseSystemReport {
            nist_fallback_policy,
            phases: phase_reports,
        };
        Ok(Self {
            phase_specs,
            phase_data,
            layout,
            report,
        })
    }

    pub fn phase_specs(&self) -> &[PhaseSpec] {
        &self.phase_specs
    }

    pub fn layout(&self) -> &SystemLayout {
        &self.layout
    }

    pub fn phase_data(&self) -> &HashMap<Option<String>, SubsData> {
        &self.phase_data
    }

    /// Typed lookup provenance for the resolved payloads.
    pub fn report(&self) -> &ResolvedPhaseSystemReport {
        &self.report
    }

    pub(crate) fn into_parts(
        self,
    ) -> (
        Vec<PhaseSpec>,
        HashMap<Option<String>, SubsData>,
        SystemLayout,
        ResolvedPhaseSystemReport,
    ) {
        (self.phase_specs, self.phase_data, self.layout, self.report)
    }
}

impl fmt::Debug for ResolvedPhaseSystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ResolvedPhaseSystem")
            .field("phase_specs", &self.phase_specs)
            .field("layout", &self.layout)
            .finish_non_exhaustive()
    }
}