1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Numerical solvers
//!
//! This module provides traits and implementations for numerical solvers.
//! A numerical solver applies a numerical method to solve the equations
//! provided by a physical model within a specific scenario.
//!
//! # Core Concepts
//!
//! ## The Architecture (WHAT vs HOW)
//!
//! The solver architecture separates concerns into three layers:
//!
//! 1. **Scenario** (`Scenario`) - WHAT to solve
//! - Physical model (equations)
//! - Domain boundaries (boundary conditions)
//! - Problem definition
//!
//! 2. **Configuration** (`SolverConfiguration`) - HOW to solve
//! - Solver type (time evolution, iterative, etc.)
//! - Numerical parameters (time steps, tolerance, etc.)
//! - Method selection
//!
//! 3. **Solver** (`Solver` trait) - The numerical method
//! - Applies the numerical scheme
//! - Returns the solution
//! - Independent of physics
//!
//! This separation allows:
//! - Same solver for different physics
//! - Different solvers for same scenario
//! - Easy benchmarking and method comparison
//! - Flexible configuration without code changes
//!
//! # Module Organization
//!
//! - **`traits`**: Core trait definitions and types
//! - `Solver` trait: Stable interface for all solvers
//! - `SolverType`: Enumeration of solver types
//! - `SolverConfiguration`: Configuration structure
//! - `SimulationResult`: Result structure
//!
//! - **`boundary`**: Boundary conditions and domain definition
//! - `DomainBoundaries`: Spatial and temporal boundaries
//! - Factory methods for common boundary types
//!
//! - **`scenario`**: Problem definition
//! - `Scenario`: Combines model + boundaries
//! - Validation and introspection methods
//!
//! - **Solver implementations**:
//! - `EulerSolver`: Forward Euler method
//! - `RK4Solver`: 4 Steps Runge Kutta method
//! - etc.
//!
//! # Quick Start Example
//!
//! ```rust
//! # use chrom_rs::physics::{PhysicalModel, PhysicalState, PhysicalQuantity, PhysicalData};
//! # use chrom_rs::solver::{Scenario, DomainBoundaries, SolverConfiguration, Solver, EulerSolver};
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Deserialize, Serialize)]
//! # struct MyModel;
//! # #[typetag::serde]
//! # impl PhysicalModel for MyModel {
//! # fn points(&self) -> usize { 1 }
//! # fn compute_physics(&self, state: &PhysicalState, _ctx: &chrom_rs::physics::ComputeContext) -> PhysicalState { state.clone() }
//! # fn setup_initial_state(&self) -> PhysicalState {
//! # PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(nalgebra::DVector::from_vec(vec![1.0])))
//! # }
//! # fn name(&self) -> &str { "MyModel" }
//! # }
//! # fn main() -> Result<(), String> {
//! // 1. Create scenario (WHAT to solve)
//! let model = Box::new(MyModel);
//! let initial_state = model.setup_initial_state();
//! let boundaries = DomainBoundaries::temporal(initial_state);
//! let scenario = Scenario::new(model, boundaries);
//!
//! // 2. Create configuration (HOW to solve)
//! let config = SolverConfiguration::time_evolution(
//! 600.0, // 10 minutes total time
//! 10000, // 10000 time steps
//! );
//!
//! // 3. Create solver and solve
//! let solver = EulerSolver::new();
//! let result = solver.solve(&scenario, &config)?;
//!
//! // 4. Access results
//! println!("Simulation completed!");
//! println!("Final state: {:?}", result.final_state);
//! # Ok(())
//! # }
//! ```
//!
//! # Workflow Diagram
//!
//! ```text
//! ┌─────────────────┐
//! │ Physical Model │ (equations)
//! └────────┬────────┘
//! │
//! ├──────────────┐
//! │ │
//! ┌────────▼────────┐ ┌──▼──────────────┐
//! │ Domain │ │ Scenario │ ← WHAT to solve
//! │ Boundaries │ │ (model + bounds)│
//! └─────────────────┘ └────────┬────────┘
//! │
//! ┌────────▼─────────────┐
//! │ Solver Configuration │ ← HOW to solve
//! │ (type + parameters) │
//! └────────┬─────────────┘
//! │
//! ┌────────▼────────┐
//! │ Numerical Solver│ ← The method
//! │ (Euler, RK4...) │
//! └────────┬────────┘
//! │
//! ┌────────▼────────────┐
//! │ Simulation Result │ ← The solution
//! │ (trajectory + meta) │
//! └─────────────────────┘
//! ```
//!
//! # Solver Types
//!
//! Different types of numerical solvers for different problem classes:
//!
//! ## Time Integrators
//!
//! Solve dy/dt = f(y) over time:
//!
//! - **Explicit methods**: Forward Euler, Runge-Kutta
//! - Simple, fast per step
//! - Require small time steps for stability
//! - Good for non-stiff problems
//!
//! - **Implicit methods**: Backward Euler, Crank-Nicolson
//! - More stable, allow larger time steps
//! - Require solving linear systems
//! - Good for stiff problems
//!
//! ## Iterative Solvers
//!
//! Solve F(x) = 0 for steady-state:
//!
//! - Newton-Raphson
//! - Fixed-point iteration
//! - Gradient descent
//!
//! ## Direct Solvers
//!
//! Solve Ax = b (linear systems):
//!
//! - LU decomposition
//! - Cholesky factorization
//! - QR decomposition
//!
//! # Creating a Scenario
//!
//! A scenario combines a physical model with boundary conditions:
//!
//! ```rust
//! # use chrom_rs::physics::{PhysicalModel, PhysicalState, PhysicalQuantity, PhysicalData};
//! # use chrom_rs::solver::{Scenario, DomainBoundaries};
//! # use nalgebra::DVector;
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Deserialize, Serialize)]
//! # struct MyModel;
//! # #[typetag::serde]
//! # impl PhysicalModel for MyModel {
//! # fn points(&self) -> usize { 1 }
//! # fn compute_physics(&self, state: &PhysicalState, _ctx: &chrom_rs::physics::ComputeContext) -> PhysicalState { state.clone() }
//! # fn setup_initial_state(&self) -> PhysicalState {
//! # PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(nalgebra::DVector::from_vec(vec![1.0])))
//! # }
//! # fn name(&self) -> &str { "MyModel" }
//! # }
//! # fn main() -> Result<(), String> {
//! // Define initial state
//! let initial_state = PhysicalState::new(
//! PhysicalQuantity::Concentration,
//! PhysicalData::Vector(DVector::from_vec(vec![1.0, 0.5, 0.2])),
//! );
//!
//! // Create boundaries (temporal only for time evolution)
//! let boundaries = DomainBoundaries::temporal(initial_state);
//!
//! // Create scenario with a model
//! let model = Box::new(MyModel);
//! let scenario = Scenario::new(model, boundaries);
//!
//! // Validate scenario
//! scenario.validate()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Configuring a Solver
//!
//! Different solver types require different configurations:
//!
//! ```rust
//! # use chrom_rs::solver::SolverConfiguration;
//! # fn main() -> Result<(), String> {
//! // Time evolution (ODE integration)
//! let config = SolverConfiguration::time_evolution(
//! 600.0, // Total time (seconds)
//! 10000, // Number of time steps
//! );
//!
//! // Iterative (convergence to steady-state)
//! let config = SolverConfiguration::iterative(
//! 1e-6, // Convergence tolerance
//! 100, // Maximum iterations
//! );
//!
//! // Analytical (exact solution at specific time)
//! let config = SolverConfiguration::analytical(5.0);
//!
//! // Spatial discretization (PDE on grid)
//! let config = SolverConfiguration::spatial_discretization(
//! 100, // Grid points
//! 1000, // Time steps
//! );
//!
//! // Validate before use
//! config.validate()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Implementing a New Solver
//!
//! To create a new numerical solver, implement the `Solver` trait:
//!
//! ```rust
//! # use chrom_rs::solver::{Solver, SolverConfiguration, SimulationResult, Scenario};
//! # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
//! # use nalgebra::DVector;
//! # use std::collections::HashMap;
//! /// My custom numerical solver
//! pub struct MyCustomSolver {
//! // Solver-specific state (if needed)
//! }
//!
//! impl Solver for MyCustomSolver {
//! fn solve(
//! &self,
//! scenario: &Scenario,
//! config: &SolverConfiguration,
//! ) -> Result<SimulationResult, String> {
//! // 1. Validate configuration
//! config.validate()?;
//! scenario.validate()?;
//!
//! // 2. Get initial state from scenario
//! let initial_state = scenario.ndim(); // Just an example usage
//!
//! // 3. Apply your numerical method
//! let time_points = vec![0.0, 1.0];
//! let final_state = PhysicalState::new(
//! PhysicalQuantity::Concentration,
//! PhysicalData::Vector(DVector::from_vec(vec![1.0]))
//! );
//! let trajectory = vec![final_state.clone(), final_state.clone()];
//!
//! // 4. Build and return result
//! Ok(SimulationResult::new(time_points, trajectory, final_state))
//! }
//!
//! fn name(&self) -> &str {
//! "My Custom Solver"
//! }
//! }
//! ```
//!
//! # Available Solvers
//!
//! Currently available numerical solvers:
//!
//! - **Forward Euler** : First-order explicit time integrator
//! - **Runge-Kutta 4** : Fourth-order explicit time integrator
//!
//! # Performance Considerations
//!
//! ## Choosing a Solver
//!
//! - **For non-stiff problems**: Explicit methods (Euler, RK4)
//! - Fast per step
//! - Require small time steps
//!
//! - **For stiff problems**: Implicit methods
//! - More expensive per step
//! - Allow much larger time steps
//!
//! - **For steady-state**: Iterative methods
//! - No time stepping
//! - Converge directly to solution
//!
//! ## Time Step Selection
//!
//! Rule of thumb for explicit methods:
//! - `dt < stability_limit` (problem-dependent)
//! - Start conservative, increase carefully
//! - Monitor solution for oscillations/divergence
//!
//! # Error Handling
//!
//! All solver methods return `Result<T, String>`:
//!
//! ```rust
//! # use chrom_rs::solver::{Solver, EulerSolver, Scenario, DomainBoundaries, SolverConfiguration};
//! # use chrom_rs::physics::{PhysicalModel, PhysicalState, PhysicalQuantity, PhysicalData};
//! # use serde::{Deserialize, Serialize};
//! # #[derive(Deserialize, Serialize)]
//! # struct MyModel;
//! # #[typetag::serde]
//! # impl PhysicalModel for MyModel {
//! # fn points(&self) -> usize { 1 }
//! # fn compute_physics(&self, state: &PhysicalState, _ctx: &chrom_rs::physics::ComputeContext) -> PhysicalState { state.clone() }
//! # fn setup_initial_state(&self) -> PhysicalState {
//! # PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Vector(nalgebra::DVector::from_vec(vec![1.0])))
//! # }
//! # fn name(&self) -> &str { "MyModel" }
//! # }
//! # fn main() {
//! # let model = Box::new(MyModel);
//! # let boundaries = DomainBoundaries::temporal(model.setup_initial_state());
//! # let scenario = Scenario::new(model, boundaries);
//! # let config = SolverConfiguration::time_evolution(1.0, 10);
//! # let solver = EulerSolver::new();
//! // Example error handling
//! match solver.solve(&scenario, &config) {
//! Ok(result) => {
//! println!("Success! {} steps computed", result.len());
//! }
//! Err(e) => {
//! eprintln!("Solver failed: {}", e);
//! // Handle error...
//! }
//! }
//! # }
//! ```
//!
//! Common errors:
//! - Invalid configuration (negative time, zero steps)
//! - Invalid scenario (incompatible boundaries)
//! - Numerical instability (divergence, NaN values)
//! - Convergence failure (max iterations exceeded)
// =================================================================================================
// Module Declarations
// =================================================================================================
/// Concrete solver implementations: Forward Euler and Runge-Kutta 4.
// =================================================================================================
// Parallel Execution Threshold
// =================================================================================================
//
// Deciding *when* to hand work off to Rayon is a numerical-execution concern,
// not a physics concern. It therefore lives here (solver) rather than in
// physics/data.rs. See DD02 for the rationale.
//
// The threshold is stored in an AtomicUsize so that it can be changed at
// runtime (useful in benchmarks and tests) without requiring a mutex on every
// `apply()` call. Relaxed ordering is sufficient: the value is a
// performance hint, not a synchronisation point.
// =================================================================================================
use ;
/// Default number of elements above which [`PhysicalData::apply()`] switches
/// to parallel iteration.
///
/// The crossover is set at 1 000 elements. Below that point the overhead of
/// Rayon's thread-pool dispatch outweighs the per-element work for the
/// arithmetic closures that chromatography simulations typically use.
const DEFAULT_PARALLEL_THRESHOLD: usize = 999;
/// Runtime-configurable parallel-execution threshold.
///
/// Read via [`parallel_threshold()`], written via [`set_parallel_threshold()`].
static PARALLEL_THRESHOLD: AtomicUsize = new;
/// Return the current parallel-execution threshold.
///
/// `PhysicalData::apply()` uses sequential iteration when the data contains
/// fewer elements than this value, and switches to Rayon when it contains
/// more — but only when the crate is compiled with the `parallel` feature.
///
/// # Example
///
/// ```rust
/// use chrom_rs::solver::parallel_threshold;
///
/// assert!(parallel_threshold() > 0);
/// ```
/// Set the parallel-execution threshold to a new value.
///
/// # Panics
///
/// Panics when `threshold == 0`. A zero-element threshold would force
/// parallel dispatch on every single-element `apply()`, which is never
/// the intended behaviour.
///
/// # Example
///
/// ```rust
/// use chrom_rs::solver::{parallel_threshold, set_parallel_threshold};
///
/// let previous = parallel_threshold();
/// set_parallel_threshold(2048);
/// assert_eq!(parallel_threshold(), 2048);
///
/// // Restore so other tests are not affected.
/// set_parallel_threshold(previous);
/// ```
/// RAII guard that saves the current threshold on construction and restores
/// it on drop.
///
/// Only compiled in test builds. Prevents one test from leaking a modified
/// threshold value into the next.
///
/// ```rust
/// # use chrom_rs::solver::{parallel_threshold, set_parallel_threshold};
/// # use chrom_rs::solver::ThresholdGuard;
/// let _guard = ThresholdGuard::save(50);
/// // threshold is now 50 …
/// // … and is automatically restored when _guard is dropped.
/// ```
pub
// Solver implementation
// =================================================================================================
// Public Re-exports
// =================================================================================================
pub use ;
pub use DomainBoundaries;
pub use Scenario;
pub use ;
// =================================================================================================
// Helper Functions
// =================================================================================================
use cratePhysicalState;
/// Validate physical state for numerical issues
///
/// Checks that the state does not contain NaN or Inf values, which would
/// indicate numerical instability or errors in the physics computation.
///
/// # Arguments
///
/// * `state` - Physical state to validate
/// * `step` - Current time step (for error reporting)
///
/// # Returns
///
/// `Ok(())` if state is valid, `Err(msg)` with diagnostic information otherwise
///
/// # Example
///
/// ```rust
/// # use chrom_rs::physics::{PhysicalState, PhysicalQuantity, PhysicalData};
/// # use chrom_rs::solver::validate_state;
/// # let state = PhysicalState::new(PhysicalQuantity::Concentration, PhysicalData::Scalar(0.0));
/// # let _ =
/// validate_state(&state, 42); // Validates state at step 42
/// ```
// =================================================================================================
// Tests
// =================================================================================================