pyrucast 0.15.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
//! ElementField — multi-component values per `(cell, Gauss point)` on a
//! [`crate::containers::finite_element_space::FiniteElementSpace`].
//!
//! Hierarchy mirroring [`crate::containers::finite_element_space`]:
//!
//! - [`SubElementField`] — multi-component values per `(cell, Gauss point)`
//!   on a single [`crate::containers::finite_element_space::SubFiniteElementSpace`]. Where
//!   [`crate::containers::node_field::SubNodeField`] stores values **at nodes**, a
//!   `SubElementField` stores them **at the Gauss points of every cell**
//!   of a finite-element subspace.
//! - [`ElementField`] — aggregate of `SubElementField`, one per subspace
//!   of a [`crate::containers::finite_element_space::FiniteElementSpace`], in the same order.
//!
//! Typical uses:
//!
//! - **material properties** (Young's modulus, density, conductivity, …)
//!   evaluated at the Gauss points where the integrals are computed;
//! - **state / internal variables** (plastic strain, damage, hardening, …)
//!   that need to be remembered cell-by-cell, point-by-point;
//! - **derived quantities** (stresses, strains, fluxes, …) extracted from
//!   a solution for post-treatment.
//!
//! # Snapshot of the FE space layout
//!
//! On construction every `SubElementField` captures three dimensions of
//! its host `SubFiniteElementSpace`:
//!
//! - `cell_count`  — number of cells (`SubMesh::cell_count` at that moment);
//! - `gauss_count` — number of Gauss points per cell;
//! - `component_count` — chosen by the caller.
//!
//! The internal buffer is sized accordingly and **never reallocated**. The
//! FE subspace has sealed its `SubMesh` (see
//! [`SubMesh::seal`](crate::containers::mesh::SubMesh::seal)): no cell can be added to it, so the
//! captured `cell_count` stays the submesh's. The nodes may still move; the
//! values are unaffected. The Gauss-point coordinates and weights are kept as
//! reference data on the `SubFiniteElementSpace` itself; only the user data
//! lives here.
//!
//! # Layout
//!
//! Values are stored flat, row-major, in the order **cell → gauss →
//! component** so that contiguous reads of a single cell or a single
//! Gauss point are cache-friendly:
//!
//! ```text
//! values[cell_idx * gauss_count * component_count
//!        + g * component_count
//!        + c]
//! ```
//!
//! # Example
//!
//! ```
//! use pyrucast::aggregate::Aggregate;
//! use pyrucast::containers::field::SubField;
//! use pyrucast::coords::Coords;
//! use pyrucast::containers::element_field::ElementField;
//! use pyrucast::atoms::ElementType;
//! use pyrucast::containers::finite_element_space::FiniteElementSpace;
//! use pyrucast::containers::mesh::{Mesh, SubMesh};
//! use pyrucast::atoms::Node;
//! use pyrucast::handle::Handle;
//!
//! let coords = Handle::new(Coords::new(2).unwrap());
//! let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
//! let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
//! let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
//! let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
//! mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
//!
//! let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
//!
//! // Linear elasticity 2D — two material properties (E, nu) on every subspace.
//! let mat = ElementField::new(&fes, vec!["E".into(), "nu".into()]).unwrap();
//! assert_eq!(mat.len(), 1);
//!
//! let sub0 = mat.get(0).unwrap();
//! {
//!     let mut s = sub0.write();
//!     s.set_uniform("E", 210e9).unwrap();
//!     s.set_uniform("nu", 0.3).unwrap();
//! }
//!
//! let s = sub0.read();
//! assert_eq!(s.cell_count(), 1);
//! assert_eq!(s.gauss_count(), 3);   // TRI3 Hammer
//! assert_eq!(s.component_count(), 2);
//! assert_eq!(s.value(0, 0, "E").unwrap(), 210e9);
//! ```

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::field::{Overlaps, SubField, ABSENT_COMPONENT, ABSENT_ROW};
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::mesh::SubMesh;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::parallel::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

// ─── SubElementField ───────────────────────────────────────────────────────

/// Multi-component values per `(cell, Gauss point)` on a single
/// [`SubFiniteElementSpace`].
///
/// Layout: flat row-major in the order *cell → gauss → component*
/// (see the module-level documentation).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// // A material zone: the values live at the **Gauss points**, not at the
/// // nodes — that is what lets a field be discontinuous from one cell to the
/// // next without averaging anything.
/// let acier = SubElementField::from_uniform_per_component(
///     zone.clone(), vec!["E".into(), "nu".into()], &[210_000.0, 0.3])?;
/// assert_eq!(acier.cell_count(), 1);
/// assert_eq!(acier.value(0, 0, "E")?, 210_000.0);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct SubElementField {
    support: Handle<SubFiniteElementSpace>,
    components: Vec<String>,
    /// Dimensions captured at construction; the buffer is never resized.
    n_cells: usize,
    n_gauss: usize,
    /// Flat row-major buffer of length `n_cells * n_gauss * components.len()`.
    values: Vec<f64>,
}

