KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, 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
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
//! Deterministic candidate selection for element-defined equilibrium systems.
//!
//! Element search is deliberately kept separate from solving.  A catalog can
//! tell us that a name occurs under an element, but that fact alone does not
//! decide which library record, physical state, or temperature interval is
//! suitable for a production equilibrium problem.  This module makes those
//! decisions explicit and returns an auditable report instead of mutating
//! `SubsData` or the repository.

use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventory;
use crate::Thermodynamics::User_PhaseOrSolution::{
    PhaseModel, PhaseSpec, SubstanceSystemFactoryError, SubstanceSystemSpec,
};
use crate::Thermodynamics::phase_layout::PhaseId;
use crate::Thermodynamics::physical_state::PhysicalState;
use crate::Thermodynamics::thermo_lib_api::{ElementSearchMode, ThermoData, ThermoRepository};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::Arc;

/// A requested temperature interval for candidate screening.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CandidateTemperatureRange {
    lower: f64,
    upper: f64,
}

impl CandidateTemperatureRange {
    /// Creates a finite, positive, non-empty temperature interval.
    pub fn new(lower: f64, upper: f64) -> Result<Self, CandidateSelectionError> {
        if !lower.is_finite() || !upper.is_finite() || lower <= 0.0 || lower > upper {
            return Err(CandidateSelectionError::InvalidPolicy(
                "temperature interval must be finite, positive, and lower <= upper".into(),
            ));
        }
        Ok(Self { lower, upper })
    }

    pub fn lower(self) -> f64 {
        self.lower
    }

    pub fn upper(self) -> f64 {
        self.upper
    }
}

/// How much temperature metadata was available in a catalog record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateTemperatureSupport {
    /// At least one stored coefficient interval covers the requested range.
    Supported,
    /// Stored intervals exist, but none covers the requested range.
    Unsupported,
    /// The library schema does not expose a recognizable interval field.
    Unknown,
}

/// Policy controlling conversion from an element query to equilibrium
/// candidates.
#[derive(Debug, Clone, PartialEq)]
pub struct EquilibriumCandidatePolicy {
    element_mode: ElementSearchMode,
    library_preference: Vec<String>,
    physical_states: Option<Vec<PhysicalState>>,
    temperature_range: Option<CandidateTemperatureRange>,
    max_candidates: Option<usize>,
}

impl Default for EquilibriumCandidatePolicy {
    fn default() -> Self {
        Self {
            element_mode: ElementSearchMode::SubsetOf,
            library_preference: Vec::new(),
            physical_states: None,
            temperature_range: None,
            max_candidates: None,
        }
    }
}

impl EquilibriumCandidatePolicy {
    pub fn new(element_mode: ElementSearchMode) -> Self {
        Self {
            element_mode,
            ..Self::default()
        }
    }

    pub fn with_library_preference(mut self, libraries: Vec<String>) -> Self {
        self.library_preference = libraries;
        self
    }

    pub fn with_physical_states(mut self, states: Vec<PhysicalState>) -> Self {
        self.physical_states = Some(states);
        self
    }

    pub fn with_temperature_range(
        mut self,
        lower: f64,
        upper: f64,
    ) -> Result<Self, CandidateSelectionError> {
        self.temperature_range = Some(CandidateTemperatureRange::new(lower, upper)?);
        Ok(self)
    }

    pub fn with_max_candidates(mut self, limit: usize) -> Result<Self, CandidateSelectionError> {
        if limit == 0 {
            return Err(CandidateSelectionError::InvalidPolicy(
                "max_candidates must be greater than zero".into(),
            ));
        }
        self.max_candidates = Some(limit);
        Ok(self)
    }

    pub fn element_mode(&self) -> ElementSearchMode {
        self.element_mode
    }

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

    pub fn physical_states(&self) -> Option<&[PhysicalState]> {
        self.physical_states.as_deref()
    }

    pub fn temperature_range(&self) -> Option<CandidateTemperatureRange> {
        self.temperature_range
    }

    pub fn max_candidates(&self) -> Option<usize> {
        self.max_candidates
    }
}

/// Why a catalog record was not selected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CandidateRejectionReason {
    ElementSetMismatch,
    LibraryNotPreferred,
    PhysicalStateMismatch,
    TemperatureUnsupported,
    MissingRecord,
    CandidateLimit,
}

/// One rejected record retained for diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidateRejection {
    substance: String,
    library: String,
    reason: CandidateRejectionReason,
}

impl CandidateRejection {
    pub fn substance(&self) -> &str {
        &self.substance
    }

    pub fn library(&self) -> &str {
        &self.library
    }

