scirs2-integrate 0.4.2

Numerical integration module for SciRS2 (scirs2-integrate)
Documentation
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
//! Advanced Adaptive Mesh Refinement (AMR) with sophisticated error indicators
//!
//! This module provides state-of-the-art adaptive mesh refinement techniques
//! including gradient-based refinement, feature detection, load balancing,
//! and hierarchical mesh management for complex PDE solutions.

use crate::common::IntegrateFloat;
use crate::error::{IntegrateError, IntegrateResult};
use scirs2_core::ndarray::{Array1, Array2};
use std::collections::{HashMap, HashSet};

/// Advanced AMR manager with multiple refinement strategies
pub struct AdvancedAMRManager<F: IntegrateFloat> {
    /// Current mesh hierarchy
    pub mesh_hierarchy: MeshHierarchy<F>,
    /// Refinement criteria
    pub refinement_criteria: Vec<Box<dyn RefinementCriterion<F>>>,
    /// Load balancing strategy
    pub load_balancer: Option<Box<dyn LoadBalancer<F>>>,
    /// Maximum refinement levels
    pub max_levels: usize,
    /// Minimum cell size
    pub min_cell_size: F,
    /// Coarsening tolerance
    pub coarsening_tolerance: F,
    /// Error tolerance for refinement
    pub refinement_tolerance: F,
    /// Adaptation frequency
    pub adaptation_frequency: usize,
    /// Current adaptation step
    current_step: usize,
}

/// Hierarchical mesh structure supporting multiple levels
#[derive(Debug, Clone)]
pub struct MeshHierarchy<F: IntegrateFloat> {
    /// Mesh levels (0 = coarsest)
    pub levels: Vec<AdaptiveMeshLevel<F>>,
    /// Parent-child relationships
    pub hierarchy_map: HashMap<CellId, Vec<CellId>>,
    /// Ghost cell information for parallel processing
    pub ghost_cells: HashMap<usize, Vec<CellId>>, // level -> ghost cells
}

/// Single level in adaptive mesh
#[derive(Debug, Clone)]
pub struct AdaptiveMeshLevel<F: IntegrateFloat> {
    /// Level number (0 = coarsest)
    pub level: usize,
    /// Active cells at this level
    pub cells: HashMap<CellId, AdaptiveCell<F>>,
    /// Grid spacing at this level
    pub grid_spacing: F,
    /// Boundary information
    pub boundary_cells: HashSet<CellId>,
}

/// Individual adaptive cell
#[derive(Debug, Clone)]
pub struct AdaptiveCell<F: IntegrateFloat> {
    /// Unique cell identifier
    pub id: CellId,
    /// Cell center coordinates
    pub center: Array1<F>,
    /// Cell size
    pub size: F,
    /// Solution value(s) in cell
    pub solution: Array1<F>,
    /// Error estimate for cell
    pub error_estimate: F,
    /// Refinement flag
    pub refinement_flag: RefinementFlag,
    /// Activity status
    pub is_active: bool,
    /// Neighboring cell IDs
    pub neighbors: Vec<CellId>,
    /// Parent cell ID (if refined)
    pub parent: Option<CellId>,
    /// Children cell IDs (if coarsened)
    pub children: Vec<CellId>,
}

/// Cell identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CellId {
    pub level: usize,
    pub index: usize,
}

/// Refinement action flags
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RefinementFlag {
    /// No action needed
    None,
    /// Cell should be refined
    Refine,
    /// Cell should be coarsened
    Coarsen,
    /// Cell marked for potential refinement
    Tagged,
}

/// Trait for refinement criteria
pub trait RefinementCriterion<F: IntegrateFloat>: Send + Sync {
    /// Evaluate refinement criterion for a cell
    fn evaluate(&self, cell: &AdaptiveCell<F>, neighbors: &[&AdaptiveCell<F>]) -> F;

    /// Get criterion name
    fn name(&self) -> &'static str;

    /// Get criterion weight in combined evaluation
    fn weight(&self) -> F {
        F::one()
    }
}

/// Gradient-based refinement criterion
pub struct GradientRefinementCriterion<F: IntegrateFloat> {
    /// Component to analyze (None = all components)
    pub component: Option<usize>,
    /// Gradient threshold
    pub threshold: F,
    /// Relative tolerance
    pub relative_tolerance: F,
}

/// Feature detection refinement criterion
pub struct FeatureDetectionCriterion<F: IntegrateFloat> {
    /// Feature detection threshold
    pub threshold: F,
    /// Feature types to detect
    pub feature_types: Vec<FeatureType>,
    /// Window size for feature detection
    pub window_size: usize,
}

/// Curvature-based refinement criterion
pub struct CurvatureRefinementCriterion<F: IntegrateFloat> {
    /// Curvature threshold
    pub threshold: F,
    /// Approximation order for curvature calculation
    pub approximation_order: usize,
}

/// Load balancing strategy trait
pub trait LoadBalancer<F: IntegrateFloat>: Send + Sync {
    /// Balance computational load across processors/threads
    fn balance(&self, hierarchy: &mut MeshHierarchy<F>) -> IntegrateResult<()>;
}

/// Zoltan-style geometric load balancer
pub struct GeometricLoadBalancer<F: IntegrateFloat> {
    /// Number of partitions
    pub num_partitions: usize,
    /// Load imbalance tolerance
    pub imbalance_tolerance: F,
    /// Partitioning method
    pub method: PartitioningMethod,
}

/// Types of features to detect
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FeatureType {
    /// Sharp gradients
    SharpGradient,
    /// Discontinuities
    Discontinuity,
    /// Local extrema
    LocalExtremum,
    /// Oscillatory behavior
    Oscillation,
    /// Boundary layers
    BoundaryLayer,
}

