1use super::*;
2
3pub struct SpatialDiscretizer {
5 discretization_method: SpatialDiscretizationMethod,
6 grid_generator: GridGenerator,
7 mesh_generator: MeshGenerator,
8 stencil_operators: StencilOperators,
9}
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub enum SpatialDiscretizationMethod {
14 Structured,
16 Unstructured,
18 AdaptiveMeshRefinement,
20 MovingMesh,
22 SpectralElement,
24 DiscontinuousGalerkin,
26}
27
28pub struct GridGenerator {
30 grid_type: GridType,
31 grid_parameters: GridParameters,
32 quality_metrics: GridQualityMetrics,
33}
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub enum GridType {
38 Cartesian,
40 Curvilinear,
42 BodyFitted,
44 Overset,
46 Chimera,
48 Adaptive,
50}
51
52#[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#[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#[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
79pub struct MeshGenerator {
81 mesh_type: MeshType,
82 mesh_parameters: MeshParameters,
83 quality_metrics: MeshQualityMetrics,
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88pub enum MeshType {
89 Triangular,
91 Quadrilateral,
93 Tetrahedral,
95 Hexahedral,
97 Mixed,
99 Hybrid,
101}
102
103#[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#[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#[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
129pub struct StencilOperators {
131 operators: HashMap<String, StencilOperator>,
132 boundary_stencils: HashMap<String, BoundaryStencil>,
133}
134
135#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146pub enum StencilType {
147 Central,
149 Forward,
151 Backward,
153 Upwind,
155 HighOrderCompact,
157 WENO,
159 ENO,
161}
162
163#[derive(Debug, Clone)]
165pub struct StencilPoint {
166 pub relative_position: Vec<i32>,
167 pub weight: f64,
168}
169
170#[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 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 pub fn initialize(&mut self) -> Result<(), PhysicsError> {
192 self.grid_generator.initialize()?;
193 self.mesh_generator.initialize()?;
194 Ok(())
195 }
196
197 pub fn get_discretization_method(&self) -> &SpatialDiscretizationMethod {
199 &self.discretization_method
200 }
201
202 pub fn set_discretization_method(&mut self, method: SpatialDiscretizationMethod) {
204 self.discretization_method = method;
205 }
206
207 pub fn get_stencil_operators(&self) -> &StencilOperators {
209 &self.stencil_operators
210 }
211
212 pub fn get_stencil_operators_mut(&mut self) -> &mut StencilOperators {
214 &mut self.stencil_operators
215 }
216}
217
218impl GridGenerator {
219 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 pub fn initialize(&mut self) -> Result<(), PhysicsError> {
230 Ok(())
231 }
232
233 pub fn get_grid_type(&self) -> &GridType {
235 &self.grid_type
236 }
237
238 pub fn set_grid_type(&mut self, grid_type: GridType) {
240 self.grid_type = grid_type;
241 }
242
243 pub fn get_grid_parameters(&self) -> &GridParameters {
245 &self.grid_parameters
246 }
247
248 pub fn get_grid_parameters_mut(&mut self) -> &mut GridParameters {
250 &mut self.grid_parameters
251 }
252
253 pub fn get_quality_metrics(&self) -> &GridQualityMetrics {
255 &self.quality_metrics
256 }
257
258 pub fn get_quality_metrics_mut(&mut self) -> &mut GridQualityMetrics {
260 &mut self.quality_metrics
261 }
262}
263
264impl GridParameters {
265 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 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 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 pub fn initialize(&mut self) -> Result<(), PhysicsError> {
301 Ok(())
302 }
303
304 pub fn get_mesh_type(&self) -> &MeshType {
306 &self.mesh_type
307 }
308
309 pub fn set_mesh_type(&mut self, mesh_type: MeshType) {
311 self.mesh_type = mesh_type;
312 }
313
314 pub fn get_mesh_parameters(&self) -> &MeshParameters {
316 &self.mesh_parameters
317 }
318
319 pub fn get_mesh_parameters_mut(&mut self) -> &mut MeshParameters {
321 &mut self.mesh_parameters
322 }
323
324 pub fn get_quality_metrics(&self) -> &MeshQualityMetrics {
326 &self.quality_metrics
327 }
328
329 pub fn get_quality_metrics_mut(&mut self) -> &mut MeshQualityMetrics {
331 &mut self.quality_metrics
332 }
333}
334
335impl MeshParameters {
336 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 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 pub fn new() -> Self {
362 Self {
363 operators: HashMap::new(),
364 boundary_stencils: HashMap::new(),
365 }
366 }
367
368 pub fn register_operator(&mut self, name: &str, stencil: StencilOperator) {
370 self.operators.insert(name.to_string(), stencil);
371 }
372
373 pub fn register_boundary_stencil(&mut self, name: &str, stencil: BoundaryStencil) {
375 self.boundary_stencils.insert(name.to_string(), stencil);
376 }
377
378 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 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 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}