pyrucast 0.12.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
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
//! Operators that **produce** a
//! [`Matrix`] — the assemblers proper.
//!
//! The nodal assemblies (`flux`, `internal_forces`) share this module's
//! machinery ([`crate::ops::scatter`], [`crate::ops::coloring`]) but end on
//! a vector, so they live in [`crate::ops::node_field`].
//!
//! The per-physics integrands live in [`crate::models`]
//! (`heat_conduction`, `dirichlet`, …). This layer orchestrates the
//! loop over sub-models, the DOF layout, and boundary-condition
//! application.
//!
//! # Material lookup
//!
//! Material data is supplied as an [`ElementField`] aggregate. For every
//! sub-model that needs material values (e.g. `HeatConduction`), the
//! assembler picks the [`SubElementField`] whose `SubFiniteElementSpace`
//! handle matches the sub-model's own FE subspace. This lets each zone
//! carry its own material — different conductivities, different
//! materials — without coupling the (declarative) model to the
//! (per-iteration, mutable) material state.
//!
//! Sub-models that don't need material data (`Dirichlet`, …) are
//! independent of the supplied `ElementField`; an `ElementField`
//! covering only some of the FE subspaces is therefore valid as long as
//! every material-hungry sub-model finds its match.

use crate::aggregate::Aggregate;
use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::{ComputedRecipe, KernelInputs, Matrix, SubMatrix};
use crate::containers::model::{Model, SubModel};
use crate::error::PyrucastError;
use crate::error::Result;
use crate::handle::Handle;
use crate::models::{Contribution, MatrixKind};
use crate::ops::element_field::behavior::previous_state_names;

/// Assemble the stiffness matrix `K` for `model`.
///
/// `materials` is an [`ElementField`] aggregate; each sub-model that
/// needs material data picks the [`SubElementField`] whose FE subspace
/// matches its own (zone-wise materials).
///
/// Each [`crate::containers::model::SubModel`] contributes one or more
/// [`crate::containers::matrix::SubMatrix`] blocks
/// (`HeatConduction` → 1 block, `Dirichlet` → C + Cᵀ).
/// The matrix is returned assembled.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{element_field, matrix};
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
/// # let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
/// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
/// # mesh.add_cell(&[a.id(), b.id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
/// # let model = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// let materials = element_field::material_field(&model, &[("k", 1.0)]).unwrap();
/// let k = matrix::stiffness(&model, &materials).unwrap();
///
/// // Un SEG2 de longueur 1, k = 1 : K = [[1, -1], [-1, 1]].
/// assert_eq!(k.n_rows().unwrap(), 2);
/// assert_eq!(k.get(a.id(), "q", a.id(), "T").unwrap(), 1.0);
/// ```
pub fn stiffness(model: &Model, materials: &ElementField) -> Result<Matrix> {
    assemble_kind(
        model,
        materials,
        MatrixKind::Stiffness,
        AssemblyInputs::MaterialOnly,
    )
}

/// What the kernels of a given [`MatrixKind`] read **besides** the material,
/// at the aggregate level — the outermost of the three forms the same fact
/// takes (`AssemblyInputs` borrows aggregates, `KernelInputs` owns per-zone
/// handles, `KernelState` borrows resolved sub-fields).
///
/// ```
/// # use pyrucast::ops::matrix::AssemblyInputs;
/// // `stiffness` and `mass` go through here; `tangent` through the variant
/// // that carries the law's inputs.
/// assert!(matches!(AssemblyInputs::MaterialOnly, AssemblyInputs::MaterialOnly));
/// ```
pub enum AssemblyInputs<'a> {
    /// Stiffness, mass.
    MaterialOnly,
    /// Geometric stiffness: the current stress.
    State(&'a ElementField),
    /// Consistent tangent: exactly what `behavior::integrate` receives.
    Behavior {
        deformation: &'a ElementField,
        prev: &'a ElementField,
        dt: Option<f64>,
    },
}

impl AssemblyInputs<'_> {
    /// The per-zone form, for the sub-model whose material lives on `fespace`.
    fn for_sub(
        &self,
        sub: &SubModel,
        fespace: &Handle<SubFiniteElementSpace>,
    ) -> Result<KernelInputs> {
        Ok(match self {
            Self::MaterialOnly => KernelInputs::MaterialOnly,
            Self::State(sf) => {
                let reads = match sub.as_kind().as_domain() {
                    Some(domain) => domain.element_state_reads(MatrixKind::Geometric),
                    None => Vec::new(),
                };
                KernelInputs::State(sf.sub_for_fespace_reading(fespace, &reads)?)
            }
            Self::Behavior {
                deformation,
                prev,
                dt,
            } => {
                let dt = match (dt, sub.requires_dt()) {
                    (Some(dt), _) => *dt,
                    (None, false) => 0.0,
                    (None, true) => {
                        return Err(PyrucastError::Message(format!(
                            "{}: this law is rate-dependent and needs a time increment — \
                             pass `dt` to tangent",
                            sub.as_kind().label()
                        )))
                    }
                };
                let law = sub.as_kind().as_behavior().ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "{}: a tangent needs a behaviour",
                        sub.as_kind().label()
                    ))
                })?;
                // Two laws sharing the subspace: each takes the zone it reads.
                let deformation =
                    deformation.sub_for_fespace_reading(fespace, &law.deformation_reads())?;
                let prev = prev.sub_for_fespace_reading(fespace, &previous_state_names(law))?;
                KernelInputs::Behavior {
                    deformation,
                    prev,
                    dt,
                }
            }
        })
    }
}

/// Assemble the element matrix of a given [`MatrixKind`] for `model` — the
/// shared engine behind [`stiffness`] (and, for the state-dependent kinds, the
/// geometric-stiffness and consistent-tangent assemblers).
///
/// The whole *computed → scatter → pattern* pipeline is matrix-agnostic: it
/// only needs, per sub-model, the block layout and the per-cell kernel to drive.
/// This function selects both by `kind` (via
/// [`SubModelKind::contributions`](crate::models::SubModelKind::contributions))
/// and threads the resolved material and — for `Geometric` / `Tangent` — the
/// per-sub-model `state` sub-field into each block's
/// [`ComputedRecipe`]. `state` is an [`ElementField`] aggregate (current stress
/// / algorithmic tangent) resolved zone-wise like `materials`, or `None` for the
/// state-free kinds.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::ElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::MatrixKind;
/// # use pyrucast::ops::{element_field, matrix, mesh, scatter};
/// # use pyrucast::ops::model;
/// # 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 maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let modele = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let materiaux = element_field::material_field(&modele,
/// #     &[("k", 1.0), ("rho", 2.0), ("cp", 3.0)]).unwrap();
/// // A single machinery for the four kinds: `stiffness` and `mass` are only
/// // its named forms.
/// let k = matrix::assemble_kind(&modele, &materiaux, MatrixKind::Stiffness, matrix::AssemblyInputs::MaterialOnly)?;
/// assert_eq!(k.to_dmatrix()?, matrix::stiffness(&modele, &materiaux)?.to_dmatrix()?);
/// let m = matrix::assemble_kind(&modele, &materiaux, MatrixKind::Mass, matrix::AssemblyInputs::MaterialOnly)?;
/// // The capacity sums to ρ·c_p × area; the conduction sums to zero.
/// assert!((m.to_dmatrix()?.sum() - 2.0 * 3.0 * 0.5).abs() < 1e-9);
/// assert!(k.to_dmatrix()?.sum().abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn assemble_kind(
    model: &Model,
    materials: &ElementField,
    kind: MatrixKind,
    inputs: AssemblyInputs,
) -> Result<Matrix> {
    let mut k = Matrix::empty();

    // Pass 1 — add every block. Each sub-model declares its
    // [`Contribution`](crate::models::Contribution)s for this `kind`; the
    // assembler folds them in without a per-type `match`. A `Computed`
    // contribution (volumetric physics) becomes a recipe-carrying block
    // scattered straight into the CSR; a `Literal` one (Dirichlet, any
    // multi-block physics — stiffness only) carries its values.
    for sub_h in model {
        // Build the contribution(s) under a read guard, then drop it before
        // `add_sub` (which takes the aggregate's write lock).
        let built = {
            let sub = sub_h.read();
            // A physics whose tangent *is* its stiffness answers a tangent
            // request with its stiffness, inputs and all: the deformation and
            // state the tangent carries are for the laws that need them.
            let tangent_by_stiffness =
                kind == MatrixKind::Tangent && sub.as_kind().tangent_is_stiffness();
            let sub_kind = if tangent_by_stiffness {
                MatrixKind::Stiffness
            } else {
                kind
            };
            // Generic over the physics: a sub-model needs material data iff it
            // declares a material FE subspace. No per-variant match.
            let material = match sub.material_fespace() {
                Some(fespace) => {
                    // Resolve the material zone by the components this physics
                    // needs, so a shared fespace carrying several
                    // component-disjoint material zones (e.g. thermal `k` +
                    // mechanical `E`/`nu` on one mesh) resolves each physics'
                    // own zone without an explicit consolidate.
                    let m = match sub.material_components() {
                        Some(required) => materials.sub_for_fespace_with(&fespace, &required)?,
                        None => materials.sub_for_fespace(&fespace)?,
                    };
                    Some(m)
                }
                None => None,
            };
            let contributions = sub.as_kind().contributions(sub_kind, material.as_ref())?;
            // Resolve the sub-model's own state sub-field (stress / tangent) the
            // same way, when a state aggregate is supplied and the physics reads
            // material on a cell fespace. A sub-model with no block of this kind
            // — a load asked for a geometric stiffness — reads nothing, and
            // must not be asked for a state it never had.
            let kernel_inputs = match sub.material_fespace() {
                Some(fespace) if !tangent_by_stiffness && !contributions.is_empty() => {
                    inputs.for_sub(&sub, &fespace)?
                }
                _ => KernelInputs::MaterialOnly,
            };
            let mut blocks = Vec::new();
            for c in contributions {
                blocks.extend(build_contribution(
                    c,
                    sub_h,
                    material.clone(),
                    sub_kind,
                    kernel_inputs.clone(),
                )?);
            }
            blocks
        };
        for block in built {
            k.add_sub(Handle::new(block))?;
        }
    }

    // Pass 2 — global assembly, injected via `set_assembled`: the global
    // assembler lives here, not in `Matrix`, since a container does not
    // depend on the models' kernels. The CSR sparsity ([`crate::ops::scatter::build_pattern`]) is a
    // function of the model's block topology for this `kind`, so it is memoised
    // per kind on the model and reused across assemblies; the values are
    // scattered into it in parallel by cell colour ([`crate::ops::scatter::scatter_parallel`]).
    let pattern = model.matrix_pattern(kind, || crate::ops::scatter::build_pattern(&k))?;
    let values = crate::ops::scatter::scatter_parallel(&k, pattern.as_ref())?;
    k.set_assembled(
        pattern.vars.clone(),
        pattern.row_keys.clone(),
        pattern.col_keys.clone(),
        pattern.assembled_csr(values),
    );
    Ok(k)
}

