KiThe 0.3.7

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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! Immutable, phase-aware equilibrium results.
//!
//! A successful nonlinear solve first produces a canonical
//! [`EquilibriumSolution`]. This module attaches that numeric snapshot to the
//! phase-qualified layout, thermochemical provenance, and backend trace that
//! created it. The result is therefore safe to query without reconstructing
//! parallel vectors or guessing whether a bare substance name is ambiguous.

use std::collections::BTreeMap;
use std::fmt;

use crate::Thermodynamics::ChemEquilibrium::equilibrium_constant_cross_validation::EquilibriumConstantCrossValidationStatus;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::ReactionExtentError;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
    EquilibriumConditions, EquilibriumSolution,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::EquilibriumSolveReport;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::{
    EquilibriumTimingCollector, EquilibriumTimingReport, EquilibriumTimingStage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_workflows::{
    MultiphaseAcceptanceReport, PhaseControlledSolveReport, PhaseStatus,
};
use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::{
    EquilibriumPhaseDescriptor, PhaseEquilibriumBuildReport, PhaseEquilibriumMetadata,
    PhaseEquilibriumSolutionBundle,
};
use crate::Thermodynamics::phase_layout::{PhaseComponentId, PhaseId};

/// One stable row in a multiphase result summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MultiphaseEquilibriumSummaryRow {
    /// Logical section, for example `conditions`, `phase`, or `backend`.
    pub section: &'static str,
    /// Stable row key.
    pub label: String,
    /// Human-readable value.
    pub value: String,
}

impl fmt::Display for MultiphaseEquilibriumSummaryRow {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {} = {}", self.section, self.label, self.value)
    }
}

/// Immutable result of a fixed-active-set phase equilibrium calculation.
///
/// Every published value is tied to the bridge metadata that produced it.
/// Fixed active-set and bounded phase-control workflows differ only in their
/// phase-status and acceptance evidence, not in component lookup semantics.
#[derive(Debug, Clone, PartialEq)]
pub struct MultiphaseEquilibriumSolution {
    /// Phase-qualified layout and lookup provenance.
    metadata: PhaseEquilibriumMetadata,
    /// Immutable thermochemical preparation evidence.
    build_report: PhaseEquilibriumBuildReport,
    /// Accepted canonical numerical solution (log-moles + positive coordinates).
    accepted_solution: EquilibriumSolution,
    /// Published physical component moles in `SystemLayout` component order.
    /// Inactive, excluded, and disappeared phases are represented by zeroes;
    /// their positive solver trace coordinates never leak into this view.
    physical_component_moles: Vec<f64>,
    /// Published physical total moles per phase in declared phase order.
    phase_totals: Vec<f64>,
    /// Published physical mole fractions per component in `SystemLayout`
    /// component order. Components of inactive phases have fraction zero.
    mole_fractions: Vec<f64>,
    /// Numerical phase totals reconstructed from the accepted log-mole vector.
    /// This is diagnostic evidence for the nonlinear layer, not physical output.
    numerical_phase_totals: Vec<f64>,
    /// Lifecycle status for each declared phase (Active, Inactive, Excluded, etc.).
    phase_statuses: Vec<PhaseStatus>,
    /// Ordered backend cascade evidence for the accepted result.
    solve_report: EquilibriumSolveReport,
    /// Optional independent equilibrium-constant cross-validation status.
    keq_validation_status: Option<EquilibriumConstantCrossValidationStatus>,
    /// Bounded active-set transition evidence when phase control was used.
    phase_control_report: Option<PhaseControlledSolveReport>,
    /// Combined numerical and complementarity evidence when phase control was
    /// used to reach a stable phase set.
    acceptance_report: Option<MultiphaseAcceptanceReport>,
    /// Optional stage timing collected while this immutable result was built.
    timing: EquilibriumTimingReport,
}

impl MultiphaseEquilibriumSolution {
    /// Converts one accepted fixed-active bridge bundle into a queryable
    /// phase-aware result.
    ///
    /// Construction repeats the cheap boundary invariants deliberately. A
    /// future caller cannot accidentally combine the accepted numerical vector
    /// with provenance or a layout belonging to another resolved system.
    pub fn from_fixed_active_bundle(
        bundle: PhaseEquilibriumSolutionBundle,
    ) -> Result<Self, ReactionExtentError> {
        let metadata = bundle.metadata().clone();
        let build_report = bundle.build_report().clone();
        let accepted_solution = bundle.solution().clone();
        let solve_report = bundle.solve_report().clone();
        let keq_validation_status = bundle.keq_validation_status().cloned();
        let timing = *bundle.timing_report();

        Self::from_parts(
            metadata,
            build_report,
            accepted_solution,
            solve_report,
            keq_validation_status,
            None,
            None,
            None,
            timing,
        )
    }

