Skip to main content

qualia_core_db/specialized_libs/chemistry_modeling/
simulation.rs

1use super::*;
2
3/// Molecular simulator for molecular dynamics simulations
4pub struct MolecularSimulator {
5    simulation_engine: SimulationEngine,
6    force_field_calculator: ForceFieldCalculator,
7    integrator: MolecularIntegrator,
8    boundary_conditions: BoundaryConditions,
9    molecule_store: HashMap<String, Molecule>,
10    linear_algebra: Option<Arc<Mutex<LinearAlgebraLibrary>>>,
11    statistical_computing: Option<Arc<Mutex<StatisticalComputingLibrary>>>,
12}
13
14/// Simulation engine
15pub struct SimulationEngine {
16    simulation_config: SimulationConfig,
17    time_step_control: TimeStepControl,
18    ensemble_manager: EnsembleManager,
19    temperature_controller: TemperatureController,
20}
21
22/// Simulation configuration
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct SimulationConfig {
25    pub simulation_id: String,
26    pub simulation_type: SimulationType,
27    pub ensemble: Ensemble,
28    pub time_step: f64,
29    pub total_time: f64,
30    pub temperature: f64,
31    pub pressure: f64,
32    pub box_size: Vec<f64>,
33    pub boundary_type: BoundaryType,
34}
35
36/// Simulation types
37#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub enum SimulationType {
39    /// Molecular dynamics
40    MolecularDynamics,
41    /// Monte Carlo
42    MonteCarlo,
43    /// Hybrid MD/MC
44    Hybrid,
45    /// Enhanced sampling
46    EnhancedSampling,
47    /// Coarse-grained
48    CoarseGrained,
49    /// Quantum mechanics/molecular mechanics
50    QMMM,
51}
52
53/// Ensembles
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub enum Ensemble {
56    NVE,  // Microcanonical
57    NVT,  // Canonical
58    NPT,  // Isothermal-isobaric
59    NPH,  // Isoenthalpic-isobaric
60    MuVT, // Grand canonical
61}
62
63/// Boundary types
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65pub enum BoundaryType {
66    Periodic,
67    NonPeriodic,
68    SemiPeriodic,
69    Ewald,
70    Boiling,
71}
72
73/// Time step control
74pub struct TimeStepControl {
75    control_type: TimeStepControlType,
76    adaptive_parameters: AdaptiveParameters,
77    stability_analysis: StabilityAnalysis,
78}
79
80/// Time step control types
81#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
82pub enum TimeStepControlType {
83    Fixed,
84    Adaptive,
85    Variable,
86    Multiple,
87}
88
89/// Adaptive parameters
90#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct AdaptiveParameters {
92    pub min_time_step: f64,
93    pub max_time_step: f64,
94    pub safety_factor: f64,
95    pub max_force: f64,
96}
97
98/// Stability analysis
99pub struct StabilityAnalysis {
100    analysis_method: StabilityAnalysisMethod,
101    energy_conservation: EnergyConservation,
102    temperature_fluctuation: TemperatureFluctuation,
103}
104
105/// Stability analysis methods
106#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
107pub enum StabilityAnalysisMethod {
108    EnergyDrift,
109    TemperatureDrift,
110    PressureDrift,
111    ConservationLaws,
112}
113
114/// Energy conservation
115#[derive(Debug, Clone)]
116pub struct EnergyConservation {
117    pub total_energy: f64,
118    pub kinetic_energy: f64,
119    pub potential_energy: f64,
120    pub drift_rate: f64,
121}
122
123/// Temperature fluctuation
124#[derive(Debug, Clone)]
125pub struct TemperatureFluctuation {
126    pub current_temperature: f64,
127    pub target_temperature: f64,
128    pub fluctuation_amplitude: f64,
129    pub heat_capacity: f64,
130}
131
132/// Ensemble manager
133pub struct EnsembleManager {
134    ensembles: HashMap<String, Ensemble>,
135    ensemble_transitions: HashMap<String, EnsembleTransition>,
136    sampling_methods: HashMap<String, SamplingMethod>,
137}
138
139/// Ensemble transitions
140#[derive(Debug, Clone)]
141pub struct EnsembleTransition {
142    pub transition_id: String,
143    pub from_ensemble: Ensemble,
144    pub to_ensemble: Ensemble,
145    pub transition_method: TransitionMethod,
146}
147
148/// Transition methods
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub enum TransitionMethod {
151    Berendsen,
152    NoséHoover,
153    Andersen,
154    ParrinelloRahman,
155    MartynaTuckerman,
156    /// Langevin dynamics thermostat (stochastic damping).
157    Langevin,
158}
159
160/// Sampling methods
161#[derive(Debug, Clone)]
162pub struct SamplingMethod {
163    pub method_id: String,
164    pub method_type: SamplingMethodType,
165    pub parameters: SamplingParameters,
166}
167
168/// Sampling method types
169#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
170pub enum SamplingMethodType {
171    Metropolis,
172    Gibbs,
173    WangLandau,
174    Umbrella,
175    ReplicaExchange,
176    /// Hamiltonian (Hybrid) Monte Carlo — uses molecular dynamics proposals.
177    Hamiltonian,
178    /// Parallel tempering (replica exchange over a temperature ladder).
179    ParallelTempering,
180}
181
182/// Sampling parameters
183#[derive(Debug, Clone, Serialize, Deserialize)]
184pub struct SamplingParameters {
185    pub acceptance_ratio: f64,
186    pub proposal_width: f64,
187    pub equilibration_steps: u32,
188    pub production_steps: u32,
189}
190
191/// Temperature controller
192pub struct TemperatureController {
193    control_method: TemperatureControlMethod,
194    thermostat_parameters: ThermostatParameters,
195    temperature_profile: TemperatureProfile,
196}
197
198/// Temperature control methods
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200pub enum TemperatureControlMethod {
201    VelocityRescaling,
202    Berendsen,
203    NoséHoover,
204    Langevin,
205    Andersen,
206}
207
208/// Thermostat parameters
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct ThermostatParameters {
211    pub coupling_constant: f64,
212    pub relaxation_time: f64,
213    pub damping_coefficient: f64,
214}
215
216/// Temperature profile
217#[derive(Debug, Clone)]
218pub struct TemperatureProfile {
219    pub profile_type: TemperatureProfileType,
220    pub initial_temperature: f64,
221    pub final_temperature: Option<f64>,
222    pub ramp_rate: Option<f64>,
223}
224
225/// Temperature profile types
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
227pub enum TemperatureProfileType {
228    Constant,
229    Linear,
230    Exponential,
231    Step,
232    Custom,
233}
234
235/// Force field calculator
236pub struct ForceFieldCalculator {
237    force_fields: HashMap<String, ForceField>,
238    interaction_calculator: InteractionCalculator,
239    energy_calculator: EnergyCalculator,
240}
241
242/// Force fields
243#[derive(Debug, Clone)]
244pub struct ForceField {
245    pub field_id: String,
246    pub field_name: String,
247    pub field_type: ForceFieldType,
248    pub parameters: ForceFieldParameters,
249}
250
251/// Force field types
252#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
253pub enum ForceFieldType {
254    AMBER,
255    CHARMM,
256    OPLS,
257    GROMOS,
258    DREIDING,
259    MMFF,
260    ReaxFF,
261    Custom,
262}
263
264/// Force field parameters
265#[derive(Debug, Clone, Serialize, Deserialize)]
266pub struct ForceFieldParameters {
267    pub bond_parameters: Vec<BondParameter>,
268    pub angle_parameters: Vec<AngleParameter>,
269    pub torsion_parameters: Vec<TorsionParameter>,
270    pub nonbonded_parameters: Vec<NonbondedParameter>,
271}
272
273/// Bond parameters
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct BondParameter {
276    pub atom_types: Vec<String>,
277    pub equilibrium_length: f64,
278    pub force_constant: f64,
279}
280
281/// Angle parameters
282#[derive(Debug, Clone, Serialize, Deserialize)]
283pub struct AngleParameter {
284    pub atom_types: Vec<String>,
285    pub equilibrium_angle: f64,
286    pub force_constant: f64,
287}
288
289/// Torsion parameters
290#[derive(Debug, Clone, Serialize, Deserialize)]
291pub struct TorsionParameter {
292    pub atom_types: Vec<String>,
293    pub barriers: Vec<f64>,
294    pub phases: Vec<f64>,
295    pub periodicities: Vec<i32>,
296}
297
298/// Nonbonded parameters
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct NonbondedParameter {
301    pub atom_type: String,
302    pub sigma: f64,
303    pub epsilon: f64,
304    pub charge: f64,
305}
306
307/// Interaction calculator
308pub struct InteractionCalculator {
309    bonded_interactions: BondedInteractions,
310    nonbonded_interactions: NonbondedInteractions,
311    long_range_interactions: LongRangeInteractions,
312}
313
314/// Bonded interactions
315pub struct BondedInteractions {
316    bond_calculator: BondCalculator,
317    angle_calculator: AngleCalculator,
318    torsion_calculator: TorsionCalculator,
319    improper_calculator: ImproperCalculator,
320}
321
322/// Bond calculator
323#[derive(Debug, Clone)]
324pub struct BondCalculator {
325    pub calculator_type: BondCalculatorType,
326    pub parameters: BondCalculatorParameters,
327}
328
329/// Bond calculator types
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
331pub enum BondCalculatorType {
332    Harmonic,
333    Morse,
334    FENE,
335    Custom,
336}
337
338/// Bond calculator parameters
339#[derive(Debug, Clone, Serialize, Deserialize)]
340pub struct BondCalculatorParameters {
341    pub force_constant: f64,
342    pub equilibrium_length: f64,
343    pub dissociation_energy: Option<f64>,
344}
345
346/// Angle calculator
347#[derive(Debug, Clone)]
348pub struct AngleCalculator {
349    pub calculator_type: AngleCalculatorType,
350    pub parameters: AngleCalculatorParameters,
351}
352
353/// Angle calculator types
354#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
355pub enum AngleCalculatorType {
356    Harmonic,
357    Cosine,
358    UreyBradley,
359    Custom,
360}
361
362/// Angle calculator parameters
363#[derive(Debug, Clone, Serialize, Deserialize)]
364pub struct AngleCalculatorParameters {
365    pub force_constant: f64,
366    pub equilibrium_angle: f64,
367    pub ub_parameters: Option<UBParameters>,
368}
369
370/// UB parameters
371#[derive(Debug, Clone, Serialize, Deserialize)]
372pub struct UBParameters {
373    pub force_constant: f64,
374    pub equilibrium_length: f64,
375}
376
377/// Torsion calculator
378#[derive(Debug, Clone)]
379pub struct TorsionCalculator {
380    pub calculator_type: TorsionCalculatorType,
381    pub parameters: TorsionCalculatorParameters,
382}
383
384/// Torsion calculator types
385#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
386pub enum TorsionCalculatorType {
387    Cosine,
388    Fourier,
389    RyckaertsBellemans,
390    Custom,
391}
392
393/// Torsion calculator parameters
394#[derive(Debug, Clone, Serialize, Deserialize)]
395pub struct TorsionCalculatorParameters {
396    pub barriers: Vec<f64>,
397    pub phases: Vec<f64>,
398    pub periodicities: Vec<i32>,
399}
400
401/// Improper calculator
402#[derive(Debug, Clone)]
403pub struct ImproperCalculator {
404    pub calculator_type: ImproperCalculatorType,
405    pub parameters: ImproperCalculatorParameters,
406}
407
408/// Improper calculator types
409#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
410pub enum ImproperCalculatorType {
411    Harmonic,
412    Cosine,
413    Custom,
414}
415
416/// Improper calculator parameters
417#[derive(Debug, Clone, Serialize, Deserialize)]
418pub struct ImproperCalculatorParameters {
419    pub force_constant: f64,
420    pub equilibrium_angle: f64,
421}
422
423/// Nonbonded interactions
424pub struct NonbondedInteractions {
425    lennard_jones: LennardJones,
426    coulomb: Coulomb,
427    buckingham: Buckingham,
428}
429
430/// Lennard-Jones potential
431#[derive(Debug, Clone)]
432pub struct LennardJones {
433    pub epsilon: f64,
434    pub sigma: f64,
435    pub cutoff: f64,
436    pub switching_distance: f64,
437}
438
439/// Coulomb potential
440#[derive(Debug, Clone)]
441pub struct Coulomb {
442    pub coulomb_constant: f64,
443    pub dielectric: f64,
444    pub cutoff: f64,
445    pub switching_distance: f64,
446}
447
448/// Buckingham potential
449#[derive(Debug, Clone)]
450pub struct Buckingham {
451    pub a: f64,
452    pub b: f64,
453    pub c: f64,
454    pub cutoff: f64,
455}
456
457/// Long-range interactions
458pub struct LongRangeInteractions {
459    ewald_summation: EwaldSummation,
460    particle_mesh: ParticleMesh,
461    reaction_field: ReactionField,
462}
463
464/// Ewald summation
465#[derive(Debug, Clone)]
466pub struct EwaldSummation {
467    pub alpha: f64,
468    pub k_max: usize,
469    pub real_cutoff: f64,
470    pub reciprocal_cutoff: f64,
471}
472
473/// Particle mesh
474#[derive(Debug, Clone)]
475pub struct ParticleMesh {
476    pub grid_size: Vec<usize>,
477    pub spline_order: usize,
478    pub cutoff: f64,
479}
480
481/// Reaction field
482#[derive(Debug, Clone)]
483pub struct ReactionField {
484    pub dielectric_inside: f64,
485    pub dielectric_outside: f64,
486    pub cutoff: f64,
487}
488
489/// Energy calculator
490pub struct EnergyCalculator {
491    kinetic_energy: KineticEnergy,
492    potential_energy: PotentialEnergy,
493    total_energy: TotalEnergy,
494}
495
496/// Kinetic energy
497#[derive(Debug, Clone)]
498pub struct KineticEnergy {
499    pub temperature: f64,
500    pub degrees_of_freedom: usize,
501    pub velocities: Vec<Vec<f64>>,
502}
503
504/// Potential energy
505#[derive(Debug, Clone)]
506pub struct PotentialEnergy {
507    pub bonded_energy: f64,
508    pub nonbonded_energy: f64,
509    pub long_range_energy: f64,
510}
511
512/// Total energy
513#[derive(Debug, Clone)]
514pub struct TotalEnergy {
515    pub kinetic: f64,
516    pub potential: f64,
517    pub total: f64,
518    pub drift: f64,
519}
520
521/// Molecular integrator
522pub struct MolecularIntegrator {
523    integrator_type: IntegratorType,
524    integrator_parameters: IntegratorParameters,
525    constraint_handler: ConstraintHandler,
526}
527
528/// Integrator types
529#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
530pub enum IntegratorType {
531    VelocityVerlet,
532    Leapfrog,
533    Beeman,
534    Gear,
535    RungeKutta,
536    Stochastic,
537}
538
539/// Integrator parameters
540#[derive(Debug, Clone, Serialize, Deserialize)]
541pub struct IntegratorParameters {
542    pub time_step: f64,
543    pub accuracy: f64,
544    pub stability_factor: f64,
545}
546
547/// Constraint handler
548pub struct ConstraintHandler {
549    constraint_algorithm: ConstraintAlgorithm,
550    constraint_parameters: ConstraintParameters,
551}
552
553/// Constraint algorithms
554#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
555pub enum ConstraintAlgorithm {
556    SHAKE,
557    RATTLE,
558    LINCS,
559    SETTLE,
560}
561
562/// Constraint parameters
563#[derive(Debug, Clone, Serialize, Deserialize)]
564pub struct ConstraintParameters {
565    pub tolerance: f64,
566    pub max_iterations: u32,
567    pub relaxation_parameter: f64,
568}
569
570/// Boundary conditions
571pub struct BoundaryConditions {
572    boundary_type: BoundaryType,
573    box_vectors: Vec<Vec<f64>>,
574    minimum_image: MinimumImage,
575}
576
577/// Minimum image convention
578#[derive(Debug, Clone)]
579pub struct MinimumImage {
580    pub box_size: Vec<f64>,
581    pub periodic: bool,
582}
583
584// Supporting implementations
585
586impl MolecularSimulator {
587    /// Create a `MolecularSimulator` with default sub-components.
588    pub fn new() -> Self {
589        Self {
590            simulation_engine: SimulationEngine::new(),
591            force_field_calculator: ForceFieldCalculator::new(),
592            integrator: MolecularIntegrator::new(),
593            boundary_conditions: BoundaryConditions::new(),
594            molecule_store: HashMap::new(),
595            linear_algebra: None,
596            statistical_computing: None,
597        }
598    }
599
600    /// Attach optional `LinearAlgebraLibrary` / `StatisticalComputingLibrary`
601    /// shared handles used by the MD integrator.
602    pub fn attach_dependencies(
603        &mut self,
604        linear_algebra: Option<Arc<Mutex<LinearAlgebraLibrary>>>,
605        statistical_computing: Option<Arc<Mutex<StatisticalComputingLibrary>>>,
606    ) {
607        self.linear_algebra = linear_algebra;
608        self.statistical_computing = statistical_computing;
609    }
610
611    /// Insert `molecule` into the simulator store keyed by `molecule_id`.
612    pub fn store_molecule(&mut self, molecule: Molecule) {
613        self.molecule_store
614            .insert(molecule.molecule_id.clone(), molecule);
615    }
616
617    /// Initialise the `MolecularSimulator` sub-components; propagates `ChemistryError`.
618    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
619        self.simulation_engine.initialize()?;
620        self.force_field_calculator.initialize()?;
621        self.integrator.initialize()?;
622
623        let _ = self.boundary_conditions.boundary_type();
624        let _ = self.boundary_conditions.box_vectors();
625        let _ = self.boundary_conditions.minimum_image();
626
627        Ok(())
628    }
629
630    /// Validate `config` — positive `time_step`/`total_time`, non-negative
631    /// `temperature`; `ValidationError` otherwise.
632    pub fn validate_config(&self, config: &SimulationConfig) -> Result<(), ChemistryError> {
633        if config.time_step <= 0.0 {
634            return Err(ChemistryError::ValidationError(
635                "Time step must be positive".to_string(),
636            ));
637        }
638        if config.total_time <= 0.0 {
639            return Err(ChemistryError::ValidationError(
640                "Total time must be positive".to_string(),
641            ));
642        }
643        if config.temperature < 0.0 {
644            return Err(ChemistryError::ValidationError(
645                "Temperature must be non-negative".to_string(),
646            ));
647        }
648        Ok(())
649    }
650
651    /// Run a real Lennard-Jones + velocity-Verlet MD via
652    /// `molecular_dynamics::run_md`; fails closed on unparameterized
653    /// input rather than fabricating a trajectory.
654    pub fn run_simulation(
655        &mut self,
656        config: &SimulationConfig,
657        molecule: &Molecule,
658    ) -> Result<SimulationTrajectory, ChemistryError> {
659        // REAL: Lennard-Jones force field + velocity-Verlet integrator, in
660        // `molecular_dynamics::run_md`. The atoms actually move under computed
661        // forces, total energy is conserved (asserted in that module's tests),
662        // and invalid inputs (no atoms / unparameterized element / bad mass)
663        // return `InsufficientData` rather than a fabricated static trajectory.
664        molecular_dynamics::run_md(
665            config,
666            molecule,
667            self.linear_algebra.clone(),
668            self.statistical_computing.clone(),
669        )
670    }
671
672    /// Force-field names understood by the force-field calculator
673    /// (AMBER/CHARMM/OPLS).
674    pub fn list_force_fields(&self) -> Vec<String> {
675        vec![
676            "AMBER".to_string(),
677            "CHARMM".to_string(),
678            "OPLS".to_string(),
679        ]
680    }
681
682    /// Clone of the stored molecule `molecule_id`, or `None`.
683    pub fn get_molecule(&self, molecule_id: &str) -> Option<Molecule> {
684        self.molecule_store.get(molecule_id).cloned()
685    }
686
687    /// Borrow the boundary-conditions configuration.
688    pub fn boundary_conditions(&self) -> &BoundaryConditions {
689        &self.boundary_conditions
690    }
691
692    /// Mutably borrow the boundary-conditions configuration.
693    pub fn boundary_conditions_mut(&mut self) -> &mut BoundaryConditions {
694        &mut self.boundary_conditions
695    }
696
697    /// Borrow the simulation engine.
698    pub fn simulation_engine(&self) -> &SimulationEngine {
699        &self.simulation_engine
700    }
701
702    /// Mutably borrow the simulation engine.
703    pub fn simulation_engine_mut(&mut self) -> &mut SimulationEngine {
704        &mut self.simulation_engine
705    }
706
707    /// Borrow the force-field calculator.
708    pub fn force_field_calculator(&self) -> &ForceFieldCalculator {
709        &self.force_field_calculator
710    }
711
712    /// Mutably borrow the force-field calculator.
713    pub fn force_field_calculator_mut(&mut self) -> &mut ForceFieldCalculator {
714        &mut self.force_field_calculator
715    }
716
717    /// Borrow the molecular integrator.
718    pub fn integrator(&self) -> &MolecularIntegrator {
719        &self.integrator
720    }
721
722    /// Mutably borrow the molecular integrator.
723    pub fn integrator_mut(&mut self) -> &mut MolecularIntegrator {
724        &mut self.integrator
725    }
726}
727
728impl SimulationEngine {
729    /// Create a `SimulationEngine` with default sub-components.
730    pub fn new() -> Self {
731        Self {
732            simulation_config: SimulationConfig::new(),
733            time_step_control: TimeStepControl::new(),
734            ensemble_manager: EnsembleManager::new(),
735            temperature_controller: TemperatureController::new(),
736        }
737    }
738
739    /// Initialise the `SimulationEngine` sub-components; propagates `ChemistryError`.
740    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
741        self.time_step_control.initialize()?;
742        self.ensemble_manager.initialize()?;
743        self.temperature_controller.initialize()?;
744        Ok(())
745    }
746
747    /// Borrow the simulation configuration.
748    pub fn simulation_config(&self) -> &SimulationConfig {
749        &self.simulation_config
750    }
751
752    /// Mutably borrow the simulation configuration.
753    pub fn simulation_config_mut(&mut self) -> &mut SimulationConfig {
754        &mut self.simulation_config
755    }
756
757    /// Borrow the time-step controller.
758    pub fn time_step_control(&self) -> &TimeStepControl {
759        &self.time_step_control
760    }
761
762    /// Mutably borrow the time-step controller.
763    pub fn time_step_control_mut(&mut self) -> &mut TimeStepControl {
764        &mut self.time_step_control
765    }
766
767    /// Borrow the ensemble manager.
768    pub fn ensemble_manager(&self) -> &EnsembleManager {
769        &self.ensemble_manager
770    }
771
772    /// Mutably borrow the ensemble manager.
773    pub fn ensemble_manager_mut(&mut self) -> &mut EnsembleManager {
774        &mut self.ensemble_manager
775    }
776
777    /// Borrow the temperature controller.
778    pub fn temperature_controller(&self) -> &TemperatureController {
779        &self.temperature_controller
780    }
781
782    /// Mutably borrow the temperature controller.
783    pub fn temperature_controller_mut(&mut self) -> &mut TemperatureController {
784        &mut self.temperature_controller
785    }
786}
787
788impl SimulationConfig {
789    /// Create a `SimulationConfig` with default sub-components.
790    pub fn new() -> Self {
791        Self {
792            simulation_id: "sim_1".to_string(),
793            simulation_type: SimulationType::MolecularDynamics,
794            ensemble: Ensemble::NVT,
795            time_step: 0.001,
796            total_time: 1.0,
797            temperature: 300.0,
798            pressure: 1.0,
799            box_size: vec![10.0, 10.0, 10.0],
800            boundary_type: BoundaryType::Periodic,
801        }
802    }
803}
804
805impl TimeStepControl {
806    /// Create a `TimeStepControl` with default sub-components.
807    pub fn new() -> Self {
808        Self {
809            control_type: TimeStepControlType::Fixed,
810            adaptive_parameters: AdaptiveParameters::new(),
811            stability_analysis: StabilityAnalysis::new(),
812        }
813    }
814
815    /// Borrow the time-step control strategy.
816    pub fn control_type(&self) -> &TimeStepControlType {
817        &self.control_type
818    }
819
820    /// Set the time-step control strategy.
821    pub fn set_control_type(&mut self, control_type: TimeStepControlType) {
822        self.control_type = control_type;
823    }
824
825    /// Borrow the adaptive time-step parameters.
826    pub fn adaptive_parameters(&self) -> &AdaptiveParameters {
827        &self.adaptive_parameters
828    }
829
830    /// Mutably borrow the adaptive time-step parameters.
831    pub fn adaptive_parameters_mut(&mut self) -> &mut AdaptiveParameters {
832        &mut self.adaptive_parameters
833    }
834
835    /// Borrow the stability analysis.
836    pub fn stability_analysis(&self) -> &StabilityAnalysis {
837        &self.stability_analysis
838    }
839
840    /// Mutably borrow the stability analysis.
841    pub fn stability_analysis_mut(&mut self) -> &mut StabilityAnalysis {
842        &mut self.stability_analysis
843    }
844
845    /// Initialise the `TimeStepControl` sub-components; propagates `ChemistryError`.
846    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
847        Ok(())
848    }
849}
850
851impl AdaptiveParameters {
852    /// Create a `AdaptiveParameters` with default sub-components.
853    pub fn new() -> Self {
854        Self {
855            min_time_step: 0.0001,
856            max_time_step: 0.01,
857            safety_factor: 0.9,
858            max_force: 1000.0,
859        }
860    }
861}
862
863impl StabilityAnalysis {
864    /// Create a `StabilityAnalysis` with default sub-components.
865    pub fn new() -> Self {
866        Self {
867            analysis_method: StabilityAnalysisMethod::EnergyDrift,
868            energy_conservation: EnergyConservation::new(),
869            temperature_fluctuation: TemperatureFluctuation::new(),
870        }
871    }
872
873    /// Borrow the stability analysis method.
874    pub fn analysis_method(&self) -> &StabilityAnalysisMethod {
875        &self.analysis_method
876    }
877
878    /// Set the stability analysis method.
879    pub fn set_analysis_method(&mut self, method: StabilityAnalysisMethod) {
880        self.analysis_method = method;
881    }
882
883    /// Borrow the energy-conservation metrics.
884    pub fn energy_conservation(&self) -> &EnergyConservation {
885        &self.energy_conservation
886    }
887
888    /// Mutably borrow the energy-conservation metrics.
889    pub fn energy_conservation_mut(&mut self) -> &mut EnergyConservation {
890        &mut self.energy_conservation
891    }
892
893    /// Borrow the temperature-fluctuation metrics.
894    pub fn temperature_fluctuation(&self) -> &TemperatureFluctuation {
895        &self.temperature_fluctuation
896    }
897
898    /// Mutably borrow the temperature-fluctuation metrics.
899    pub fn temperature_fluctuation_mut(&mut self) -> &mut TemperatureFluctuation {
900        &mut self.temperature_fluctuation
901    }
902}
903
904impl EnergyConservation {
905    /// Create a `EnergyConservation` with default sub-components.
906    pub fn new() -> Self {
907        Self {
908            total_energy: 0.0,
909            kinetic_energy: 0.0,
910            potential_energy: 0.0,
911            drift_rate: 0.0,
912        }
913    }
914}
915
916impl TemperatureFluctuation {
917    /// Create a `TemperatureFluctuation` with default sub-components.
918    pub fn new() -> Self {
919        Self {
920            current_temperature: 300.0,
921            target_temperature: 300.0,
922            fluctuation_amplitude: 5.0,
923            heat_capacity: 100.0,
924        }
925    }
926}
927
928impl EnsembleManager {
929    /// Create a `EnsembleManager` with default sub-components.
930    pub fn new() -> Self {
931        Self {
932            ensembles: HashMap::new(),
933            ensemble_transitions: HashMap::new(),
934            sampling_methods: HashMap::new(),
935        }
936    }
937
938    /// Initialise the `EnsembleManager` sub-components; propagates `ChemistryError`.
939    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
940        // Standard thermodynamic ensembles. GCMC (grand canonical) maps to the
941        // `MuVT` variant.
942        self.ensembles.insert("NVE".to_string(), Ensemble::NVE);
943        self.ensembles.insert("NVT".to_string(), Ensemble::NVT);
944        self.ensembles.insert("NPT".to_string(), Ensemble::NPT);
945        self.ensembles.insert("GCMC".to_string(), Ensemble::MuVT);
946
947        // Standard ensemble transition / thermostat methods.
948        self.ensemble_transitions.insert(
949            "Berendsen".to_string(),
950            EnsembleTransition {
951                transition_id: "trans_berendsen".to_string(),
952                from_ensemble: Ensemble::NVE,
953                to_ensemble: Ensemble::NVT,
954                transition_method: TransitionMethod::Berendsen,
955            },
956        );
957        self.ensemble_transitions.insert(
958            "Nosé-Hoover".to_string(),
959            EnsembleTransition {
960                transition_id: "trans_nose_hoover".to_string(),
961                from_ensemble: Ensemble::NVT,
962                to_ensemble: Ensemble::NVT,
963                transition_method: TransitionMethod::NoséHoover,
964            },
965        );
966        self.ensemble_transitions.insert(
967            "Parrinello-Rahman".to_string(),
968            EnsembleTransition {
969                transition_id: "trans_parrinello_rahman".to_string(),
970                from_ensemble: Ensemble::NPT,
971                to_ensemble: Ensemble::NPT,
972                transition_method: TransitionMethod::ParrinelloRahman,
973            },
974        );
975        self.ensemble_transitions.insert(
976            "Langevin".to_string(),
977            EnsembleTransition {
978                transition_id: "trans_langevin".to_string(),
979                from_ensemble: Ensemble::NVT,
980                to_ensemble: Ensemble::NVT,
981                transition_method: TransitionMethod::Langevin,
982            },
983        );
984
985        // Standard sampling methods.
986        self.sampling_methods.insert(
987            "Metropolis".to_string(),
988            SamplingMethod {
989                method_id: "sample_metropolis".to_string(),
990                method_type: SamplingMethodType::Metropolis,
991                parameters: SamplingParameters::new(),
992            },
993        );
994        self.sampling_methods.insert(
995            "Gibbs".to_string(),
996            SamplingMethod {
997                method_id: "sample_gibbs".to_string(),
998                method_type: SamplingMethodType::Gibbs,
999                parameters: SamplingParameters::new(),
1000            },
1001        );
1002        self.sampling_methods.insert(
1003            "Hamiltonian".to_string(),
1004            SamplingMethod {
1005                method_id: "sample_hmc".to_string(),
1006                method_type: SamplingMethodType::Hamiltonian,
1007                parameters: SamplingParameters::new(),
1008            },
1009        );
1010        self.sampling_methods.insert(
1011            "ParallelTempering".to_string(),
1012            SamplingMethod {
1013                method_id: "sample_pt".to_string(),
1014                method_type: SamplingMethodType::ParallelTempering,
1015                parameters: SamplingParameters::new(),
1016            },
1017        );
1018
1019        Ok(())
1020    }
1021
1022    /// Look up a registered ensemble by name.
1023    pub fn get_ensemble(&self, name: &str) -> Option<&Ensemble> {
1024        self.ensembles.get(name)
1025    }
1026
1027    /// List the names of all registered ensembles.
1028    pub fn list_ensembles(&self) -> Vec<String> {
1029        self.ensembles.keys().cloned().collect()
1030    }
1031
1032    /// List the names of all registered ensemble transition methods.
1033    pub fn list_transitions(&self) -> Vec<String> {
1034        self.ensemble_transitions.keys().cloned().collect()
1035    }
1036
1037    /// List the names of all registered sampling methods.
1038    pub fn list_sampling_methods(&self) -> Vec<String> {
1039        self.sampling_methods.keys().cloned().collect()
1040    }
1041}
1042
1043impl EnsembleTransition {
1044    /// Create a `EnsembleTransition` with default sub-components.
1045    pub fn new() -> Self {
1046        Self {
1047            transition_id: "transition_1".to_string(),
1048            from_ensemble: Ensemble::NVE,
1049            to_ensemble: Ensemble::NVT,
1050            transition_method: TransitionMethod::Berendsen,
1051        }
1052    }
1053}
1054
1055impl SamplingMethod {
1056    /// Create a `SamplingMethod` with default sub-components.
1057    pub fn new() -> Self {
1058        Self {
1059            method_id: "method_1".to_string(),
1060            method_type: SamplingMethodType::Metropolis,
1061            parameters: SamplingParameters::new(),
1062        }
1063    }
1064}
1065
1066impl SamplingParameters {
1067    /// Create a `SamplingParameters` with default sub-components.
1068    pub fn new() -> Self {
1069        Self {
1070            acceptance_ratio: 0.5,
1071            proposal_width: 1.0,
1072            equilibration_steps: 1000,
1073            production_steps: 10000,
1074        }
1075    }
1076}
1077
1078impl TemperatureController {
1079    /// Create a `TemperatureController` with default sub-components.
1080    pub fn new() -> Self {
1081        Self {
1082            control_method: TemperatureControlMethod::NoséHoover,
1083            thermostat_parameters: ThermostatParameters::new(),
1084            temperature_profile: TemperatureProfile::new(),
1085        }
1086    }
1087
1088    /// Borrow the temperature control method.
1089    pub fn control_method(&self) -> &TemperatureControlMethod {
1090        &self.control_method
1091    }
1092
1093    /// Set the temperature control method.
1094    pub fn set_control_method(&mut self, method: TemperatureControlMethod) {
1095        self.control_method = method;
1096    }
1097
1098    /// Borrow the thermostat parameters.
1099    pub fn thermostat_parameters(&self) -> &ThermostatParameters {
1100        &self.thermostat_parameters
1101    }
1102
1103    /// Mutably borrow the thermostat parameters.
1104    pub fn thermostat_parameters_mut(&mut self) -> &mut ThermostatParameters {
1105        &mut self.thermostat_parameters
1106    }
1107
1108    /// Borrow the temperature profile.
1109    pub fn temperature_profile(&self) -> &TemperatureProfile {
1110        &self.temperature_profile
1111    }
1112
1113    /// Mutably borrow the temperature profile.
1114    pub fn temperature_profile_mut(&mut self) -> &mut TemperatureProfile {
1115        &mut self.temperature_profile
1116    }
1117
1118    /// Initialise the `TemperatureController` sub-components; propagates `ChemistryError`.
1119    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1120        Ok(())
1121    }
1122}
1123
1124impl ThermostatParameters {
1125    /// Create a `ThermostatParameters` with default sub-components.
1126    pub fn new() -> Self {
1127        Self {
1128            coupling_constant: 1.0,
1129            relaxation_time: 100.0,
1130            damping_coefficient: 1.0,
1131        }
1132    }
1133}
1134
1135impl TemperatureProfile {
1136    /// Create a `TemperatureProfile` with default sub-components.
1137    pub fn new() -> Self {
1138        Self {
1139            profile_type: TemperatureProfileType::Constant,
1140            initial_temperature: 300.0,
1141            final_temperature: None,
1142            ramp_rate: None,
1143        }
1144    }
1145}
1146
1147impl ForceFieldCalculator {
1148    /// Create a `ForceFieldCalculator` with default sub-components.
1149    pub fn new() -> Self {
1150        Self {
1151            force_fields: HashMap::new(),
1152            interaction_calculator: InteractionCalculator::new(),
1153            energy_calculator: EnergyCalculator::new(),
1154        }
1155    }
1156
1157    /// Initialise the `ForceFieldCalculator` sub-components; propagates `ChemistryError`.
1158    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1159        self.interaction_calculator.initialize()?;
1160        self.energy_calculator.initialize()?;
1161        // Populate the standard force-field catalogue. Each entry ships with a
1162        // default parameter set (≥1 bond/angle/torsion/nonbonded entry) so the
1163        // calculator is usable immediately after initialization.
1164        self.register_standard_force_fields();
1165        Ok(())
1166    }
1167
1168    /// Register the built-in force-field definitions (AMBER, CHARMM, OPLS-AA,
1169    /// GROMOS, Universal/UFF). `Universal` has no dedicated `ForceFieldType`
1170    /// variant, so it is tagged `Custom` with a descriptive name.
1171    fn register_standard_force_fields(&mut self) {
1172        self.force_fields.insert(
1173            "AMBER".to_string(),
1174            ForceField {
1175                field_id: "ff_amber".to_string(),
1176                field_name: "AMBER".to_string(),
1177                field_type: ForceFieldType::AMBER,
1178                parameters: ForceFieldParameters::new(),
1179            },
1180        );
1181        self.force_fields.insert(
1182            "CHARMM".to_string(),
1183            ForceField {
1184                field_id: "ff_charmm".to_string(),
1185                field_name: "CHARMM".to_string(),
1186                field_type: ForceFieldType::CHARMM,
1187                parameters: ForceFieldParameters::new(),
1188            },
1189        );
1190        self.force_fields.insert(
1191            "OPLS".to_string(),
1192            ForceField {
1193                field_id: "ff_opls".to_string(),
1194                field_name: "OPLS-AA".to_string(),
1195                field_type: ForceFieldType::OPLS,
1196                parameters: ForceFieldParameters::new(),
1197            },
1198        );
1199        self.force_fields.insert(
1200            "GROMOS".to_string(),
1201            ForceField {
1202                field_id: "ff_gromos".to_string(),
1203                field_name: "GROMOS".to_string(),
1204                field_type: ForceFieldType::GROMOS,
1205                parameters: ForceFieldParameters::new(),
1206            },
1207        );
1208        self.force_fields.insert(
1209            "Universal".to_string(),
1210            ForceField {
1211                field_id: "ff_uff".to_string(),
1212                field_name: "Universal (UFF)".to_string(),
1213                field_type: ForceFieldType::Custom,
1214                parameters: ForceFieldParameters::new(),
1215            },
1216        );
1217    }
1218
1219    /// Look up a registered force field by name.
1220    pub fn get_force_field(&self, name: &str) -> Option<&ForceField> {
1221        self.force_fields.get(name)
1222    }
1223
1224    /// List the names of all registered force fields.
1225    pub fn list_force_fields(&self) -> Vec<String> {
1226        self.force_fields.keys().cloned().collect()
1227    }
1228
1229    /// Register a custom force field under `name`, replacing any existing entry.
1230    pub fn register_force_field(&mut self, name: &str, force_field: ForceField) {
1231        self.force_fields.insert(name.to_string(), force_field);
1232    }
1233}
1234
1235impl ForceField {
1236    /// Create a `ForceField` with default sub-components.
1237    pub fn new() -> Self {
1238        Self {
1239            field_id: "ff_1".to_string(),
1240            field_name: "AMBER".to_string(),
1241            field_type: ForceFieldType::AMBER,
1242            parameters: ForceFieldParameters::new(),
1243        }
1244    }
1245}
1246
1247impl ForceFieldParameters {
1248    /// Create a `ForceFieldParameters` with default sub-components.
1249    pub fn new() -> Self {
1250        Self {
1251            bond_parameters: vec![BondParameter::new()],
1252            angle_parameters: vec![AngleParameter::new()],
1253            torsion_parameters: vec![TorsionParameter::new()],
1254            nonbonded_parameters: vec![NonbondedParameter::new()],
1255        }
1256    }
1257}
1258
1259impl BondParameter {
1260    /// Create a `BondParameter` with default sub-components.
1261    pub fn new() -> Self {
1262        Self {
1263            atom_types: vec!["C".to_string(), "H".to_string()],
1264            equilibrium_length: 1.09,
1265            force_constant: 450.0,
1266        }
1267    }
1268}
1269
1270impl AngleParameter {
1271    /// Create a `AngleParameter` with default sub-components.
1272    pub fn new() -> Self {
1273        Self {
1274            atom_types: vec!["C".to_string(), "H".to_string(), "H".to_string()],
1275            equilibrium_angle: 109.5,
1276            force_constant: 50.0,
1277        }
1278    }
1279}
1280
1281impl TorsionParameter {
1282    /// Create a `TorsionParameter` with default sub-components.
1283    pub fn new() -> Self {
1284        Self {
1285            atom_types: vec![
1286                "C".to_string(),
1287                "C".to_string(),
1288                "C".to_string(),
1289                "C".to_string(),
1290            ],
1291            barriers: vec![0.0, 1.0],
1292            phases: vec![0.0, 180.0],
1293            periodicities: vec![1, 2],
1294        }
1295    }
1296}
1297
1298impl NonbondedParameter {
1299    /// Create a `NonbondedParameter` with default sub-components.
1300    pub fn new() -> Self {
1301        Self {
1302            atom_type: "C".to_string(),
1303            sigma: 3.4,
1304            epsilon: 0.086,
1305            charge: 0.0,
1306        }
1307    }
1308}
1309
1310impl InteractionCalculator {
1311    /// Create a `InteractionCalculator` with default sub-components.
1312    pub fn new() -> Self {
1313        Self {
1314            bonded_interactions: BondedInteractions::new(),
1315            nonbonded_interactions: NonbondedInteractions::new(),
1316            long_range_interactions: LongRangeInteractions::new(),
1317        }
1318    }
1319
1320    /// Borrow the bonded-interactions calculator.
1321    pub fn bonded_interactions(&self) -> &BondedInteractions {
1322        &self.bonded_interactions
1323    }
1324
1325    /// Mutably borrow the bonded-interactions calculator.
1326    pub fn bonded_interactions_mut(&mut self) -> &mut BondedInteractions {
1327        &mut self.bonded_interactions
1328    }
1329
1330    /// Borrow the nonbonded-interactions calculator.
1331    pub fn nonbonded_interactions(&self) -> &NonbondedInteractions {
1332        &self.nonbonded_interactions
1333    }
1334
1335    /// Mutably borrow the nonbonded-interactions calculator.
1336    pub fn nonbonded_interactions_mut(&mut self) -> &mut NonbondedInteractions {
1337        &mut self.nonbonded_interactions
1338    }
1339
1340    /// Borrow the long-range-interactions calculator.
1341    pub fn long_range_interactions(&self) -> &LongRangeInteractions {
1342        &self.long_range_interactions
1343    }
1344
1345    /// Mutably borrow the long-range-interactions calculator.
1346    pub fn long_range_interactions_mut(&mut self) -> &mut LongRangeInteractions {
1347        &mut self.long_range_interactions
1348    }
1349
1350    /// Initialise the `InteractionCalculator` sub-components; propagates `ChemistryError`.
1351    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1352        let _ = self.nonbonded_interactions.lennard_jones();
1353        let _ = self.nonbonded_interactions.coulomb();
1354        let _ = self.nonbonded_interactions.buckingham();
1355        let _ = self.long_range_interactions.ewald_summation();
1356        let _ = self.long_range_interactions.particle_mesh();
1357        let _ = self.long_range_interactions.reaction_field();
1358        Ok(())
1359    }
1360}
1361
1362impl BondedInteractions {
1363    /// Create a `BondedInteractions` with default sub-components.
1364    pub fn new() -> Self {
1365        Self {
1366            bond_calculator: BondCalculator::new(),
1367            angle_calculator: AngleCalculator::new(),
1368            torsion_calculator: TorsionCalculator::new(),
1369            improper_calculator: ImproperCalculator::new(),
1370        }
1371    }
1372
1373    /// Borrow the bond-stretch calculator.
1374    pub fn bond_calculator(&self) -> &BondCalculator {
1375        &self.bond_calculator
1376    }
1377
1378    /// Mutably borrow the bond-stretch calculator.
1379    pub fn bond_calculator_mut(&mut self) -> &mut BondCalculator {
1380        &mut self.bond_calculator
1381    }
1382
1383    /// Borrow the angle-bend calculator.
1384    pub fn angle_calculator(&self) -> &AngleCalculator {
1385        &self.angle_calculator
1386    }
1387
1388    /// Mutably borrow the angle-bend calculator.
1389    pub fn angle_calculator_mut(&mut self) -> &mut AngleCalculator {
1390        &mut self.angle_calculator
1391    }
1392
1393    /// Borrow the torsion calculator.
1394    pub fn torsion_calculator(&self) -> &TorsionCalculator {
1395        &self.torsion_calculator
1396    }
1397
1398    /// Mutably borrow the torsion calculator.
1399    pub fn torsion_calculator_mut(&mut self) -> &mut TorsionCalculator {
1400        &mut self.torsion_calculator
1401    }
1402
1403    /// Borrow the improper-torsion calculator.
1404    pub fn improper_calculator(&self) -> &ImproperCalculator {
1405        &self.improper_calculator
1406    }
1407
1408    /// Mutably borrow the improper-torsion calculator.
1409    pub fn improper_calculator_mut(&mut self) -> &mut ImproperCalculator {
1410        &mut self.improper_calculator
1411    }
1412}
1413
1414impl BondCalculator {
1415    /// Create a `BondCalculator` with default sub-components.
1416    pub fn new() -> Self {
1417        Self {
1418            calculator_type: BondCalculatorType::Harmonic,
1419            parameters: BondCalculatorParameters::new(),
1420        }
1421    }
1422}
1423
1424impl BondCalculatorParameters {
1425    /// Create a `BondCalculatorParameters` with default sub-components.
1426    pub fn new() -> Self {
1427        Self {
1428            force_constant: 450.0,
1429            equilibrium_length: 1.09,
1430            dissociation_energy: None,
1431        }
1432    }
1433}
1434
1435impl AngleCalculator {
1436    /// Create a `AngleCalculator` with default sub-components.
1437    pub fn new() -> Self {
1438        Self {
1439            calculator_type: AngleCalculatorType::Harmonic,
1440            parameters: AngleCalculatorParameters::new(),
1441        }
1442    }
1443}
1444
1445impl AngleCalculatorParameters {
1446    /// Create a `AngleCalculatorParameters` with default sub-components.
1447    pub fn new() -> Self {
1448        Self {
1449            force_constant: 50.0,
1450            equilibrium_angle: 109.5,
1451            ub_parameters: None,
1452        }
1453    }
1454}
1455
1456impl TorsionCalculator {
1457    /// Create a `TorsionCalculator` with default sub-components.
1458    pub fn new() -> Self {
1459        Self {
1460            calculator_type: TorsionCalculatorType::Cosine,
1461            parameters: TorsionCalculatorParameters::new(),
1462        }
1463    }
1464}
1465
1466impl TorsionCalculatorParameters {
1467    /// Create a `TorsionCalculatorParameters` with default sub-components.
1468    pub fn new() -> Self {
1469        Self {
1470            barriers: vec![0.0, 1.0],
1471            phases: vec![0.0, 180.0],
1472            periodicities: vec![1, 2],
1473        }
1474    }
1475}
1476
1477impl ImproperCalculator {
1478    /// Create a `ImproperCalculator` with default sub-components.
1479    pub fn new() -> Self {
1480        Self {
1481            calculator_type: ImproperCalculatorType::Harmonic,
1482            parameters: ImproperCalculatorParameters::new(),
1483        }
1484    }
1485}
1486
1487impl ImproperCalculatorParameters {
1488    /// Create a `ImproperCalculatorParameters` with default sub-components.
1489    pub fn new() -> Self {
1490        Self {
1491            force_constant: 50.0,
1492            equilibrium_angle: 109.5,
1493        }
1494    }
1495}
1496
1497impl NonbondedInteractions {
1498    /// Create a `NonbondedInteractions` with default sub-components.
1499    pub fn new() -> Self {
1500        Self {
1501            lennard_jones: LennardJones::new(),
1502            coulomb: Coulomb::new(),
1503            buckingham: Buckingham::new(),
1504        }
1505    }
1506
1507    /// Borrow the Lennard-Jones potential parameters.
1508    pub fn lennard_jones(&self) -> &LennardJones {
1509        &self.lennard_jones
1510    }
1511
1512    /// Mutably borrow the Lennard-Jones potential parameters.
1513    pub fn lennard_jones_mut(&mut self) -> &mut LennardJones {
1514        &mut self.lennard_jones
1515    }
1516
1517    /// Borrow the Coulomb potential parameters.
1518    pub fn coulomb(&self) -> &Coulomb {
1519        &self.coulomb
1520    }
1521
1522    /// Mutably borrow the Coulomb potential parameters.
1523    pub fn coulomb_mut(&mut self) -> &mut Coulomb {
1524        &mut self.coulomb
1525    }
1526
1527    /// Borrow the Buckingham potential parameters.
1528    pub fn buckingham(&self) -> &Buckingham {
1529        &self.buckingham
1530    }
1531
1532    /// Mutably borrow the Buckingham potential parameters.
1533    pub fn buckingham_mut(&mut self) -> &mut Buckingham {
1534        &mut self.buckingham
1535    }
1536}
1537
1538impl LennardJones {
1539    /// Create a `LennardJones` with default sub-components.
1540    pub fn new() -> Self {
1541        Self {
1542            epsilon: 0.086,
1543            sigma: 3.4,
1544            cutoff: 12.0,
1545            switching_distance: 10.0,
1546        }
1547    }
1548}
1549
1550impl Coulomb {
1551    /// Create a `Coulomb` with default sub-components.
1552    pub fn new() -> Self {
1553        Self {
1554            coulomb_constant: 332.06,
1555            dielectric: 1.0,
1556            cutoff: 12.0,
1557            switching_distance: 10.0,
1558        }
1559    }
1560}
1561
1562impl Buckingham {
1563    /// Create a `Buckingham` with default sub-components.
1564    pub fn new() -> Self {
1565        Self {
1566            a: 1000.0,
1567            b: 3.5,
1568            c: 0.0,
1569            cutoff: 12.0,
1570        }
1571    }
1572}
1573
1574impl LongRangeInteractions {
1575    /// Create a `LongRangeInteractions` with default sub-components.
1576    pub fn new() -> Self {
1577        Self {
1578            ewald_summation: EwaldSummation::new(),
1579            particle_mesh: ParticleMesh::new(),
1580            reaction_field: ReactionField::new(),
1581        }
1582    }
1583
1584    /// Borrow the Ewald-summation parameters.
1585    pub fn ewald_summation(&self) -> &EwaldSummation {
1586        &self.ewald_summation
1587    }
1588
1589    /// Mutably borrow the Ewald-summation parameters.
1590    pub fn ewald_summation_mut(&mut self) -> &mut EwaldSummation {
1591        &mut self.ewald_summation
1592    }
1593
1594    /// Borrow the particle-mesh (PME) parameters.
1595    pub fn particle_mesh(&self) -> &ParticleMesh {
1596        &self.particle_mesh
1597    }
1598
1599    /// Mutably borrow the particle-mesh (PME) parameters.
1600    pub fn particle_mesh_mut(&mut self) -> &mut ParticleMesh {
1601        &mut self.particle_mesh
1602    }
1603
1604    /// Borrow the reaction-field parameters.
1605    pub fn reaction_field(&self) -> &ReactionField {
1606        &self.reaction_field
1607    }
1608
1609    /// Mutably borrow the reaction-field parameters.
1610    pub fn reaction_field_mut(&mut self) -> &mut ReactionField {
1611        &mut self.reaction_field
1612    }
1613}
1614
1615impl EwaldSummation {
1616    /// Create a `EwaldSummation` with default sub-components.
1617    pub fn new() -> Self {
1618        Self {
1619            alpha: 0.3,
1620            k_max: 10,
1621            real_cutoff: 12.0,
1622            reciprocal_cutoff: 10.0,
1623        }
1624    }
1625}
1626
1627impl ParticleMesh {
1628    /// Create a `ParticleMesh` with default sub-components.
1629    pub fn new() -> Self {
1630        Self {
1631            grid_size: vec![32, 32, 32],
1632            spline_order: 4,
1633            cutoff: 12.0,
1634        }
1635    }
1636}
1637
1638impl ReactionField {
1639    /// Create a `ReactionField` with default sub-components.
1640    pub fn new() -> Self {
1641        Self {
1642            dielectric_inside: 1.0,
1643            dielectric_outside: 78.5,
1644            cutoff: 12.0,
1645        }
1646    }
1647}
1648
1649impl EnergyCalculator {
1650    /// Create a `EnergyCalculator` with default sub-components.
1651    pub fn new() -> Self {
1652        Self {
1653            kinetic_energy: KineticEnergy::new(),
1654            potential_energy: PotentialEnergy::new(),
1655            total_energy: TotalEnergy::new(),
1656        }
1657    }
1658
1659    /// Borrow the kinetic-energy state.
1660    pub fn kinetic_energy(&self) -> &KineticEnergy {
1661        &self.kinetic_energy
1662    }
1663
1664    /// Mutably borrow the kinetic-energy state.
1665    pub fn kinetic_energy_mut(&mut self) -> &mut KineticEnergy {
1666        &mut self.kinetic_energy
1667    }
1668
1669    /// Borrow the potential-energy state.
1670    pub fn potential_energy(&self) -> &PotentialEnergy {
1671        &self.potential_energy
1672    }
1673
1674    /// Mutably borrow the potential-energy state.
1675    pub fn potential_energy_mut(&mut self) -> &mut PotentialEnergy {
1676        &mut self.potential_energy
1677    }
1678
1679    /// Borrow the total-energy state.
1680    pub fn total_energy(&self) -> &TotalEnergy {
1681        &self.total_energy
1682    }
1683
1684    /// Mutably borrow the total-energy state.
1685    pub fn total_energy_mut(&mut self) -> &mut TotalEnergy {
1686        &mut self.total_energy
1687    }
1688
1689    /// Initialise the `EnergyCalculator` sub-components; propagates `ChemistryError`.
1690    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1691        Ok(())
1692    }
1693}
1694
1695impl KineticEnergy {
1696    /// Create a `KineticEnergy` with default sub-components.
1697    pub fn new() -> Self {
1698        Self {
1699            temperature: 300.0,
1700            degrees_of_freedom: 0,
1701            velocities: Vec::new(),
1702        }
1703    }
1704}
1705
1706impl PotentialEnergy {
1707    /// Create a `PotentialEnergy` with default sub-components.
1708    pub fn new() -> Self {
1709        Self {
1710            bonded_energy: 0.0,
1711            nonbonded_energy: 0.0,
1712            long_range_energy: 0.0,
1713        }
1714    }
1715}
1716
1717impl TotalEnergy {
1718    /// Create a `TotalEnergy` with default sub-components.
1719    pub fn new() -> Self {
1720        Self {
1721            kinetic: 0.0,
1722            potential: 0.0,
1723            total: 0.0,
1724            drift: 0.0,
1725        }
1726    }
1727}
1728
1729impl MolecularIntegrator {
1730    /// Create a `MolecularIntegrator` with default sub-components.
1731    pub fn new() -> Self {
1732        Self {
1733            integrator_type: IntegratorType::VelocityVerlet,
1734            integrator_parameters: IntegratorParameters::new(),
1735            constraint_handler: ConstraintHandler::new(),
1736        }
1737    }
1738
1739    /// Borrow the integrator type.
1740    pub fn integrator_type(&self) -> &IntegratorType {
1741        &self.integrator_type
1742    }
1743
1744    /// Set the integrator type.
1745    pub fn set_integrator_type(&mut self, integrator_type: IntegratorType) {
1746        self.integrator_type = integrator_type;
1747    }
1748
1749    /// Borrow the integrator parameters.
1750    pub fn integrator_parameters(&self) -> &IntegratorParameters {
1751        &self.integrator_parameters
1752    }
1753
1754    /// Mutably borrow the integrator parameters.
1755    pub fn integrator_parameters_mut(&mut self) -> &mut IntegratorParameters {
1756        &mut self.integrator_parameters
1757    }
1758
1759    /// Initialise the `MolecularIntegrator` sub-components; propagates `ChemistryError`.
1760    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1761        self.constraint_handler.initialize()?;
1762        Ok(())
1763    }
1764}
1765
1766impl IntegratorParameters {
1767    /// Create a `IntegratorParameters` with default sub-components.
1768    pub fn new() -> Self {
1769        Self {
1770            time_step: 0.001,
1771            accuracy: 1e-6,
1772            stability_factor: 0.9,
1773        }
1774    }
1775}
1776
1777impl ConstraintHandler {
1778    /// Create a `ConstraintHandler` with default sub-components.
1779    pub fn new() -> Self {
1780        Self {
1781            constraint_algorithm: ConstraintAlgorithm::SHAKE,
1782            constraint_parameters: ConstraintParameters::new(),
1783        }
1784    }
1785
1786    /// Borrow the constraint algorithm.
1787    pub fn constraint_algorithm(&self) -> &ConstraintAlgorithm {
1788        &self.constraint_algorithm
1789    }
1790
1791    /// Set the constraint algorithm.
1792    pub fn set_constraint_algorithm(&mut self, algorithm: ConstraintAlgorithm) {
1793        self.constraint_algorithm = algorithm;
1794    }
1795
1796    /// Borrow the constraint parameters.
1797    pub fn constraint_parameters(&self) -> &ConstraintParameters {
1798        &self.constraint_parameters
1799    }
1800
1801    /// Mutably borrow the constraint parameters.
1802    pub fn constraint_parameters_mut(&mut self) -> &mut ConstraintParameters {
1803        &mut self.constraint_parameters
1804    }
1805
1806    /// Initialise the `ConstraintHandler` sub-components; propagates `ChemistryError`.
1807    pub fn initialize(&mut self) -> Result<(), ChemistryError> {
1808        Ok(())
1809    }
1810}
1811
1812impl ConstraintParameters {
1813    /// Create a `ConstraintParameters` with default sub-components.
1814    pub fn new() -> Self {
1815        Self {
1816            tolerance: 1e-6,
1817            max_iterations: 100,
1818            relaxation_parameter: 0.1,
1819        }
1820    }
1821}
1822
1823impl BoundaryConditions {
1824    /// Create a `BoundaryConditions` with default sub-components.
1825    pub fn new() -> Self {
1826        Self {
1827            boundary_type: BoundaryType::Periodic,
1828            box_vectors: vec![
1829                vec![10.0, 0.0, 0.0],
1830                vec![0.0, 10.0, 0.0],
1831                vec![0.0, 0.0, 10.0],
1832            ],
1833            minimum_image: MinimumImage::new(),
1834        }
1835    }
1836
1837    /// Borrow the boundary type.
1838    pub fn boundary_type(&self) -> &BoundaryType {
1839        &self.boundary_type
1840    }
1841
1842    /// Set the boundary type.
1843    pub fn set_boundary_type(&mut self, boundary_type: BoundaryType) {
1844        self.boundary_type = boundary_type;
1845    }
1846
1847    /// Borrow the simulation box vectors.
1848    pub fn box_vectors(&self) -> &Vec<Vec<f64>> {
1849        &self.box_vectors
1850    }
1851
1852    /// Mutably borrow the simulation box vectors.
1853    pub fn box_vectors_mut(&mut self) -> &mut Vec<Vec<f64>> {
1854        &mut self.box_vectors
1855    }
1856
1857    /// Borrow the minimum-image convention state.
1858    pub fn minimum_image(&self) -> &MinimumImage {
1859        &self.minimum_image
1860    }
1861
1862    /// Mutably borrow the minimum-image convention state.
1863    pub fn minimum_image_mut(&mut self) -> &mut MinimumImage {
1864        &mut self.minimum_image
1865    }
1866}
1867
1868impl MinimumImage {
1869    /// Create a `MinimumImage` with default sub-components.
1870    pub fn new() -> Self {
1871        Self {
1872            box_size: vec![10.0, 10.0, 10.0],
1873            periodic: true,
1874        }
1875    }
1876}