    pub fn reason(&self) -> &CandidateRejectionReason {
        &self.reason
    }
}

/// A record that passed the candidate policy and can be used to construct a
/// `PhaseSpec`/lookup request.
#[derive(Debug, Clone, PartialEq)]
pub struct EquilibriumCandidate {
    substance: String,
    library: String,
    record_key: String,
    physical_state: Option<PhysicalState>,
    elements: Vec<String>,
    temperature_support: CandidateTemperatureSupport,
    library_rank: usize,
}

impl EquilibriumCandidate {
    pub fn substance(&self) -> &str {
        &self.substance
    }

    pub fn library(&self) -> &str {
        &self.library
    }

    pub fn record_key(&self) -> &str {
        &self.record_key
    }

    pub fn physical_state(&self) -> Option<PhysicalState> {
        self.physical_state
    }

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

    pub fn temperature_support(&self) -> CandidateTemperatureSupport {
        self.temperature_support
    }

    pub fn library_rank(&self) -> usize {
        self.library_rank
    }
}

/// Complete immutable evidence from one candidate-selection transaction.
#[derive(Debug, Clone, PartialEq)]
pub struct EquilibriumCandidateSelectionReport {
    requested_elements: Vec<String>,
    policy: EquilibriumCandidatePolicy,
    selected: Vec<EquilibriumCandidate>,
    rejected: Vec<CandidateRejection>,
    truncated: bool,
}

/// Immutable automatic-selection evidence tied to the closed elemental
/// inventory that initiated it.
///
/// The nested report remains reusable for ordinary catalog queries, while this
/// wrapper preserves the physical `b` required to reproduce an element-defined
/// equilibrium problem after candidate selection is complete.
#[derive(Debug, Clone, PartialEq)]
pub struct ElementInventoryCandidateSelection {
    inventory: ElementInventory,
    report: EquilibriumCandidateSelectionReport,
}

impl ElementInventoryCandidateSelection {
    pub fn inventory(&self) -> &ElementInventory {
        &self.inventory
    }

    pub fn report(&self) -> &EquilibriumCandidateSelectionReport {
        &self.report
    }

    pub fn into_parts(self) -> (ElementInventory, EquilibriumCandidateSelectionReport) {
        (self.inventory, self.report)
    }
}

impl EquilibriumCandidateSelectionReport {
    pub fn requested_elements(&self) -> &[String] {
        &self.requested_elements
    }

    pub fn policy(&self) -> &EquilibriumCandidatePolicy {
        &self.policy
    }

    pub fn selected(&self) -> &[EquilibriumCandidate] {
        &self.selected
    }

    pub fn rejected(&self) -> &[CandidateRejection] {
        &self.rejected
    }

    /// Whether `max_candidates` excluded otherwise eligible records.
    pub fn is_truncated(&self) -> bool {
        self.truncated
    }
}

/// Explicit assignment of selected records to one physical phase.
///
/// Candidate selection answers "which records satisfy the catalog policy?";
/// it must not answer "which activity model should this phase use?".  This
/// value keeps that decision visible at the production boundary.  Components
/// are identified by their exact `record_key`, not by a broadened base name,
/// so condensed polymorphs such as `Fe(a)` and `Fe(c)` cannot be silently
/// substituted for one another.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EquilibriumCandidatePhaseAssignment {
    phase_id: PhaseId,
    physical_state: PhysicalState,
    model: PhaseModel,
    record_keys: Vec<String>,
}

impl EquilibriumCandidatePhaseAssignment {
    /// Creates one explicit phase assignment.
    pub fn new(
        phase_id: PhaseId,
        physical_state: PhysicalState,
        model: PhaseModel,
        record_keys: Vec<String>,
    ) -> Self {
        Self {
            phase_id,
            physical_state,
            model,
            record_keys,
        }
    }

    /// Convenience constructor for the currently supported ideal-gas model.
    pub fn ideal_gas(phase_id: PhaseId, record_keys: Vec<String>) -> Self {
        Self::new(
            phase_id,
            PhysicalState::Gas,
            PhaseModel::IdealGas,
            record_keys,
        )
    }

    /// Convenience constructor for a one-component pure condensed phase.
    pub fn pure_condensed(
        phase_id: PhaseId,
        physical_state: PhysicalState,
        record_keys: Vec<String>,
    ) -> Self {
        Self::new(
            phase_id,
            physical_state,
            PhaseModel::PureCondensed,
            record_keys,
        )
    }