// The composition path lives here rather than in `containers/matrix.rs`: it
// needs the scatter machinery of `ops/`, and a container must not depend on an
// operator. Rust lets an inherent `impl` sit in any module of the defining
// crate, so `Matrix` gains the method without the container gaining the
// dependency.
impl Matrix {
    /// Assemble this matrix **from its blocks alone** — no `Model` — on the
    /// configuration active now.
    ///
    /// A matrix is assembled once: one that already is keeps its values, and
    /// this does nothing. The values of another configuration come from a new
    /// matrix.
    ///
    /// The sparsity is built from the blocks
    /// ([`crate::ops::scatter::build_pattern`], self-contained: a computed
    /// block resolves its fill through its recipe, a written block through its
    /// COO) and the values are scattered into it. This is the path of a matrix
    /// whose blocks were put together without their values: written by hand,
    /// `add_sub`, `|`, `filter`, `exclude` — which [`stiffness`] cannot reach
    /// (it only knows a `Model`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::matrix::{DofOrdering, Matrix, SubMatrix, Symmetry};
    /// # use pyrucast::containers::mesh::SubMesh;
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(1).unwrap());
    /// # let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
    /// # let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
    /// # let support = {
    /// #     let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
    /// #     sm.add_cell(&[a.id()]).unwrap();
    /// #     sm.add_cell(&[b.id()]).unwrap();
    /// #     Handle::new(sm)
    /// # };
    /// # let mut bloc = SubMatrix::new(
    /// #     support.clone(), support.clone(), vec!["q".into()], vec!["T".into()],
    /// #     DofOrdering::NodesThenVars, Symmetry::Full).unwrap();
    /// # bloc.add_entry(a.id(), "q", a.id(), "T", 2.0).unwrap();
    /// # bloc.add_entry(a.id(), "q", b.id(), "T", -1.0).unwrap();
    /// # bloc.add_entry(b.id(), "q", a.id(), "T", -1.0).unwrap();
    /// # bloc.add_entry(b.id(), "q", b.id(), "T", 2.0).unwrap();
    /// let mut k = Matrix::empty();
    /// k.add_sub(Handle::new(bloc))?;
    /// // The size reads off the blocks, without assembly…
    /// assert_eq!((k.n_rows()?, k.n_cols()?), (2, 2));
    /// // …but the values exist only once the matrix is assembled.
    /// assert!(k.to_csr().is_err());
    /// k.assemble()?;
    /// assert_eq!(k.to_csr()?.nnz(), 4);
    /// // Once is enough: a second call reassembles nothing.
    /// k.assemble()?;
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    ///
    /// Unlike [`stiffness`], this does not consult the model's cached pattern
    /// (there is no model here), so it builds the sparsity each call — fine
    /// for the occasional composition; hot repeated assembly of a fixed model
    /// should keep going through [`stiffness`].
    pub fn assemble(&mut self) -> Result<()> {
        if self.is_assembled() {
            return Ok(());
        }
        let pattern = crate::ops::scatter::build_pattern(self)?;
        let values = crate::ops::scatter::scatter_parallel(self, &pattern)?;
        let csr = pattern.assembled_csr(values);
        self.set_assembled(pattern.vars, pattern.row_keys, pattern.col_keys, csr);
        Ok(())
    }
}

/// Turn one [`Contribution`] into a [`SubMatrix`] block ready to add to the
/// aggregate. A `Computed` contribution is wrapped into a recipe-carrying block
/// (material resolved by the assembler, sub-model handle threaded in); a
/// `Literal` one is passed through as-is. Yields a `Vec` because a single
/// literal contribution may carry several blocks (Dirichlet's C / Cᵀ).
fn build_contribution(
    contribution: Contribution,
    sub_h: &Handle<SubModel>,
    material: Option<Handle<SubElementField>>,
    kind: MatrixKind,
    inputs: KernelInputs,
) -> Result<Vec<SubMatrix>> {
    let mut blocks = match contribution {
        Contribution::Computed(layout) => {
            let recipe = ComputedRecipe {
                submodel: sub_h.clone(),
                fespaces: layout.fespaces,
                material,
                kind,
                inputs,
                col_fespaces: Vec::new(),
            };
            vec![SubMatrix::computed(
                layout.support.clone(),
                layout.support,
                layout.dual_vars,
                layout.primal_vars,
                layout.ordering,
                layout.symmetry,
                recipe,
            )?]
        }
        // An inter-mesh block: same computed path, but rows and columns on
        // different supports. Never symmetric on its own — the law declares its
        // two off-diagonal blocks a pair, exactly as Dirichlet does for C / Cᵀ,
        // and the aggregate checks both are present.
        Contribution::Coupling(layout) => {
            let recipe = ComputedRecipe {
                submodel: sub_h.clone(),
                fespaces: layout.fespaces,
                material,
                kind,
                inputs,
                col_fespaces: layout.col_fespaces,
            };
            vec![SubMatrix::computed(
                layout.row_support,
                layout.col_support,
                layout.dual_vars,
                layout.primal_vars,
                layout.ordering,
                layout.symmetry,
                recipe,
            )?]
        }
        Contribution::Literal(blocks) => blocks,
    };
    // Tag every emitted block with its sub-model's physics nature set — computed
    // and literal alike (so a Dirichlet C/Cᵀ pair is tagged too) — for
    // Matrix::filter.
    let physics = sub_h.read().physics().to_vec();
    for b in &mut blocks {
        b.set_physics(physics.clone());
    }
    Ok(blocks)
}