/// Partitioning methods
#[derive(Debug, Clone, Copy)]
pub enum PartitioningMethod {
    /// Recursive coordinate bisection
    RCB,
    /// Space-filling curves
    SFC,
    /// Graph partitioning
    Graph,
}

/// AMR adaptation result
pub struct AMRAdaptationResult<F: IntegrateFloat> {
    /// Number of cells refined
    pub cells_refined: usize,
    /// Number of cells coarsened
    pub cells_coarsened: usize,
    /// Total active cells after adaptation
    pub total_active_cells: usize,
    /// Load balance quality metric
    pub load_balance_quality: F,
    /// Memory usage change
    pub memory_change: i64,
    /// Adaptation time
    pub adaptation_time: std::time::Duration,
}

impl<F: IntegrateFloat> AdvancedAMRManager<F> {
    /// Create new advanced AMR manager
    pub fn new(_initial_mesh: AdaptiveMeshLevel<F>, max_levels: usize, min_cellsize: F) -> Self {
        let mesh_hierarchy = MeshHierarchy {
            levels: vec![_initial_mesh],
            hierarchy_map: HashMap::new(),
            ghost_cells: HashMap::new(),
        };

        Self {
            mesh_hierarchy,
            refinement_criteria: Vec::new(),
            load_balancer: None,
            max_levels,
            min_cell_size: min_cellsize,
            coarsening_tolerance: F::from(0.1).expect("Failed to convert constant to float"),
            refinement_tolerance: F::from(1.0).expect("Failed to convert constant to float"),
            adaptation_frequency: 1,
            current_step: 0,
        }
    }

    /// Add refinement criterion
    pub fn add_criterion(&mut self, criterion: Box<dyn RefinementCriterion<F>>) {
        self.refinement_criteria.push(criterion);
    }

    /// Set load balancer
    pub fn set_load_balancer(&mut self, balancer: Box<dyn LoadBalancer<F>>) {
        self.load_balancer = Some(balancer);
    }

    /// Perform adaptive mesh refinement
    pub fn adapt_mesh(&mut self, solution: &Array2<F>) -> IntegrateResult<AMRAdaptationResult<F>> {
        let start_time = std::time::Instant::now();
        let initial_cells = self.count_active_cells();

        self.current_step += 1;

        // Skip adaptation if not at adaptation frequency
        if !self.current_step.is_multiple_of(self.adaptation_frequency) {
            return Ok(AMRAdaptationResult {
                cells_refined: 0,
                cells_coarsened: 0,
                total_active_cells: initial_cells,
                load_balance_quality: F::one(),
                memory_change: 0,
                adaptation_time: start_time.elapsed(),
            });
        }

        // Step 1: Update solution values in cells
        self.update_cell_solutions(solution)?;

        // Step 2: Evaluate refinement criteria
        self.evaluate_refinement_criteria()?;

        // Step 3: Flag cells for refinement/coarsening
        let _refine_count_coarsen_count = self.flag_cells_for_adaptation()?;

        // Step 4: Perform refinement
        let cells_refined = self.refine_flagged_cells()?;

        // Step 5: Perform coarsening
        let cells_coarsened = self.coarsen_flagged_cells()?;

        // Step 6: Load balancing
        let load_balance_quality = if let Some(ref balancer) = self.load_balancer {
            balancer.balance(&mut self.mesh_hierarchy)?;
            self.assess_load_balance()
        } else {
            F::one()
        };

        // Step 7: Update ghost cells
        self.update_ghost_cells()?;

        let final_cells = self.count_active_cells();
        let memory_change = (final_cells as i64 - initial_cells as i64) * 8; // Rough estimate

        Ok(AMRAdaptationResult {
            cells_refined,
            cells_coarsened,
            total_active_cells: final_cells,
            load_balance_quality,
            memory_change,
            adaptation_time: start_time.elapsed(),
        })
    }

    /// Update solution values in mesh cells
    fn update_cell_solutions(&mut self, solution: &Array2<F>) -> IntegrateResult<()> {
        // Map solution array to mesh cells
        // This is a simplified mapping - in practice would need sophisticated interpolation
        for level in &mut self.mesh_hierarchy.levels {
            for cell in level.cells.values_mut() {
                if cell.is_active {
                    // Simple mapping - in practice would use proper interpolation
                    let i = (cell.center[0] * F::from(solution.nrows()).expect("Operation failed"))
                        .to_usize()
                        .unwrap_or(0)
                        .min(solution.nrows() - 1);
                    let j = if solution.ncols() > 1 && cell.center.len() > 1 {
                        (cell.center[1] * F::from(solution.ncols()).expect("Operation failed"))
                            .to_usize()
                            .unwrap_or(0)
                            .min(solution.ncols() - 1)
                    } else {
                        0
                    };

                    // Update cell solution (simplified)
                    if cell.solution.len() == 1 {
                        cell.solution[0] = solution[[i, j]];
                    }
                }
            }
        }
        Ok(())
    }

    /// Evaluate all refinement criteria for all cells
    fn evaluate_refinement_criteria(&mut self) -> IntegrateResult<()> {
        for level in &mut self.mesh_hierarchy.levels {
            let cellids: Vec<CellId> = level.cells.keys().cloned().collect();

            for cellid in cellids {
                if let Some(cell) = level.cells.get(&cellid) {
                    if !cell.is_active {
                        continue;
                    }

                    // Get neighboring cells
                    let neighbor_cells: Vec<&AdaptiveCell<F>> = cell
                        .neighbors
                        .iter()
                        .filter_map(|&neighbor_id| level.cells.get(&neighbor_id))
                        .collect();

                    // Evaluate all criteria
                    let mut total_error = F::zero();
                    let mut total_weight = F::zero();

                    for criterion in &self.refinement_criteria {
                        let error = criterion.evaluate(cell, &neighbor_cells);
                        let weight = criterion.weight();
                        total_error += error * weight;
                        total_weight += weight;
                    }

                    // Normalize error estimate
                    let error_estimate = if total_weight > F::zero() {
                        total_error / total_weight
                    } else {
                        F::zero()
                    };

                    // Update cell error estimate
                    if let Some(cell) = level.cells.get_mut(&cellid) {
                        cell.error_estimate = error_estimate;
                    }
                }
            }
        }
        Ok(())
    }