    /// Convenience constructor for an explicitly ideal condensed solution.
    pub fn ideal_solution(
        phase_id: PhaseId,
        physical_state: PhysicalState,
        record_keys: Vec<String>,
    ) -> Self {
        Self::new(
            phase_id,
            physical_state,
            PhaseModel::IdealSolution,
            record_keys,
        )
    }

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

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

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

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

/// Physical phase plan that turns selected catalog records into a solver
/// specification.
///
/// The plan is deliberately separate from [`EquilibriumCandidatePolicy`].
/// The former is a user/model decision; the latter is a repository search
/// decision.  Keeping them separate prevents a broad element search from
/// accidentally creating an ideal-gas phase or a solution model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EquilibriumCandidatePhasePlan {
    assignments: Vec<EquilibriumCandidatePhaseAssignment>,
}

impl EquilibriumCandidatePhasePlan {
    pub fn new(assignments: Vec<EquilibriumCandidatePhaseAssignment>) -> Self {
        Self { assignments }
    }

    pub fn assignments(&self) -> &[EquilibriumCandidatePhaseAssignment] {
        &self.assignments
    }

    /// Builds a typed specification and pins each selected record to the
    /// library reported by the selection transaction.
    pub fn build_spec(
        &self,
        selection: &EquilibriumCandidateSelectionReport,
    ) -> Result<SubstanceSystemSpec, SubstanceSystemFactoryError> {
        let selected_by_key: HashMap<_, _> = selection
            .selected()
            .iter()
            .map(|candidate| (candidate.record_key().to_string(), candidate))
            .collect();
        if selected_by_key.len() != selection.selected().len() {
            return Err(invalid_plan(
                "candidate selection contains duplicate record keys",
            ));
        }

        let mut assigned = HashSet::new();
        let mut phase_specs = Vec::with_capacity(self.assignments.len());
        let mut explicit_libraries = HashMap::with_capacity(selected_by_key.len());
        let mut library_order = selection
            .selected()
            .iter()
            .map(|candidate| (candidate.library_rank(), candidate.library().to_string()))
            .collect::<Vec<_>>();
        library_order.sort_by_key(|(rank, _)| *rank);
        library_order.dedup_by(|left, right| left.1 == right.1);

        for assignment in &self.assignments {
            let mut components = Vec::with_capacity(assignment.record_keys.len());
            for record_key in &assignment.record_keys {
                let Some(candidate) = selected_by_key.get(record_key) else {
                    return Err(invalid_plan(format!(
                        "phase {:?} references unselected record '{}'",
                        assignment.phase_id.as_option(),
                        record_key
                    )));
                };
                if !assigned.insert(record_key.clone()) {
                    return Err(invalid_plan(format!(
                        "record '{}' is assigned to more than one phase",
                        record_key
                    )));
                }
                components.push(record_key.clone());
                explicit_libraries.insert(record_key.clone(), candidate.library().to_string());
            }
            let phase = PhaseSpec::new(
                assignment.phase_id.clone(),
                components,
                assignment.physical_state,
                assignment.model,
            )
            .map_err(|error| invalid_plan(error.to_string()))?;
            phase_specs.push(phase);
        }

        if assigned.len() != selected_by_key.len() {
            let missing = selected_by_key
                .keys()
                .filter(|record_key| !assigned.contains(*record_key))
                .cloned()
                .collect::<Vec<_>>();
            return Err(invalid_plan(format!(
                "selected records were not assigned to a phase: {missing:?}"
            )));
        }

        SubstanceSystemSpec::from_phases(phase_specs).map(|spec| {
            spec.with_lookup_policy(
                library_order
                    .iter()
                    .map(|(_, library)| library.clone())
                    .collect(),
                library_order
                    .iter()
                    .map(|(_, library)| library.clone())
                    .collect(),
                Some(explicit_libraries),
                false,
            )
        })
    }
}

fn invalid_plan(reason: impl Into<String>) -> SubstanceSystemFactoryError {
    SubstanceSystemFactoryError::InvalidSpecification {
        field: "candidate phase plan".to_string(),
        reason: reason.into(),
    }
}

/// Typed errors raised before any equilibrium problem is constructed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CandidateSelectionError {
    InvalidPolicy(String),
    EmptyElementSet,
    UnknownLibrary(String),
}

impl fmt::Display for CandidateSelectionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidPolicy(message) => write!(f, "invalid candidate policy: {message}"),
            Self::EmptyElementSet => write!(f, "candidate selection requires at least one element"),
            Self::UnknownLibrary(library) => {
                write!(f, "unknown thermochemical library '{library}'")
            }
        }
    }
}

impl std::error::Error for CandidateSelectionError {}

/// Selects real thermochemical records without mutating the repository.
pub struct EquilibriumCandidateSelector {
    repository: Arc<ThermoRepository>,
}