/// Assemble the consistent **mass** matrix `M` for `model` (Cast3M `MASS`), or
/// the **heat-capacity** matrix `C` for a thermal model (Cast3M `CAPA`).
///
/// Mechanics contributes `M = ∫ ρ Nᵀ N` (material `rho`); heat conduction
/// contributes `C = ∫ ρ cp Nᵀ N` (material `rho`, `cp`). A physics with no mass
/// term (a boundary Robin/convection term, or a Lagrange constraint) contributes
/// nothing. `materials` supplies the density/heat coefficients zone-wise, exactly
/// like [`stiffness`].
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{element_field, matrix};
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
/// # let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
/// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
/// # mesh.add_cell(&[a.id(), b.id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
/// # let model = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// // A conduction's capacity matrix reads `rho` **and** `cp`: it is ρ·c_p
/// // that multiplies ∫ Nᵀ N, not the density alone.
/// let materials =
///     element_field::material_field(&model, &[("k", 1.0), ("rho", 2.0), ("cp", 1.0)]).unwrap();
/// let m = matrix::mass(&model, &materials).unwrap();
///
/// // Capacité totale d'un SEG2 de longueur 1, ρ = 2, c_p = 1 : 2.
/// let total: f64 = m.to_dmatrix().unwrap().sum();
/// assert!((total - 2.0).abs() < 1e-12);
/// ```
pub fn mass(model: &Model, materials: &ElementField) -> Result<Matrix> {
    assemble_kind(
        model,
        materials,
        MatrixKind::Mass,
        AssemblyInputs::MaterialOnly,
    )
}

/// Assemble the **geometric (initial-stress) stiffness** `K_g` for `model`
/// (Cast3M `KSIG`): `K_g = ∫ Gᵀ σ̂ G`, the stress-stiffening term for buckling
/// and prestress analyses.
///
/// `stress` is the current Cauchy-stress [`ElementField`] (Voigt-named
/// `sigma_*`, e.g. the output of [`crate::ops::element_field::behavior::integrate`]), resolved
/// zone-wise like `materials`; the kernel is law-independent given it. `materials`
/// is still used to resolve each mechanical zone (its `E`/`nu`).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # 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::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::ops::{element_field, matrix};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::QUA4));
/// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id(), n[3].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
/// # let model = model::elasticity(&fes, Kinematics::PlaneStress, MaterialSymmetry::Isotropic, StrainMeasure::Linear).unwrap();
/// # let materials =
/// #     element_field::material_field(&model, &[("E", 210.0), ("nu", 0.3)]).unwrap();
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::ops::model;
/// // A uniaxial stress σ_xx = 3, carried at the Gauss points.
/// let mut stress =
///     ElementField::new(&fes, vec!["sigma_xx".into(), "sigma_yy".into(), "sigma_xy".into()])
///         .unwrap();
/// stress.get(0).unwrap().write().set_uniform("sigma_xx", 3.0).unwrap();
///
/// let kg = matrix::geometric(&model, &materials, &stress).unwrap();
/// assert_eq!(kg.n_rows().unwrap(), kg.n_cols().unwrap());
/// ```
pub fn geometric(model: &Model, materials: &ElementField, stress: &ElementField) -> Result<Matrix> {
    assemble_kind(
        model,
        materials,
        MatrixKind::Geometric,
        AssemblyInputs::State(stress),
    )
}

/// Assemble the **consistent (algorithmic) tangent** `K_t = ∫ Bᵀ D_alg B` for
/// `model` (Cast3M `KTAN`) — the operator that gives quadratic Newton
/// convergence for a non-linear law.
///
/// `D_alg` is evaluated **at the Gauss point**, from the inputs
/// [`crate::ops::element_field::behavior::integrate`] takes: the end-of-step
/// `deformation`, the state at A `prev` —
/// [`initial_state`](fn@crate::ops::element_field::behavior::initial_state) on
/// a first step — and `dt`. No modulus field is materialized: it would have had
/// this assembler as its only reader. `materials` resolves each zone exactly
/// like [`stiffness`].
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # 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::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::ops::{element_field, matrix};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::QUA4));
/// # mesh.add_cell(&[n[0].id(), n[1].id(), n[2].id(), n[3].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
/// # let model = model::elasticity(&fes, Kinematics::PlaneStress, MaterialSymmetry::Isotropic, StrainMeasure::Linear).unwrap();
/// # let materials =
/// #     element_field::material_field(&model, &[("E", 210.0), ("nu", 0.3)]).unwrap();
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::ops::model;
/// // Elasticity: its tangent is constant, and the stiffness comes back —
/// // without any modulus field having been materialized to carry it there.
/// let strain = ElementField::new(
///     &fes, vec!["eps_xx".into(), "eps_yy".into(), "eps_xy".into()]).unwrap();
/// let repos = element_field::behavior::initial_state(&model, &materials).unwrap();
/// let kt = matrix::tangent(&model, &materials, &strain, &repos, None).unwrap();
/// let k = matrix::stiffness(&model, &materials).unwrap();
///
/// assert_eq!(kt.to_dmatrix().unwrap(), k.to_dmatrix().unwrap());
/// ```
pub fn tangent(
    model: &Model,
    materials: &ElementField,
    deformation: &ElementField,
    prev: &ElementField,
    dt: Option<f64>,
) -> Result<Matrix> {
    assemble_kind(
        model,
        materials,
        MatrixKind::Tangent,
        AssemblyInputs::Behavior {
            deformation,
            prev,
            dt,
        },
    )
}

/// **Lump** an assembled matrix into a diagonal one by **row-sum concentration**
/// (Cast3M `LUMP`): each diagonal entry becomes the sum of its row, every
/// off-diagonal is dropped. Applied to a consistent mass / heat-capacity matrix
/// it yields the diagonal (lumped) mass, which conserves the total mass
/// (`Σ_i M_lumped[i,i] = Σ_ij M[i,j]`) — the cheap, decoupled form used by
/// explicit transient schemes and simple eigen estimates.
///
/// The input must be assembled and square, row `i` and column `i` naming the
/// same node, as they do for a mass/capacity matrix. The result is a new
/// assembled [`Matrix`] with the same rows and columns, in the same order; the
/// input is untouched. It describes itself like any other matrix: one
/// diagonal block per row support of the input, carrying the variables and
/// physics of the blocks found there, so `solve`, `* x`, `filter` and a save
/// read it as they read the input.
///
/// **Errors**: a matrix that is not assembled or not square, or whose row `i`
/// and column `i` name two nodes, or pair one dual variable with two primal
/// ones.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::Model;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::{element_field, matrix};
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
/// # let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
/// # let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
/// # mesh.add_cell(&[a.id(), b.id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
/// # let model = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let materials = element_field::material_field(
/// #     &model, &[("k", 1.0), ("rho", 2.0), ("cp", 1.0)]).unwrap();
/// let m = matrix::mass(&model, &materials).unwrap();
/// let diagonale = matrix::lump(&m).unwrap();
///
/// // The sum is preserved; the off-diagonal terms are folded onto it.
/// let somme = |x: &pyrucast::containers::matrix::Matrix| -> f64 {
///     x.to_dmatrix().unwrap().sum()
/// };
/// assert!((somme(&m) - somme(&diagonale)).abs() < 1e-12);
/// assert_eq!(diagonale.get(a.id(), "q", b.id(), "T").unwrap(), 0.0);
/// ```
pub fn lump(m: &Matrix) -> Result<Matrix> {
    use crate::containers::matrix::{dof_node, dof_var, AssembledCsr, Symmetry};
    use nalgebra_sparse::CooMatrix;

    let (offsets, _, values) = m.csr_arrays()?;
    let vars = m.dof_vars();
    let row_keys = m.row_dof_keys()?;
    let col_keys = m.col_dof_keys()?;
    let n = row_keys.len();
    if col_keys.len() != n {
        return Err(PyrucastError::Message(format!(
            "lump: matrix must be square, got {}×{}",
            n,
            col_keys.len()
        )));
    }

    // One diagonal block per distinct row support of `m`, holding the dual
    // variables its blocks put there: together they hold exactly `m`'s rows.
    let mut groups: Vec<LumpedBlock> = Vec::new();
    for h in m {
        let b = h.read();
        let g = match groups
            .iter()
            .position(|g| g.support.same_object(b.row_support()))
        {
            Some(g) => g,
            None => {
                groups.push(LumpedBlock::new(
                    b.row_support().clone(),
                    b.ordering(),
                    vars.len(),
                ));
                groups.len() - 1
            }
        };
        let g = &mut groups[g];
        for d in b.dual_vars() {
            let slot = vars
                .iter()
                .position(|v| v == d)
                .expect("the name table holds every variable of the blocks");
            if g.rank[slot] == NONE {
                g.rank[slot] = g.duals.len();
                g.duals.push(slot);
            }
        }
        for &p in b.physics() {
            if !g.physics.contains(&p) {
                g.physics.push(p);
            }
        }
    }

    // Row by row: its sum, and its place in the first block whose support and
    // variables hold it. The primal variable of each dual one is read off
    // column `i`, which must name the same node.
    let supports: Vec<_> = groups.iter().map(|g| g.support.read()).collect();
    let mut entries: Vec<Vec<(usize, f64)>> = groups
        .iter()
        .zip(&supports)
        .map(|(g, s)| Vec::with_capacity(s.cell_count() * g.duals.len()))
        .collect();
    let mut primal_of = vec![NONE; vars.len()];
    let mut diag_values = Vec::with_capacity(n);
    'rows: for i in 0..n {
        let (row, col) = (row_keys[i], col_keys[i]);
        let node = dof_node(row);
        let (dual, primal) = (dof_var(row) as usize, dof_var(col) as usize);
        if dof_node(col) != node || (primal_of[dual] != NONE && primal_of[dual] != primal) {
            return Err(PyrucastError::Message(format!(
                "lump: row {i} and column {i} do not pair one degree of freedom \
                 with its conjugate (same node, one primal per dual variable); \
                 only a mass-like matrix can be lumped"
            )));
        }
        primal_of[dual] = primal;
        let value: f64 = values[offsets[i]..offsets[i + 1]].iter().sum();
        diag_values.push(value);
        for ((g, s), e) in groups.iter().zip(&supports).zip(&mut entries) {
            if g.rank[dual] == NONE {
                continue;
            }
            if let Some(&local) = s.node_index().get(&node) {
                let k = g
                    .ordering
                    .to_index(local, g.rank[dual], s.cell_count(), g.duals.len());
                e.push((k, value));
                continue 'rows;
            }
        }
        unreachable!("every row of a matrix comes from one of its blocks");
    }
    drop(supports);

    let mut out = Matrix::empty();
    for (g, e) in groups.into_iter().zip(entries) {
        let size = g.support.read().cell_count() * g.duals.len();
        let (idx, vals): (Vec<usize>, Vec<f64>) = e.into_iter().unzip();
        let coo = CooMatrix::try_from_triplets(size, size, idx.clone(), idx, vals)
            .map_err(|e| PyrucastError::Message(format!("lump: invalid COO: {e}")))?;
        let duals = g.duals.iter().map(|&d| vars[d].clone()).collect();
        let primals = g
            .duals
            .iter()
            .map(|&d| vars[primal_of[d]].clone())
            .collect();
        let mut block = SubMatrix::from_coo(
            g.support.clone(),
            g.support,
            duals,
            primals,
            g.ordering,
            Symmetry::Full,
            coo,
        )?;
        block.set_physics(g.physics);
        out.add_sub(Handle::new(block))?;
    }
    // Diagonal CSR: one entry per row, so the offsets are the row index itself.
    let diag = AssembledCsr {
        row_offsets: std::sync::Arc::new((0..=n).collect()),
        col_indices: std::sync::Arc::new((0..n).collect()),
        values: diag_values,
        ncols: n,
    };
    out.set_assembled(vars, row_keys, col_keys, diag);
    Ok(out)
}