    /// Flag cells for refinement or coarsening
    fn flag_cells_for_adaptation(&mut self) -> IntegrateResult<(usize, usize)> {
        let mut refine_count = 0;
        let mut coarsen_count = 0;

        // Collect cells that can be coarsened first to avoid borrowing issues
        let mut cells_to_check: Vec<(usize, CellId, F, usize, F)> = Vec::new();

        for level in &self.mesh_hierarchy.levels {
            for cell in level.cells.values() {
                if cell.is_active {
                    cells_to_check.push((
                        level.level,
                        cell.id,
                        cell.error_estimate,
                        level.level,
                        cell.size,
                    ));
                }
            }
        }

        // Now flag cells based on collected information
        for (level_idx, cellid, error_estimate, level_num, cell_size) in cells_to_check {
            if let Some(level) = self.mesh_hierarchy.levels.get_mut(level_idx) {
                if let Some(cell) = level.cells.get_mut(&cellid) {
                    // Refinement criterion
                    if error_estimate > self.refinement_tolerance
                        && level_num < self.max_levels
                        && cell_size > self.min_cell_size
                    {
                        cell.refinement_flag = RefinementFlag::Refine;
                        refine_count += 1;
                    }
                    // Coarsening criterion (simplified check)
                    else if error_estimate < self.coarsening_tolerance && level_num > 0 {
                        cell.refinement_flag = RefinementFlag::Coarsen;
                        coarsen_count += 1;
                    } else {
                        cell.refinement_flag = RefinementFlag::None;
                    }
                }
            }
        }

        Ok((refine_count, coarsen_count))
    }

    /// Check if cell can be coarsened (all siblings must be flagged)
    fn can_coarsen_cell(&self, cell: &AdaptiveCell<F>) -> bool {
        if let Some(parent_id) = cell.parent {
            // Check if all sibling cells are also flagged for coarsening
            if let Some(parent_children) = self.mesh_hierarchy.hierarchy_map.get(&parent_id) {
                for &child_id in parent_children {
                    if let Some(level) = self.mesh_hierarchy.levels.get(child_id.level) {
                        if let Some(sibling) = level.cells.get(&child_id) {
                            if sibling.refinement_flag != RefinementFlag::Coarsen {
                                return false;
                            }
                        }
                    }
                }
                return true;
            }
        }
        false
    }

    /// Refine flagged cells
    fn refine_flagged_cells(&mut self) -> IntegrateResult<usize> {
        let mut cells_refined = 0;

        // Process each level separately to avoid borrowing issues
        for level_idx in 0..self.mesh_hierarchy.levels.len() {
            let cells_to_refine: Vec<CellId> = self.mesh_hierarchy.levels[level_idx]
                .cells
                .values()
                .filter(|cell| cell.refinement_flag == RefinementFlag::Refine)
                .map(|cell| cell.id)
                .collect();

            for cellid in cells_to_refine {
                self.refine_cell(cellid)?;
                cells_refined += 1;
            }
        }

        Ok(cells_refined)
    }

    /// Refine a single cell
    fn refine_cell(&mut self, cellid: CellId) -> IntegrateResult<()> {
        let parent_cell = if let Some(level) = self.mesh_hierarchy.levels.get(cellid.level) {
            level.cells.get(&cellid).cloned()
        } else {
            return Err(IntegrateError::ValueError("Invalid cell level".to_string()));
        };

        let parent_cell =
            parent_cell.ok_or_else(|| IntegrateError::ValueError("Cell not found".to_string()))?;

        // Create child level if it doesn't exist
        let child_level = cellid.level + 1;
        while self.mesh_hierarchy.levels.len() <= child_level {
            let new_level = AdaptiveMeshLevel {
                level: self.mesh_hierarchy.levels.len(),
                cells: HashMap::new(),
                grid_spacing: if let Some(last_level) = self.mesh_hierarchy.levels.last() {
                    last_level.grid_spacing
                        / F::from(2.0).expect("Failed to convert constant to float")
                } else {
                    F::one()
                },
                boundary_cells: HashSet::new(),
            };
            self.mesh_hierarchy.levels.push(new_level);
        }

        // Create child cells (2D refinement = 4 children, 3D = 8 children)
        let num_children = 2_usize.pow(parent_cell.center.len() as u32);
        let mut child_ids = Vec::new();
        let child_size =
            parent_cell.size / F::from(2.0).expect("Failed to convert constant to float");

        for child_idx in 0..num_children {
            let child_id = CellId {
                level: child_level,
                index: self.mesh_hierarchy.levels[child_level].cells.len(),
            };

            // Compute child center
            let mut child_center = parent_cell.center.clone();
            let offset = child_size / F::from(2.0).expect("Failed to convert constant to float");

            // Binary representation determines position
            for dim in 0..parent_cell.center.len() {
                if (child_idx >> dim) & 1 == 1 {
                    child_center[dim] += offset;
                } else {
                    child_center[dim] -= offset;
                }
            }

            let child_cell = AdaptiveCell {
                id: child_id,
                center: child_center,
                size: child_size,
                solution: parent_cell.solution.clone(), // Inherit parent solution
                error_estimate: F::zero(),
                refinement_flag: RefinementFlag::None,
                is_active: true,
                neighbors: Vec::new(),
                parent: Some(cellid),
                children: Vec::new(),
            };

            self.mesh_hierarchy.levels[child_level]
                .cells
                .insert(child_id, child_cell);
            child_ids.push(child_id);
        }

        // Update hierarchy map
        self.mesh_hierarchy
            .hierarchy_map
            .insert(cellid, child_ids.clone());

        // Deactivate parent cell
        if let Some(parent) = self.mesh_hierarchy.levels[cellid.level]
            .cells
            .get_mut(&cellid)
        {
            parent.is_active = false;
            parent.children = child_ids;
        }

        // Update neighbor relationships
        self.update_neighbor_relationships(child_level)?;

        Ok(())
    }