    /// Converts accepted bounded phase-control evidence into the same public
    /// immutable result model used by fixed active-set solves.
    ///
    /// `phase_statuses` must remain aligned to the canonical bridge phase
    /// descriptors. This prevents an outer-loop report for one phase layout
    /// from being attached to moles or provenance belonging to another.
    pub(crate) fn from_phase_control_parts(
        metadata: PhaseEquilibriumMetadata,
        build_report: PhaseEquilibriumBuildReport,
        accepted_solution: EquilibriumSolution,
        solve_report: EquilibriumSolveReport,
        keq_validation_status: Option<EquilibriumConstantCrossValidationStatus>,
        phase_control_report: PhaseControlledSolveReport,
        acceptance_report: MultiphaseAcceptanceReport,
        phase_statuses: Vec<PhaseStatus>,
        timing: EquilibriumTimingReport,
    ) -> Result<Self, ReactionExtentError> {
        if acceptance_report.phase_control != phase_control_report {
            return Err(ReactionExtentError::InvalidCandidate {
                field: "multiphase_acceptance",
                message: "acceptance report does not retain the published phase-control report"
                    .to_string(),
            });
        }
        Self::from_parts(
            metadata,
            build_report,
            accepted_solution,
            solve_report,
            keq_validation_status,
            Some(phase_control_report),
            Some(acceptance_report),
            Some(phase_statuses),
            timing,
        )
    }