impl EquilibriumCandidateSelector {
    pub fn new(repository: Arc<ThermoRepository>) -> Self {
        Self { repository }
    }

    pub fn repository(&self) -> &Arc<ThermoRepository> {
        &self.repository
    }

    /// Selects records for a validated closed elemental inventory.
    ///
    /// Only the nonzero element directions in the inventory are used for the
    /// catalog query. Amounts remain physical conservation data for the later
    /// bridge and are never interpreted as species amounts by this selector.
    pub fn select_inventory(
        &self,
        inventory: &ElementInventory,
        policy: EquilibriumCandidatePolicy,
    ) -> Result<EquilibriumCandidateSelectionReport, CandidateSelectionError> {
        let elements = inventory
            .element_labels()
            .map(str::to_owned)
            .collect::<Vec<_>>();
        self.select(&elements, policy)
    }

    /// Performs typed selection while retaining both the immutable physical
    /// inventory and the full catalog selected/rejected report.
    pub fn select_inventory_with_provenance(
        &self,
        inventory: ElementInventory,
        policy: EquilibriumCandidatePolicy,
    ) -> Result<ElementInventoryCandidateSelection, CandidateSelectionError> {
        let report = self.select_inventory(&inventory, policy)?;
        Ok(ElementInventoryCandidateSelection { inventory, report })
    }

    /// Performs one deterministic, auditable selection transaction.
    pub fn select(
        &self,
        elements: &[String],
        policy: EquilibriumCandidatePolicy,
    ) -> Result<EquilibriumCandidateSelectionReport, CandidateSelectionError> {
        let requested_elements = normalize_elements(elements)?;
        let libraries = ordered_libraries(&self.repository, &policy)?;
        let library_ranks: HashMap<_, _> = libraries
            .iter()
            .enumerate()
            .map(|(rank, library)| (library.clone(), rank))
            .collect();
        let requested_set: HashSet<_> = requested_elements.iter().cloned().collect();

        let mut element_sets: HashMap<(String, String), HashSet<String>> = HashMap::new();
        for (element, pairs) in self.repository.ElementsData.iter() {
            for pair in pairs {
                if pair.len() < 2 {
                    continue;
                }
                let library = ThermoData::canonical_library_name(&pair[1]);
                if library_ranks.contains_key(&library) {
                    element_sets
                        .entry((library, pair[0].clone()))
                        .or_default()
                        .insert(element.clone());
                }
            }
        }

        let mut keys: Vec<_> = element_sets.keys().cloned().collect();
        keys.sort_by(|left, right| {
            library_ranks[&left.0]
                .cmp(&library_ranks[&right.0])
                .then_with(|| left.1.cmp(&right.1))
        });

        let mut selected = Vec::new();
        let mut rejected = Vec::new();
        let mut truncated = false;
        let mut selected_substances = HashSet::new();
        for (library, substance) in keys {
            let elements = &element_sets[&(library.clone(), substance.clone())];
            if !element_match(&requested_set, elements, policy.element_mode()) {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::ElementSetMismatch,
                ));
                continue;
            }
            let Some(records) = self.repository.LibThermoData.get(&library) else {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::MissingRecord,
                ));
                continue;
            };
            let Some(data) = records.get(&substance) else {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::MissingRecord,
                ));
                continue;
            };
            let query = crate::Thermodynamics::physical_state::ThermoRecordQuery::new(&substance);
            let Some(record) = self
                .repository
                .resolve_thermo_record(&library, &query)
                .map_err(|_| CandidateSelectionError::UnknownLibrary(library.clone()))?
            else {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::MissingRecord,
                ));
                continue;
            };
            if !physical_state_match(record.physical_state, policy.physical_states()) {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::PhysicalStateMismatch,
                ));
                continue;
            }
            let support = temperature_support(data, policy.temperature_range());
            if support == CandidateTemperatureSupport::Unsupported {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::TemperatureUnsupported,
                ));
                continue;
            }
            if policy
                .max_candidates()
                .is_some_and(|limit| selected.len() >= limit)
            {
                truncated = true;
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::CandidateLimit,
                ));
                continue;
            }
            if selected_substances.contains(&substance) {
                rejected.push(rejection(
                    &substance,
                    &library,
                    CandidateRejectionReason::LibraryNotPreferred,
                ));
                continue;
            }
            let library_rank = library_ranks[&library];
            let mut elements = elements.iter().cloned().collect::<Vec<_>>();
            elements.sort();
            selected.push(EquilibriumCandidate {
                substance: substance.clone(),
                library,
                record_key: record.record_key,
                physical_state: record.physical_state,
                elements,
                temperature_support: support,
                library_rank,
            });
            selected_substances.insert(substance);
        }

        Ok(EquilibriumCandidateSelectionReport {
            requested_elements,
            policy,
            selected,
            rejected,
            truncated,
        })
    }
}

