Skip to main content

qualia_core_db/specialized_libs/chemistry_modeling/
kinetics.rs

1use super::*;
2
3/// Reaction analyzer for chemical reaction analysis
4pub struct ReactionAnalyzer {
5    reaction_network: ReactionNetwork,
6    kinetics_calculator: KineticsCalculator,
7    thermodynamics_calculator: ThermodynamicsCalculator,
8}
9
10/// Reaction network
11pub struct ReactionNetwork {
12    reactions: HashMap<String, Reaction>,
13    species: HashMap<String, Species>,
14    pathways: Vec<ReactionPathway>,
15}
16
17/// Reactions
18#[derive(Debug, Clone)]
19pub struct Reaction {
20    pub reaction_id: String,
21    pub reaction_name: String,
22    pub reactants: Vec<String>,
23    pub products: Vec<String>,
24    pub reaction_type: ReactionType,
25    pub mechanism: ReactionMechanism,
26}
27
28/// Reaction types
29#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
30pub enum ReactionType {
31    Elementary,
32    Complex,
33    Catalytic,
34    Chain,
35    Photochemical,
36    Electrochemical,
37}
38
39/// Reaction mechanisms
40#[derive(Debug, Clone)]
41pub struct ReactionMechanism {
42    pub mechanism_id: String,
43    pub steps: Vec<ReactionStep>,
44    pub intermediates: Vec<String>,
45}
46
47/// Reaction steps
48#[derive(Debug, Clone)]
49pub struct ReactionStep {
50    pub step_id: String,
51    pub reactants: Vec<String>,
52    pub products: Vec<String>,
53    pub rate_constant: f64,
54    pub activation_energy: f64,
55}
56
57/// Species
58#[derive(Debug, Clone)]
59pub struct Species {
60    pub species_id: String,
61    pub species_name: String,
62    pub formula: String,
63    pub molecular_weight: f64,
64    pub properties: SpeciesProperties,
65}
66
67/// Species properties
68#[derive(Debug, Clone)]
69pub struct SpeciesProperties {
70    pub enthalpy: f64,
71    pub entropy: f64,
72    pub gibbs_free_energy: f64,
73    pub heat_capacity: f64,
74}
75
76/// Reaction pathways
77#[derive(Debug, Clone)]
78pub struct ReactionPathway {
79    pub pathway_id: String,
80    pub pathway_name: String,
81    pub reactions: Vec<String>,
82    pub branching_ratios: Vec<f64>,
83}
84
85/// Kinetics calculator
86pub struct KineticsCalculator {
87    rate_laws: HashMap<String, RateLaw>,
88    rate_constants: HashMap<String, RateConstant>,
89    reaction_rates: HashMap<String, f64>,
90}
91
92/// Rate laws
93#[derive(Debug, Clone)]
94pub struct RateLaw {
95    pub law_id: String,
96    pub law_type: RateLawType,
97    pub rate_expression: String,
98    pub parameters: RateLawParameters,
99}
100
101/// Rate law types
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub enum RateLawType {
104    Elementary,
105    MichaelisMenten,
106    Hill,
107    Custom,
108}
109
110/// Rate law parameters
111#[derive(Debug, Clone, Serialize, Deserialize)]
112pub struct RateLawParameters {
113    pub rate_constant: f64,
114    pub reaction_orders: Vec<f64>,
115    pub saturation_constants: Vec<f64>,
116}
117
118/// Rate constants
119#[derive(Debug, Clone)]
120pub struct RateConstant {
121    pub constant_id: String,
122    pub value: f64,
123    pub temperature_dependence: TemperatureDependence,
124    pub pressure_dependence: PressureDependence,
125}
126
127/// Temperature dependence
128#[derive(Debug, Clone)]
129pub struct TemperatureDependence {
130    pub arrhenius_parameters: ArrheniusParameters,
131    pub modified_arrhenius: Option<ModifiedArrheniusParameters>,
132}
133
134/// Arrhenius parameters
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct ArrheniusParameters {
137    pub pre_exponential: f64,
138    pub activation_energy: f64,
139}
140
141/// Modified Arrhenius parameters
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct ModifiedArrheniusParameters {
144    pub pre_exponential: f64,
145    pub activation_energy: f64,
146    pub temperature_exponent: f64,
147}
148
149/// Pressure dependence
150#[derive(Debug, Clone)]
151pub struct PressureDependence {
152    pub fall_off_parameters: FallOffParameters,
153    pub third_body_efficiency: f64,
154}
155
156/// Fall-off parameters
157#[derive(Debug, Clone, Serialize, Deserialize)]
158pub struct FallOffParameters {
159    pub low_pressure_limit: f64,
160    pub high_pressure_limit: f64,
161    pub fall_off_exponent: f64,
162}
163
164/// Thermodynamics calculator
165pub struct ThermodynamicsCalculator {
166    thermodynamic_data: HashMap<String, ThermodynamicData>,
167    equilibrium_calculator: EquilibriumCalculator,
168    phase_calculator: PhaseCalculator,
169}
170
171/// Thermodynamic data
172#[derive(Debug, Clone)]
173pub struct ThermodynamicData {
174    pub data_id: String,
175    pub temperature_range: (f64, f64),
176    pub enthalpy: f64,
177    pub entropy: f64,
178    pub gibbs_free_energy: f64,
179    pub heat_capacity: f64,
180}
181
182/// Equilibrium calculator
183pub struct EquilibriumCalculator {
184    equilibrium_constant: EquilibriumConstant,
185    reaction_quotient: ReactionQuotient,
186    gibbs_energy: GibbsEnergy,
187}
188
189/// Equilibrium constant
190#[derive(Debug, Clone)]
191pub struct EquilibriumConstant {
192    pub value: f64,
193    pub temperature: f64,
194    pub pressure: f64,
195}
196
197/// Reaction quotient
198#[derive(Debug, Clone)]
199pub struct ReactionQuotient {
200    pub value: f64,
201    pub concentrations: HashMap<String, f64>,
202}
203
204/// Gibbs energy
205#[derive(Debug, Clone)]
206pub struct GibbsEnergy {
207    pub standard_gibbs: f64,
208    pub actual_gibbs: f64,
209    pub delta_g: f64,
210}
211
212/// Phase calculator
213pub struct PhaseCalculator {
214    phase_diagrams: HashMap<String, PhaseDiagram>,
215    phase_transitions: HashMap<String, PhaseTransition>,
216    phase_equilibria: HashMap<String, PhaseEquilibrium>,
217}
218
219/// Phase diagrams
220#[derive(Debug, Clone)]
221pub struct PhaseDiagram {
222    pub diagram_id: String,
223    pub phases: Vec<Phase>,
224    pub boundaries: Vec<PhaseBoundary>,
225}
226
227/// Phases
228#[derive(Debug, Clone)]
229pub struct Phase {
230    pub phase_id: String,
231    pub phase_name: String,
232    pub phase_type: PhaseType,
233    pub composition: HashMap<String, f64>,
234}
235
236/// Phase types
237#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
238pub enum PhaseType {
239    Solid,
240    Liquid,
241    Gas,
242    Plasma,
243    Supercritical,
244}
245
246/// Phase boundaries
247#[derive(Debug, Clone)]
248pub struct PhaseBoundary {
249    pub boundary_id: String,
250    pub boundary_type: BoundaryType,
251    pub conditions: Vec<BoundaryCondition>,
252}
253
254/// Phase boundary types
255#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
256pub enum PhaseBoundaryType {
257    Melting,
258    Boiling,
259    Sublimation,
260    Triple,
261    Critical,
262}
263
264/// Boundary conditions
265#[derive(Debug, Clone)]
266pub struct BoundaryCondition {
267    pub temperature: f64,
268    pub pressure: f64,
269    pub composition: HashMap<String, f64>,
270}
271
272/// Phase transitions
273#[derive(Debug, Clone)]
274pub struct PhaseTransition {
275    pub transition_id: String,
276    pub transition_type: TransitionType,
277    pub enthalpy_change: f64,
278    pub entropy_change: f64,
279}
280
281/// Transition types
282#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
283pub enum TransitionType {
284    Fusion,
285    Vaporization,
286    Sublimation,
287    Deposition,
288    Ionization,
289}
290
291/// Phase equilibria
292#[derive(Debug, Clone)]
293pub struct PhaseEquilibrium {
294    pub equilibrium_id: String,
295    pub phases: Vec<String>,
296    pub equilibrium_conditions: EquilibriumConditions,
297}
298
299/// Equilibrium conditions
300#[derive(Debug, Clone)]
301pub struct EquilibriumConditions {
302    pub temperature: f64,
303    pub pressure: f64,
304    pub chemical_potentials: HashMap<String, f64>,
305}
306
307impl ReactionAnalyzer {
308    /// Construct a `ReactionAnalyzer` with default field values.
309    pub fn new() -> Self {
310        Self {
311            reaction_network: ReactionNetwork::new(),
312            kinetics_calculator: KineticsCalculator::new(),
313            thermodynamics_calculator: ThermodynamicsCalculator::new(),
314        }
315    }
316
317    /// Borrow the reaction network.
318    pub fn reaction_network(&self) -> &ReactionNetwork {
319        &self.reaction_network
320    }
321
322    /// Mutably borrow the reaction network.
323    pub fn reaction_network_mut(&mut self) -> &mut ReactionNetwork {
324        &mut self.reaction_network
325    }
326
327    /// Initialize `ReactionAnalyzer`; `Ok` when ready.
328    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
329        self.kinetics_calculator.initialize()?;
330        self.thermodynamics_calculator.initialize()?;
331        Ok(())
332    }
333
334    /// Structural validation: rejects reactions with no reactants or no products.
335    pub fn validate_reaction(&self, reaction: &Reaction) -> Result<(), ChemistryError> {
336        if reaction.reactants.is_empty() {
337            return Err(ChemistryError::ValidationError(
338                "Reaction must have at least one reactant".to_string(),
339            ));
340        }
341        if reaction.products.is_empty() {
342            return Err(ChemistryError::ValidationError(
343                "Reaction must have at least one product".to_string(),
344            ));
345        }
346        Ok(())
347    }
348
349    /// Real Arrhenius analysis: k = A·exp(−Ea/RT) over the
350    /// rate-determining step (highest Ea); fails `ValidationError` on
351    /// non-positive temperature.
352    pub fn analyze_kinetics(
353        &mut self,
354        reaction: &Reaction,
355        conditions: &ReactionConditions,
356    ) -> Result<KineticsResults, ChemistryError> {
357        // REAL chemical kinetics via the Arrhenius equation:  k = A·exp(−Ea / (R·T)).
358        // The mechanism's rate-determining step (highest activation energy) governs the overall
359        // rate. `ReactionStep.rate_constant` is taken as the pre-exponential / frequency factor A
360        // and `activation_energy` as Ea in kJ/mol. Half-life follows from the reaction order.
361        const R: f64 = 8.314_462_618; // universal gas constant, J/(mol·K)
362
363        let t = conditions.temperature; // Kelvin
364        if !(t.is_finite() && t > 0.0) {
365            return Err(ChemistryError::ValidationError(
366                "temperature must be a positive value in Kelvin".to_string(),
367            ));
368        }
369
370        // Rate-determining elementary step = the one with the highest activation barrier.
371        let rds = reaction
372            .mechanism
373            .steps
374            .iter()
375            .max_by(|a, b| {
376                a.activation_energy
377                    .partial_cmp(&b.activation_energy)
378                    .unwrap_or(std::cmp::Ordering::Equal)
379            })
380            .ok_or_else(|| {
381                ChemistryError::InsufficientData(
382                    "reaction has no mechanism steps; cannot determine rate-determining step"
383                        .to_string(),
384                )
385            })?;
386
387        let a_factor = rds.rate_constant; // pre-exponential (frequency) factor A
388        let ea_kj = rds.activation_energy; // kJ/mol
389        if !(a_factor.is_finite() && ea_kj.is_finite()) {
390            return Err(ChemistryError::ValidationError(
391                "rate-determining step has non-finite A or Ea".to_string(),
392            ));
393        }
394        let ea_j = ea_kj * 1000.0; // kJ/mol → J/mol
395        let rate_constant = a_factor * (-ea_j / (R * t)).exp(); // k(T)
396
397        // Overall order ≈ number of distinct reactant species (elementary-rate approximation).
398        let reaction_order = reaction.reactants.len().max(1) as u32;
399
400        // Initial concentration of the first reactant (for order-dependent half-life).
401        let c0 = reaction
402            .reactants
403            .first()
404            .and_then(|name| conditions.concentration.get(name).copied())
405            .unwrap_or(1.0);
406
407        // Half-life by integrated rate law.
408        let half_life = if rate_constant <= 0.0 {
409            f64::INFINITY
410        } else {
411            match reaction_order {
412                0 => c0 / (2.0 * rate_constant), // t½ = [A]₀ / 2k
413                2 => {
414                    if c0 > 0.0 {
415                        1.0 / (rate_constant * c0)
416                    } else {
417                        f64::INFINITY
418                    }
419                } // 1 / (k[A]₀)
420                _ => std::f64::consts::LN_2 / rate_constant, // first order: ln2 / k
421            }
422        };
423
424        Ok(KineticsResults {
425            rate_constant,
426            activation_energy: ea_kj,
427            reaction_order,
428            half_life,
429        })
430    }
431}
432
433impl ReactionNetwork {
434    /// Construct a `ReactionNetwork` with default field values.
435    pub fn new() -> Self {
436        Self {
437            reactions: HashMap::new(),
438            species: HashMap::new(),
439            pathways: Vec::new(),
440        }
441    }
442
443    /// Register a reaction under its `reaction_id`, replacing any existing entry.
444    pub fn add_reaction(&mut self, reaction: Reaction) {
445        self.reactions
446            .insert(reaction.reaction_id.clone(), reaction);
447    }
448
449    /// Look up a reaction by id.
450    pub fn get_reaction(&self, reaction_id: &str) -> Option<&Reaction> {
451        self.reactions.get(reaction_id)
452    }
453
454    /// List the ids of all registered reactions.
455    pub fn list_reactions(&self) -> Vec<String> {
456        self.reactions.keys().cloned().collect()
457    }
458
459    /// Remove a reaction by id.
460    pub fn remove_reaction(&mut self, reaction_id: &str) -> Option<Reaction> {
461        self.reactions.remove(reaction_id)
462    }
463
464    /// Register a species under its `species_id`, replacing any existing entry.
465    pub fn add_species(&mut self, species: Species) {
466        self.species.insert(species.species_id.clone(), species);
467    }
468
469    /// Look up a species by id.
470    pub fn get_species(&self, species_id: &str) -> Option<&Species> {
471        self.species.get(species_id)
472    }
473
474    /// List the ids of all registered species.
475    pub fn list_species(&self) -> Vec<String> {
476        self.species.keys().cloned().collect()
477    }
478
479    /// Remove a species by id.
480    pub fn remove_species(&mut self, species_id: &str) -> Option<Species> {
481        self.species.remove(species_id)
482    }
483
484    /// Append a reaction pathway.
485    pub fn add_pathway(&mut self, pathway: ReactionPathway) {
486        self.pathways.push(pathway);
487    }
488
489    /// Borrow the reaction pathways.
490    pub fn pathways(&self) -> &Vec<ReactionPathway> {
491        &self.pathways
492    }
493
494    /// Mutably borrow the reaction pathways.
495    pub fn pathways_mut(&mut self) -> &mut Vec<ReactionPathway> {
496        &mut self.pathways
497    }
498}
499
500impl Reaction {
501    /// Construct a `Reaction` with default field values.
502    pub fn new() -> Self {
503        Self {
504            reaction_id: "rxn_1".to_string(),
505            reaction_name: "Test reaction".to_string(),
506            reactants: vec!["A".to_string()],
507            products: vec!["B".to_string()],
508            reaction_type: ReactionType::Elementary,
509            mechanism: ReactionMechanism::new(),
510        }
511    }
512}
513
514impl ReactionMechanism {
515    /// Construct a `ReactionMechanism` with default field values.
516    pub fn new() -> Self {
517        Self {
518            mechanism_id: "mech_1".to_string(),
519            steps: vec![ReactionStep::new()],
520            intermediates: Vec::new(),
521        }
522    }
523}
524
525impl ReactionStep {
526    /// Construct a `ReactionStep` with default field values.
527    pub fn new() -> Self {
528        Self {
529            step_id: "step_1".to_string(),
530            reactants: vec!["A".to_string()],
531            products: vec!["B".to_string()],
532            rate_constant: 1.0,
533            activation_energy: 10.0,
534        }
535    }
536}
537
538impl Species {
539    /// Construct a `Species` with default field values.
540    pub fn new() -> Self {
541        Self {
542            species_id: "species_1".to_string(),
543            species_name: "Test species".to_string(),
544            formula: "CH4".to_string(),
545            molecular_weight: 16.04,
546            properties: SpeciesProperties::new(),
547        }
548    }
549}
550
551impl SpeciesProperties {
552    /// Construct a `SpeciesProperties` with default field values.
553    pub fn new() -> Self {
554        Self {
555            enthalpy: -74.8,
556            entropy: 186.3,
557            gibbs_free_energy: -50.8,
558            heat_capacity: 35.7,
559        }
560    }
561}
562
563impl ReactionPathway {
564    /// Construct a `ReactionPathway` with default field values.
565    pub fn new() -> Self {
566        Self {
567            pathway_id: "pathway_1".to_string(),
568            pathway_name: "Test pathway".to_string(),
569            reactions: vec!["rxn_1".to_string()],
570            branching_ratios: vec![1.0],
571        }
572    }
573}
574
575impl KineticsCalculator {
576    /// Construct a `KineticsCalculator` with default field values.
577    pub fn new() -> Self {
578        Self {
579            rate_laws: HashMap::new(),
580            rate_constants: HashMap::new(),
581            reaction_rates: HashMap::new(),
582        }
583    }
584
585    /// Register a rate law under its `law_id`, replacing any existing entry.
586    pub fn add_rate_law(&mut self, law: RateLaw) {
587        self.rate_laws.insert(law.law_id.clone(), law);
588    }
589
590    /// Look up a rate law by id.
591    pub fn get_rate_law(&self, law_id: &str) -> Option<&RateLaw> {
592        self.rate_laws.get(law_id)
593    }
594
595    /// List the ids of all registered rate laws.
596    pub fn list_rate_laws(&self) -> Vec<String> {
597        self.rate_laws.keys().cloned().collect()
598    }
599
600    /// Register a rate constant under its `constant_id`, replacing any existing entry.
601    pub fn add_rate_constant(&mut self, constant: RateConstant) {
602        self.rate_constants
603            .insert(constant.constant_id.clone(), constant);
604    }
605
606    /// Look up a rate constant by id.
607    pub fn get_rate_constant(&self, constant_id: &str) -> Option<&RateConstant> {
608        self.rate_constants.get(constant_id)
609    }
610
611    /// List the ids of all registered rate constants.
612    pub fn list_rate_constants(&self) -> Vec<String> {
613        self.rate_constants.keys().cloned().collect()
614    }
615
616    /// Record the instantaneous rate for a reaction id.
617    pub fn set_reaction_rate(&mut self, reaction_id: &str, rate: f64) {
618        self.reaction_rates.insert(reaction_id.to_string(), rate);
619    }
620
621    /// Look up the recorded rate for a reaction id.
622    pub fn get_reaction_rate(&self, reaction_id: &str) -> Option<&f64> {
623        self.reaction_rates.get(reaction_id)
624    }
625
626    /// List the reaction ids that have a recorded rate.
627    pub fn list_reaction_rates(&self) -> Vec<String> {
628        self.reaction_rates.keys().cloned().collect()
629    }
630
631    /// Initialize `KineticsCalculator`; `Ok` when ready.
632    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
633        Ok(())
634    }
635}
636
637impl RateLaw {
638    /// Construct a `RateLaw` with default field values.
639    pub fn new() -> Self {
640        Self {
641            law_id: "law_1".to_string(),
642            law_type: RateLawType::Elementary,
643            rate_expression: "k * [A]".to_string(),
644            parameters: RateLawParameters::new(),
645        }
646    }
647}
648
649impl RateLawParameters {
650    /// Construct a `RateLawParameters` with default field values.
651    pub fn new() -> Self {
652        Self {
653            rate_constant: 1.0,
654            reaction_orders: vec![1.0],
655            saturation_constants: Vec::new(),
656        }
657    }
658}
659
660impl RateConstant {
661    /// Construct a `RateConstant` with default field values.
662    pub fn new() -> Self {
663        Self {
664            constant_id: "const_1".to_string(),
665            value: 1.0,
666            temperature_dependence: TemperatureDependence::new(),
667            pressure_dependence: PressureDependence::new(),
668        }
669    }
670}
671
672impl TemperatureDependence {
673    /// Construct a `TemperatureDependence` with default field values.
674    pub fn new() -> Self {
675        Self {
676            arrhenius_parameters: ArrheniusParameters::new(),
677            modified_arrhenius: None,
678        }
679    }
680}
681
682impl ArrheniusParameters {
683    /// Construct a `ArrheniusParameters` with default field values.
684    pub fn new() -> Self {
685        Self {
686            pre_exponential: 1.0e13,
687            activation_energy: 10000.0,
688        }
689    }
690}
691
692impl ModifiedArrheniusParameters {
693    /// Construct a `ModifiedArrheniusParameters` with default field values.
694    pub fn new() -> Self {
695        Self {
696            pre_exponential: 1.0e13,
697            activation_energy: 10000.0,
698            temperature_exponent: 0.0,
699        }
700    }
701}
702
703impl PressureDependence {
704    /// Construct a `PressureDependence` with default field values.
705    pub fn new() -> Self {
706        Self {
707            fall_off_parameters: FallOffParameters::new(),
708            third_body_efficiency: 1.0,
709        }
710    }
711}
712
713impl FallOffParameters {
714    /// Construct a `FallOffParameters` with default field values.
715    pub fn new() -> Self {
716        Self {
717            low_pressure_limit: 1.0,
718            high_pressure_limit: 1.0,
719            fall_off_exponent: 1.0,
720        }
721    }
722}
723
724impl ThermodynamicsCalculator {
725    /// Construct a `ThermodynamicsCalculator` with default field values.
726    pub fn new() -> Self {
727        Self {
728            thermodynamic_data: HashMap::new(),
729            equilibrium_calculator: EquilibriumCalculator::new(),
730            phase_calculator: PhaseCalculator::new(),
731        }
732    }
733
734    /// Register thermodynamic data under its `data_id`, replacing any existing entry.
735    pub fn add_thermodynamic_data(&mut self, data: ThermodynamicData) {
736        self.thermodynamic_data.insert(data.data_id.clone(), data);
737    }
738
739    /// Look up thermodynamic data by id.
740    pub fn get_thermodynamic_data(&self, data_id: &str) -> Option<&ThermodynamicData> {
741        self.thermodynamic_data.get(data_id)
742    }
743
744    /// List the ids of all registered thermodynamic data entries.
745    pub fn list_thermodynamic_data(&self) -> Vec<String> {
746        self.thermodynamic_data.keys().cloned().collect()
747    }
748
749    /// Remove thermodynamic data by id.
750    pub fn remove_thermodynamic_data(&mut self, data_id: &str) -> Option<ThermodynamicData> {
751        self.thermodynamic_data.remove(data_id)
752    }
753
754    /// Initialize `ThermodynamicsCalculator`; `Ok` when ready.
755    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
756        self.equilibrium_calculator.initialize()?;
757        self.phase_calculator.initialize()?;
758        Ok(())
759    }
760}
761
762impl ThermodynamicData {
763    /// Construct a `ThermodynamicData` with default field values.
764    pub fn new() -> Self {
765        Self {
766            data_id: "data_1".to_string(),
767            temperature_range: (200.0, 400.0),
768            enthalpy: -74.8,
769            entropy: 186.3,
770            gibbs_free_energy: -50.8,
771            heat_capacity: 35.7,
772        }
773    }
774}
775
776impl EquilibriumCalculator {
777    /// Construct a `EquilibriumCalculator` with default field values.
778    pub fn new() -> Self {
779        Self {
780            equilibrium_constant: EquilibriumConstant::new(),
781            reaction_quotient: ReactionQuotient::new(),
782            gibbs_energy: GibbsEnergy::new(),
783        }
784    }
785
786    /// Borrow the equilibrium constant.
787    pub fn equilibrium_constant(&self) -> &EquilibriumConstant {
788        &self.equilibrium_constant
789    }
790
791    /// Mutably borrow the equilibrium constant.
792    pub fn equilibrium_constant_mut(&mut self) -> &mut EquilibriumConstant {
793        &mut self.equilibrium_constant
794    }
795
796    /// Borrow the reaction quotient.
797    pub fn reaction_quotient(&self) -> &ReactionQuotient {
798        &self.reaction_quotient
799    }
800
801    /// Mutably borrow the reaction quotient.
802    pub fn reaction_quotient_mut(&mut self) -> &mut ReactionQuotient {
803        &mut self.reaction_quotient
804    }
805
806    /// Borrow the Gibbs energy.
807    pub fn gibbs_energy(&self) -> &GibbsEnergy {
808        &self.gibbs_energy
809    }
810
811    /// Mutably borrow the Gibbs energy.
812    pub fn gibbs_energy_mut(&mut self) -> &mut GibbsEnergy {
813        &mut self.gibbs_energy
814    }
815
816    /// Initialize `EquilibriumCalculator`; `Ok` when ready.
817    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
818        Ok(())
819    }
820}
821
822impl EquilibriumConstant {
823    /// Construct a `EquilibriumConstant` with default field values.
824    pub fn new() -> Self {
825        Self {
826            value: 1.0,
827            temperature: 298.15,
828            pressure: 1.0,
829        }
830    }
831}
832
833impl ReactionQuotient {
834    /// Construct a `ReactionQuotient` with default field values.
835    pub fn new() -> Self {
836        Self {
837            value: 1.0,
838            concentrations: HashMap::new(),
839        }
840    }
841}
842
843impl GibbsEnergy {
844    /// Construct a `GibbsEnergy` with default field values.
845    pub fn new() -> Self {
846        Self {
847            standard_gibbs: -50.8,
848            actual_gibbs: -50.8,
849            delta_g: 0.0,
850        }
851    }
852}
853
854impl PhaseCalculator {
855    /// Construct a `PhaseCalculator` with default field values.
856    pub fn new() -> Self {
857        Self {
858            phase_diagrams: HashMap::new(),
859            phase_transitions: HashMap::new(),
860            phase_equilibria: HashMap::new(),
861        }
862    }
863
864    /// Register a phase diagram under its `diagram_id`, replacing any existing entry.
865    pub fn add_phase_diagram(&mut self, diagram: PhaseDiagram) {
866        self.phase_diagrams
867            .insert(diagram.diagram_id.clone(), diagram);
868    }
869
870    /// Look up a phase diagram by id.
871    pub fn get_phase_diagram(&self, diagram_id: &str) -> Option<&PhaseDiagram> {
872        self.phase_diagrams.get(diagram_id)
873    }
874
875    /// List the ids of all registered phase diagrams.
876    pub fn list_phase_diagrams(&self) -> Vec<String> {
877        self.phase_diagrams.keys().cloned().collect()
878    }
879
880    /// Register a phase transition under its `transition_id`, replacing any existing entry.
881    pub fn add_phase_transition(&mut self, transition: PhaseTransition) {
882        self.phase_transitions
883            .insert(transition.transition_id.clone(), transition);
884    }
885
886    /// Look up a phase transition by id.
887    pub fn get_phase_transition(&self, transition_id: &str) -> Option<&PhaseTransition> {
888        self.phase_transitions.get(transition_id)
889    }
890
891    /// List the ids of all registered phase transitions.
892    pub fn list_phase_transitions(&self) -> Vec<String> {
893        self.phase_transitions.keys().cloned().collect()
894    }
895
896    /// Register a phase equilibrium under its `equilibrium_id`, replacing any existing entry.
897    pub fn add_phase_equilibrium(&mut self, equilibrium: PhaseEquilibrium) {
898        self.phase_equilibria
899            .insert(equilibrium.equilibrium_id.clone(), equilibrium);
900    }
901
902    /// Look up a phase equilibrium by id.
903    pub fn get_phase_equilibrium(&self, equilibrium_id: &str) -> Option<&PhaseEquilibrium> {
904        self.phase_equilibria.get(equilibrium_id)
905    }
906
907    /// List the ids of all registered phase equilibria.
908    pub fn list_phase_equilibria(&self) -> Vec<String> {
909        self.phase_equilibria.keys().cloned().collect()
910    }
911
912    /// Initialize `PhaseCalculator`; `Ok` when ready.
913    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
914        Ok(())
915    }
916}
917
918impl PhaseDiagram {
919    /// Construct a `PhaseDiagram` with default field values.
920    pub fn new() -> Self {
921        Self {
922            diagram_id: "diagram_1".to_string(),
923            phases: vec![Phase::new()],
924            boundaries: Vec::new(),
925        }
926    }
927}
928
929impl Phase {
930    /// Construct a `Phase` with default field values.
931    pub fn new() -> Self {
932        Self {
933            phase_id: "phase_1".to_string(),
934            phase_name: "Liquid".to_string(),
935            phase_type: PhaseType::Liquid,
936            composition: HashMap::new(),
937        }
938    }
939}
940
941impl PhaseBoundary {
942    /// Construct a `PhaseBoundary` with default field values.
943    pub fn new() -> Self {
944        Self {
945            boundary_id: "boundary_1".to_string(),
946            boundary_type: BoundaryType::Boiling,
947            conditions: vec![BoundaryCondition::new()],
948        }
949    }
950}
951
952impl BoundaryCondition {
953    /// Construct a `BoundaryCondition` with default field values.
954    pub fn new() -> Self {
955        Self {
956            temperature: 373.15,
957            pressure: 1.0,
958            composition: HashMap::new(),
959        }
960    }
961}
962
963impl PhaseTransition {
964    /// Construct a `PhaseTransition` with default field values.
965    pub fn new() -> Self {
966        Self {
967            transition_id: "transition_1".to_string(),
968            transition_type: TransitionType::Fusion,
969            enthalpy_change: 6.01,
970            entropy_change: 22.0,
971        }
972    }
973}
974
975impl PhaseEquilibrium {
976    /// Construct a `PhaseEquilibrium` with default field values.
977    pub fn new() -> Self {
978        Self {
979            equilibrium_id: "eq_1".to_string(),
980            phases: vec!["phase_1".to_string()],
981            equilibrium_conditions: EquilibriumConditions::new(),
982        }
983    }
984}
985
986impl EquilibriumConditions {
987    /// Construct a `EquilibriumConditions` with default field values.
988    pub fn new() -> Self {
989        Self {
990            temperature: 273.15,
991            pressure: 1.0,
992            chemical_potentials: HashMap::new(),
993        }
994    }
995}