    fn from_parts(
        metadata: PhaseEquilibriumMetadata,
        build_report: PhaseEquilibriumBuildReport,
        accepted_solution: EquilibriumSolution,
        solve_report: EquilibriumSolveReport,
        keq_validation_status: Option<EquilibriumConstantCrossValidationStatus>,
        phase_control_report: Option<PhaseControlledSolveReport>,
        acceptance_report: Option<MultiphaseAcceptanceReport>,
        phase_statuses: Option<Vec<PhaseStatus>>,
        timing: EquilibriumTimingReport,
    ) -> Result<Self, ReactionExtentError> {
        if metadata.layout_fingerprint() != build_report.layout_fingerprint() {
            return Err(ReactionExtentError::InvalidCandidate {
                field: "multiphase_solution_layout",
                message: "accepted result and build report have different layout fingerprints"
                    .to_string(),
            });
        }
        if accepted_solution.conditions() != build_report.conditions() {
            return Err(ReactionExtentError::InvalidCandidate {
                field: "multiphase_solution_conditions",
                message: "accepted result and build report have different thermodynamic conditions"
                    .to_string(),
            });
        }
        if metadata.components().len() != accepted_solution.moles().len()
            || metadata.components().len() != build_report.components().len()
        {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "multiphase result has {} components, solution has {} moles, and build report has {} rows",
                metadata.components().len(),
                accepted_solution.moles().len(),
                build_report.components().len(),
            )));
        }
        let phase_statuses =
            phase_statuses.unwrap_or_else(|| vec![PhaseStatus::Active; metadata.phases().len()]);
        if phase_statuses.len() != metadata.phases().len() {
            return Err(ReactionExtentError::DimensionMismatch(format!(
                "multiphase result has {} phase descriptors but {} statuses",
                metadata.phases().len(),
                phase_statuses.len(),
            )));
        }

        let mut phase_totals = Vec::with_capacity(metadata.phases().len());
        let mut numerical_phase_totals = Vec::with_capacity(metadata.phases().len());
        let mut physical_component_moles = vec![0.0; metadata.components().len()];
        let mut mole_fractions = vec![0.0; metadata.components().len()];
        for phase in metadata.phases() {
            let range = phase.component_range();
            let numerical_total = accepted_solution.moles()[range.clone()].iter().sum::<f64>();
            if !numerical_total.is_finite() || numerical_total <= 0.0 {
                return Err(ReactionExtentError::InvalidCandidate {
                    field: "multiphase_phase_total",
                    message: format!(
                        "phase {:?} has invalid accepted numerical total {numerical_total:e}",
                        phase.id().as_option()
                    ),
                });
            }
            numerical_phase_totals.push(numerical_total);

            let phase_index = phase.index().index();
            if phase_statuses[phase_index].is_active() {
                for component_index in range.clone() {
                    physical_component_moles[component_index] =
                        accepted_solution.moles()[component_index];
                    mole_fractions[component_index] =
                        accepted_solution.moles()[component_index] / numerical_total;
                }
                phase_totals.push(numerical_total);
            } else {
                // The solver must keep a positive coordinate for log-space
                // evaluation, but an absent physical phase has zero inventory.
                phase_totals.push(0.0);
            }
        }

        Ok(Self {
            metadata,
            build_report,
            accepted_solution,
            physical_component_moles,
            phase_totals,
            mole_fractions,
            numerical_phase_totals,
            phase_statuses,
            solve_report,
            keq_validation_status,
            phase_control_report,
            acceptance_report,
            timing,
        })
    }

    /// Fixed pressure-temperature conditions retained by the accepted snapshot.
    pub fn conditions(&self) -> EquilibriumConditions {
        self.accepted_solution.conditions()
    }

    /// Canonical phase-qualified layout and provenance identity.
    pub fn metadata(&self) -> &PhaseEquilibriumMetadata {
        &self.metadata
    }

    /// Layout fingerprint that must match the originating resolved system.
    pub fn layout_fingerprint(&self) -> u64 {
        self.metadata.layout_fingerprint()
    }

    /// Original immutable standard-state and lookup evidence.
    pub fn build_report(&self) -> &PhaseEquilibriumBuildReport {
        &self.build_report
    }

    /// Optional stage timing collected while this immutable result was built.
    pub fn timing_report(&self) -> &EquilibriumTimingReport {
        &self.timing
    }

    /// Updates only the wall-clock total after an enclosing public operation
    /// has completed. Stage measurements remain unchanged.
    pub(crate) fn with_timing_total(mut self, total: std::time::Duration) -> Self {
        if self.timing.enabled() {
            let mut collector = EquilibriumTimingCollector::from_report(self.timing);
            collector.set_total(total);
            self.timing = collector.finish();
        }
        self
    }

    /// Adds one enclosing-operation stage without rebuilding the result.
    pub(crate) fn with_timing_stage(
        mut self,
        stage: EquilibriumTimingStage,
        duration: std::time::Duration,
    ) -> Self {
        if self.timing.enabled() {
            let mut collector = EquilibriumTimingCollector::from_report(self.timing);
            collector.record(stage, duration);
            self.timing = collector.finish();
        }
        self
    }

    /// Canonical accepted numerical log-mole/positive-mole snapshot.
    ///
    /// This is the solver coordinate record. It may contain trace-floor
    /// amounts for absent phases and is therefore not the physical result view.
    pub fn accepted_solution(&self) -> &EquilibriumSolution {
        &self.accepted_solution
    }

    /// Published physical component amounts in exact `SystemLayout` order.
    ///
    /// Inactive, excluded, and disappeared phases are exactly zero here even
    /// though their numerical log-mole coordinates remain positive internally.
    pub fn component_moles(&self) -> &[f64] {
        &self.physical_component_moles
    }

    /// Numerical positive-mole coordinates retained for diagnostics.
    pub fn numerical_component_moles(&self) -> &[f64] {
        self.accepted_solution.moles()
    }

    /// Finds the accepted amount of one fully-qualified component.
    pub fn moles_for(&self, component: &PhaseComponentId) -> Option<f64> {
        self.metadata
            .component_index(component)
            .map(|index| self.physical_component_moles[index])
    }

    /// Finds the numerical positive-mole coordinate of one component.
    pub fn numerical_moles_for(&self, component: &PhaseComponentId) -> Option<f64> {
        self.metadata
            .component_index(component)
            .map(|index| self.accepted_solution.moles()[index])
    }

    /// Finds the local mole fraction of one fully-qualified component.
    pub fn mole_fraction_for(&self, component: &PhaseComponentId) -> Option<f64> {
        self.metadata
            .component_index(component)
            .map(|index| self.mole_fractions[index])
    }

    /// Ordered phase descriptors used by the accepted snapshot.
    pub fn phases(&self) -> &[EquilibriumPhaseDescriptor] {
        self.metadata.phases()
    }

    /// Accepted total mole amount in one semantic phase.
    pub fn phase_total(&self, phase: &PhaseId) -> Option<f64> {
        self.metadata
            .phase_index(phase)
            .map(|index| self.phase_totals[index.index()])
    }

    /// Numerical positive-mole total retained for one phase.
    pub fn numerical_phase_total(&self, phase: &PhaseId) -> Option<f64> {
        self.metadata
            .phase_index(phase)
            .map(|index| self.numerical_phase_totals[index.index()])
    }

    /// Explicit lifecycle state for one semantic phase.
    pub fn phase_status(&self, phase: &PhaseId) -> Option<PhaseStatus> {
        self.metadata
            .phase_index(phase)
            .map(|index| self.phase_statuses[index.index()])
    }

    /// Aggregates published physical amounts by bare substance as an explicit derived
    /// view. It is intentionally not used for solver identity because a name
    /// can occur in several physical phases.
    pub fn aggregate_moles_by_substance(&self) -> BTreeMap<String, f64> {
        let mut totals = BTreeMap::new();
        for (descriptor, moles) in self
            .metadata
            .components()
            .iter()
            .zip(self.physical_component_moles.iter().copied())
        {
            *totals
                .entry(descriptor.substance().to_string())
                .or_insert(0.0) += moles;
        }
        totals
    }

    /// Aggregates numerical positive-mole coordinates by bare substance.
    ///
    /// This diagnostic view is useful when explaining a trace-floor or a
    /// backend acceptance decision; it must not be used as physical inventory.
    pub fn aggregate_numerical_moles_by_substance(&self) -> BTreeMap<String, f64> {
        let mut totals = BTreeMap::new();
        for (descriptor, &moles) in self
            .metadata
            .components()
            .iter()
            .zip(self.accepted_solution.moles())
        {
            *totals
                .entry(descriptor.substance().to_string())
                .or_insert(0.0) += moles;
        }
        totals
    }

    /// Complete backend cascade evidence for the accepted solve.
    pub fn solve_report(&self) -> &EquilibriumSolveReport {
        &self.solve_report
    }

    /// Optional independent equilibrium-constant validation evidence.
    pub fn keq_validation_status(&self) -> Option<&EquilibriumConstantCrossValidationStatus> {
        self.keq_validation_status.as_ref()
    }

    /// Bounded phase-control evidence when this result was solved through the
    /// active-set outer loop.
    pub fn phase_control_report(&self) -> Option<&PhaseControlledSolveReport> {
        self.phase_control_report.as_ref()
    }

    /// Final complementarity/validation evidence when phase control was used.
    pub fn acceptance_report(&self) -> Option<&MultiphaseAcceptanceReport> {
        self.acceptance_report.as_ref()
    }

    /// Stable summary rows for CLI, snapshots, and a future GUI.
    pub fn summary_rows(&self) -> Vec<MultiphaseEquilibriumSummaryRow> {
        let mut rows = vec![
            MultiphaseEquilibriumSummaryRow {
                section: "conditions",
                label: "temperature_k".to_string(),
                value: format!("{:.6}", self.conditions().temperature()),
            },
            MultiphaseEquilibriumSummaryRow {
                section: "conditions",
                label: "pressure_pa".to_string(),
                value: format!("{:.6}", self.conditions().pressure()),
            },
            MultiphaseEquilibriumSummaryRow {
                section: "layout",
                label: "fingerprint".to_string(),
                value: self.layout_fingerprint().to_string(),
            },
            MultiphaseEquilibriumSummaryRow {
                section: "backend",
                label: "accepted".to_string(),
                value: format!("{:?}", self.solve_report.accepted_backend),
            },
            MultiphaseEquilibriumSummaryRow {
                section: "validation",
                label: "residual_l2_norm".to_string(),
                value: format!(
                    "{:.6e}",
                    self.accepted_solution.validation().residual_l2_norm
                ),
            },
        ];

        for (index, phase) in self.metadata.phases().iter().enumerate() {
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "phase",
                label: phase
                    .id()
                    .as_option()
                    .clone()
                    .unwrap_or_else(|| "single".to_string()),
                value: format!(
                    "total={:.6e}, status={:?}",
                    self.phase_totals[index], self.phase_statuses[index]
                ),
            });
        }
        if let Some(report) = &self.phase_control_report {
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "phase_control",
                label: "iterations".to_string(),
                value: report.iterations.to_string(),
            });
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "phase_control",
                label: "transitions".to_string(),
                value: report.transitions.len().to_string(),
            });
        }
        if let Some(report) = &self.acceptance_report {
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "acceptance",
                label: "complementarity_satisfied".to_string(),
                value: report.complementarity.satisfied.to_string(),
            });
        }
        if let Some(status) = &self.keq_validation_status {
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "keq_validation",
                label: "status".to_string(),
                value: match status {
                    EquilibriumConstantCrossValidationStatus::Compared(report) => {
                        format!("compared accepted={}", report.accepted)
                    }
                    EquilibriumConstantCrossValidationStatus::CanonicalFailed { .. } => {
                        "canonical_failed".to_string()
                    }
                    EquilibriumConstantCrossValidationStatus::ValidatorFailed { .. } => {
                        "validator_failed".to_string()
                    }
                    EquilibriumConstantCrossValidationStatus::ValidatorNotApplicable { .. } => {
                        "not_applicable".to_string()
                    }
                },
            });
        }
        for (index, component) in self.metadata.components().iter().enumerate() {
            rows.push(MultiphaseEquilibriumSummaryRow {
                section: "component",
                label: component.label(),
                value: format!(
                    "moles={:.6e}, x={:.6e}",
                    self.physical_component_moles[index], self.mole_fractions[index]
                ),
            });
        }
        rows
    }
}