    /// Coarsen flagged cells
    fn coarsen_flagged_cells(&mut self) -> IntegrateResult<usize> {
        let mut cells_coarsened = 0;

        // Process from finest to coarsest level
        for level_idx in (1..self.mesh_hierarchy.levels.len()).rev() {
            let parent_cells_to_activate: Vec<CellId> = self.mesh_hierarchy.levels[level_idx]
                .cells
                .values()
                .filter(|cell| cell.refinement_flag == RefinementFlag::Coarsen)
                .filter_map(|cell| cell.parent)
                .collect::<HashSet<_>>()
                .into_iter()
                .collect();

            for parent_id in parent_cells_to_activate {
                if self.coarsen_to_parent(parent_id)? {
                    cells_coarsened += 1;
                }
            }
        }

        Ok(cells_coarsened)
    }

    /// Coarsen children back to parent cell
    fn coarsen_to_parent(&mut self, parentid: CellId) -> IntegrateResult<bool> {
        let child_ids = if let Some(children) = self.mesh_hierarchy.hierarchy_map.get(&parentid) {
            children.clone()
        } else {
            return Ok(false);
        };

        // Verify all children are flagged for coarsening
        for &child_id in &child_ids {
            if let Some(level) = self.mesh_hierarchy.levels.get(child_id.level) {
                if let Some(child) = level.cells.get(&child_id) {
                    if child.refinement_flag != RefinementFlag::Coarsen {
                        return Ok(false);
                    }
                }
            }
        }

        // Average child solutions for parent
        let mut avg_solution = Array1::zeros(child_ids.len());
        if !child_ids.is_empty() {
            if let Some(first_child_level) = self.mesh_hierarchy.levels.get(child_ids[0].level) {
                if let Some(first_child) = first_child_level.cells.get(&child_ids[0]) {
                    avg_solution = Array1::zeros(first_child.solution.len());

                    for &child_id in &child_ids {
                        if let Some(child_level) = self.mesh_hierarchy.levels.get(child_id.level) {
                            if let Some(child) = child_level.cells.get(&child_id) {
                                avg_solution = &avg_solution + &child.solution;
                            }
                        }
                    }
                    avg_solution /= F::from(child_ids.len()).expect("Operation failed");
                }
            }
        }

        // Reactivate parent cell
        if let Some(parent_level) = self.mesh_hierarchy.levels.get_mut(parentid.level) {
            if let Some(parent) = parent_level.cells.get_mut(&parentid) {
                parent.is_active = true;
                parent.solution = avg_solution;
                parent.children.clear();
                parent.refinement_flag = RefinementFlag::None;
            }
        }

        // Remove children from hierarchy
        for &child_id in &child_ids {
            if let Some(child_level) = self.mesh_hierarchy.levels.get_mut(child_id.level) {
                child_level.cells.remove(&child_id);
            }
        }

        // Remove from hierarchy map
        self.mesh_hierarchy.hierarchy_map.remove(&parentid);

        Ok(true)
    }