impl SubElementField {
    /// Build a sub-field on the given FE subspace with the supplied
    /// component names. Every value is initialized to `0.0`.
    ///
    /// # Errors
    ///
    /// - `components` is empty;
    /// - `components` contains a duplicate name.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// // A material zone: one field per Gauss point, all zero.
    /// let f = SubElementField::new(zone.clone(), vec!["E".into(), "nu".into()])?;
    /// assert_eq!(f.component_count(), 2);
    /// assert_eq!(f.get(0, 0, 0)?, 0.0);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(fespace: Handle<SubFiniteElementSpace>, components: Vec<String>) -> Result<Self> {
        crate::containers::field::check_components("SubElementField", &components)?;
        let (n_cells, n_gauss) = {
            let s = fespace.read();
            (s.cell_count(), s.gauss_count())
        };
        let n_comp = components.len();
        let values = vec![0.0; n_cells * n_gauss * n_comp];
        Ok(Self {
            support: fespace,
            components,
            n_cells,
            n_gauss,
            values,
        })
    }

    /// Convenience: build a sub-field with a uniform value per component.
    ///
    /// `values_per_component` must have the same length as `components`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// // The common form of a homogeneous material: one value per component.
    /// let acier = SubElementField::from_uniform_per_component(
    ///     zone.clone(), vec!["E".into(), "nu".into()], &[210_000.0, 0.3])?;
    /// assert_eq!(acier.value(0, 0, "E")?, 210_000.0);
    /// assert_eq!(acier.value(0, 2, "nu")?, 0.3); // tous les points de Gauss
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn from_uniform_per_component(
        fespace: Handle<SubFiniteElementSpace>,
        components: Vec<String>,
        values_per_component: &[f64],
    ) -> Result<Self> {
        if values_per_component.len() != components.len() {
            return Err(PyrucastError::Message(format!(
                "from_uniform_per_component: {} values supplied for {} components",
                values_per_component.len(),
                components.len()
            )));
        }
        let mut field = Self::new(fespace, components)?;
        // One pass tiling the per-component values across every point, rather
        // than one strided pass per component over the whole buffer.
        let ncomp = values_per_component.len();
        if ncomp > 0 {
            use crate::parallel::*;
            field
                .values
                .par_chunks_mut(ncomp)
                .with_min_len((MIN_PARALLEL_LEN / ncomp).max(1))
                .for_each(|row| row.copy_from_slice(values_per_component));
        }
        Ok(field)
    }

    // ── Structural accessors ────────────────────────────────────────────────

    /// Number of cells captured at construction.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let f = SubElementField::new(zone.clone(), vec!["k".into()])?;
    /// assert_eq!(f.cell_count(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn cell_count(&self) -> usize {
        self.n_cells
    }

    /// Number of Gauss points per cell.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let f = SubElementField::new(zone.clone(), vec!["k".into()])?;
    /// // Le champ tient autant de valeurs que l'espace EF a de points de Gauss.
    /// assert_eq!(f.gauss_count(), zone.read().gauss_count());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn gauss_count(&self) -> usize {
        self.n_gauss
    }

    // `components`, `component_count`, `component_index`, … come from
    // the [`crate::containers::field::SubField`] trait.

    // ── Value access by indices ─────────────────────────────────────────────

    /// Read the value at `(cell, gauss, component_index)`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let mut f = SubElementField::new(zone.clone(), vec!["k".into()])?;
    /// f.set(0, 0, 0, 1.5)?;
    /// assert_eq!(f.get(0, 0, 0)?, 1.5);
    /// // All three indices are checked: cell, Gauss point, component.
    /// assert!(f.get(0, 0, 1).is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn get(&self, cell: usize, gauss: usize, comp: usize) -> Result<f64> {
        let idx = self.linear_index(cell, gauss, comp)?;
        Ok(self.values[idx])
    }

    /// Write the value at `(cell, gauss, component_index)`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let mut f = SubElementField::new(zone.clone(), vec!["k".into()])?;
    /// f.set(0, 1, 0, 2.0)?; // le second point de Gauss seulement
    /// assert_eq!(f.get(0, 0, 0)?, 0.0);
    /// assert_eq!(f.get(0, 1, 0)?, 2.0);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn set(&mut self, cell: usize, gauss: usize, comp: usize, value: f64) -> Result<()> {
        let idx = self.linear_index(cell, gauss, comp)?;
        self.values[idx] = value;
        Ok(())
    }

    /// All component values at `(cell, gauss)`, in component order
    /// (length = `component_count`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let f = SubElementField::from_uniform_per_component(
    ///     zone.clone(), vec!["s_xx".into(), "s_yy".into(), "s_xy".into()],
    ///     &[10.0, 20.0, 5.0])?;
    /// // The whole tensor at one point, in the components' order.
    /// assert_eq!(f.point_values(0, 0)?, &[10.0, 20.0, 5.0]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn point_values(&self, cell: usize, gauss: usize) -> Result<&[f64]> {
        self.check_cell(cell)?;
        self.check_gauss(gauss)?;
        let n_comp = self.components.len();
        let start = (cell * self.n_gauss + gauss) * n_comp;
        Ok(&self.values[start..start + n_comp])
    }

    /// [`point_values`](Self::point_values) **without the checks** — the form a
    /// kernel calls.
    ///
    /// A per-cell or per-Gauss-point kernel is driven over `0..cell_count` ×
    /// `0..gauss_count` of *this very field*, which the driver matched against
    /// the FE subspace before the parallel region. Both indices are therefore
    /// facts of the zone, and re-proving them at every point costs three
    /// comparisons and an error path for a question already settled — the same
    /// reason [`Coords::position_alive`](crate::coords::Coords) exists next to
    /// the checked read.
    ///
    /// Read it by the indices a layout resolved once
    /// ([`ZoneLayout`](crate::models::ZoneLayout) /
    /// [`ElementLayout`](crate::models::ElementLayout)), never by name.
    pub(crate) fn row(&self, cell: usize, gauss: usize) -> &[f64] {
        let n_comp = self.components.len();
        let start = (cell * self.n_gauss + gauss) * n_comp;
        &self.values[start..start + n_comp]
    }

    // ── Value access by component name ──────────────────────────────────────

    /// Read by `(cell, gauss, component name)`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let f = SubElementField::from_uniform_per_component(
    ///     zone.clone(), vec!["E".into(), "nu".into()], &[210_000.0, 0.3])?;
    /// assert_eq!(f.value(0, 0, "nu")?, 0.3);
    /// assert!(f.value(0, 0, "rho").is_err()); // composante inconnue
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn value(&self, cell: usize, gauss: usize, component: &str) -> Result<f64> {
        let c = self.component_index_or_err(component)?;
        self.get(cell, gauss, c)
    }

    /// Write by `(cell, gauss, component name)`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let mut f = SubElementField::new(zone.clone(), vec!["E".into()])?;
    /// f.set_value(0, 0, "E", 210_000.0)?;
    /// assert_eq!(f.value(0, 0, "E")?, 210_000.0);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn set_value(
        &mut self,
        cell: usize,
        gauss: usize,
        component: &str,
        value: f64,
    ) -> Result<()> {
        let c = self.component_index_or_err(component)?;
        self.set(cell, gauss, c, value)
    }

    // ── Bulk fillers ────────────────────────────────────────────────────────

    // `set_uniform` (constant-per-domain material properties) comes from
    // the [`crate::containers::field::SubField`] trait.

    /// Set every Gauss point of a given cell to the same value for one
    /// component (cell-piecewise-constant material).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// let mut f = SubElementField::new(zone.clone(), vec!["k".into()])?;
    /// // Material constant per cell: every Gauss point at once.
    /// f.set_cell_uniform(0, "k", 4.0)?;
    /// assert!((0..f.gauss_count()).all(|g| f.value(0, g, "k").unwrap() == 4.0));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn set_cell_uniform(&mut self, cell: usize, component: &str, value: f64) -> Result<()> {
        self.check_cell(cell)?;
        let c = self.component_index_or_err(component)?;
        let n_comp = self.components.len();
        for g in 0..self.n_gauss {
            self.values[(cell * self.n_gauss + g) * n_comp + c] = value;
        }
        Ok(())
    }

    // Scalar per-component operations (`add_to_component`, …) come from
    // the [`crate::containers::field::SubField`] trait.

    // ── Internals ───────────────────────────────────────────────────────────

    fn linear_index(&self, cell: usize, gauss: usize, comp: usize) -> Result<usize> {
        self.check_cell(cell)?;
        self.check_gauss(gauss)?;
        self.check_comp(comp)?;
        let n_comp = self.components.len();
        Ok((cell * self.n_gauss + gauss) * n_comp + comp)
    }

    fn check_cell(&self, cell: usize) -> Result<()> {
        if cell >= self.n_cells {
            return Err(PyrucastError::Message(format!(
                "SubElementField: cell index {} ≥ cell_count {}",
                cell, self.n_cells
            )));
        }
        Ok(())
    }

    fn check_gauss(&self, gauss: usize) -> Result<()> {
        if gauss >= self.n_gauss {
            return Err(PyrucastError::Message(format!(
                "SubElementField: gauss index {} ≥ gauss_count {}",
                gauss, self.n_gauss
            )));
        }
        Ok(())
    }

    fn check_comp(&self, comp: usize) -> Result<()> {
        if comp >= self.components.len() {
            return Err(PyrucastError::Message(format!(
                "SubElementField: component index {} ≥ component_count {}",
                comp,
                self.components.len()
            )));
        }
        Ok(())
    }
}