/// Marks a variable slot that no block of the group, or no column, names yet.
const NONE: usize = usize::MAX;

/// One diagonal block of [`lump`]'s result while it is gathered: a row support
/// of the input, the dual variables the input's blocks put there (as slots of
/// the name table, `rank[slot]` being their place in the block), and their
/// physics.
struct LumpedBlock {
    support: Handle<crate::containers::mesh::SubMesh>,
    ordering: crate::containers::matrix::DofOrdering,
    duals: Vec<usize>,
    rank: Vec<usize>,
    physics: Vec<crate::models::Physics>,
}

impl LumpedBlock {
    fn new(
        support: Handle<crate::containers::mesh::SubMesh>,
        ordering: crate::containers::matrix::DofOrdering,
        n_vars: usize,
    ) -> Self {
        Self {
            support,
            ordering,
            duals: Vec::new(),
            rank: vec![NONE; n_vars],
            physics: Vec::new(),
        }
    }
}

// ─── Delegation methods ─────────────────────────────────────────────────────
//
// See `CONVENTIONS.md` § "The verb also exposed as a method". The name changes
// between the two forms: the free function gets its qualifier from its
// module (`matrix::stiffness`), the method has none and must carry it
// (`model.stiffness_matrix`).

impl Model {
    /// See [`matrix::stiffness`](fn@crate::ops::matrix::stiffness).
    pub fn stiffness_matrix(&self, materials: &ElementField) -> Result<Matrix> {
        stiffness(self, materials)
    }

    /// See [`matrix::mass`](fn@crate::ops::matrix::mass).
    pub fn mass_matrix(&self, materials: &ElementField) -> Result<Matrix> {
        mass(self, materials)
    }

    /// See [`matrix::geometric`](fn@crate::ops::matrix::geometric).
    pub fn geometric_matrix(
        &self,
        materials: &ElementField,
        stress: &ElementField,
    ) -> Result<Matrix> {
        geometric(self, materials, stress)
    }

    /// See [`matrix::tangent`](fn@crate::ops::matrix::tangent).
    pub fn tangent_matrix(
        &self,
        materials: &ElementField,
        deformation: &ElementField,
        prev: &ElementField,
        dt: Option<f64>,
    ) -> Result<Matrix> {
        tangent(self, materials, deformation, prev, dt)
    }
}

