pyrucast 0.9.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
//! 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};

/// 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 aggregate is finalized before being returned.
///
/// ```
/// # 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).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"), 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. `prev`
    /// is optional **here and nowhere below** — `None` means the rest state,
    /// which is materialised per sub-model before any recipe is built.
    Behavior {
        deformation: &'a ElementField,
        prev: Option<&'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) => KernelInputs::State(sf.sub_for_fespace(fespace)?),
            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 deformation = deformation.sub_for_fespace(fespace)?;
                // Below this line, `prev` is always a real field.
                let prev = match prev {
                    Some(p) => p.sub_for_fespace(fespace)?,
                    None => Handle::new(
                        sub.as_kind()
                            .as_behavior()
                            .ok_or_else(|| {
                                PyrucastError::Message(format!(
                                    "{}: a tangent needs a behaviour",
                                    sub.as_kind().label()
                                ))
                            })?
                            .initial_state(&deformation.read())?,
                    ),
                };
                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::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).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.dense()?, matrix::stiffness(&modele, &materiaux)?.dense()?);
/// 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.dense()?.iter().sum::<f64>() - 2.0 * 3.0 * 0.5).abs() < 1e-9);
/// assert!(k.dense()?.iter().sum::<f64>().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();
            // 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,
            };
            // 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.
            let kernel_inputs = match sub.material_fespace() {
                Some(fespace) => inputs.for_sub(&sub, &fespace)?,
                None => KernelInputs::MaterialOnly,
            };
            let mut blocks = Vec::new();
            for c in sub.as_kind().contributions(kind, material.as_ref())? {
                blocks.extend(build_contribution(
                    c,
                    sub_h,
                    material.clone(),
                    kind,
                    kernel_inputs.clone(),
                )?);
            }
            blocks
        };
        for block in built {
            k.add_sub(Handle::new(block))?;
        }
    }

    // Pass 2 — global assembly, injected via `set_assembled` (Option B: the
    // global assembler lives here, not in `Matrix`, so there is no
    // matrix↔kernel cycle). 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 (or re-assemble) this matrix **from its blocks alone** — no
    /// `Model`.
    ///
    /// The sparsity is rebuilt from the current blocks
    /// ([`crate::ops::scatter::build_pattern`], self-contained: a computed
    /// block resolves its fill through its recipe, a literal block through its
    /// COO) and the values are scattered into it. This is the composition path:
    /// after adding a block of any provenance to an already assembled matrix —
    /// which [`Matrix::finalize`] cannot handle once computed blocks are
    /// present, and which [`stiffness`] cannot reach (it only knows a `Model`)
    /// — call this to fold the new block in.
    ///
    /// ```ignore
    /// let mut k = crate::ops::matrix::stiffness(&model, &materials)?;
    /// k.add_sub(Handle::new(some_block))?;   // invalidates the assembled state
    /// k.assemble()?;                    // re-assembles, new block included
    /// ```
    ///
    /// Unlike [`stiffness`], this does not consult the model's cached pattern
    /// (there is no model here), so it rebuilds 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<()> {
        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::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).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.dense().unwrap().iter().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::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).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.
///
/// `state` is the behaviour field produced by [`crate::ops::element_field::behavior::integrate`]
/// at the current iterate: besides the stress it carries the per-Gauss
/// evaluated **at the Gauss point**, from what the law asks for — the same
/// inputs as `behavior::integrate`. No modulus field is materialized: it would
/// have had this assembler as its only reader. `prev` at `None` means the rest
/// state, resolved here and never further down. `materials` resolves each zone
/// [`stiffness`].
///
/// ```
/// # 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).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 kt = matrix::tangent(&model, &materials, &strain, None, None).unwrap();
/// let k = matrix::stiffness(&model, &materials).unwrap();
///
/// assert_eq!(kt.dense().unwrap(), k.dense().unwrap());
/// ```
pub fn tangent(
    model: &Model,
    materials: &ElementField,
    deformation: &ElementField,
    prev: Option<&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 and column DOFs coincide
/// position-for-position, as they do for a mass/capacity matrix). The result is
/// a new assembled [`Matrix`] with the same DOF layout; the input is untouched.
///
/// ```
/// # 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).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.dense().unwrap().iter().sum()
/// };
/// assert!((somme(&m) - somme(&diagonale)).abs() < 1e-12);
/// assert_eq!(diagonale.get(a.id(), "q", b.id(), "T"), 0.0);
/// ```
pub fn lump(m: &Matrix) -> Result<Matrix> {
    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(crate::error::PyrucastError::Message(format!(
            "lump: matrix must be square, got {}×{}",
            n,
            col_keys.len()
        )));
    }
    // Diagonal = per-row sum, written straight into a diagonal CSR: one entry
    // per row, so the offsets are the row index itself.
    let diag_values: Vec<f64> = (0..n)
        .map(|r| values[offsets[r]..offsets[r + 1]].iter().sum())
        .collect();
    let diag = crate::containers::matrix::AssembledCsr {
        row_offsets: std::sync::Arc::new((0..=n).collect()),
        col_indices: std::sync::Arc::new((0..n).collect()),
        values: diag_values,
        ncols: n,
    };
    let mut out = Matrix::empty();
    out.set_assembled(vars, row_keys, col_keys, diag);
    Ok(out)
}

// ─── Méthodes de délégation ────────────────────────────────────────────────
//
// Voir `CONVENTIONS.md` § « Le verbe exposé aussi en méthode ». Le nom change
// between the two forms: the free function gets its qualifier from its
// module (`matrix::stiffness`), la méthode n'en a pas et doit le porter
// (`model.stiffness_matrix`).

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

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

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

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