impl crate::containers::field::SubField for SubElementField {
    type Support = SubFiniteElementSpace;
    fn support(&self) -> Handle<SubFiniteElementSpace> {
        self.support.clone()
    }
    fn components(&self) -> &[String] {
        &self.components
    }
    fn values(&self) -> &[f64] {
        &self.values
    }
    fn values_mut(&mut self) -> &mut [f64] {
        &mut self.values
    }
    fn same_support_with(&self, components: Vec<String>) -> Result<Self> {
        Self::new(self.support.clone(), components)
    }
}

// ─── Clone ─────────────────────────────────────────────────────────────────

impl Clone for SubElementField {
    fn clone(&self) -> Self {
        Self {
            support: self.support.clone(),
            components: self.components.clone(),
            n_cells: self.n_cells,
            n_gauss: self.n_gauss,
            values: self.values.clone(),
        }
    }
}

// ─── Debug / Display ───────────────────────────────────────────────────────

impl fmt::Debug for SubElementField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Bounded structure only — the per-(cell, gauss) values live in `dump()`.
        f.debug_struct("SubElementField")
            .field("support", &self.support)
            .field("cell_count", &self.n_cells)
            .field("gauss_count", &self.n_gauss)
            .field("components", &self.components)
            .finish()
    }
}

impl fmt::Display for SubElementField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SubElementField: {} cell(s) × {} gauss × {} component(s) [{}]",
            self.n_cells,
            self.n_gauss,
            self.components.len(),
            self.components.join(", ")
        )
    }
}

impl crate::dump::Dump for SubElementField {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        use crate::dump::{fmt_float, table};
        let ncomp = self.components.len();
        let mut headers = vec!["cell".to_string(), "gauss".to_string()];
        headers.extend(self.components.iter().cloned());
        let mut rows = Vec::with_capacity(self.n_cells * self.n_gauss);
        for cell in 0..self.n_cells {
            for g in 0..self.n_gauss {
                let base = (cell * self.n_gauss + g) * ncomp;
                let mut row = vec![cell.to_string(), g.to_string()];
                for c in 0..ncomp {
                    row.push(fmt_float(self.values[base + c], opts.precision));
                }
                rows.push(row);
            }
        }
        // The support, which `Display` does not name: without it the "content" level
        // would say less than the "structure" level.
        format!(
            "{self}\n  support: {}\n{}",
            self.support,
            table(&headers, &rows, opts)
        )
    }
}

// ─── Operators field OP f64 ────────────────────────────────────────────────
//
// Consuming versions (mutate self in place); reference versions clone first.
// Generated by the shared macro, exactly like `SubNodeField`.

crate::impl_subfield_scalar_ops!(SubElementField);

// ─── Operators field OP field (same support) ───────────────────────────────
//
// `&a + &b` (and `a + b`) delegate to `SubField::merge_components` (union of
// components with passthrough); fallible (same support required) ⇒ output
// `Result<SubElementField>`.

crate::impl_subfield_field_ops!(SubElementField);

// ─── ElementField (aggregate) ──────────────────────────────────────────────

/// Aggregate of [`SubElementField`] — one per subspace of a
/// [`FiniteElementSpace`], in the same order.
///
/// Mirrors the [`FiniteElementSpace`] / [`SubFiniteElementSpace`] hierarchy: an
/// `ElementField` is to `FiniteElementSpace` what a `SubElementField` is
/// to `SubFiniteElementSpace`. The component lists captured by the underlying
/// sub-fields may differ from one subspace to the next.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::{ElementField, SubElementField};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// // The aggregate: one zone per FE subspace, each with its components.
/// let mut f = ElementField::new(&fes, vec!["k".into()])?;
/// f.get(0)?.write().set_uniform("k", 1.5)?;
/// assert_eq!(f.get(0)?.read().value(0, 0, "k")?, 1.5);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize, Default)]
pub struct ElementField {
    subs: Vec<Handle<SubElementField>>,
}

crate::impl_aggregate!(ElementField, SubElementField, subfield, "subfield(s)", {
    /// Refuse a zone whose FE subspace stands on another `Coords` than the
    /// first zone's: node ids, hence the whole field, only mean something
    /// inside one `Coords`.
    fn check_push(&self, h: &Handle<SubElementField>) -> Result<()> {
        let Some(first) = self.subs.first() else {
            return Ok(());
        };
        let a = first.read().support().read().coords();
        let b = h.read().support().read().coords();
        crate::coords::ensure_same_coords(&a, &b)
    }

    /// Refuse a zone carrying, on its support, a component a zone of the field
    /// already carries there: on one support, each component lives in one
    /// zone.
    fn check_add(&self, h: &Handle<SubElementField>) -> Result<()> {
        crate::containers::field::check_component_free(self, h)
    }

    /// Validate the zone decomposition after a union (`a | b`): **no component
    /// may be carried by two zones on the same support**. Zones on the same
    /// support with disjoint components are kept side by side (no fusion, no new
    /// `SubElementField`); a duplicated component is an error. To fuse zones that
    /// legitimately share a support, call
    /// [`crate::ops::element_field::consolidate`](fn@crate::ops::element_field::consolidate)
    /// explicitly.
    fn finalize(&mut self) -> Result<()> {
        crate::ops::element_field::check_unique_component_per_support(self)
    }
});
crate::impl_aggregate_dump!(ElementField);

