Skip to main content

qualia_core_db/specialized_libs/physics_simulation/
discretization.rs

1use super::*;
2
3/// Spatial discretizer
4pub struct SpatialDiscretizer {
5    discretization_method: SpatialDiscretizationMethod,
6    grid_generator: GridGenerator,
7    mesh_generator: MeshGenerator,
8    stencil_operators: StencilOperators,
9}
10
11/// Spatial discretization methods
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub enum SpatialDiscretizationMethod {
14    /// Structured grid
15    Structured,
16    /// Unstructured grid
17    Unstructured,
18    /// Adaptive mesh refinement
19    AdaptiveMeshRefinement,
20    /// Moving mesh
21    MovingMesh,
22    /// Spectral element
23    SpectralElement,
24    /// Discontinuous Galerkin
25    DiscontinuousGalerkin,
26}
27
28/// Grid generator
29pub struct GridGenerator {
30    grid_type: GridType,
31    grid_parameters: GridParameters,
32    quality_metrics: GridQualityMetrics,
33}
34
35/// Grid types
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum GridType {
38    /// Cartesian grid
39    Cartesian,
40    /// Curvilinear grid
41    Curvilinear,
42    /// Body-fitted grid
43    BodyFitted,
44    /// Overset grid
45    Overset,
46    /// Chimera grid
47    Chimera,
48    /// Adaptive grid
49    Adaptive,
50}
51
52/// Grid parameters
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct GridParameters {
55    pub domain_bounds: Vec<(f64, f64)>,
56    pub grid_spacing: Vec<f64>,
57    pub stretching_function: Option<String>,
58    pub boundary_layer: Option<BoundaryLayerConfig>,
59}
60
61/// Boundary layer configuration
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct BoundaryLayerConfig {
64    pub thickness: f64,
65    pub stretching_ratio: f64,
66    pub num_points: usize,
67}
68
69/// Grid quality metrics
70#[derive(Debug, Clone)]
71pub struct GridQualityMetrics {
72    pub orthogonality: f64,
73    pub skewness: f64,
74    pub aspect_ratio: f64,
75    pub smoothness: f64,
76    pub expansion_ratio: f64,
77}
78
79/// Mesh generator
80pub struct MeshGenerator {
81    mesh_type: MeshType,
82    mesh_parameters: MeshParameters,
83    quality_metrics: MeshQualityMetrics,
84}
85
86/// Mesh types
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum MeshType {
89    /// Triangular mesh
90    Triangular,
91    /// Quadrilateral mesh
92    Quadrilateral,
93    /// Tetrahedral mesh
94    Tetrahedral,
95    /// Hexahedral mesh
96    Hexahedral,
97    /// Mixed mesh
98    Mixed,
99    /// Hybrid mesh
100    Hybrid,
101}
102
103/// Mesh parameters
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct MeshParameters {
106    pub element_size: f64,
107    pub grading_factor: f64,
108    pub refinement_regions: Vec<RefinementRegion>,
109    pub boundary_layer: Option<BoundaryLayerConfig>,
110}
111
112/// Refinement regions
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct RefinementRegion {
115    pub region_bounds: Vec<(f64, f64)>,
116    pub refinement_factor: f64,
117    pub element_size: f64,
118}
119
120/// Mesh quality metrics
121#[derive(Debug, Clone)]
122pub struct MeshQualityMetrics {
123    pub element_quality: f64,
124    pub node_distribution: f64,
125    pub connectivity: f64,
126    pub aspect_ratio: f64,
127}
128
129/// Stencil operators
130pub struct StencilOperators {
131    operators: HashMap<String, StencilOperator>,
132    boundary_stencils: HashMap<String, BoundaryStencil>,
133}
134
135/// Stencil operator
136#[derive(Debug, Clone)]
137pub struct StencilOperator {
138    pub operator_id: String,
139    pub operator_type: StencilType,
140    pub stencil_points: Vec<StencilPoint>,
141    pub coefficients: Vec<f64>,
142}
143
144/// Stencil types
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub enum StencilType {
147    /// Central difference
148    Central,
149    /// Forward difference
150    Forward,
151    /// Backward difference
152    Backward,
153    /// Upwind
154    Upwind,
155    /// High-order compact
156    HighOrderCompact,
157    /// WENO scheme
158    WENO,
159    /// ENO scheme
160    ENO,
161}
162
163/// Stencil point
164#[derive(Debug, Clone)]
165pub struct StencilPoint {
166    pub relative_position: Vec<i32>,
167    pub weight: f64,
168}
169
170/// Boundary stencil
171#[derive(Debug, Clone)]
172pub struct BoundaryStencil {
173    pub stencil_id: String,
174    pub boundary_type: BoundaryType,
175    pub stencil_points: Vec<StencilPoint>,
176    pub coefficients: Vec<f64>,
177}
178
179impl SpatialDiscretizer {
180    /// Creates a discretizer with default grid/mesh/stencil components.
181    pub fn new() -> Self {
182        Self {
183            discretization_method: SpatialDiscretizationMethod::Structured,
184            grid_generator: GridGenerator::new(),
185            mesh_generator: MeshGenerator::new(),
186            stencil_operators: StencilOperators::new(),
187        }
188    }
189
190    /// Initializes grid and mesh generators; `PhysicsError` propagates.
191    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
192        self.grid_generator.initialize()?;
193        self.mesh_generator.initialize()?;
194        Ok(())
195    }
196
197    /// Get the discretization method.
198    pub fn get_discretization_method(&self) -> &SpatialDiscretizationMethod {
199        &self.discretization_method
200    }
201
202    /// Set the discretization method.
203    pub fn set_discretization_method(&mut self, method: SpatialDiscretizationMethod) {
204        self.discretization_method = method;
205    }
206
207    /// Get a reference to the stencil operators.
208    pub fn get_stencil_operators(&self) -> &StencilOperators {
209        &self.stencil_operators
210    }
211
212    /// Get a mutable reference to the stencil operators.
213    pub fn get_stencil_operators_mut(&mut self) -> &mut StencilOperators {
214        &mut self.stencil_operators
215    }
216}
217
218impl GridGenerator {
219    /// Creates a grid generator with default parameters/quality metrics.
220    pub fn new() -> Self {
221        Self {
222            grid_type: GridType::Cartesian,
223            grid_parameters: GridParameters::new(),
224            quality_metrics: GridQualityMetrics::new(),
225        }
226    }
227
228    /// No-op returning `Ok(())`.
229    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
230        Ok(())
231    }
232
233    /// Get the grid type.
234    pub fn get_grid_type(&self) -> &GridType {
235        &self.grid_type
236    }
237
238    /// Set the grid type.
239    pub fn set_grid_type(&mut self, grid_type: GridType) {
240        self.grid_type = grid_type;
241    }
242
243    /// Get a reference to the grid parameters.
244    pub fn get_grid_parameters(&self) -> &GridParameters {
245        &self.grid_parameters
246    }
247
248    /// Get a mutable reference to the grid parameters.
249    pub fn get_grid_parameters_mut(&mut self) -> &mut GridParameters {
250        &mut self.grid_parameters
251    }
252
253    /// Get a reference to the grid quality metrics.
254    pub fn get_quality_metrics(&self) -> &GridQualityMetrics {
255        &self.quality_metrics
256    }
257
258    /// Get a mutable reference to the grid quality metrics.
259    pub fn get_quality_metrics_mut(&mut self) -> &mut GridQualityMetrics {
260        &mut self.quality_metrics
261    }
262}
263
264impl GridParameters {
265    /// Creates default `GridParameters`.
266    pub fn new() -> Self {
267        Self {
268            domain_bounds: vec![(0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],
269            grid_spacing: vec![0.01, 0.01, 0.01],
270            stretching_function: None,
271            boundary_layer: None,
272        }
273    }
274}
275
276impl GridQualityMetrics {
277    /// Creates zeroed `GridQualityMetrics`.
278    pub fn new() -> Self {
279        Self {
280            orthogonality: 1.0,
281            skewness: 0.0,
282            aspect_ratio: 1.0,
283            smoothness: 1.0,
284            expansion_ratio: 1.0,
285        }
286    }
287}
288
289impl MeshGenerator {
290    /// Creates a mesh generator with default parameters/quality metrics.
291    pub fn new() -> Self {
292        Self {
293            mesh_type: MeshType::Hexahedral,
294            mesh_parameters: MeshParameters::new(),
295            quality_metrics: MeshQualityMetrics::new(),
296        }
297    }
298
299    /// No-op returning `Ok(())`.
300    pub fn initialize(&mut self) -> Result<(), PhysicsError> {
301        Ok(())
302    }
303
304    /// Get the mesh type.
305    pub fn get_mesh_type(&self) -> &MeshType {
306        &self.mesh_type
307    }
308
309    /// Set the mesh type.
310    pub fn set_mesh_type(&mut self, mesh_type: MeshType) {
311        self.mesh_type = mesh_type;
312    }
313
314    /// Get a reference to the mesh parameters.
315    pub fn get_mesh_parameters(&self) -> &MeshParameters {
316        &self.mesh_parameters
317    }
318
319    /// Get a mutable reference to the mesh parameters.
320    pub fn get_mesh_parameters_mut(&mut self) -> &mut MeshParameters {
321        &mut self.mesh_parameters
322    }
323
324    /// Get a reference to the mesh quality metrics.
325    pub fn get_quality_metrics(&self) -> &MeshQualityMetrics {
326        &self.quality_metrics
327    }
328
329    /// Get a mutable reference to the mesh quality metrics.
330    pub fn get_quality_metrics_mut(&mut self) -> &mut MeshQualityMetrics {
331        &mut self.quality_metrics
332    }
333}
334
335impl MeshParameters {
336    /// Creates default `MeshParameters`.
337    pub fn new() -> Self {
338        Self {
339            element_size: 0.01,
340            grading_factor: 1.2,
341            refinement_regions: Vec::new(),
342            boundary_layer: None,
343        }
344    }
345}
346
347impl MeshQualityMetrics {
348    /// Creates zeroed `MeshQualityMetrics`.
349    pub fn new() -> Self {
350        Self {
351            element_quality: 1.0,
352            node_distribution: 1.0,
353            connectivity: 1.0,
354            aspect_ratio: 1.0,
355        }
356    }
357}
358
359impl StencilOperators {
360    /// Creates default finite-difference stencil operators.
361    pub fn new() -> Self {
362        Self {
363            operators: HashMap::new(),
364            boundary_stencils: HashMap::new(),
365        }
366    }
367
368    /// Register a named stencil operator.
369    pub fn register_operator(&mut self, name: &str, stencil: StencilOperator) {
370        self.operators.insert(name.to_string(), stencil);
371    }
372
373    /// Register a named boundary stencil.
374    pub fn register_boundary_stencil(&mut self, name: &str, stencil: BoundaryStencil) {
375        self.boundary_stencils.insert(name.to_string(), stencil);
376    }
377
378    /// Apply a registered stencil to compute the spatial derivative at `index`.
379    ///
380    /// The derivative is computed as:
381    /// ```text
382    ///   sum_i( coefficients[i] * field[index + offset_i] ) / dx
383    /// ```
384    /// where `offset_i` is taken from `stencil_points[i].relative_position[0]`.
385    /// The coefficients are expected to already include the normalisation factor
386    /// (e.g. `[-0.5, 0.0, 0.5]` for a 2nd-order central difference).
387    pub fn apply_derivative(
388        &self,
389        name: &str,
390        field: &[f64],
391        dx: f64,
392        index: usize,
393    ) -> Result<f64, PhysicsError> {
394        let stencil = self.operators.get(name).ok_or_else(|| {
395            PhysicsError::SolverError(format!("Stencil operator '{}' not registered", name))
396        })?;
397
398        if stencil.stencil_points.len() != stencil.coefficients.len() {
399            return Err(PhysicsError::SolverError(format!(
400                "Stencil operator '{}' has mismatched points/coefficients",
401                name
402            )));
403        }
404
405        let n = field.len() as isize;
406        let mut sum = 0.0f64;
407        for (point, coeff) in stencil
408            .stencil_points
409            .iter()
410            .zip(stencil.coefficients.iter())
411        {
412            let offset = point.relative_position.first().copied().unwrap_or(0) as isize;
413            let idx = index as isize + offset;
414            if idx < 0 || idx >= n {
415                return Err(PhysicsError::SolverError(format!(
416                    "Stencil operator '{}' accesses out-of-bounds index {} (field len {})",
417                    name, idx, n
418                )));
419            }
420            sum += coeff * field[idx as usize];
421        }
422
423        if dx <= 0.0 {
424            return Err(PhysicsError::SolverError("dx must be positive".to_string()));
425        }
426
427        Ok(sum / dx)
428    }
429
430    /// Create a 3-point 2nd-order central difference stencil.
431    ///
432    /// Coefficients `[-0.5, 0.0, 0.5]` at offsets `[-1, 0, +1]` give
433    /// `(field[i+1] - field[i-1]) / (2*dx)`.
434    pub fn central_difference_2nd_order() -> StencilOperator {
435        StencilOperator {
436            operator_id: "central_difference_2nd_order".to_string(),
437            operator_type: StencilType::Central,
438            stencil_points: vec![
439                StencilPoint {
440                    relative_position: vec![-1],
441                    weight: 1.0,
442                },
443                StencilPoint {
444                    relative_position: vec![0],
445                    weight: 1.0,
446                },
447                StencilPoint {
448                    relative_position: vec![1],
449                    weight: 1.0,
450                },
451            ],
452            coefficients: vec![-0.5, 0.0, 0.5],
453        }
454    }
455
456    /// Create a 2-point 1st-order forward difference stencil.
457    ///
458    /// Coefficients `[-1.0, 1.0]` at offsets `[0, +1]` give
459    /// `(field[i+1] - field[i]) / dx`.
460    pub fn forward_difference_1st_order() -> StencilOperator {
461        StencilOperator {
462            operator_id: "forward_difference_1st_order".to_string(),
463            operator_type: StencilType::Forward,
464            stencil_points: vec![
465                StencilPoint {
466                    relative_position: vec![0],
467                    weight: 1.0,
468                },
469                StencilPoint {
470                    relative_position: vec![1],
471                    weight: 1.0,
472                },
473            ],
474            coefficients: vec![-1.0, 1.0],
475        }
476    }
477}