impl fmt::Display for MultiphaseEquilibriumSolution {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for row in self.summary_rows() {
            writeln!(f, "{row}")?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    //! Boundary regressions for immutable phase-aware result publication.
    //!
    //! The fixture uses two independently valid local NASA gas requests.  The
    //! test then attempts to combine metadata from one request with the build
    //! evidence from the other, which must fail before a public result exists.

    use std::collections::HashMap;

    use crate::Thermodynamics::ChemEquilibrium::equilibrium_multiphase_domain::{
        MultiphaseEquilibriumLayout, MultiphaseInitialComposition,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_problem::{
        EquilibriumConditions, TraceSpeciesSeedPolicy,
    };
    use crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::{
        PhaseEquilibriumBuildRequest, build_phase_equilibrium_problem,
    };
    use crate::Thermodynamics::User_PhaseOrSolution::{PhaseSpec, ResolvedPhaseSystem};
    use crate::Thermodynamics::User_substances::{LibraryPriority, SubsData};
    use crate::Thermodynamics::phase_layout::PhaseId;

    use super::MultiphaseEquilibriumSolution;

    fn accepted_local_nasa_gas(phase_name: &str) -> crate::Thermodynamics::ChemEquilibrium::phase_equilibrium_problem::PhaseEquilibriumSolutionBundle{
        let phase_id = PhaseId::new(Some(phase_name.to_string()));
        let phase = PhaseSpec::ideal_gas(
            phase_id.clone(),
            vec!["H2".to_string(), "O2".to_string(), "H2O".to_string()],
        )
        .unwrap();
        let mut data = SubsData::new();
        data.substances = vec!["H2".to_string(), "O2".to_string(), "H2O".to_string()];
        data.set_multiple_library_priorities(
            vec!["NASA_gas".to_string()],
            LibraryPriority::Priority,
        );
        data.search_substances().unwrap();
        data.parse_all_thermal_coeffs().unwrap();
        let resolved = ResolvedPhaseSystem::new(
            vec![phase],
            HashMap::from([(Some(phase_name.to_string()), data)]),
        )
        .unwrap();
        let layout = MultiphaseEquilibriumLayout::new(resolved.phase_specs().to_vec()).unwrap();
        let composition =
            MultiphaseInitialComposition::from_dense(&layout, vec![2.0, 1.0, 0.0]).unwrap();

        build_phase_equilibrium_problem(
            PhaseEquilibriumBuildRequest::new(
                &resolved,
                EquilibriumConditions::new(1200.0, 101_325.0, 101_325.0).unwrap(),
                composition,
                TraceSpeciesSeedPolicy::Absolute { floor: 1e-30 },
                Default::default(),
            )
            .unwrap(),
        )
        .unwrap()
        .solve()
        .unwrap()
    }

    #[test]
    fn reconstruction_rejects_metadata_and_build_report_from_different_layouts() {
        let gas = accepted_local_nasa_gas("gas");
        let other = accepted_local_nasa_gas("other_gas");
        assert_ne!(
            gas.metadata().layout_fingerprint(),
            other.build_report().layout_fingerprint()
        );

        let error = MultiphaseEquilibriumSolution::from_parts(
            gas.metadata().clone(),
            other.build_report().clone(),
            gas.solution().clone(),
            gas.solve_report().clone(),
            gas.keq_validation_status().cloned(),
            None,
            None,
            None,
            crate::Thermodynamics::ChemEquilibrium::equilibrium_timing::
                EquilibriumTimingReport::default(),
        )
        .unwrap_err();

        assert!(matches!(
            error,
            crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::ReactionExtentError::InvalidCandidate {
                field: "multiphase_solution_layout",
                ..
            }
        ));
    }
}