// ─── Operators ElementField OP {ElementField, f64} ─────────────────────────
//
// `&a + &b` (per support and component, union with passthrough) via
// `Field::merge_field`; `&a + 2.0` (scalar broadcast) via
// `Field::combine_scalar`, and `2.0 * &a` its mirror. Fallible (zone pairing)
// ⇒ output `Result<ElementField>`.

crate::impl_field_ops!(ElementField);

impl ElementField {
    /// Build an `ElementField` on `fespace` with the **same** `components`
    /// on every subspace.
    ///
    /// `fespace` must have at least one subspace.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// // The same components on every zone of the FE space.
    /// let f = ElementField::new(&fes, vec!["E".into(), "nu".into()])?;
    /// assert_eq!(f.len(), fes.len());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(fespace: &FiniteElementSpace, components: Vec<String>) -> Result<Self> {
        let n_sub = fespace.len();
        if n_sub == 0 {
            return Err(PyrucastError::Message(
                "ElementField: FE space has no subspace".into(),
            ));
        }
        crate::containers::field::check_components("SubElementField", &components)?;
        if let Some((first, i)) = crate::aggregate::repeated_sub(fespace) {
            return Err(PyrucastError::Message(format!(
                "ElementField: subspaces {first} and {i} of the FE space are the same \
                 subspace, and a field carries each component once on a subspace — take \
                 each subspace once with a union (`fes | fes`)"
            )));
        }
        let mut subs = Vec::with_capacity(n_sub);
        for i in 0..n_sub {
            let sub = fespace.get(i)?;
            let sf = SubElementField::new(sub, components.clone())?;
            subs.push(Handle::new(sf));
        }
        Ok(Self { subs })
    }

    /// Every [`SubElementField`] living on `fespace`, in aggregate order.
    ///
    /// The honest multi-zone accessor: a union (`a | b`) may leave several
    /// **component-disjoint** zones on one support (see
    /// [`crate::ops::element_field::check_unique_component_per_support`]); this returns
    /// all of them. Empty when none match. Prefer this whenever a support may
    /// legitimately carry more than one zone.
    pub(crate) fn subs_for_fespace(
        &self,
        fespace: &Handle<SubFiniteElementSpace>,
    ) -> Vec<Handle<SubElementField>> {
        let mut out = Vec::new();
        for h in self {
            let matches = {
                let f = h.read().support();
                f.same_object(fespace)
            };
            if matches {
                out.push(h.clone());
            }
        }
        out
    }

    /// The **unique** [`SubElementField`] on `fespace`.
    ///
    /// The per-zone field-matching primitive shared by the assembly and
    /// behaviour operators, for the common case of one zone per support. Errors
    /// if no sub-field of the aggregate lives on `fespace` (a missing per-zone
    /// material / deformation is always a caller error, never a silent skip),
    /// **and also if more than one zone lives on the support** — it never
    /// silently returns the first of many, which would let `strain | state`
    /// drop the state. When a support may carry several zones, use
    /// [`subs_for_fespace`](Self::subs_for_fespace) or fuse them with
    /// [`crate::ops::element_field::consolidate`].
    pub(crate) fn sub_for_fespace(
        &self,
        fespace: &Handle<SubFiniteElementSpace>,
    ) -> Result<Handle<SubElementField>> {
        let mut zones = self.subs_for_fespace(fespace);
        match zones.len() {
            1 => Ok(zones.pop().expect("length checked to be 1")),
            0 => Err(PyrucastError::Message(format!(
                "no SubElementField in this ElementField matches the FE space \
                 {fespace}"
            ))),
            n => Err(PyrucastError::Message(format!(
                "{n} SubElementFields live on the FE space {fespace}; \
                 sub_for_fespace needs a unique zone. Use subs_for_fespace, or \
                 element_field::consolidate to fuse the zones."
            ))),
        }
    }

    /// The **unique** [`SubElementField`] on `fespace` that carries **every**
    /// component in `required`.
    ///
    /// Like [`sub_for_fespace`](Self::sub_for_fespace) but discriminates zones by
    /// their component set, not by support alone. A support may then legitimately
    /// hold several **component-disjoint** zones — e.g. the per-physics material
    /// zones a union leaves side by side (`k` for conduction, `E`/`nu` for
    /// elasticity on one shared mesh) — and each caller resolves *its own* zone by
    /// naming the components it needs, without an explicit
    /// [`consolidate`](crate::ops::element_field::consolidate). It stays
    /// safe: it never silently returns the first of several — it errors if **no**
    /// zone carries the full set, or if **more than one** does (a genuine
    /// ambiguity the caller must resolve). `required` must be non-empty (an empty
    /// set matches every zone and is a caller error).
    pub(crate) fn sub_for_fespace_with(
        &self,
        fespace: &Handle<SubFiniteElementSpace>,
        required: &[String],
    ) -> Result<Handle<SubElementField>> {
        let mut matching: Vec<Handle<SubElementField>> = Vec::new();
        for h in self.subs_for_fespace(fespace) {
            let carries_all = {
                let comps = h.read().components().to_vec();
                required.iter().all(|r| comps.contains(r))
            };
            if carries_all {
                matching.push(h);
            }
        }
        match matching.len() {
            1 => Ok(matching.pop().expect("length checked to be 1")),
            0 => Err(PyrucastError::Message(format!(
                "no SubElementField on the FE space {fespace} carries \
                 all of {required:?} — supply it via material_field"
            ))),
            n => Err(PyrucastError::Message(format!(
                "{n} SubElementFields on the FE space {fespace} each \
                 carry all of {required:?}; the zone is ambiguous — fuse them with \
                 element_field::consolidate or narrow the components"
            ))),
        }
    }

    /// The zone on `fespace` handed to a consumer that reads `names`.
    ///
    /// The only zone of the support, whatever it carries: the consumer's own
    /// layout then names a missing component. When **several** zones share the
    /// support — the strains or states of two laws on one mesh, a temperature
    /// gradient beside a strain — the one carrying every name in `names`, the
    /// way [`sub_for_fespace_with`](Self::sub_for_fespace_with) tells material
    /// zones apart. Errors when no zone lives on the support, or when the
    /// names single out none or several.
    pub(crate) fn sub_for_fespace_reading(
        &self,
        fespace: &Handle<SubFiniteElementSpace>,
        names: &[String],
    ) -> Result<Handle<SubElementField>> {
        let zones = self.subs_for_fespace(fespace);
        if zones.len() <= 1 || names.is_empty() {
            return self.sub_for_fespace(fespace);
        }
        let n_zones = zones.len();
        let mut carrying: Vec<Handle<SubElementField>> = zones
            .into_iter()
            .filter(|h| {
                let z = h.read();
                names.iter().all(|n| z.components().contains(n))
            })
            .collect();
        match carrying.len() {
            1 => Ok(carrying.pop().expect("length checked to be 1")),
            0 => Err(PyrucastError::Message(format!(
                "{n_zones} zones live on the FE space {fespace} and none carries all of \
                 {names:?}"
            ))),
            n => Err(PyrucastError::Message(format!(
                "{n} zones on the FE space {fespace} each carry all of {names:?}; the zone \
                 is ambiguous — fuse them with element_field::consolidate"
            ))),
        }
    }

    /// Build an `ElementField` with an explicit `components` list per
    /// subspace. `components_per_subspace.len()` must equal
    /// `fespace.len()`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::{ElementField, SubElementField};
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// // A list of components **per zone**: that is what lets a
    /// // modèle multi-physique de porter `k` ici et `E`, `nu` là.
    /// let f = ElementField::with(&fes, &[vec!["k".into()]])?;
    /// assert_eq!(f.get(0)?.read().components(), &["k".to_string()]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn with(
        fespace: &FiniteElementSpace,
        components_per_subspace: &[Vec<String>],
    ) -> Result<Self> {
        let n_sub = fespace.len();
        if n_sub == 0 {
            return Err(PyrucastError::Message(
                "ElementField: FE space has no subspace".into(),
            ));
        }
        if components_per_subspace.len() != n_sub {
            return Err(PyrucastError::Message(format!(
                "ElementField: {} component list(s) supplied for {} subspace(s)",
                components_per_subspace.len(),
                n_sub
            )));
        }
        // Through `add_sub`: a subspace listed twice may carry two component
        // lists, never the same component twice.
        let mut field = Self::default();
        for (i, comps) in components_per_subspace.iter().enumerate() {
            let sub = fespace.get(i)?;
            field.add_sub(Handle::new(SubElementField::new(sub, comps.clone())?))?;
        }
        Ok(field)
    }

    /// The finite-element space this field lives on: each zone's subspace,
    /// **one per zone, in order** — `f.support()[i]` is `f[i].support()`,
    /// shared, not copied. A field built by [`ElementField::new`] on `fes`
    /// gives back `fes`'s subspaces, so a field created on the result combines
    /// point by point with this one. Two zones on one subspace list it twice;
    /// a union of the result with itself keeps each subspace once.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::ElementField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// let k = ElementField::new(&fes, vec!["k".into()])?;
    /// // Back from the field to its space: the same subspace, not a copy.
    /// assert!(k.support().get(0)?.same_object(&fes.get(0)?));
    /// // One subspace per zone: a second zone on it lists it a second time.
    /// let both = k.union(&ElementField::new(&fes, vec!["E".into()])?)?;
    /// assert_eq!(both.support().len(), 2);
    /// assert_eq!(both.support().union(&both.support())?.len(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn support(&self) -> FiniteElementSpace {
        let mut fes = FiniteElementSpace::empty();
        for h in self {
            // Same `Coords` for every zone (`check_push`), hence for the space.
            fes.push(h.read().support());
        }
        fes
    }

    /// Visualize this field on its own support: each zone knows its
    /// submesh through its FE subspace, so the mesh is reconstructed
    /// (shared, not copied) and coloured by `component` — per-element
    /// nodal fit of the Gauss values, discontinuities preserved.
    /// `smooth` is the subdivision level (`0` = flat per cell).
    #[cfg(feature = "viz")]
    pub fn plot(
        &self,
        view: crate::viz::View,
        save: Option<&std::path::Path>,
        component: Option<&str>,
        scale: crate::viz::ColorScale,
        smooth: usize,
        title: Option<&str>,
    ) -> Result<()> {
        let mut mesh = crate::containers::mesh::Mesh::empty();
        for h in self {
            let fespace = h.read().support();
            let sm = fespace.read().submesh();
            mesh.add_sub(sm)?;
        }
        crate::viz::render_mesh_with_field(
            &mesh,
            crate::viz::FieldArg::Element(self),
            component,
            scale,
            smooth,
            view,
            save,
            title,
        )
    }
}