    /// Update neighbor relationships after refinement
    fn update_neighbor_relationships(&mut self, level: usize) -> IntegrateResult<()> {
        // Collect neighbor relationships first to avoid borrowing conflicts
        let mut all_neighbor_relationships: Vec<(CellId, Vec<CellId>)> = Vec::new();

        if let Some(mesh_level) = self.mesh_hierarchy.levels.get(level) {
            let cellids: Vec<CellId> = mesh_level.cells.keys().cloned().collect();

            // Build spatial hash map for efficient neighbor searching
            let mut spatial_hash: HashMap<(i32, i32, i32), Vec<CellId>> = HashMap::new();
            let grid_spacing = mesh_level.grid_spacing;

            // Hash all cells based on their spatial location
            for cellid in &cellids {
                if let Some(cell) = mesh_level.cells.get(cellid) {
                    if cell.center.len() >= 3 {
                        let hash_x = (cell.center[0] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);
                        let hash_y = (cell.center[1] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);
                        let hash_z = (cell.center[2] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);

                        spatial_hash
                            .entry((hash_x, hash_y, hash_z))
                            .or_default()
                            .push(*cellid);
                    }
                }
            }

            for cellid in &cellids {
                if let Some(cell) = mesh_level.cells.get(cellid) {
                    let mut neighbors = Vec::new();

                    if cell.center.len() >= 3 {
                        let hash_x = (cell.center[0] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);
                        let hash_y = (cell.center[1] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);
                        let hash_z = (cell.center[2] / grid_spacing)
                            .floor()
                            .to_i32()
                            .unwrap_or(0);

                        // Search in 27 neighboring hash buckets (3x3x3)
                        for dx in -1..=1 {
                            for dy in -1..=1 {
                                for dz in -1..=1 {
                                    let hash_key = (hash_x + dx, hash_y + dy, hash_z + dz);

                                    if let Some(potential_neighbors) = spatial_hash.get(&hash_key) {
                                        for &neighbor_id in potential_neighbors {
                                            if neighbor_id != *cellid {
                                                if let Some(neighbor_cell) =
                                                    mesh_level.cells.get(&neighbor_id)
                                                {
                                                    // Check if cells are actually neighbors (face/edge/vertex sharing)
                                                    if self.are_cells_neighbors(cell, neighbor_cell)
                                                    {
                                                        neighbors.push(neighbor_id);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    all_neighbor_relationships.push((*cellid, neighbors));
                }
            }
        }

        // Now apply all neighbor relationships with mutable access
        if let Some(mesh_level) = self.mesh_hierarchy.levels.get_mut(level) {
            for (cellid, neighbors) in all_neighbor_relationships {
                if let Some(cell) = mesh_level.cells.get_mut(&cellid) {
                    cell.neighbors = neighbors;
                }
            }
        }

        // Now update inter-level neighbors separately to avoid borrowing conflicts
        let cellids: Vec<CellId> = if let Some(mesh_level) = self.mesh_hierarchy.levels.get(level) {
            mesh_level.cells.keys().cloned().collect()
        } else {
            Vec::new()
        };

        for cellid in cellids {
            self.update_interlevel_neighbors(cellid, level)?;
        }

        Ok(())
    }

    /// Check if two cells are geometric neighbors
    fn are_cells_neighbors(&self, cell1: &AdaptiveCell<F>, cell2: &AdaptiveCell<F>) -> bool {
        if cell1.center.len() != cell2.center.len() || cell1.center.len() < 3 {
            return false;
        }

        let max_size = cell1.size.max(cell2.size);
        let tolerance = max_size * F::from(1.1).expect("Failed to convert constant to float"); // 10% tolerance

        // Calculate distance between cell centers
        let mut distance_squared = F::zero();
        for i in 0..cell1.center.len() {
            let diff = cell1.center[i] - cell2.center[i];
            distance_squared += diff * diff;
        }

        let distance = distance_squared.sqrt();

        // Cells are neighbors if distance is approximately equal to sum of half-sizes
        let expected_distance =
            (cell1.size + cell2.size) / F::from(2.0).expect("Failed to convert constant to float");

        distance <= tolerance
            && distance
                >= expected_distance * F::from(0.7).expect("Failed to convert constant to float")
    }

    /// Update neighbor relationships across different mesh levels
    fn update_interlevel_neighbors(&mut self, cellid: CellId, level: usize) -> IntegrateResult<()> {
        // Collect neighbor relationships first to avoid borrowing conflicts
        let mut coarser_neighbors = Vec::new();
        let mut finer_neighbors = Vec::new();

        // Check neighbors at level-1 (coarser level)
        if level > 0 {
            if let (Some(current_level), Some(coarser_level)) = (
                self.mesh_hierarchy.levels.get(level),
                self.mesh_hierarchy.levels.get(level - 1),
            ) {
                if let Some(current_cell) = current_level.cells.get(&cellid) {
                    for (coarser_cellid, coarser_cell) in &coarser_level.cells {
                        if self.are_cells_neighbors(current_cell, coarser_cell) {
                            coarser_neighbors.push(*coarser_cellid);
                        }
                    }
                }
            }
        }

        // Check neighbors at level+1 (finer level)
        if level + 1 < self.mesh_hierarchy.levels.len() {
            if let (Some(current_level), Some(finer_level)) = (
                self.mesh_hierarchy.levels.get(level),
                self.mesh_hierarchy.levels.get(level + 1),
            ) {
                if let Some(current_cell) = current_level.cells.get(&cellid) {
                    for (finer_cellid, finer_cell) in &finer_level.cells {
                        if self.are_cells_neighbors(current_cell, finer_cell) {
                            finer_neighbors.push(*finer_cellid);
                        }
                    }
                }
            }
        }

        // Now apply the neighbor relationships with mutable access
        if let Some(current_level) = self.mesh_hierarchy.levels.get_mut(level) {
            if let Some(current_cell) = current_level.cells.get_mut(&cellid) {
                for coarser_id in coarser_neighbors {
                    if !current_cell.neighbors.contains(&coarser_id) {
                        current_cell.neighbors.push(coarser_id);
                    }
                }

                for finer_id in finer_neighbors {
                    if !current_cell.neighbors.contains(&finer_id) {
                        current_cell.neighbors.push(finer_id);
                    }
                }
            }
        }

        Ok(())
    }

    /// Update ghost cells for parallel processing
    fn update_ghost_cells(&mut self) -> IntegrateResult<()> {
        // Clear existing ghost cells
        self.mesh_hierarchy.ghost_cells.clear();

        // Identify boundary cells and their external neighbors for each level
        for level_idx in 0..self.mesh_hierarchy.levels.len() {
            let mut ghost_cells_for_level = Vec::new();
            let mut boundary_cells = HashSet::new();

            // First pass: identify boundary cells (cells with fewer neighbors than expected)
            let expected_neighbors = self.calculate_expected_neighbors();

            if let Some(mesh_level) = self.mesh_hierarchy.levels.get(level_idx) {
                for (cellid, cell) in &mesh_level.cells {
                    // A cell is on the boundary if it has fewer neighbors than expected
                    // or if it's marked as a boundary cell
                    if cell.neighbors.len() < expected_neighbors
                        || mesh_level.boundary_cells.contains(cellid)
                    {
                        boundary_cells.insert(*cellid);
                    }
                }

                // Second pass: create ghost cells for parallel processing
                for boundary_cellid in &boundary_cells {
                    if let Some(boundary_cell) = mesh_level.cells.get(boundary_cellid) {
                        // Create ghost cells in the expected neighbor positions
                        let ghost_cells =
                            self.create_ghost_cells_for_boundary(boundary_cell, level_idx)?;
                        ghost_cells_for_level.extend(ghost_cells);
                    }
                }

                // Third pass: handle inter-level ghost cells
                self.create_interlevel_ghost_cells(level_idx, &mut ghost_cells_for_level)?;
            }

            self.mesh_hierarchy
                .ghost_cells
                .insert(level_idx, ghost_cells_for_level);
        }

        Ok(())
    }

    /// Calculate expected number of neighbors for a regular cell
    fn calculate_expected_neighbors(&self) -> usize {
        // For a 3D structured grid, a regular internal cell should have 6 face neighbors
        // For 2D: 4 neighbors, for 1D: 2 neighbors
        // This is a simplification - actual count depends on mesh structure
        6
    }

    /// Create ghost cells for a boundary cell
    fn create_ghost_cells_for_boundary(
        &self,
        boundary_cell: &AdaptiveCell<F>,
        level: usize,
    ) -> IntegrateResult<Vec<CellId>> {
        let mut ghost_cells = Vec::new();

        if boundary_cell.center.len() >= 3 {
            let cell_size = boundary_cell.size;

            // Create ghost cells in the 6 cardinal directions (±x, ±y, ±z)
            let directions = [
                [F::one(), F::zero(), F::zero()],  // +x
                [-F::one(), F::zero(), F::zero()], // -x
                [F::zero(), F::one(), F::zero()],  // +y
                [F::zero(), -F::one(), F::zero()], // -y
                [F::zero(), F::zero(), F::one()],  // +z
                [F::zero(), F::zero(), -F::one()], // -z
            ];

            for (dir_idx, direction) in directions.iter().enumerate() {
                // Calculate ghost _cell position
                let mut ghost_center = boundary_cell.center.clone();
                for i in 0..3 {
                    ghost_center[i] += direction[i] * cell_size;
                }

                // Check if a real _cell exists at this position
                if !self.cell_exists_at_position(&ghost_center, level) {
                    // Create ghost _cell ID (using high indices to avoid conflicts)
                    let ghost_id = CellId {
                        level,
                        index: 1_000_000 + boundary_cell.id.index * 10 + dir_idx,
                    };

                    ghost_cells.push(ghost_id);
                }
            }
        }

        Ok(ghost_cells)
    }

    /// Create ghost cells for inter-level communication
    fn create_interlevel_ghost_cells(
        &self,
        level: usize,
        ghost_cells: &mut Vec<CellId>,
    ) -> IntegrateResult<()> {
        // Handle ghost _cells needed for communication between mesh levels

        // Check if we need ghost _cells from coarser level
        if level > 0 {
            if let Some(current_level) = self.mesh_hierarchy.levels.get(level) {
                for (cellid, cell) in &current_level.cells {
                    // If this fine cell doesn't have a parent at the coarser level,
                    // it might need ghost cell communication
                    if cell.parent.is_none() {
                        let ghost_id = CellId {
                            level: level - 1,
                            index: 2_000_000 + cellid.index,
                        };
                        ghost_cells.push(ghost_id);
                    }
                }
            }
        }

        // Check if we need ghost _cells from finer level
        if level + 1 < self.mesh_hierarchy.levels.len() {
            if let Some(current_level) = self.mesh_hierarchy.levels.get(level) {
                for (cellid, cell) in &current_level.cells {
                    // If this coarse cell has children at the finer level,
                    // it might need ghost cell communication
                    if !cell.children.is_empty() {
                        let ghost_id = CellId {
                            level: level + 1,
                            index: 3_000_000 + cellid.index,
                        };
                        ghost_cells.push(ghost_id);
                    }
                }
            }
        }

        Ok(())
    }

    /// Check if a cell exists at the given position and level
    fn cell_exists_at_position(&self, position: &Array1<F>, level: usize) -> bool {
        if let Some(mesh_level) = self.mesh_hierarchy.levels.get(level) {
            let tolerance = mesh_level.grid_spacing
                * F::from(0.1).expect("Failed to convert constant to float");

            for cell in mesh_level.cells.values() {
                if position.len() == cell.center.len() {
                    let mut distance_squared = F::zero();
                    for i in 0..position.len() {
                        let diff = position[i] - cell.center[i];
                        distance_squared += diff * diff;
                    }

                    if distance_squared.sqrt() < tolerance {
                        return true;
                    }
                }
            }
        }
        false
    }

    /// Count total active cells across all levels
    fn count_active_cells(&self) -> usize {
        self.mesh_hierarchy
            .levels
            .iter()
            .map(|level| level.cells.values().filter(|cell| cell.is_active).count())
            .sum()
    }

    /// Assess load balance quality
    fn assess_load_balance(&self) -> F {
        let total_cells = self.count_active_cells();
        if total_cells == 0 {
            return F::one(); // Empty mesh is perfectly balanced
        }

        // Calculate multiple load balance metrics
        let cell_distribution_balance = self.calculate_cell_distribution_balance();
        let computational_load_balance = self.calculate_computational_load_balance();
        let communication_overhead_balance = self.calculate_communication_balance();
        let memory_distribution_balance = self.calculate_memory_balance();

        // Weighted combination of different balance metrics
        let weight_cell = F::from(0.3).expect("Failed to convert constant to float");
        let weight_compute = F::from(0.4).expect("Failed to convert constant to float");
        let weight_comm = F::from(0.2).expect("Failed to convert constant to float");
        let weight_memory = F::from(0.1).expect("Failed to convert constant to float");

        let overall_balance = weight_cell * cell_distribution_balance
            + weight_compute * computational_load_balance
            + weight_comm * communication_overhead_balance
            + weight_memory * memory_distribution_balance;

        // Clamp to [0, 1] range where 1.0 = perfect balance
        overall_balance.min(F::one()).max(F::zero())
    }

    /// Calculate cell count distribution balance across levels
    fn calculate_cell_distribution_balance(&self) -> F {
        if self.mesh_hierarchy.levels.is_empty() {
            return F::one();
        }

        // Calculate cells per level
        let mut cells_per_level: Vec<usize> = Vec::new();
        let mut total_cells = 0;

        for level in &self.mesh_hierarchy.levels {
            let active_cells = level.cells.values().filter(|c| c.is_active).count();
            cells_per_level.push(active_cells);
            total_cells += active_cells;
        }

        if total_cells == 0 {
            return F::one();
        }

        // Calculate variance in cell distribution
        let mean_cells = total_cells as f64 / cells_per_level.len() as f64;
        let variance: f64 = cells_per_level
            .iter()
            .map(|&count| {
                let diff = count as f64 - mean_cells;
                diff * diff
            })
            .sum::<f64>()
            / cells_per_level.len() as f64;

        let std_dev = variance.sqrt();
        let coefficient_of_variation = if mean_cells > 0.0 {
            std_dev / mean_cells
        } else {
            0.0
        };

        // Convert to balance score (lower variation = better balance)
        let balance = (1.0 - coefficient_of_variation.min(1.0)).max(0.0);
        F::from(balance).unwrap_or(F::zero())
    }

    /// Calculate computational load balance based on cell error estimates
    fn calculate_computational_load_balance(&self) -> F {
        let mut level_computational_loads: Vec<F> = Vec::new();
        let mut total_load = F::zero();

        for level in &self.mesh_hierarchy.levels {
            let mut level_load = F::zero();

            for cell in level.cells.values() {
                if cell.is_active {
                    // Computational cost is proportional to error estimate and refinement complexity
                    let cell_cost = cell.error_estimate * cell.size * cell.size; // O(h^2) scaling
                    level_load += cell_cost;
                }
            }

            level_computational_loads.push(level_load);
            total_load += level_load;
        }

        if total_load <= F::zero() {
            return F::one();
        }

        // Calculate coefficient of variation for computational loads
        let mean_load =
            total_load / F::from(level_computational_loads.len()).expect("Operation failed");
        let mut variance = F::zero();

        for &load in &level_computational_loads {
            let diff = load - mean_load;
            variance += diff * diff;
        }

        variance /= F::from(level_computational_loads.len()).expect("Operation failed");
        let std_dev = variance.sqrt();

        let coeff_var = if mean_load > F::zero() {
            std_dev / mean_load
        } else {
            F::zero()
        };

        // Convert to balance score
        let balance = F::one() - coeff_var.min(F::one());
        balance.max(F::zero())
    }

    /// Calculate communication balance based on ghost cell overhead
    fn calculate_communication_balance(&self) -> F {
        let mut level_comm_costs: Vec<F> = Vec::new();
        let mut total_comm_cost = F::zero();

        for (level_idx, level) in self.mesh_hierarchy.levels.iter().enumerate() {
            let active_cells = level.cells.values().filter(|c| c.is_active).count();
            let ghost_cells = self
                .mesh_hierarchy
                .ghost_cells
                .get(&level_idx)
                .map(|ghosts| ghosts.len())
                .unwrap_or(0);

            // Communication cost is proportional to ghost cells per active cell
            let comm_cost = if active_cells > 0 {
                F::from(ghost_cells as f64 / active_cells as f64).unwrap_or(F::zero())
            } else {
                F::zero()
            };

            level_comm_costs.push(comm_cost);
            total_comm_cost += comm_cost;
        }

        if level_comm_costs.is_empty() || total_comm_cost <= F::zero() {
            return F::one();
        }

        // Calculate variance in communication costs
        let mean_comm =
            total_comm_cost / F::from(level_comm_costs.len()).expect("Operation failed");
        let mut variance = F::zero();

        for &cost in &level_comm_costs {
            let diff = cost - mean_comm;
            variance += diff * diff;
        }

        variance /= F::from(level_comm_costs.len()).expect("Operation failed");
        let std_dev = variance.sqrt();

        let coeff_var = if mean_comm > F::zero() {
            std_dev / mean_comm
        } else {
            F::zero()
        };

        // Convert to balance score
        let balance = F::one() - coeff_var.min(F::one());
        balance.max(F::zero())
    }

    /// Calculate memory distribution balance
    fn calculate_memory_balance(&self) -> F {
        let mut level_memory_usage: Vec<F> = Vec::new();
        let mut total_memory = F::zero();

        for level in &self.mesh_hierarchy.levels {
            // Estimate memory usage: cells + solution data + neighbor lists
            let cell_count = level.cells.len();
            let total_neighbors: usize = level.cells.values().map(|c| c.neighbors.len()).sum();

            let solution_size: usize = level.cells.values().map(|c| c.solution.len()).sum();

            // Memory estimate (simplified)
            let memory_estimate = F::from(cell_count + total_neighbors + solution_size)
                .expect("Failed to convert to float");
            level_memory_usage.push(memory_estimate);
            total_memory += memory_estimate;
        }

        if level_memory_usage.is_empty() || total_memory <= F::zero() {
            return F::one();
        }

        // Calculate memory distribution balance
        let mean_memory =
            total_memory / F::from(level_memory_usage.len()).expect("Operation failed");
        let mut variance = F::zero();

        for &memory in &level_memory_usage {
            let diff = memory - mean_memory;
            variance += diff * diff;
        }

        variance /= F::from(level_memory_usage.len()).expect("Operation failed");
        let std_dev = variance.sqrt();

        let coeff_var = if mean_memory > F::zero() {
            std_dev / mean_memory
        } else {
            F::zero()
        };

        // Convert to balance score
        let balance = F::one() - coeff_var.min(F::one());
        balance.max(F::zero())
    }
}

// Refinement criterion implementations
impl<F: IntegrateFloat + Send + Sync> RefinementCriterion<F> for GradientRefinementCriterion<F> {
    fn evaluate(&self, cell: &AdaptiveCell<F>, neighbors: &[&AdaptiveCell<F>]) -> F {
        if neighbors.is_empty() {
            return F::zero();
        }

        let mut max_gradient = F::zero();

        for neighbor in neighbors {
            let gradient = if let Some(comp) = self.component {
                if comp < cell.solution.len() && comp < neighbor.solution.len() {
                    (cell.solution[comp] - neighbor.solution[comp]).abs() / cell.size
                } else {
                    F::zero()
                }
            } else {
                // Use L2 norm of solution difference
                let diff = &cell.solution - &neighbor.solution;
                diff.mapv(|x| x.powi(2)).sum().sqrt() / cell.size
            };

            max_gradient = max_gradient.max(gradient);
        }

        // Relative criterion
        let solution_magnitude = if let Some(comp) = self.component {
            cell.solution
                .get(comp)
                .map(|&x| x.abs())
                .unwrap_or(F::zero())
        } else {
            cell.solution.mapv(|x| x.abs()).sum()
        };

        if solution_magnitude > F::zero() {
            max_gradient / solution_magnitude
        } else {
            max_gradient
        }
    }

    fn name(&self) -> &'static str {
        "Gradient"
    }
}

impl<F: IntegrateFloat + Send + Sync> RefinementCriterion<F> for FeatureDetectionCriterion<F> {
    fn evaluate(&self, cell: &AdaptiveCell<F>, neighbors: &[&AdaptiveCell<F>]) -> F {
        let mut feature_score = F::zero();

        for &feature_type in &self.feature_types {
            match feature_type {
                FeatureType::SharpGradient
                    // Detect sharp gradients
                    if neighbors.len() >= 2 => {
                        let gradients: Vec<F> = neighbors
                            .iter()
                            .map(|n| (&cell.solution - &n.solution).mapv(|x| x.abs()).sum())
                            .collect();

                        let max_grad = gradients.iter().fold(F::zero(), |acc, &x| acc.max(x));
                        let avg_grad = gradients.iter().fold(F::zero(), |acc, &x| acc + x)
                            / F::from(gradients.len()).expect("Operation failed");

                        if avg_grad > F::zero() {
                            feature_score += max_grad / avg_grad;
                        }
                    }
                FeatureType::LocalExtremum => {
                    // Detect local extrema
                    let cell_value = cell.solution.mapv(|x| x.abs()).sum();
                    let mut is_extremum = true;

                    for neighbor in neighbors {
                        let neighbor_value = neighbor.solution.mapv(|x| x.abs()).sum();
                        if (neighbor_value - cell_value).abs() < self.threshold {
                            is_extremum = false;
                            break;
                        }
                    }

                    if is_extremum {
                        feature_score += F::one();
                    }
                }
                _ => {
                    // Other feature types would be implemented here
                }
            }
        }

        feature_score
    }

    fn name(&self) -> &'static str {
        "FeatureDetection"
    }
}

impl<F: IntegrateFloat + Send + Sync> RefinementCriterion<F> for CurvatureRefinementCriterion<F> {
    fn evaluate(&self, cell: &AdaptiveCell<F>, neighbors: &[&AdaptiveCell<F>]) -> F {
        if neighbors.len() < 2 {
            return F::zero();
        }

        // Estimate curvature using second differences
        let mut curvature = F::zero();

        for component in 0..cell.solution.len() {
            let center_value = cell.solution[component];
            let neighbor_values: Vec<F> = neighbors
                .iter()
                .filter_map(|n| n.solution.get(component).copied())
                .collect();

            if neighbor_values.len() >= 2 {
                // Simple second difference approximation
                let avg_neighbor = neighbor_values.iter().fold(F::zero(), |acc, &x| acc + x)
                    / F::from(neighbor_values.len()).expect("Operation failed");

                let second_diff = (avg_neighbor - center_value).abs() / (cell.size * cell.size);
                curvature += second_diff;
            }
        }

        curvature
    }

    fn name(&self) -> &'static str {
        "Curvature"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_amr_manager_creation() {
        let initial_level = AdaptiveMeshLevel {
            level: 0,
            cells: HashMap::new(),
            grid_spacing: 1.0,
            boundary_cells: HashSet::new(),
        };

        let amr = AdvancedAMRManager::new(initial_level, 5, 0.01);
        assert_eq!(amr.max_levels, 5);
        assert_eq!(amr.mesh_hierarchy.levels.len(), 1);
    }

    #[test]
    fn test_gradient_criterion() {
        let cell = AdaptiveCell {
            id: CellId { level: 0, index: 0 },
            center: Array1::from_vec(vec![0.5, 0.5]),
            size: 0.1,
            solution: Array1::from_vec(vec![1.0]),
            error_estimate: 0.0,
            refinement_flag: RefinementFlag::None,
            is_active: true,
            neighbors: vec![],
            parent: None,
            children: vec![],
        };

        let neighbor = AdaptiveCell {
            id: CellId { level: 0, index: 1 },
            center: Array1::from_vec(vec![0.6, 0.5]),
            size: 0.1,
            solution: Array1::from_vec(vec![2.0]),
            error_estimate: 0.0,
            refinement_flag: RefinementFlag::None,
            is_active: true,
            neighbors: vec![],
            parent: None,
            children: vec![],
        };

        let criterion = GradientRefinementCriterion {
            component: Some(0),
            threshold: 1.0,
            relative_tolerance: 0.1,
        };

        let neighbors = vec![&neighbor];
        let result = criterion.evaluate(&cell, &neighbors);
        assert!(result > 0.0);
    }
}