fn normalize_elements(elements: &[String]) -> Result<Vec<String>, CandidateSelectionError> {
    let mut normalized: Vec<_> = elements
        .iter()
        .map(|element| element.trim().to_string())
        .filter(|element| !element.is_empty())
        .collect();
    normalized.sort();
    normalized.dedup();
    if normalized.is_empty() {
        return Err(CandidateSelectionError::EmptyElementSet);
    }
    Ok(normalized)
}

fn ordered_libraries(
    repository: &ThermoRepository,
    policy: &EquilibriumCandidatePolicy,
) -> Result<Vec<String>, CandidateSelectionError> {
    let source = if policy.library_preference().is_empty() {
        repository.thermo_libs.as_ref().clone()
    } else {
        policy.library_preference().to_vec()
    };
    let mut libraries = Vec::new();
    for library in source {
        let canonical = ThermoData::canonical_library_name(&library);
        if !repository.LibThermoData.contains_key(&canonical) {
            return Err(CandidateSelectionError::UnknownLibrary(library));
        }
        if !libraries.contains(&canonical) {
            libraries.push(canonical);
        }
    }
    Ok(libraries)
}

fn element_match(
    requested: &HashSet<String>,
    candidate: &HashSet<String>,
    mode: ElementSearchMode,
) -> bool {
    match mode {
        ElementSearchMode::AnyRequested => !requested.is_disjoint(candidate),
        ElementSearchMode::SubsetOf => candidate.is_subset(requested),
        ElementSearchMode::ExactSet => candidate == requested,
    }
}

fn physical_state_match(
    observed: Option<PhysicalState>,
    requested: Option<&[PhysicalState]>,
) -> bool {
    requested.is_none_or(|states| {
        observed.is_some_and(|observed| states.iter().any(|state| state.accepts(observed)))
    })
}

fn rejection(
    substance: &str,
    library: &str,
    reason: CandidateRejectionReason,
) -> CandidateRejection {
    CandidateRejection {
        substance: substance.to_string(),
        library: library.to_string(),
        reason,
    }
}

fn temperature_support(
    data: &Value,
    requested: Option<CandidateTemperatureRange>,
) -> CandidateTemperatureSupport {
    let Some(requested) = requested else {
        return CandidateTemperatureSupport::Unknown;
    };
    let ranges = temperature_ranges(data);
    if ranges.is_empty() {
        return CandidateTemperatureSupport::Unknown;
    }
    if ranges
        .iter()
        .any(|(lower, upper)| *lower <= requested.lower() && *upper >= requested.upper())
    {
        CandidateTemperatureSupport::Supported
    } else {
        CandidateTemperatureSupport::Unsupported
    }
}

/// Extracts only interval-like fields, avoiding accidental interpretation of
/// arbitrary coefficient arrays as temperature ranges.
fn temperature_ranges(value: &Value) -> Vec<(f64, f64)> {
    let mut ranges = Vec::new();
    if let Value::Object(object) = value {
        for (key, value) in object {
            let key_lower = key.to_ascii_lowercase();
            let hinted =
                key == "T" || key_lower.contains("temperature") || key_lower.contains("range");
            if hinted {
                collect_ranges(value, &mut ranges);
            }
        }
    }
    ranges.sort_by(|left, right| left.partial_cmp(right).unwrap_or(std::cmp::Ordering::Equal));
    ranges.dedup();
    ranges
}