/// Zero-copy view of an [`ElementField`]'s zones — the
/// [`crate::containers::field::FieldView`] aggregate view specialised
/// to Gauss-point fields (built by `Field::view`). A zone is resolved
/// from its support submesh by handle identity
/// ([`Handle::same_object`]), the reciprocal of
/// [`ElementField::sub_for_fespace`].
pub(crate) type ElementFieldView = crate::containers::field::FieldView<SubElementField>;

impl ElementFieldView {
    /// The zone supported on `submesh` (matched through the zone's FE
    /// subspace), or `None` if no zone lives on it.
    pub(crate) fn zone_for_submesh(
        &self,
        submesh: &Handle<crate::containers::mesh::SubMesh>,
    ) -> Option<&SubElementField> {
        for z in &self.zones {
            let sm = z.support().read().submesh();
            if sm.same_object(submesh) {
                return Some(z);
            }
        }
        None
    }

    /// The zones of this view that hold at least one cell of `target`, among
    /// those carrying a component of `reads`, each with the rank of every cell
    /// of `target` in it: see [`Overlaps`].
    ///
    /// A zone takes part only under the **same finite-element definition** as
    /// `target` — same element type, interpolation and quadrature — checked
    /// once per zone before any cell is looked at. Such a zone holds a cell of
    /// `target` when it holds the same cell: the same nodes in the same order.
    /// A zone on the same `SubMesh` as `target` holds cell `t` as its own cell
    /// `t`. Any other is searched cell by cell of `target`, in parallel,
    /// through a table of its cells built once per `SubMesh`. `target` stands
    /// on the `Coords` of the view: on another one, a node id names another
    /// node.
    ///
    /// The pendant of `NodeFieldView::overlaps`; the copy that follows is
    /// [`gather_rows`](crate::containers::field::FieldView::gather_rows).
    pub(crate) fn overlaps(
        &self,
        target: &Handle<SubFiniteElementSpace>,
        reads: &[Vec<u32>],
    ) -> Overlaps {
        let (definition, target_mesh) = {
            let t = target.read();
            (
                (t.element_type(), t.interpolation(), t.quadrature()),
                t.submesh(),
            )
        };
        let sources: Vec<(usize, Handle<SubMesh>)> = self
            .zones
            .iter()
            .zip(reads)
            .enumerate()
            .filter(|(_, (_, idx))| idx.iter().any(|&ci| ci != ABSENT_COMPONENT))
            .filter_map(|(z, (zone, _))| {
                let support = zone.support();
                let s = support.read();
                let same = (s.element_type(), s.interpolation(), s.quadrature()) == definition;
                same.then(|| (z, s.submesh()))
            })
            .collect();
        let npc = definition.0.nodes_per_cell();
        let guard = target_mesh.read();
        let cells = guard.connectivity();
        Overlaps::new(&target_mesh, sources, |_, source| {
            let source = source.read();
            // From the last cell to the first: a cell listed twice finds its
            // first.
            let table: HashMap<&[NodeId], u32> = source
                .connectivity()
                .chunks_exact(npc)
                .enumerate()
                .rev()
                .map(|(i, cell)| (cell, i as u32))
                .collect();
            cells
                .par_chunks_exact(npc)
                .with_min_len((MIN_PARALLEL_LEN / npc).max(1))
                .map(|cell| table.get(cell).copied().unwrap_or(ABSENT_ROW))
                .collect()
        })
    }
}