impl Matrix {
    /// Voir [`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};
    use crate::containers::finite_element_space::FiniteElementSpace;
    use crate::containers::matrix::Symmetry;
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::coords::Coords;
    use crate::ops::element_field::material_field_per_sub_model;

    /// Assemble the stiffness the **literal** way: every sub-model fills its
    /// `SubMatrix` blocks eagerly and `finalize` scatters them. This is the
    /// historical path the computed path must match bit-for-bit — kept here
    /// purely as the equivalence 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.finalize()?;
        Ok(k)
    }

    /// Two heat-conduction zones sharing a node, plus a Dirichlet constraint —
    /// so the assembly mixes **computed** blocks (the two zones) with **literal**
    /// ones (Dirichlet's C / Cᵀ), and a shared node forces accumulation.
    fn two_zone_heat_with_dirichlet() -> (Model, ElementField) {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
        let mut mesh = Mesh::empty();
        let sm_a = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n0.id(), n1.id()]).unwrap();
            Handle::new(sm)
        };
        let sm_b = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
            sm.add_cell(&[n1.id(), n2.id()]).unwrap();
            Handle::new(sm)
        };
        mesh.add_sub(sm_a).unwrap();
        mesh.add_sub(sm_b).unwrap();
        let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();

        let mut model = Model::empty();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(0).unwrap()).unwrap(),
            ))
            .unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&n0)).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        model
            .add_sub(Handle::new(
                SubModel::dirichlet(&model, "T", &imposed, &multiplier, Default::default())
                    .unwrap(),
            ))
            .unwrap();
        model
            .add_sub(Handle::new(
                SubModel::heat_conduction(fes.get(1).unwrap()).unwrap(),
            ))
            .unwrap();

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

    /// 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()).unwrap(),
            ))
            .unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&nodes[0])).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        model
            .add_sub(Handle::new(
                SubModel::dirichlet(&model, "T", &imposed, &multiplier, 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, one identity, two of
    /// each member. The matrix is symmetric, and the count of members — rather
    /// than of blocks — is what lets the aggregate see 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()).unwrap(),
            ))
            .unwrap();
        let imposed =
            Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&nodes[0])).unwrap());
        let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
        // Twice, on the same supports and the same variable: the two pairs hash
        // alike, so all four blocks share one identity.
        for _ in 0..2 {
            model
                .add_sub(Handle::new(
                    SubModel::dirichlet(&model, "T", &imposed, &multiplier, 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");
        assert!(ids.windows(2).all(|w| w[0] == w[1]), "one identity");

        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).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(&physics, &bar, &host, 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 — and the two walks used to
    /// discover them in opposite order: the array came out `0.5` away from
    /// symmetric while the flag said it was symmetric. A plain Dirichlet hid
    /// 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. `finalize` (literal 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.finalize().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)
                .unwrap();
        let contact = crate::ops::model::contact(
            &elasticity,
            &slave,
            &master,
            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.
    ///
    /// It used to be a Timoshenko beam, which carried the same two-quadrature
    /// layout. The beam now assembles an exact closed form on a single space, so
    /// the shell is what still exercises this 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::ShellModel::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);
    }

    /// `SubMatrix::factor` scales every entry the **serial** scatter emits, on
    /// both branches: the computed heat-conduction blocks and the literal
    /// Dirichlet C/Cᵀ block (`assemble_computed_blocks` mixes both, per its doc).
    #[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 `finalize()` / `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}"
            );
        }

        // Re-assembling from the blocks computes `Σ (v · s)` where the scaling
        // computed `(Σ v) · s`: the same quantity, to within rounding.
        let mut reassembled = &k * 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 still cannot be finalized:
        // the element kernel lives outside `containers`, so a computed block
        // sends the caller to `assemble()`. (Owned `*`, so this also exercises
        // the in-place path.)
        let mut unassembled = assemble_computed_blocks(&model, &materials) * 2.5;
        assert!(
            unassembled.finalize().is_err(),
            "finalize must still refuse an unassembled computed block"
        );
    }

    /// 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`]. `finalize` refuses (computed blocks present),
    /// but `assemble` 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()).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");

        // 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,
        );
        blk.add_entry(a.id(), "q", a.id(), "T", 10.0).unwrap();
        k.add_sub(Handle::new(blk)).unwrap();

        // `finalize` can't (computed block present); the self-contained path can.
        assert!(k.finalize().is_err());
        k.assemble().unwrap();

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

    /// A matrix carrying a computed block cannot be assembled through
    /// `finalize` — it must go through `ops::matrix`. `finalize` says so
    /// rather than silently dropping the computed contribution.
    #[test]
    fn finalize_rejects_computed_block() {
        let (model, materials) = two_zone_heat_with_dirichlet();
        // Build the blocks (computed for the HC zones) but stop before the
        // global assembly, then try to finalize directly.
        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());
                sub.as_kind().stiffness_layout().map(|layout| {
                    SubMatrix::computed(
                        layout.support.clone(),
                        layout.support,
                        layout.dual_vars,
                        layout.primal_vars,
                        layout.ordering,
                        layout.symmetry,
                        ComputedRecipe {
                            submodel: sub_h.clone(),
                            fespaces: layout.fespaces,
                            material,
                            kind: MatrixKind::Stiffness,
                            inputs: KernelInputs::MaterialOnly,
                            col_fespaces: Vec::new(),
                        },
                    )
                })
            };
            if let Some(block) = built {
                k.add_sub(Handle::new(block)).unwrap();
            }
        }
        assert!(k.finalize().is_err());
    }

    /// 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()).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"
        );
    }
}