Skip to main content

qualia_core_db/specialized_libs/physics_simulation/
solvers.rs

1use super::*;
2
3/// Physics solver
4pub struct PhysicsSolver {
5    solver_type: SolverType,
6    linear_solver: LinearSolver,
7    nonlinear_solver: NonlinearSolver,
8    eigenvalue_solver: EigenvalueSolver,
9    optimization_solver: OptimizationSolver,
10}
11
12/// Solver types
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub enum SolverType {
15    /// Direct solver
16    Direct,
17    /// Iterative solver
18    Iterative,
19    /// Multigrid solver
20    Multigrid,
21    /// Domain decomposition solver
22    DomainDecomposition,
23    /// Hybrid solver
24    Hybrid,
25}
26
27/// CFD (Computational Fluid Dynamics) solver
28pub struct CfdSolver {
29    solver_id: String,
30    solver_method: LinearSolverMethod,
31    preconditioner: Preconditioner,
32    convergence_criteria: ConvergenceCriteria,
33    solver_parameters: SolverParameters,
34}
35
36/// Solver result for physics computations
37pub struct SolverResult {
38    pub solver_id: String,
39    pub iterations: u64,
40    pub residual_norm: f64,
41    pub convergence_time: f64,
42    pub error_message: Option<String>,
43}
44
45/// Distribution of simulation work across mesh nodes
46pub struct NodeDistribution {
47    pub node_ids: Vec<String>,
48    pub node_loads: Vec<f64>,
49    pub communication_pattern: CommunicationPattern,
50}
51
52/// Linear solver
53pub struct LinearSolver {
54    solver_method: LinearSolverMethod,
55    preconditioner: Preconditioner,
56    convergence_criteria: ConvergenceCriteria,
57    solver_parameters: SolverParameters,
58}
59
60/// Linear solver methods
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub enum LinearSolverMethod {
63    /// Gaussian elimination
64    GaussianElimination,
65    /// LU decomposition
66    LUDecomposition,
67    /// Cholesky decomposition
68    CholeskyDecomposition,
69    /// QR decomposition
70    QRDecomposition,
71    /// Conjugate gradient method
72    ConjugateGradient,
73    /// GMRES method
74    GMRES,
75    /// BiCGSTAB method
76    BiCGSTAB,
77    /// Multigrid method
78    Multigrid,
79}
80
81/// Preconditioner
82#[derive(Debug, Clone)]
83pub struct Preconditioner {
84    preconditioner_type: PreconditionerType,
85    preconditioner_parameters: PreconditionerParameters,
86}
87
88/// Preconditioner types
89#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
90pub enum PreconditionerType {
91    /// Jacobi preconditioner
92    Jacobi,
93    /// Gauss-Seidel preconditioner
94    GaussSeidel,
95    /// Successive over-relaxation (SOR)
96    SOR,
97    /// Incomplete LU (ILU)
98    ILU,
99    /// Algebraic multigrid (AMG)
100    AMG,
101    /// Block preconditioner
102    Block,
103}
104
105/// Preconditioner parameters
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct PreconditionerParameters {
108    pub relaxation_factor: f64,
109    pub fill_level: usize,
110    pub tolerance: f64,
111    pub max_iterations: usize,
112}
113
114/// Convergence criteria
115#[derive(Debug, Clone)]
116pub struct ConvergenceCriteria {
117    pub tolerance: f64,
118    pub max_iterations: usize,
119    pub relative_tolerance: f64,
120    pub absolute_tolerance: f64,
121    pub divergence_check: bool,
122}
123
124/// Solver parameters
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct SolverParameters {
127    pub tolerance: f64,
128    pub max_iterations: usize,
129    pub restart_frequency: usize,
130    pub orthogonalization: OrthogonalizationMethod,
131}
132
133/// Orthogonalization methods
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub enum OrthogonalizationMethod {
136    /// Classical Gram-Schmidt
137    ClassicalGramSchmidt,
138    /// Modified Gram-Schmidt
139    ModifiedGramSchmidt,
140    /// Householder
141    Householder,
142    /// Givens rotations
143    Givens,
144}
145
146/// Nonlinear solver
147pub struct NonlinearSolver {
148    solver_method: NonlinearSolverMethod,
149    linear_solver: LinearSolver,
150    convergence_criteria: ConvergenceCriteria,
151    solver_parameters: NonlinearSolverParameters,
152}
153
154/// Nonlinear solver methods
155#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub enum NonlinearSolverMethod {
157    /// Newton-Raphson method
158    NewtonRaphson,
159    /// Quasi-Newton method
160    QuasiNewton,
161    /// Fixed-point iteration
162    FixedPoint,
163    /// Picard iteration
164    Picard,
165    /// Anderson acceleration
166    Anderson,
167    /// Broyden's method
168    Broyden,
169}
170
171/// Nonlinear solver parameters
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct NonlinearSolverParameters {
174    pub tolerance: f64,
175    pub max_iterations: usize,
176    pub line_search: LineSearchMethod,
177    pub trust_region: TrustRegionMethod,
178}
179
180/// Line search methods
181#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
182pub enum LineSearchMethod {
183    /// Backtracking line search
184    Backtracking,
185    /// Wolfe conditions
186    Wolfe,
187    /// Goldstein conditions
188    Goldstein,
189    /// Armijo rule
190    Armijo,
191}
192
193/// Trust region methods
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
195pub enum TrustRegionMethod {
196    /// Dogleg method
197    Dogleg,
198    /// Double dogleg method
199    DoubleDogleg,
200    /// Powell method
201    Powell,
202    /// Levenberg-Marquardt
203    LevenbergMarquardt,
204}
205
206impl PhysicsSolver {
207    /// Creates a solver facade with default linear/nonlinear solver state.
208    pub fn new() -> Self {
209        Self {
210            solver_type: SolverType::Iterative,
211            linear_solver: LinearSolver::new(),
212            nonlinear_solver: NonlinearSolver::new(),
213            eigenvalue_solver: EigenvalueSolver::new(),
214            optimization_solver: OptimizationSolver::new(),
215        }
216    }
217
218    /// Initializes the linear and nonlinear solvers; `PhysicsError` propagates.
219    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
220        self.linear_solver.initialize()?;
221        self.nonlinear_solver.initialize()?;
222        self.eigenvalue_solver.initialize()?;
223        self.optimization_solver.initialize()?;
224        Ok(())
225    }
226
227    /// Builds a `CfdSolver` configured with GMRES + default preconditioner/convergence/parameters (ignores `_config` — fixed configuration).
228    pub fn create_cfd_solver(&self, _config: &SimulationConfig) -> Result<CfdSolver, PhysicsError> {
229        let solver = CfdSolver {
230            solver_id: "cfd_solver".to_string(),
231            solver_method: LinearSolverMethod::GMRES,
232            preconditioner: Preconditioner::new(),
233            convergence_criteria: ConvergenceCriteria::new(),
234            solver_parameters: SolverParameters::new(),
235        };
236
237        Ok(solver)
238    }
239
240    /// Computes a real steady-state residual: L2 norm of the 1-D Burgers operator `ν·u_xx − u·u_x` over the velocity field (ν=1.5e-5); `residual_norm = f64::MAX` and 0 iterations when no velocity field is present.
241    pub fn solve_cfd_step(
242        &self,
243        _solver: &CfdSolver,
244        fields: &[PhysicsField],
245        _mesh: &Mesh,
246    ) -> Result<SolverResult, PhysicsError> {
247        // Real steady-state residual of the velocity field: the L2 norm of the Burgers
248        // operator ‖ν·u_xx − u·u_x‖ over the interior nodes — a genuine measure of how far
249        // the field is from a steady solution. (Previously this returned a fabricated 1e-7.)
250        let start = std::time::Instant::now();
251        let velocity = fields
252            .iter()
253            .find(|f| f.metadata.physical_quantity == "Velocity");
254        let (iterations, residual_norm) = match velocity {
255            Some(v) if v.data.len() >= 3 => {
256                let u = &v.data;
257                let n = u.len();
258                let dx = 1.0 / n as f64;
259                let nu = 1.5e-5_f64;
260                let mut sumsq = 0.0f64;
261                for i in 1..n - 1 {
262                    let u_x = (u[i + 1] - u[i - 1]) / (2.0 * dx);
263                    let u_xx = (u[i + 1] - 2.0 * u[i] + u[i - 1]) / (dx * dx);
264                    let r = nu * u_xx - u[i] * u_x;
265                    sumsq += r * r;
266                }
267                (1u64, sumsq.sqrt())
268            }
269            _ => (0u64, f64::MAX),
270        };
271
272        Ok(SolverResult {
273            solver_id: "cfd_solver".to_string(),
274            iterations,
275            residual_norm,
276            convergence_time: start.elapsed().as_secs_f64(),
277            error_message: None,
278        })
279    }
280
281    /// Get the solver type.
282    pub fn get_solver_type(&self) -> &SolverType {
283        &self.solver_type
284    }
285
286    /// Set the solver type.
287    pub fn set_solver_type(&mut self, solver_type: SolverType) {
288        self.solver_type = solver_type;
289    }
290}
291
292impl LinearSolver {
293    /// Creates a linear solver with default preconditioner and convergence criteria.
294    pub fn new() -> Self {
295        Self {
296            solver_method: LinearSolverMethod::GMRES,
297            preconditioner: Preconditioner::new(),
298            convergence_criteria: ConvergenceCriteria::new(),
299            solver_parameters: SolverParameters::new(),
300        }
301    }
302
303    /// No-op returning `Ok(())`.
304    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
305        Ok(())
306    }
307
308    /// Get the solver method.
309    pub fn get_solver_method(&self) -> &LinearSolverMethod {
310        &self.solver_method
311    }
312
313    /// Set the solver method.
314    pub fn set_solver_method(&mut self, method: LinearSolverMethod) {
315        self.solver_method = method;
316    }
317
318    /// Get a reference to the preconditioner.
319    pub fn get_preconditioner(&self) -> &Preconditioner {
320        &self.preconditioner
321    }
322
323    /// Get a mutable reference to the preconditioner.
324    pub fn get_preconditioner_mut(&mut self) -> &mut Preconditioner {
325        &mut self.preconditioner
326    }
327
328    /// Get a reference to the convergence criteria.
329    pub fn get_convergence_criteria(&self) -> &ConvergenceCriteria {
330        &self.convergence_criteria
331    }
332
333    /// Get a mutable reference to the convergence criteria.
334    pub fn get_convergence_criteria_mut(&mut self) -> &mut ConvergenceCriteria {
335        &mut self.convergence_criteria
336    }
337
338    /// Get a reference to the solver parameters.
339    pub fn get_solver_parameters(&self) -> &SolverParameters {
340        &self.solver_parameters
341    }
342
343    /// Get a mutable reference to the solver parameters.
344    pub fn get_solver_parameters_mut(&mut self) -> &mut SolverParameters {
345        &mut self.solver_parameters
346    }
347}
348
349impl CfdSolver {
350    /// Get the solver ID.
351    pub fn get_solver_id(&self) -> &str {
352        &self.solver_id
353    }
354
355    /// Get the solver method.
356    pub fn get_solver_method(&self) -> &LinearSolverMethod {
357        &self.solver_method
358    }
359
360    /// Set the solver method.
361    pub fn set_solver_method(&mut self, method: LinearSolverMethod) {
362        self.solver_method = method;
363    }
364
365    /// Get a reference to the preconditioner.
366    pub fn get_preconditioner(&self) -> &Preconditioner {
367        &self.preconditioner
368    }
369
370    /// Get a mutable reference to the preconditioner.
371    pub fn get_preconditioner_mut(&mut self) -> &mut Preconditioner {
372        &mut self.preconditioner
373    }
374
375    /// Get a reference to the convergence criteria.
376    pub fn get_convergence_criteria(&self) -> &ConvergenceCriteria {
377        &self.convergence_criteria
378    }
379
380    /// Get a mutable reference to the convergence criteria.
381    pub fn get_convergence_criteria_mut(&mut self) -> &mut ConvergenceCriteria {
382        &mut self.convergence_criteria
383    }
384
385    /// Get a reference to the solver parameters.
386    pub fn get_solver_parameters(&self) -> &SolverParameters {
387        &self.solver_parameters
388    }
389
390    /// Get a mutable reference to the solver parameters.
391    pub fn get_solver_parameters_mut(&mut self) -> &mut SolverParameters {
392        &mut self.solver_parameters
393    }
394}
395
396impl Preconditioner {
397    /// Creates a default `Preconditioner`.
398    pub fn new() -> Self {
399        Self {
400            preconditioner_type: PreconditionerType::ILU,
401            preconditioner_parameters: PreconditionerParameters::new(),
402        }
403    }
404
405    /// Get the preconditioner type.
406    pub fn get_preconditioner_type(&self) -> &PreconditionerType {
407        &self.preconditioner_type
408    }
409
410    /// Set the preconditioner type.
411    pub fn set_preconditioner_type(&mut self, ptype: PreconditionerType) {
412        self.preconditioner_type = ptype;
413    }
414
415    /// Get a reference to the preconditioner parameters.
416    pub fn get_preconditioner_parameters(&self) -> &PreconditionerParameters {
417        &self.preconditioner_parameters
418    }
419
420    /// Get a mutable reference to the preconditioner parameters.
421    pub fn get_preconditioner_parameters_mut(&mut self) -> &mut PreconditionerParameters {
422        &mut self.preconditioner_parameters
423    }
424}
425
426impl PreconditionerParameters {
427    /// Creates default `PreconditionerParameters`.
428    pub fn new() -> Self {
429        Self {
430            relaxation_factor: 1.0,
431            fill_level: 0,
432            tolerance: 1e-6,
433            max_iterations: 100,
434        }
435    }
436}
437
438impl ConvergenceCriteria {
439    /// Creates default `ConvergenceCriteria`.
440    pub fn new() -> Self {
441        Self {
442            tolerance: 1e-6,
443            max_iterations: 1000,
444            relative_tolerance: 1e-6,
445            absolute_tolerance: 1e-12,
446            divergence_check: true,
447        }
448    }
449}
450
451impl SolverParameters {
452    /// Creates default `SolverParameters`.
453    pub fn new() -> Self {
454        Self {
455            tolerance: 1e-6,
456            max_iterations: 1000,
457            restart_frequency: 100,
458            orthogonalization: OrthogonalizationMethod::ModifiedGramSchmidt,
459        }
460    }
461}
462
463impl NonlinearSolver {
464    /// Creates a nonlinear solver with default parameters.
465    pub fn new() -> Self {
466        Self {
467            solver_method: NonlinearSolverMethod::NewtonRaphson,
468            linear_solver: LinearSolver::new(),
469            convergence_criteria: ConvergenceCriteria::new(),
470            solver_parameters: NonlinearSolverParameters::new(),
471        }
472    }
473
474    /// No-op returning `Ok(())`.
475    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
476        self.linear_solver.initialize()?;
477        Ok(())
478    }
479
480    /// Get the solver method.
481    pub fn get_solver_method(&self) -> &NonlinearSolverMethod {
482        &self.solver_method
483    }
484
485    /// Set the solver method.
486    pub fn set_solver_method(&mut self, method: NonlinearSolverMethod) {
487        self.solver_method = method;
488    }
489
490    /// Get a reference to the convergence criteria.
491    pub fn get_convergence_criteria(&self) -> &ConvergenceCriteria {
492        &self.convergence_criteria
493    }
494
495    /// Get a mutable reference to the convergence criteria.
496    pub fn get_convergence_criteria_mut(&mut self) -> &mut ConvergenceCriteria {
497        &mut self.convergence_criteria
498    }
499
500    /// Get a reference to the solver parameters.
501    pub fn get_solver_parameters(&self) -> &NonlinearSolverParameters {
502        &self.solver_parameters
503    }
504
505    /// Get a mutable reference to the solver parameters.
506    pub fn get_solver_parameters_mut(&mut self) -> &mut NonlinearSolverParameters {
507        &mut self.solver_parameters
508    }
509}
510
511impl NonlinearSolverParameters {
512    /// Creates default `NonlinearSolverParameters`.
513    pub fn new() -> Self {
514        Self {
515            tolerance: 1e-6,
516            max_iterations: 100,
517            line_search: LineSearchMethod::Backtracking,
518            trust_region: TrustRegionMethod::LevenbergMarquardt,
519        }
520    }
521}