// ─── Unit tests ────────────────────────────────────────────────────────────

// ─── Archive ────────────────────────────────────────────────────────────────

impl crate::archive::Archivable for SubElementField {
    const TAG: &'static str = "SubElementField";
}

impl crate::archive::Archivable for ElementField {
    const TAG: &'static str = "ElementField";
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::ElementType;
    use crate::atoms::Interpolation;
    use crate::atoms::Node;
    use crate::atoms::QuadratureRule;
    use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::coords::Coords;
    use crate::handle::Handle;

    fn make_tri3_subfespace() -> Handle<SubFiniteElementSpace> {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let sm = {
            let mut sm = SubMesh::new(coords, ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
            Handle::new(sm)
        };
        Handle::new(
            SubFiniteElementSpace::new(sm, Interpolation::Lagrange1, QuadratureRule::Gauss)
                .unwrap(),
        )
    }

    fn make_multi_cell_tri3_subfespace(n_cells: usize) -> Handle<SubFiniteElementSpace> {
        // n_cells triangles sharing a common apex, like a fan from origin.
        let coords = Handle::new(Coords::new(2).unwrap());
        let apex = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let mut perimeter = Vec::with_capacity(n_cells + 1);
        for i in 0..=n_cells {
            let t = i as f64 / n_cells as f64;
            perimeter.push(Node::create_in(coords.clone(), &[1.0, t]).unwrap());
        }
        let sm = {
            let mut sm = SubMesh::new(coords, ElementType::TRI3);
            for i in 0..n_cells {
                sm.add_cell(&[apex.id(), perimeter[i].id(), perimeter[i + 1].id()])
                    .unwrap();
            }
            Handle::new(sm)
        };
        Handle::new(
            SubFiniteElementSpace::new(sm, Interpolation::Lagrange1, QuadratureRule::Gauss)
                .unwrap(),
        )
    }

    fn make_mesh_with_tri_and_qua() -> Mesh {
        let coords = Handle::new(Coords::new(2).unwrap());
        let n0 = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let n1 = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let n2 = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let n3 = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let mut mesh = Mesh::empty();
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[n0.id(), n1.id(), n2.id()]).unwrap();
            Handle::new(sm)
        };
        let sm_qua = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
            sm.add_cell(&[n0.id(), n1.id(), n3.id(), n2.id()]).unwrap();
            Handle::new(sm)
        };
        mesh.add_sub(sm_tri).unwrap();
        mesh.add_sub(sm_qua).unwrap();
        mesh
    }

    // ── SubElementField ─────────────────────────────────────────────────────

    /// A strain and a temperature gradient side by side on one space: each
    /// reader gets its own zone, a lone zone is handed over whatever it
    /// carries, and names that single out nothing are an error.
    #[test]
    fn a_reader_takes_the_zone_carrying_what_it_reads() {
        let fes = make_tri3_subfespace();
        let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        let strain = SubElementField::new(fes.clone(), names(&["eps_xx", "eps_yy"])).unwrap();
        let gradient = SubElementField::new(fes.clone(), names(&["grad_T_x"])).unwrap();
        let mut both = ElementField::empty();
        both.add_sub(Handle::new(strain)).unwrap();
        both.add_sub(Handle::new(gradient)).unwrap();

        let got = both
            .sub_for_fespace_reading(&fes, &names(&["grad_T_x"]))
            .unwrap();
        assert_eq!(got.read().components(), names(&["grad_T_x"]).as_slice());
        let got = both
            .sub_for_fespace_reading(&fes, &names(&["eps_xx"]))
            .unwrap();
        assert_eq!(
            got.read().components(),
            names(&["eps_xx", "eps_yy"]).as_slice()
        );
        let err = both
            .sub_for_fespace_reading(&fes, &names(&["sigma_xx"]))
            .unwrap_err();
        assert!(format!("{err}").contains("none carries"), "{err}");

        let mut alone = ElementField::empty();
        let lone = SubElementField::new(fes.clone(), names(&["eps_xx"])).unwrap();
        alone.add_sub(Handle::new(lone)).unwrap();
        assert!(alone
            .sub_for_fespace_reading(&fes, &names(&["sigma_xx"]))
            .is_ok());
    }

    #[test]
    fn sub_new_zero_initialized() {
        let sub = make_tri3_subfespace();
        let f = SubElementField::new(sub, vec!["E".into(), "nu".into()]).unwrap();
        assert_eq!(f.cell_count(), 1);
        assert_eq!(f.gauss_count(), 3);
        assert_eq!(f.component_count(), 2);
        for g in 0..3 {
            assert_eq!(f.get(0, g, 0).unwrap(), 0.0);
            assert_eq!(f.get(0, g, 1).unwrap(), 0.0);
        }
    }

    #[test]
    fn sub_new_rejects_empty_components() {
        let sub = make_tri3_subfespace();
        assert!(SubElementField::new(sub, vec![]).is_err());
    }

    #[test]
    fn sub_new_rejects_duplicate_components() {
        let sub = make_tri3_subfespace();
        assert!(SubElementField::new(sub, vec!["E".into(), "E".into()]).is_err());
    }

    #[test]
    fn sub_get_set_roundtrip() {
        let sub = make_multi_cell_tri3_subfespace(3);
        let mut f = SubElementField::new(sub, vec!["sigma_xx".into(), "sigma_yy".into()]).unwrap();
        assert_eq!(f.cell_count(), 3);
        f.set(0, 0, 0, 1.0).unwrap();
        f.set(1, 2, 1, -3.5).unwrap();
        assert_eq!(f.get(0, 0, 0).unwrap(), 1.0);
        assert_eq!(f.get(1, 2, 1).unwrap(), -3.5);
        assert_eq!(f.get(0, 0, 1).unwrap(), 0.0);
    }

    #[test]
    fn sub_value_and_set_value_by_name() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["T".into(), "P".into()]).unwrap();
        f.set_value(0, 1, "P", 42.0).unwrap();
        assert_eq!(f.value(0, 1, "P").unwrap(), 42.0);
        assert!(f.value(0, 0, "unknown").is_err());
        assert!(f.set_value(0, 0, "unknown", 1.0).is_err());
    }

    #[test]
    fn sub_point_values_returns_all_components() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["a".into(), "b".into(), "c".into()]).unwrap();
        f.set(0, 1, 0, 1.0).unwrap();
        f.set(0, 1, 1, 2.0).unwrap();
        f.set(0, 1, 2, 3.0).unwrap();
        assert_eq!(f.point_values(0, 1).unwrap(), &[1.0, 2.0, 3.0]);
    }

    #[test]
    fn sub_out_of_bounds_errors() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        assert!(f.get(99, 0, 0).is_err());
        assert!(f.get(0, 99, 0).is_err());
        assert!(f.get(0, 0, 99).is_err());
        assert!(f.set(99, 0, 0, 0.0).is_err());
        assert!(f.point_values(99, 0).is_err());
    }

    #[test]
    fn sub_set_uniform_fills_every_point_of_one_component() {
        let sub = make_multi_cell_tri3_subfespace(2);
        let mut f = SubElementField::new(sub, vec!["E".into(), "nu".into()]).unwrap();
        f.set_uniform("E", 210e9).unwrap();
        for cell in 0..2 {
            for g in 0..3 {
                assert_eq!(f.get(cell, g, 0).unwrap(), 210e9);
                assert_eq!(f.get(cell, g, 1).unwrap(), 0.0);
            }
        }
    }

    #[test]
    fn sub_set_cell_uniform_touches_only_one_cell() {
        let sub = make_multi_cell_tri3_subfespace(2);
        let mut f = SubElementField::new(sub, vec!["rho".into()]).unwrap();
        f.set_cell_uniform(1, "rho", 7800.0).unwrap();
        for g in 0..3 {
            assert_eq!(f.get(0, g, 0).unwrap(), 0.0);
            assert_eq!(f.get(1, g, 0).unwrap(), 7800.0);
        }
    }

    #[test]
    fn sub_from_uniform_per_component_constructor() {
        let sub = make_tri3_subfespace();
        let f = SubElementField::from_uniform_per_component(
            sub,
            vec!["E".into(), "nu".into(), "rho".into()],
            &[210e9, 0.3, 7800.0],
        )
        .unwrap();
        for g in 0..3 {
            assert_eq!(f.get(0, g, 0).unwrap(), 210e9);
            assert_eq!(f.get(0, g, 1).unwrap(), 0.3);
            assert_eq!(f.get(0, g, 2).unwrap(), 7800.0);
        }
    }

    #[test]
    fn sub_from_uniform_per_component_length_mismatch_errors() {
        let sub = make_tri3_subfespace();
        assert!(SubElementField::from_uniform_per_component(
            sub,
            vec!["a".into(), "b".into()],
            &[1.0]
        )
        .is_err());
    }

    #[test]
    fn sub_component_scalar_ops_isolate_components() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["a".into(), "b".into()]).unwrap();
        f.set_uniform("a", 10.0).unwrap();
        f.set_uniform("b", 1.0).unwrap();
        f.add_to_component("a", 5.0).unwrap();
        f.sub_to_component("a", 2.0).unwrap();
        f.mul_to_component("a", 3.0).unwrap();
        f.div_to_component("a", 13.0).unwrap();
        // a went 10 → 15 → 13 → 39 → 3.0
        for g in 0..3 {
            assert!((f.get(0, g, 0).unwrap() - 3.0).abs() < 1e-12);
            assert_eq!(f.get(0, g, 1).unwrap(), 1.0); // unchanged
        }
    }

    #[test]
    fn sub_component_scalar_div_by_zero_errors() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        assert!(f.div_to_component("x", 0.0).is_err());
    }

    #[test]
    fn sub_component_scalar_unknown_name_errors() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        assert!(f.add_to_component("missing", 1.0).is_err());
        assert!(f.sub_to_component("missing", 1.0).is_err());
        assert!(f.mul_to_component("missing", 1.0).is_err());
        assert!(f.div_to_component("missing", 1.0).is_err());
    }

    #[test]
    fn sub_clone_is_independent() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        f.set(0, 0, 0, 1.0).unwrap();
        let g = f.clone();
        f.set(0, 0, 0, 99.0).unwrap();
        assert_eq!(g.get(0, 0, 0).unwrap(), 1.0);
    }

    #[test]
    fn sub_operator_add_f64_reference_keeps_self_intact() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        f.set(0, 1, 0, 4.0).unwrap();
        let g = &f + 10.0;
        assert_eq!(g.get(0, 1, 0).unwrap(), 14.0);
        assert_eq!(f.get(0, 1, 0).unwrap(), 4.0); // f unchanged
    }

    #[test]
    fn sub_operator_chained_sub_mul_div() {
        let sub = make_tri3_subfespace();
        let mut f = SubElementField::new(sub, vec!["x".into()]).unwrap();
        f.set_uniform("x", 12.0).unwrap();
        let g = (f.clone() - 2.0) * 3.0 / 2.0;
        for gp in 0..3 {
            assert!((g.get(0, gp, 0).unwrap() - 15.0).abs() < 1e-12);
        }
    }

    #[test]
    fn sub_debug_and_display() {
        let sub = make_multi_cell_tri3_subfespace(2);
        let f = SubElementField::new(sub, vec!["E".into(), "nu".into()]).unwrap();
        let d = format!("{:?}", f);
        assert!(d.contains("SubElementField"));
        assert!(d.contains("cell_count"));
        assert!(d.contains("E"));
        let s = format!("{}", f);
        assert!(s.contains("SubElementField"));
        assert!(s.contains("2 cell(s)"));
        assert!(s.contains("3 gauss"));
        assert!(s.contains("2 component(s)"));
        assert!(s.contains("E, nu"));
    }

    // ── ElementField (aggregate) ────────────────────────────────────────────

    #[test]
    fn ef_new_creates_one_subfield_per_subspace() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["E".into(), "nu".into()]).unwrap();
        assert_eq!(ef.len(), 2);

        // TRI3: 1 cell × 3 gauss × 2 components
        {
            let s = ef.get(0).unwrap().read();
            assert_eq!(s.cell_count(), 1);
            assert_eq!(s.gauss_count(), 3);
            assert_eq!(s.component_count(), 2);
            assert_eq!(s.components(), &["E", "nu"]);
        }

        // QUA4: 1 cell × 4 gauss × 2 components
        {
            let s = ef.get(1).unwrap().read();
            assert_eq!(s.cell_count(), 1);
            assert_eq!(s.gauss_count(), 4);
            assert_eq!(s.component_count(), 2);
        }
    }

    #[test]
    fn ef_with_supports_per_subspace_components() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let comps = vec![vec!["k".into()], vec!["E".into(), "nu".into()]];
        let ef = ElementField::with(&fes, &comps).unwrap();
        assert_eq!(ef.len(), 2);
        assert_eq!(ef.get(0).unwrap().read().components(), &["k"]);
        assert_eq!(ef.get(1).unwrap().read().components(), &["E", "nu"]);
    }

    #[test]
    fn ef_with_rejects_mismatched_length() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let comps_one = vec![vec!["k".into()]];
        assert!(ElementField::with(&fes, &comps_one).is_err());
        let comps_three = vec![vec!["k".into()], vec!["k".into()], vec!["k".into()]];
        assert!(ElementField::with(&fes, &comps_three).is_err());
    }

    #[test]
    fn ef_subfield_out_of_bounds_errors() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
        mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["k".into()]).unwrap();
        assert!(ef.get(5).is_err());
    }

    #[test]
    fn ef_aggregate_iter_and_index() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["k".into()]).unwrap();
        // Iteration walks all subfields in order.
        let counts: Vec<usize> = ef.into_iter().map(|h| h.read().gauss_count()).collect();
        assert_eq!(counts, vec![3, 4]);
        // Indexing matches subfield().
        let _h = &ef[0];
    }

    #[test]
    fn ef_subfields_are_mutated_independently() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["k".into()]).unwrap();
        ef.get(0).unwrap().write().set_uniform("k", 1.5).unwrap();
        ef.get(1).unwrap().write().set_uniform("k", 2.5).unwrap();
        assert_eq!(ef.get(0).unwrap().read().value(0, 0, "k").unwrap(), 1.5);
        assert_eq!(ef.get(1).unwrap().read().value(0, 0, "k").unwrap(), 2.5);
    }

    #[test]
    fn ef_debug_and_display() {
        let mesh = make_mesh_with_tri_and_qua();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let ef = ElementField::new(&fes, vec!["k".into()]).unwrap();
        let d = format!("{:?}", ef);
        assert!(d.contains("ElementField"));
        let s = format!("{}", ef);
        assert!(s.contains("ElementField"));
        assert!(s.contains("2 subfield"));
    }

    #[test]
    fn ef_refuses_a_zone_on_another_coords() {
        // Each helper call builds its own Coords: the same cell ids would name
        // two different triangles.
        let ici = SubElementField::new(make_tri3_subfespace(), vec!["k".into()]).unwrap();
        let ailleurs = SubElementField::new(make_tri3_subfespace(), vec!["E".into()]).unwrap();
        let mut f = ElementField::empty();
        f.add_sub(Handle::new(ici)).unwrap();
        let err = f.add_sub(Handle::new(ailleurs)).unwrap_err();
        assert!(err.to_string().contains("mismatched Coords"), "{err}");
        assert_eq!(f.len(), 1);
    }

    #[test]
    fn a_scalar_on_the_left_mirrors_the_right() {
        let zone = SubElementField::from_uniform_per_component(
            make_tri3_subfespace(),
            vec!["k".into()],
            &[1.5],
        )
        .unwrap();
        assert_eq!((2.0 * &zone).values(), (&zone * 2.0).values());
        assert_eq!((2.0 + &zone).values(), (&zone + 2.0).values());
        // Not commutative: the scalar on the left is the left operand.
        assert_eq!((1.0 - &zone).value(0, 0, "k").unwrap(), -0.5);
        assert_eq!((3.0 / &zone).value(0, 0, "k").unwrap(), 2.0);
        let mut f = ElementField::empty();
        f.add_sub(Handle::new(zone)).unwrap();
        let read = |g: ElementField| g.get(0).unwrap().read().value(0, 0, "k").unwrap();
        assert_eq!(read((2.0 * &f).unwrap()), 3.0);
        assert_eq!(read((2.0 + &f).unwrap()), 3.5);
        assert_eq!(read((1.0 - &f).unwrap()), -0.5);
        assert_eq!(read((3.0 / &f).unwrap()), 2.0);
    }

    #[test]
    fn support_gives_back_each_zones_subspace_in_order() {
        let fes = FiniteElementSpace::lagrange1(&make_mesh_with_tri_and_qua()).unwrap();
        let mat = ElementField::with(&fes, &[vec!["k".into()], vec!["E".into()]]).unwrap();
        // A second zone on the first subspace: the space lists it a second time.
        let extra = SubElementField::new(fes.get(0).unwrap(), vec!["nu".into()]).unwrap();
        let f = mat.union_sub(&Handle::new(extra)).unwrap();
        let back = f.support();
        assert_eq!(back.len(), 3);
        for (i, zone) in f.iter().enumerate() {
            assert!(back.get(i).unwrap().same_object(&zone.read().support()));
        }
        assert!(back.get(2).unwrap().same_object(&fes.get(0).unwrap()));
    }
}