fn collect_ranges(value: &Value, ranges: &mut Vec<(f64, f64)>) {
    match value {
        Value::Array(values) if values.len() == 2 => {
            if let (Some(lower), Some(upper)) = (values[0].as_f64(), values[1].as_f64()) {
                if lower.is_finite() && upper.is_finite() && lower > 0.0 && lower <= upper {
                    ranges.push((lower, upper));
                    return;
                }
            }
            for value in values {
                collect_ranges(value, ranges);
            }
        }
        Value::Array(values) => {
            for value in values {
                collect_ranges(value, ranges);
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::collections::HashMap;

    #[test]
    fn policy_validates_temperature_and_candidate_limits() {
        assert!(CandidateTemperatureRange::new(300.0, 1000.0).is_ok());
        assert!(CandidateTemperatureRange::new(0.0, 1000.0).is_err());
        assert!(
            EquilibriumCandidatePolicy::default()
                .with_max_candidates(0)
                .is_err()
        );
    }

    #[test]
    fn temperature_metadata_is_conservative() {
        let data = serde_json::json!({"T": [[200.0, 1000.0], [1000.0, 6000.0]], "Cp": [1.0]});
        assert_eq!(
            temperature_support(
                &data,
                Some(CandidateTemperatureRange::new(300.0, 500.0).unwrap())
            ),
            CandidateTemperatureSupport::Supported
        );
        assert_eq!(
            temperature_support(
                &data,
                Some(CandidateTemperatureRange::new(7000.0, 8000.0).unwrap())
            ),
            CandidateTemperatureSupport::Unsupported
        );
        assert_eq!(
            temperature_support(
                &serde_json::json!({"Cp": [1.0]}),
                Some(CandidateTemperatureRange::new(300.0, 500.0).unwrap())
            ),
            CandidateTemperatureSupport::Unknown
        );
    }

    #[test]
    fn selector_is_exact_state_aware_and_does_not_mutate_repository() {
        let repository = Arc::new(ThermoRepository::from_parts(
            vec![
                ("NASA_gas".into(), "CO".into()),
                ("NASA_gas".into(), "CO2".into()),
                ("NASA_cond".into(), "CO2(s)".into()),
            ],
            HashMap::from([
                (
                    "NASA_gas".into(),
                    HashMap::from([
                        (
                            "CO".into(),
                            json!({"T": [[200.0, 6000.0]], "model": "NASA"}),
                        ),
                        (
                            "CO2".into(),
                            json!({"T": [[200.0, 6000.0]], "model": "NASA"}),
                        ),
                    ]),
                ),
                (
                    "NASA_cond".into(),
                    HashMap::from([(
                        "CO2(s)".into(),
                        json!({"T": [[200.0, 1000.0]], "model": "NASA"}),
                    )]),
                ),
            ]),
            HashMap::from([
                (
                    "C".into(),
                    vec![
                        vec!["CO".into(), "NASA_gas".into()],
                        vec!["CO2".into(), "NASA_gas".into()],
                        vec!["CO2(s)".into(), "NASA_cond".into()],
                    ],
                ),
                (
                    "O".into(),
                    vec![
                        vec!["CO".into(), "NASA_gas".into()],
                        vec!["CO2".into(), "NASA_gas".into()],
                        vec!["CO2(s)".into(), "NASA_cond".into()],
                    ],
                ),
            ]),
            vec!["NASA_gas".into(), "NASA_cond".into()],
            HashMap::new(),
            HashMap::new(),
            vec!["NASA_gas".into(), "NASA_cond".into()],
            Vec::new(),
        ));
        let before = repository.ElementsData.as_ref().clone();
        let selector = EquilibriumCandidateSelector::new(Arc::clone(&repository));
        let policy = EquilibriumCandidatePolicy::new(ElementSearchMode::ExactSet)
            .with_library_preference(vec!["NASA_cond".into(), "NASA_gas".into()])
            .with_physical_states(vec![PhysicalState::Solid])
            .with_temperature_range(300.0, 900.0)
            .unwrap();
        let report = selector
            .select(&["O".into(), "C".into(), "C".into()], policy)
            .unwrap();

        assert_eq!(report.selected().len(), 1);
        assert_eq!(report.selected()[0].substance(), "CO2(s)");
        assert_eq!(report.selected()[0].library(), "NASA_cond");
        assert_eq!(
            report.selected()[0].temperature_support(),
            CandidateTemperatureSupport::Supported
        );
        assert_eq!(
            report.selected()[0].elements(),
            &["C".to_string(), "O".to_string()]
        );
        assert_eq!(repository.ElementsData.as_ref(), &before);
    }

    #[test]
    fn typed_element_inventory_uses_the_same_deterministic_catalog_query() {
        let repository = Arc::new(ThermoRepository::from_parts(
            vec![("NASA_gas".into(), "H2O".into())],
            HashMap::from([(
                "NASA_gas".into(),
                HashMap::from([(
                    "H2O".into(),
                    json!({"T": [[200.0, 6000.0]], "model": "NASA"}),
                )]),
            )]),
            HashMap::from([
                ("H".into(), vec![vec!["H2O".into(), "NASA_gas".into()]]),
                ("O".into(), vec![vec!["H2O".into(), "NASA_gas".into()]]),
            ]),
            vec!["NASA_gas".into()],
            HashMap::new(),
            HashMap::new(),
            vec!["NASA_gas".into()],
            Vec::new(),
        ));
        let selector = EquilibriumCandidateSelector::new(repository);
        let inventory = ElementInventory::from_amounts([("O", 1.0), ("H", 2.0)]).unwrap();
        let typed = selector
            .select_inventory(&inventory, EquilibriumCandidatePolicy::default())
            .unwrap();
        let strings = selector
            .select(
                &["H".into(), "O".into()],
                EquilibriumCandidatePolicy::default(),
            )
            .unwrap();

        assert_eq!(typed, strings);
        assert_eq!(typed.requested_elements(), ["H", "O"]);
        assert_eq!(typed.selected()[0].substance(), "H2O");

        let provenance = selector
            .select_inventory_with_provenance(
                inventory.clone(),
                EquilibriumCandidatePolicy::default(),
            )
            .unwrap();
        assert_eq!(provenance.inventory(), &inventory);
        assert_eq!(provenance.report(), &typed);
    }

    #[test]
    fn subset_inventory_selection_is_deterministic_and_excludes_absent_elements() {
        fn repository() -> Arc<ThermoRepository> {
            let records = ["H2", "O2", "H2O", "OH", "CO", "CO2", "N2"];
            Arc::new(ThermoRepository::from_parts(
                records
                    .iter()
                    .map(|substance| ("NASA_gas".into(), (*substance).into()))
                    .collect(),
                HashMap::from([(
                    "NASA_gas".into(),
                    records
                        .iter()
                        .map(|substance| ((*substance).into(), json!({"T": [[200.0, 6000.0]]})))
                        .collect(),
                )]),
                HashMap::from([
                    (
                        "H".into(),
                        vec![
                            vec!["H2".into(), "NASA_gas".into()],
                            vec!["H2O".into(), "NASA_gas".into()],
                            vec!["OH".into(), "NASA_gas".into()],
                            vec!["CO".into(), "NASA_gas".into()],
                            vec!["CO2".into(), "NASA_gas".into()],
                        ],
                    ),
                    (
                        "O".into(),
                        vec![
                            vec!["O2".into(), "NASA_gas".into()],
                            vec!["H2O".into(), "NASA_gas".into()],
                            vec!["OH".into(), "NASA_gas".into()],
                            vec!["CO".into(), "NASA_gas".into()],
                            vec!["CO2".into(), "NASA_gas".into()],
                        ],
                    ),
                    (
                        "C".into(),
                        vec![
                            vec!["CO".into(), "NASA_gas".into()],
                            vec!["CO2".into(), "NASA_gas".into()],
                        ],
                    ),
                    ("N".into(), vec![vec!["N2".into(), "NASA_gas".into()]]),
                ]),
                vec!["NASA_gas".into()],
                HashMap::new(),
                HashMap::new(),
                vec!["NASA_gas".into()],
                Vec::new(),
            ))
        }

        let policy = EquilibriumCandidatePolicy::default()
            .with_temperature_range(300.0, 1200.0)
            .unwrap();
        let inventory = ElementInventory::from_amounts([("O", 2.0), ("H", 4.0)]).unwrap();
        let first = EquilibriumCandidateSelector::new(repository())
            .select_inventory(&inventory, policy.clone())
            .unwrap();
        let second = EquilibriumCandidateSelector::new(repository())
            .select_inventory(&inventory, policy.clone())
            .unwrap();

        assert_eq!(first, second);
        assert_eq!(
            first
                .selected()
                .iter()
                .map(|candidate| candidate.substance())
                .collect::<Vec<_>>(),
            vec!["H2", "H2O", "O2", "OH"]
        );
        assert!(first.selected().iter().all(|candidate| {
            candidate
                .elements()
                .iter()
                .all(|element| element == "H" || element == "O")
        }));
        assert!(first.rejected().iter().any(|rejection| {
            rejection.substance() == "CO"
                && rejection.reason() == &CandidateRejectionReason::ElementSetMismatch
        }));
        assert!(first.rejected().iter().any(|rejection| {
            rejection.substance() == "N2"
                && rejection.reason() == &CandidateRejectionReason::ElementSetMismatch
        }));

        let limited = EquilibriumCandidateSelector::new(repository())
            .select_inventory(&inventory, policy.with_max_candidates(2).unwrap())
            .unwrap();
        assert_eq!(limited.selected().len(), 2);
        assert!(limited.is_truncated());
        assert!(
            limited
                .rejected()
                .iter()
                .any(|rejection| rejection.reason() == &CandidateRejectionReason::CandidateLimit)
        );
    }

    #[test]
    fn distinct_state_qualified_records_survive_candidate_selection() {
        let repository = Arc::new(ThermoRepository::from_parts(
            vec![
                ("NASA_cond".into(), "Fe(a)".into()),
                ("NASA_cond".into(), "Fe(c)".into()),
            ],
            HashMap::from([(
                "NASA_cond".into(),
                HashMap::from([
                    ("Fe(a)".into(), json!({"T": [[200.0, 1800.0]]})),
                    ("Fe(c)".into(), json!({"T": [[200.0, 1800.0]]})),
                ]),
            )]),
            HashMap::from([(
                "Fe".into(),
                vec![
                    vec!["Fe(a)".into(), "NASA_cond".into()],
                    vec!["Fe(c)".into(), "NASA_cond".into()],
                ],
            )]),
            vec!["NASA_cond".into()],
            HashMap::new(),
            HashMap::new(),
            vec!["NASA_cond".into()],
            Vec::new(),
        ));

        let report = EquilibriumCandidateSelector::new(repository)
            .select(
                &["Fe".into()],
                EquilibriumCandidatePolicy::new(ElementSearchMode::SubsetOf)
                    .with_physical_states(vec![PhysicalState::Solid]),
            )
            .unwrap();

        assert_eq!(
            report
                .selected()
                .iter()
                .map(|candidate| candidate.record_key())
                .collect::<Vec<_>>(),
            vec!["Fe(a)", "Fe(c)"]
        );
    }

    #[test]
    fn phase_plan_preserves_exact_record_and_library_provenance() {
        let repository = Arc::new(ThermoRepository::from_parts(
            vec![("NASA_cond".into(), "CO2(s)".into())],
            HashMap::from([(
                "NASA_cond".into(),
                HashMap::from([("CO2(s)".into(), json!({"T": [[200.0, 1000.0]]}))]),
            )]),
            HashMap::from([
                (
                    "C".into(),
                    vec![vec!["CO2(s)".to_string(), "NASA_cond".to_string()]],
                ),
                (
                    "O".into(),
                    vec![vec!["CO2(s)".to_string(), "NASA_cond".to_string()]],
                ),
            ]),
            vec!["NASA_cond".into()],
            HashMap::new(),
            HashMap::new(),
            vec!["NASA_cond".into()],
            Vec::new(),
        ));
        let selection = EquilibriumCandidateSelector::new(Arc::clone(&repository))
            .select(
                &["C".to_string(), "O".to_string()],
                EquilibriumCandidatePolicy::new(ElementSearchMode::ExactSet)
                    .with_physical_states(vec![PhysicalState::Solid]),
            )
            .unwrap();
        assert_eq!(selection.selected().len(), 1);

        let plan = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::pure_condensed(
                PhaseId::new(Some("solid".to_string())),
                PhysicalState::Solid,
                vec!["CO2(s)".into()],
            ),
        ]);
        let spec = plan.build_spec(&selection).unwrap();

        assert_eq!(spec.phases()[0].components(), &["CO2(s)".to_string()]);
        assert_eq!(spec.library_priorities(), &["NASA_cond".to_string()]);
        assert_eq!(spec.permitted_libraries(), &["NASA_cond".to_string()]);
        assert_eq!(
            spec.explicit_search_instructions()
                .and_then(|instructions| instructions.get("CO2(s)")),
            Some(&"NASA_cond".to_string())
        );
        assert!(!spec.search_in_nist());
    }

    #[test]
    fn phase_plan_rejects_unassigned_duplicate_and_unknown_records() {
        let selection = EquilibriumCandidateSelectionReport {
            requested_elements: vec!["C".into()],
            policy: EquilibriumCandidatePolicy::default(),
            selected: vec![EquilibriumCandidate {
                substance: "C(gr)".into(),
                library: "NASA_cond".into(),
                record_key: "C(gr)".into(),
                physical_state: Some(PhysicalState::Solid),
                elements: vec!["C".into()],
                temperature_support: CandidateTemperatureSupport::Unknown,
                library_rank: 0,
            }],
            rejected: Vec::new(),
            truncated: false,
        };

        let omitted = EquilibriumCandidatePhasePlan::new(Vec::new());
        assert!(omitted.build_spec(&selection).is_err());

        let unknown = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::pure_condensed(
                PhaseId::new(Some("solid".to_string())),
                PhysicalState::Solid,
                vec!["missing".into()],
            ),
        ]);
        assert!(unknown.build_spec(&selection).is_err());

        let duplicate = EquilibriumCandidatePhasePlan::new(vec![
            EquilibriumCandidatePhaseAssignment::pure_condensed(
                PhaseId::new(Some("first".to_string())),
                PhysicalState::Solid,
                vec!["C(gr)".into()],
            ),
            EquilibriumCandidatePhaseAssignment::pure_condensed(
                PhaseId::new(Some("second".to_string())),
                PhysicalState::Solid,
                vec!["C(gr)".into()],
            ),
        ]);
        assert!(duplicate.build_spec(&selection).is_err());
    }
}