impl Matrix {
    /// See [`matrix::lump`](fn@crate::ops::matrix::lump).
    pub fn lump(&self) -> Result<Matrix> {
        lump(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::{ElementType, Node, NodeId};
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::matrix::Symmetry;
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::coords::Coords;
    use crate::models::symmetry::MaterialSymmetry;
    use crate::ops::coords::in_config;
    use crate::ops::element_field::material_field_per_sub_model;
    use crate::ops::element_field::StrainMeasure;

    /// Assemble the stiffness the **literal** way: every sub-model fills its
    /// `SubMatrix` blocks eagerly and `assemble_written` sums them. The
    /// computed path must match it bit-for-bit: it is kept here as the
    /// reference.
    ///
    /// It reuses the [`Contribution`] seam so it stays honest: a `Literal`
    /// contribution (Dirichlet's C / Cᵀ) is taken as-is, while a `Computed` one
    /// is materialised through its physics' `build_stiffness_blocks` — the very
    /// literal kernel the scatter path is being checked against.
    fn assemble_literal_reference(model: &Model, materials: &ElementField) -> Result<Matrix> {
        let mut k = Matrix::empty();
        for sub_h in model {
            let blocks = {
                let sub = sub_h.read();
                let material = match sub.material_fespace() {
                    Some(fespace) => Some(materials.sub_for_fespace(&fespace)?),
                    None => None,
                };
                let phys = sub.as_kind();
                let mut blocks = Vec::new();
                for c in phys.contributions(MatrixKind::Stiffness, material.as_ref())? {
                    match c {
                        Contribution::Computed(_) => {
                            // A computed contribution comes from a physics with
                            // an element kernel, which declares a material FE
                            // subspace: resolved above, required here.
                            let mat = material.as_ref().ok_or_else(|| {
                                crate::error::PyrucastError::Message(format!(
                                    "{}: a computed stiffness needs material data",
                                    phys.label()
                                ))
                            })?;
                            blocks.extend(phys.build_stiffness_blocks(mat)?);
                        }
                        Contribution::Literal(bs) => blocks.extend(bs),
                        // The literal path exists as the bit-for-bit equivalence
                        // reference of the *computed* single-mesh path; an
                        // inter-mesh block has no such counterpart to compare to.
                        Contribution::Coupling(_) => {
                            return Err(crate::error::PyrucastError::Message(format!(
                                "{}: an inter-mesh coupling block has no literal form — \
                                 use the computed path (ops::matrix::stiffness)",
                                phys.label()
                            )))
                        }
                    }
                }
                blocks
            };
            for block in blocks {
                k.add_sub(Handle::new(block))?;
            }
        }
        k.assemble_written()?;
        Ok(k)
    }

    /// A single heat-conduction zone over an `n_elems`-element SEG2 chain, plus
    /// a Dirichlet constraint at the left end. Interior nodes are shared by two
    /// cells, so the zone needs a real (two-colour) cell colouring — the
    /// parallel scatter genuinely reorders per-slot summation, unlike a
    /// one-cell-per-block mesh.
    fn chain_heat_with_dirichlet(n_elems: usize) -> (Model, ElementField) {
        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = (0..=n_elems)
            .map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        for i in 0..n_elems {
            sm.add_cell(&[nodes[i].id(), nodes[i + 1].id()]).unwrap();
        }
        let mesh = Mesh::from_submesh(sm);
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(0).unwrap(), MaterialSymmetry::Isotropic)
                    .unwrap(),
            ))
            .unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&nodes[0])).unwrap());
        model
            .add_sub(Handle::new(
                SubModel::dirichlet(&imposed, &model, "T", Default::default()).unwrap(),
            ))
            .unwrap();

        let materials = material_field_per_sub_model(&model, &[&[("k", 2.0)], &[]]).unwrap();
        (model, materials)
    }

    /// Is the assembled CSR itself symmetric? Measured, not asked — this is what
    /// the declared flag is confronted with below.
    fn csr_is_symmetric(k: &Matrix) -> bool {
        let (offsets, cols, vals) = k.csr_arrays().unwrap();
        let at = |r: usize, c: usize| {
            let (lo, hi) = (offsets[r], offsets[r + 1]);
            cols[lo..hi]
                .binary_search(&c)
                .map(|i| vals[lo + i])
                .unwrap_or(0.0)
        };
        // Only square makes the question meaningful — and a matrix that lost half
        // of a constraint pair is not even square any more.
        if k.n_rows().unwrap() != k.n_cols().unwrap() {
            return false;
        }
        // Rows and columns of an assembled matrix are conjugate index for index,
        // so `(i, j)` and `(j, i)` name transposed entries.
        (0..offsets.len() - 1).all(|r| {
            (offsets[r]..offsets[r + 1]).all(|k| {
                let c = cols[k];
                (vals[k] - at(c, r)).abs() <= 1e-12 * (1.0 + vals[k].abs())
            })
        })
    }

    /// The case the whole flag exists for. A Dirichlet contributes two
    /// rectangular blocks, neither symmetric alone; before pairing was
    /// expressible, the aggregate answered `false` for every constrained
    /// matrix — that is to say for every real problem.
    #[test]
    fn a_constrained_stiffness_is_symmetric_and_says_so() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let k = stiffness(&model, &materials).unwrap();

        assert!(csr_is_symmetric(&k), "the assembled CSR must be symmetric");
        assert!(
            k.symmetric(),
            "and the declaration must agree with the measurement"
        );
    }

    /// Slicing a matrix can separate a pair. The half that remains carries no
    /// symmetry, and the aggregate must say so — the CSR agrees.
    #[test]
    fn slicing_a_pair_apart_drops_the_symmetry() {
        let (model, materials) = chain_heat_with_dirichlet(4);
        let k = stiffness(&model, &materials).unwrap();

        // Blocks: the conduction one, then the constraint's C and Cᵀ. Keeping
        // the physics and one half leaves a matrix that is genuinely not
        // symmetric any more.
        let mut halves: Vec<usize> = k
            .iter()
            .enumerate()
            .filter(|(_, h)| !matches!(h.read().symmetry(), Symmetry::Half(_)))
            .map(|(i, _)| i)
            .collect();
        halves.push(k.len() - 1);
        let mut sliced = k.subset(halves).unwrap();
        sliced.assemble().unwrap();

        assert!(!csr_is_symmetric(&sliced), "one half really breaks it");
        assert!(!sliced.symmetric(), "and the declaration follows");
    }

    /// The same constraint declared twice: four blocks, and since each
    /// declaration mints its own multiplier nodes, two identities, each with
    /// both its members. The matrix is symmetric, and the aggregate sees it.
    #[test]
    fn a_constraint_declared_twice_still_pairs_up() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = (0..=3)
            .map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        for i in 0..3 {
            sm.add_cell(&[nodes[i].id(), nodes[i + 1].id()]).unwrap();
        }
        let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(0).unwrap(), MaterialSymmetry::Isotropic)
                    .unwrap(),
            ))
            .unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&nodes[0])).unwrap());
        // Twice, on the same imposed node and the same variable: each pair on
        // multiplier nodes of its own.
        for _ in 0..2 {
            model
                .add_sub(Handle::new(
                    SubModel::dirichlet(&imposed, &model, "T", Default::default()).unwrap(),
                ))
                .unwrap();
        }
        let materials = material_field_per_sub_model(&model, &[&[("k", 2.0)], &[], &[]]).unwrap();
        let k = stiffness(&model, &materials).unwrap();

        let ids: Vec<u64> = k
            .iter()
            .filter_map(|h| match h.read().symmetry() {
                Symmetry::Half(id) => Some(id & !1),
                _ => None,
            })
            .collect();
        assert_eq!(ids.len(), 4, "four halves");
        let mut distinct = ids.clone();
        distinct.sort_unstable();
        distinct.dedup();
        assert_eq!(distinct.len(), 2, "one identity per declaration");
        assert!(
            distinct
                .iter()
                .all(|d| ids.iter().filter(|i| *i == d).count() == 2),
            "each with both its members"
        );

        assert!(csr_is_symmetric(&k));
        assert!(k.symmetric(), "two of each member is a complete pairing");
    }

    /// One TRI3 of heat conduction with a node immersed in it, plus its
    /// multiplier — five DOFs.
    fn immersed_node_in_a_triangle() -> (Model, ElementField) {
        let coords = Handle::new(Coords::new(2).unwrap());
        let corners: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
            .iter()
            .map(|c| Node::create_in(coords.clone(), c).unwrap())
            .collect();
        let mut host = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        host.add_cell(&corners.iter().map(|n| n.id()).collect::<Vec<_>>())
            .unwrap();
        let fes = FiniteElementSpace::lagrange1(&host).unwrap();
        let physics =
            crate::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();

        let immersed = Node::create_in(coords, &[0.25, 0.25]).unwrap();
        let bar = Mesh::from_submesh(SubMesh::poi1_from_nodes(&[immersed]).unwrap());

        let mut model = Model::empty();
        model.add_sub(physics.get(0).unwrap()).unwrap();
        model
            .add_sub(Handle::new(
                SubModel::embedded(&bar, &host, &physics, vec!["T".into()], 1e-9).unwrap(),
            ))
            .unwrap();
        let materials = material_field_per_sub_model(&model, &[&[("k", 1.0)], &[]]).unwrap();
        (model, materials)
    }

    /// The case that proved the two DOF orders were collected independently.
    ///
    /// `embedded` brings **two** new nodes at once — the immersed node, which no
    /// physics ever numbered, and its multiplier. Two independent walks would
    /// discover them in opposite order, leaving the array `0.5` away from
    /// symmetric while the flag says symmetric. A plain Dirichlet cannot show
    /// this, its constrained node being numbered by the physics already.
    #[test]
    fn an_immersed_node_does_not_cross_the_two_dof_orders() {
        let (model, materials) = immersed_node_in_a_triangle();
        let k = stiffness(&model, &materials).unwrap();

        assert!(
            csr_is_symmetric(&k),
            "the assembled CSR must be symmetric, not merely the operator"
        );
        assert!(k.symmetric(), "and the declaration must agree");
    }

    /// The same, through the other assembly path. `assemble_written` (written
    /// blocks) and `assemble` (scattered kernels) are deliberately parallel so the two can be
    /// compared — which only means something if they number the DOFs alike.
    #[test]
    fn both_assembly_paths_number_the_immersed_case_alike() {
        let (model, materials) = immersed_node_in_a_triangle();
        let scattered = stiffness(&model, &materials).unwrap();
        let mut literal = assemble_literal_reference(&model, &materials).unwrap();
        literal.assemble_written().unwrap();

        assert_eq!(scattered.row_dofs().unwrap(), literal.row_dofs().unwrap());
        assert_eq!(scattered.col_dofs().unwrap(), literal.col_dofs().unwrap());
        assert!(csr_is_symmetric(&literal), "and the literal path too");
    }

    /// The other producer that mints pairs. Two `QUA4` blocks, the lower one's
    /// top edge as master and the upper one's bottom nodes as slaves: node-facet
    /// coupling across two meshes, with coefficients varying node by node.
    #[test]
    fn a_contact_pair_keeps_the_two_dof_orders_conjugate() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let node = |x: f64, y: f64| Node::create_in(coords.clone(), &[x, y]).unwrap();
        // Lower block y ∈ [0, 1], upper block y ∈ [1.1, 2.1].
        let lower: Vec<Node> = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
            .iter()
            .map(|&(x, y)| node(x, y))
            .collect();
        let upper: Vec<Node> = [(0.0, 1.1), (1.0, 1.1), (1.0, 2.1), (0.0, 2.1)]
            .iter()
            .map(|&(x, y)| node(x, y))
            .collect();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
        for block in [&lower, &upper] {
            mesh.add_cell(&block.iter().map(|n| n.id()).collect::<Vec<_>>())
                .unwrap();
        }
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();

        // Master runs in −x so the facet normal points +y, toward the slaves.
        let mut master = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        master.add_cell(&[lower[2].id(), lower[3].id()]).unwrap();
        let slave = Mesh::from_submesh(
            SubMesh::poi1_from_nodes(&[upper[0].clone(), upper[1].clone()]).unwrap(),
        );

        let elasticity = crate::ops::model::elasticity(
            &fes,
            crate::models::tensor::Kinematics::PlaneStress,
            MaterialSymmetry::Isotropic,
            StrainMeasure::Linear,
        )
        .unwrap();
        let contact = crate::ops::model::contact(
            &slave,
            &master,
            &elasticity,
            vec!["u_x".into(), "u_y".into()],
        )
        .unwrap();
        let model = elasticity.union(&contact).unwrap();
        let materials =
            material_field_per_sub_model(&model, &[&[("E", 1.0), ("nu", 0.3)], &[]]).unwrap();
        let k = stiffness(&model, &materials).unwrap();

        assert!(csr_is_symmetric(&k), "the assembled CSR must be symmetric");
        assert!(k.symmetric(), "and the declaration must agree");
    }

    /// A thick shell over an `n`×1 strip of `QUA4` facets in 3-D. Exercises the
    /// **multi-fespace** computed path: each block integrates two FE subspaces
    /// (membrane/bending at full Gauss + transverse shear reduced) sharing one
    /// mesh, and interior nodes are shared so the parallel scatter genuinely
    /// colours the cells.
    ///
    /// The beam assembles an exact closed form on a single space, so the shell
    /// is what exercises this two-quadrature path.
    fn multi_fespace_shell(n: usize) -> (Model, ElementField) {
        let coords = Handle::new(Coords::new(3).unwrap());
        let mut row = Vec::new();
        for i in 0..=n {
            let x = i as f64;
            row.push((
                Node::create_in(coords.clone(), &[x, 0.0, 0.0]).unwrap(),
                Node::create_in(coords.clone(), &[x, 1.0, 0.0]).unwrap(),
            ));
        }
        let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
        for i in 0..n {
            let (a0, a1) = &row[i];
            let (b0, b1) = &row[i + 1];
            sm.add_cell(&[a0.id(), b0.id(), b1.id(), a1.id()]).unwrap();
        }
        let mesh = Mesh::from_submesh(sm);
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::shell(
                    fes.get(0).unwrap(),
                    crate::models::shell::ShellFormulation::Thick,
                )
                .unwrap(),
            ))
            .unwrap();
        let materials =
            material_field_per_sub_model(&model, &[&[("E", 2.1e5), ("nu", 0.3), ("h", 0.02)]])
                .unwrap();
        (model, materials)
    }

    /// Pass 1 of [`stiffness`] alone: the block aggregate (computed blocks for
    /// the volumetric zones, literal for the rest) **before** the global
    /// scatter. Lets a test drive `crate::ops::scatter::*` directly on the same blocks the
    /// real assembler builds.
    fn assemble_computed_blocks(model: &Model, materials: &ElementField) -> Matrix {
        let mut k = Matrix::empty();
        for sub_h in model {
            let built = {
                let sub = sub_h.read();
                let material = sub
                    .material_fespace()
                    .map(|fespace| materials.sub_for_fespace(&fespace).unwrap());
                let mut blocks = Vec::new();
                for c in sub
                    .as_kind()
                    .contributions(MatrixKind::Stiffness, material.as_ref())
                    .unwrap()
                {
                    blocks.extend(
                        build_contribution(
                            c,
                            sub_h,
                            material.clone(),
                            MatrixKind::Stiffness,
                            KernelInputs::MaterialOnly,
                        )
                        .unwrap(),
                    );
                }
                blocks
            };
            for b in built {
                k.add_sub(Handle::new(b)).unwrap();
            }
        }
        k
    }

    /// The **serial** scatter (`build_pattern` + `scatter_serial`) reproduces the
    /// literal reference **bit-for-bit**: same sparsity and same values to the
    /// last bit (it accumulates each slot in the triplet-stream order).
    #[test]
    fn serial_scatter_equals_literal_bit_for_bit() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let k = assemble_computed_blocks(&model, &materials);
        let pattern = crate::ops::scatter::build_pattern(&k).unwrap();
        let values = crate::ops::scatter::scatter_serial(&k, &pattern).unwrap();

        let k_ref = assemble_literal_reference(&model, &materials).unwrap();
        let (offsets_ref, cols_ref, values_ref) = k_ref.csr_arrays().unwrap();

        assert_eq!(&pattern.row_offsets[..], offsets_ref);
        assert_eq!(&pattern.col_indices[..], cols_ref);
        assert_eq!(values, values_ref);
    }

    #[test]
    fn scatter_serial_applies_factor_to_computed_and_literal_blocks() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let k = assemble_computed_blocks(&model, &materials);
        let pattern = crate::ops::scatter::build_pattern(&k).unwrap();
        let unscaled = crate::ops::scatter::scatter_serial(&k, &pattern).unwrap();

        let scaled = &k * 3.0;
        let pattern_scaled = crate::ops::scatter::build_pattern(&scaled).unwrap();
        let scaled_values = crate::ops::scatter::scatter_serial(&scaled, &pattern_scaled).unwrap();

        assert_eq!(pattern_scaled.row_offsets, pattern.row_offsets);
        assert_eq!(pattern_scaled.col_indices, pattern.col_indices);
        for (x, y) in scaled_values.iter().zip(&unscaled) {
            assert!(
                (x - 3.0 * y).abs() <= 1e-9 * (1.0 + y.abs()),
                "value mismatch: {x} vs 3×{y}"
            );
        }
    }

    /// The **parallel** colour-driven scatter (`stiffness`) matches the literal
    /// reference to floating tolerance — the sparsity is identical, the values
    /// agree up to the reordered summation the colouring induces (so *not*
    /// bit-for-bit with the serial path, by construction).
    #[test]
    fn parallel_scatter_matches_literal_within_tol() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let k_new = stiffness(&model, &materials).unwrap();
        let k_ref = assemble_literal_reference(&model, &materials).unwrap();
        let csr_new = k_new.to_csr().unwrap();
        let csr_ref = k_ref.to_csr().unwrap();

        assert_eq!(csr_new.row_offsets(), csr_ref.row_offsets());
        assert_eq!(csr_new.col_indices(), csr_ref.col_indices());
        for (x, y) in csr_new.values().iter().zip(csr_ref.values()) {
            assert!(
                (x - y).abs() <= 1e-12 * (1.0 + y.abs()),
                "value mismatch: {x} vs {y}"
            );
        }
    }

    /// Scaling the real production `stiffness()` output (computed volumetric
    /// blocks + literal Dirichlet block) with `Matrix * f64` matches the literal
    /// reference scaled by hand — and needs **no re-assembly** to do so: the
    /// scaling carries the assembled CSR along, scaled, rather than dropping it
    /// and making `assemble()` re-run every element kernel for one scalar.
    #[test]
    fn scaled_stiffness_matches_scaled_literal_reference() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let k = stiffness(&model, &materials).unwrap();
        let scaled = &k * 2.5;

        // Read straight back: no `assemble()` in between.
        let k_ref = assemble_literal_reference(&model, &materials).unwrap();
        let csr_new = scaled.to_csr().unwrap();
        let csr_ref = k_ref.to_csr().unwrap();
        assert_eq!(csr_new.row_offsets(), csr_ref.row_offsets());
        assert_eq!(csr_new.col_indices(), csr_ref.col_indices());
        for (x, y) in csr_new.values().iter().zip(csr_ref.values()) {
            assert!(
                (x - 2.5 * y).abs() <= 1e-9 * (1.0 + y.abs()),
                "value mismatch: {x} vs 2.5×{y}"
            );
        }

        // Assembling the scaled blocks computes `Σ (v · s)` where the scaling
        // computed `(Σ v) · s`: the same quantity, to within rounding.
        let mut reassembled = assemble_computed_blocks(&model, &materials) * 2.5;
        reassembled.assemble().unwrap();
        for (x, y) in reassembled
            .to_csr()
            .unwrap()
            .values()
            .iter()
            .zip(csr_new.values())
        {
            assert!(
                (x - y).abs() <= 1e-12 * (1.0 + y.abs()),
                "scaled vs re-assembled: {x} vs {y}"
            );
        }

        // A scaled matrix that was **not** assembled has no values until
        // `assemble()`. (Owned `*`, so this also exercises the in-place path.)
        let mut unassembled = assemble_computed_blocks(&model, &materials) * 2.5;
        assert!(unassembled.to_csr().is_err());
        unassembled.assemble().unwrap();
        assert!(unassembled.to_csr().is_ok());
    }

    /// A bar of two SEG2 of length 1 and conductivity 1, with a second
    /// configuration where every length doubles; and its middle node.
    fn bar_with_a_stretched_configuration() -> (Model, ElementField, Handle<Coords>, usize, NodeId)
    {
        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = [0.0, 1.0, 2.0]
            .iter()
            .map(|&x| Node::create_in(coords.clone(), &[x]).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[nodes[0].id(), nodes[1].id()]).unwrap();
        sm.add_cell(&[nodes[1].id(), nodes[2].id()]).unwrap();
        let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
        let model = crate::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
        let materials = crate::ops::element_field::material_field(&model, &[("k", 1.0)]).unwrap();
        let stretched = coords.write().add_config("stretched");
        in_config(&coords, stretched, || {
            for (n, x) in nodes.iter().zip([0.0, 2.0, 4.0]) {
                n.set_position(&[x])?;
            }
            Ok(())
        })
        .unwrap();
        (model, materials, coords, stretched, nodes[1].id())
    }

    /// A sum adds the values each operand was assembled with, whatever
    /// configuration is active when it is taken; and a matrix is assembled
    /// once — neither another active configuration nor a second `assemble`
    /// reaches its values.
    #[test]
    fn a_sum_adds_each_operand_as_it_was_assembled() {
        let (model, materials, coords, stretched, middle) = bar_with_a_stretched_configuration();
        let at_middle = |m: &Matrix| m.get(middle, "q", middle, "T").unwrap();
        let close = |x: f64, y: f64| (x - y).abs() < 1e-12;

        // Two conductances 1/ℓ meet at the middle node: 2 at rest, 1 stretched.
        let on_reference = stiffness(&model, &materials).unwrap();
        let on_stretched = in_config(&coords, stretched, || stiffness(&model, &materials)).unwrap();
        assert!(close(at_middle(&on_reference), 2.0));
        assert!(close(at_middle(&on_stretched), 1.0));

        let mut sum = (&on_reference + &on_stretched).unwrap();
        assert!(close(at_middle(&sum), 3.0), "{}", at_middle(&sum));
        assert!(close(
            at_middle(&(&on_reference - &on_stretched).unwrap()),
            1.0
        ));
        in_config(&coords, stretched, || sum.assemble()).unwrap();
        assert!(
            close(at_middle(&sum), 3.0),
            "assembled once: {}",
            at_middle(&sum)
        );
    }

    /// Operands on different degrees of freedom — a stiffness carrying a
    /// Dirichlet's multiplier, a capacity without it — add over the union,
    /// numbered and valued as the same blocks assembled together, with or
    /// without a solver permutation; the sum stays symmetric entry for entry,
    /// as the solver reads it.
    #[test]
    fn a_sum_over_different_dofs_equals_its_blocks_assembled_together() {
        for permuted in [false, true] {
            let (model, materials) = chain_heat_with_dirichlet(4);
            if permuted {
                let coords = model.multiplier_mesh().unwrap().coords().unwrap();
                let capacity = coords.read().capacity();
                let reversed: Vec<u32> = (0..capacity as u32).rev().collect();
                coords.write().set_permutation(reversed).unwrap();
            }
            sum_over_different_dofs(&model, &materials);
        }
    }

    fn sum_over_different_dofs(model: &Model, materials: &ElementField) {
        let conduction = model.exclude(crate::models::Physics::Constraint);
        let heat =
            material_field_per_sub_model(&conduction, &[&[("k", 2.0), ("rho", 3.0), ("cp", 0.5)]])
                .unwrap();
        let k = stiffness(model, materials).unwrap();
        let c = &mass(&conduction, &heat).unwrap() * 10.0;
        assert_ne!(
            c.row_dof_keys().unwrap().len(),
            k.row_dof_keys().unwrap().len()
        );

        let sum = (&c + &k).unwrap();
        let mut together = c.union(&k).unwrap();
        together.assemble().unwrap();
        let (rows, cols) = (together.row_dofs().unwrap(), together.col_dofs().unwrap());
        assert_eq!(sum.row_dofs().unwrap(), rows);
        assert_eq!(sum.col_dofs().unwrap(), cols);
        for (rn, rv) in &rows {
            for (cn, cv) in &cols {
                let x = sum.get(*rn, rv, *cn, cv).unwrap();
                let y = together.get(*rn, rv, *cn, cv).unwrap();
                assert!(
                    (x - y).abs() <= 1e-12 * (1.0 + y.abs()),
                    "{rv}/{cv}: {x} vs {y}"
                );
            }
        }
        assert!(sum.symmetric());
        let n = rows.len();
        let dense = sum.to_dmatrix().unwrap();
        for i in 0..n {
            for j in 0..n {
                assert_eq!(dense[(i, j)], dense[(j, i)], "({i}, {j})");
            }
        }
    }

    /// A lumped mass holds values and no block: a sum keeps it.
    #[test]
    fn a_lumped_mass_survives_a_sum() {
        let (model, materials) = chain_heat_with_dirichlet(3);
        let conduction = model.exclude(crate::models::Physics::Constraint);
        let heat =
            material_field_per_sub_model(&conduction, &[&[("k", 2.0), ("rho", 1.0), ("cp", 1.0)]])
                .unwrap();
        let k = stiffness(&model, &materials).unwrap();
        let lumped = lump(&mass(&conduction, &heat).unwrap()).unwrap();
        let sum = (&k + &lumped).unwrap();
        for (rn, rv) in sum.row_dofs().unwrap() {
            for (cn, cv) in sum.col_dofs().unwrap() {
                let expected =
                    k.get(rn, &rv, cn, &cv).unwrap() + lumped.get(rn, &rv, cn, &cv).unwrap();
                let x = sum.get(rn, &rv, cn, &cv).unwrap();
                assert!((x - expected).abs() < 1e-12, "{rv}/{cv}: {x} vs {expected}");
            }
        }
    }

    /// The lumped mass describes itself: a diagonal block on the mass's row
    /// support, tagged like the mass, in the mass's row order — so the solver
    /// lays its result on that support.
    #[test]
    fn a_lumped_mass_carries_its_diagonal_block() {
        use crate::containers::field::SubField;
        use crate::containers::node_field::NodeField;
        let (model, _) = chain_heat_with_dirichlet(3);
        let conduction = model.exclude(crate::models::Physics::Constraint);
        let heat =
            material_field_per_sub_model(&conduction, &[&[("k", 1.0), ("rho", 1.0), ("cp", 1.0)]])
                .unwrap();
        let m = mass(&conduction, &heat).unwrap();
        let lumped = lump(&m).unwrap();
        assert_eq!(lumped.len(), 1);
        assert_eq!(lumped.physics(), m.physics());
        assert!(lumped.symmetric());
        assert_eq!(lumped.row_dofs().unwrap(), m.row_dofs().unwrap());
        assert_eq!(lumped.col_dofs().unwrap(), m.col_dofs().unwrap());

        let rhs = NodeField::from_submesh(
            &lumped.row_mesh().unwrap().get(0).unwrap(),
            vec!["q".into()],
        )
        .unwrap();
        rhs.get(0)
            .unwrap()
            .write()
            .add_to_component("q", 1.0)
            .unwrap();
        let t = crate::ops::solver::solve(&lumped, &rhs).unwrap();
        for (node, _) in lumped.row_dofs().unwrap() {
            let d = lumped.get(node, "q", node, "T").unwrap();
            assert!((t.value(node, "T").unwrap() * d - 1.0).abs() < 1e-12);
        }
    }

    /// Blocks put together without their values — `filter` here — have none to
    /// add or read until assembled: an error, not a zero. A computed block has
    /// none of its own either.
    #[test]
    fn values_never_assembled_are_an_error_to_add_or_read() {
        let (model, materials) = chain_heat_with_dirichlet(2);
        let k = stiffness(&model, &materials).unwrap();
        let mut thermal = k.filter(crate::models::Physics::Thermal);
        let a = k.row_dofs().unwrap()[0].0;
        assert!((&thermal + &k).is_err());
        assert!((&k - &thermal).is_err());
        assert!(thermal.get(a, "q", a, "T").is_err());
        assert!(thermal.iter_entries().is_err());
        // A computed block holds no value: every reader says so alike.
        {
            let block = k.iter().find(|h| h.read().is_computed()).unwrap();
            let block = block.read();
            assert!(block.get(a, "q", a, "T").is_err());
            assert!(block.iter_entries().is_err());
            assert!(block.to_dmatrix().is_err());
            assert!(block.to_coo().is_err());
            assert!(block.to_csr().is_err());
            assert!(block.to_csc().is_err());
        }

        thermal.assemble().unwrap();
        // Assembled, its entries are the values `get` reads.
        for (rn, rv, cn, cv, v) in thermal.iter_entries().unwrap() {
            assert_eq!(v, thermal.get(rn, &rv, cn, &cv).unwrap());
        }
        let sum = (&thermal + &k).unwrap();
        let expected = 2.0 * k.get(a, "q", a, "T").unwrap();
        assert!((sum.get(a, "q", a, "T").unwrap() - expected).abs() < 1e-12);
    }

    /// The colouring is fixed and each colour's writes are disjoint, so the
    /// parallel scatter is reproducible: two assemblies of the same model give
    /// bit-for-bit identical values (independent of thread scheduling).
    #[test]
    fn parallel_scatter_is_deterministic() {
        let (model, materials) = chain_heat_with_dirichlet(6);
        let a = stiffness(&model, &materials).unwrap();
        let b = stiffness(&model, &materials).unwrap();
        assert_eq!(a.to_csr().unwrap().values(), b.to_csr().unwrap().values());
    }

    /// A **multi-fespace** element (a thick shell: membrane/bending at full
    /// Gauss + transverse shear reduced, two subspaces over one mesh) assembles
    /// through the computed serial scatter **bit-for-bit** identically to its
    /// literal reference — the two `CellGeom` per cell produce the exact same
    /// triplet stream as the single-block driver.
    #[test]
    fn multi_fespace_serial_equals_literal_bit_for_bit() {
        let (model, materials) = multi_fespace_shell(5);
        let k = assemble_computed_blocks(&model, &materials);
        let pattern = crate::ops::scatter::build_pattern(&k).unwrap();
        let values = crate::ops::scatter::scatter_serial(&k, &pattern).unwrap();

        let k_ref = assemble_literal_reference(&model, &materials).unwrap();
        let (offsets_ref, cols_ref, values_ref) = k_ref.csr_arrays().unwrap();

        assert_eq!(&pattern.row_offsets[..], offsets_ref);
        assert_eq!(&pattern.col_indices[..], cols_ref);
        assert_eq!(values, values_ref);
    }

    /// The same shell through the **parallel** colour-driven scatter (the real
    /// `stiffness` path): identical sparsity, values within tolerance.
    #[test]
    fn multi_fespace_parallel_matches_literal_within_tol() {
        let (model, materials) = multi_fespace_shell(5);
        let k_new = stiffness(&model, &materials).unwrap();
        let k_ref = assemble_literal_reference(&model, &materials).unwrap();
        let csr_new = k_new.to_csr().unwrap();
        let csr_ref = k_ref.to_csr().unwrap();

        assert_eq!(csr_new.row_offsets(), csr_ref.row_offsets());
        assert_eq!(csr_new.col_indices(), csr_ref.col_indices());
        for (x, y) in csr_new.values().iter().zip(csr_ref.values()) {
            assert!(
                (x - y).abs() <= 1e-12 * (1.0 + y.abs()),
                "timoshenko value mismatch: {x} vs {y}"
            );
        }
    }

    /// The sparsity pattern is memoised on the model and reused across
    /// assemblies — a second assembly with **different materials** hits the
    /// cache yet must still produce the correct values (the pattern is
    /// material-independent, the values are not).
    #[test]
    fn cached_pattern_reused_across_materials() {
        let (model, _) = chain_heat_with_dirichlet(6);
        // First assembly (cache miss) with k = 2.
        let m1 = material_field_per_sub_model(&model, &[&[("k", 2.0)], &[]]).unwrap();
        let _ = stiffness(&model, &m1).unwrap();
        // Second assembly (cache hit) with k = 7 on the same model.
        let m2 = material_field_per_sub_model(&model, &[&[("k", 7.0)], &[]]).unwrap();
        let k2 = stiffness(&model, &m2).unwrap();

        let k_ref = assemble_literal_reference(&model, &m2).unwrap();
        let csr2 = k2.to_csr().unwrap();
        let csr_ref = k_ref.to_csr().unwrap();
        assert_eq!(csr2.row_offsets(), csr_ref.row_offsets());
        assert_eq!(csr2.col_indices(), csr_ref.col_indices());
        for (x, y) in csr2.values().iter().zip(csr_ref.values()) {
            assert!(
                (x - y).abs() <= 1e-12 * (1.0 + y.abs()),
                "cached-pattern reassembly value mismatch: {x} vs {y}"
            );
        }
    }

    /// Composition: after `stiffness`, add a **literal block of arbitrary
    /// provenance** to the (computed-block) matrix and re-assemble it with the
    /// self-contained [`assemble`], which rebuilds the sparsity from the blocks
    /// and folds the new contribution in.
    #[test]
    fn assemble_composes_extra_literal_block() {
        // One heat element on nodes a—b.
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[a.id(), b.id()]).unwrap();
        let mesh = Mesh::from_submesh(sm);
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(0).unwrap(), MaterialSymmetry::Isotropic)
                    .unwrap(),
            ))
            .unwrap();
        let materials = material_field_per_sub_model(&model, &[&[("k", 1.0)]]).unwrap();

        let mut k = stiffness(&model, &materials).unwrap();
        let before = k.get(a.id(), "q", a.id(), "T").unwrap();

        // A hand-built literal block (no model behind it) adding +10 at (a,q)×(a,T).
        let support = Handle::new(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let mut blk = SubMatrix::new(
            support.clone(),
            support,
            vec!["q".into()],
            vec!["T".into()],
            crate::containers::matrix::DofOrdering::NodesThenVars,
            Symmetry::Full,
        )
        .unwrap();
        blk.add_entry(a.id(), "q", a.id(), "T", 10.0).unwrap();
        k.add_sub(Handle::new(blk)).unwrap();

        k.assemble().unwrap();

        let after = k.get(a.id(), "q", a.id(), "T").unwrap();
        assert!(
            (after - (before + 10.0)).abs() <= 1e-12 * (1.0 + before.abs()),
            "composition failed: before {before}, after {after}"
        );
    }

    /// The support a stiffness block carries (its `col_support`) is the cached
    /// `to_poi1` of its fespace submesh — the very slot `restrict` onto the same
    /// mesh lands on. So a solve/`K·x` output and a `restrict` onto that mesh
    /// share one support and combine directly by the field operators.
    #[test]
    fn stiffness_support_matches_restrict_onto_the_same_mesh() {
        use crate::aggregate::Aggregate;
        use crate::containers::node_field::{NodeField, SubNodeField};
        use crate::ops::node_field::restrict;

        let coords = Handle::new(Coords::new(1).unwrap());
        let nodes: Vec<Node> = (0..=2)
            .map(|i| Node::create_in(coords.clone(), &[i as f64]).unwrap())
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[nodes[0].id(), nodes[1].id()]).unwrap();
        sm.add_cell(&[nodes[1].id(), nodes[2].id()]).unwrap();
        let mesh = Mesh::from_submesh(sm);

        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(0).unwrap(), MaterialSymmetry::Isotropic)
                    .unwrap(),
            ))
            .unwrap();
        let materials = material_field_per_sub_model(&model, &[&[("k", 1.0)]]).unwrap();
        let k = stiffness(&model, &materials).unwrap();

        // A field restricted onto the very same mesh.
        let mut psm = SubMesh::new(coords.clone(), ElementType::POI1);
        for nd in &nodes {
            psm.add_cell(&[nd.id()]).unwrap();
        }
        let f = NodeField::from_sub(
            SubNodeField::from_poi1(&Handle::new(psm), vec!["T".into()]).unwrap(),
        );
        let r = restrict(&f, &mesh).unwrap();

        let col = k.iter().next().unwrap().read().col_support().clone();
        let rsup = r.get(0).unwrap().read().support();
        assert!(
            col.same_object(&rsup),
            "block support and restrict onto the same mesh share one slot"
        );
    }
}