pyrucast 0.14.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
//! The **continuum in small strains** — the modelling three mechanical law
//! families stand on.
//!
//! A physics of the continuum is two independent things: *how the medium is
//! discretised* — the strain-displacement operator `B`, the Voigt nomenclature,
//! the kinematic hypothesis, the element kernels that integrate `Bᵀ · B` — and
//! *which constitutive law* runs at the Gauss point. This module is the first.
//! [`elasticity`](crate::models::elasticity),
//! [`plasticity`](crate::models::plasticity) and
//! [`damage`](crate::models::damage) each hold a [`Continuum`] and differ only
//! by their law.
//!
//! Before it existed, the modelling lived in `elasticity.rs` and the other two
//! reached into it — nine calls apiece. That worked, and said the wrong thing:
//! plasticity does not borrow from elasticity, they share a modelling.
//!
//! ## Axes
//!
//! Two hypotheses combine freely here and must not be confused:
//!
//! - the **kinematic** one ([`Kinematics`]) — plane stress, plane strain,
//!   axisymmetric, solid — which is a dimensional reduction, and
//! - the **material symmetry**
//!   ([`MaterialSymmetry`]) — which
//!   belongs to the law, and is passed to the kernels rather than stored here.

pub mod elastic;
pub(crate) mod finite_strain;
pub mod internal_force;
pub mod material;
pub mod voigt;

use crate::containers::element_field::SubElementField;
use crate::containers::field::ABSENT_COMPONENT;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::mesh::SubMesh;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::kernel::MAX_CELL_DOFS;
use crate::models::symmetry::{self, MaterialSymmetry};
use crate::models::tensor::{voigt_names, Kinematics};
use crate::models::{CellGeom, ElementLayout, MatrixKind};
use crate::ops::element_field::StrainMeasure;

use elastic::RHO_SLOT;
use voigt::{b_matrix_into, voigt_size, VoigtRows};

/// Reject an FE subspace whose elements are a **manifold** in their space
/// (`ref_dim < space_dim`) for a continuum-mechanics physics named `label`.
///
/// The continuum kernels build `B` from `∂N_i/∂x_a`, which on a manifold is the
/// *tangent* gradient: the resulting `Bᵀ D B` would be rank-deficient in the
/// normal direction and silently meaningless. A boundary sub-mesh (`SEG2` in
/// 2-D, `TRI3` in 3-D) is a support for loads
/// ([`flux`](crate::models::flux)) or convection, not a solid — and a
/// structural element (bar, beam) is a different physics with its own kernel.
fn check_continuum_dimensions(label: &str, space_dim: usize, ref_dim: usize) -> Result<()> {
    if ref_dim != space_dim {
        return Err(PyrucastError::Message(format!(
            "{label}: a {ref_dim}-D element in a {space_dim}-D space is a manifold, not a \
             solid — a boundary mesh carries loads (flux, convection), and a bar or beam \
             is a structural physics of its own (truss, frame, timoshenko)"
        )));
    }
    Ok(())
}

/// The continuum modelling of one FE subspace: its geometry, its support, the
/// kinematic hypothesis under which strains are measured, and the strain
/// measure its law reads.
///
/// Held by every continuum physics — what they add is a law, not a geometry.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::continuum::Continuum;
/// # use pyrucast::models::tensor::Kinematics;
/// # 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()])?;
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
/// // The modelling, independently of any law: it is what names the strains
/// // the kernel will read.
/// let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
/// assert_eq!(c.strain_reads(), ["eps_xx", "eps_yy", "eps_xy"]);
/// // And it is what refuses a kinematics impossible in that space.
/// assert!(Continuum::new(fes.get(0)?, Kinematics::Full3D, "Elasticity").is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Continuum {
    pub(crate) fespace: Handle<SubFiniteElementSpace>,
    /// POI1 support over the subspace's unique nodes (row/col support).
    pub(crate) support: Handle<SubMesh>,
    pub(crate) space_dim: usize,
    pub(crate) kinematics: Kinematics,
    /// The strain measure the law reads — `linear` unless the modelling was
    /// built for large transformations ([`with_measure`](Self::with_measure)).
    pub(crate) measure: StrainMeasure,
}

impl Continuum {
    /// The continuum modelling of `fespace` under `kinematics`, validated.
    ///
    /// `label` names the physics in the error messages — the three checks it
    /// runs used to be copied verbatim into every continuum constructor, and
    /// only the label differed:
    ///
    /// 1. the elements are solids, not a manifold in their space;
    /// 2. the kinematics is possible in that space dimension;
    /// 3. the kinematics and the geometry agree **both ways** about axisymmetry
    ///    — the `2πr` measure comes from the `Coords` while the hoop row comes
    ///    from the kinematics, so a mismatch would silently pair a plane
    ///    constitutive law with a revolved measure.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// // The `label` is only there to name itself when one of the three
    /// // consistencies is violated — here the kinematics and the space.
    /// match Continuum::new(fes.get(0)?, Kinematics::Full3D, "Elasticity") {
    ///     Err(e) => assert!(format!("{e}").starts_with("Elasticity:")),
    ///     Ok(_) => panic!("3-D kinematics in a 2-D space is refused"),
    /// }
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(
        fespace: Handle<SubFiniteElementSpace>,
        kinematics: Kinematics,
        label: &str,
    ) -> Result<Self> {
        let (submesh, space_dim, ref_dim, axisymmetric) = {
            let s = fespace.read();
            (s.submesh(), s.space_dim(), s.ref_dim(), s.is_axisymmetric())
        };
        check_continuum_dimensions(label, space_dim, ref_dim)?;
        #[allow(clippy::match_like_matches_macro)]
        let ok = match (space_dim, kinematics) {
            (2, Kinematics::PlaneStress | Kinematics::PlaneStrain) => true,
            (2, Kinematics::Axisymmetric) => true,
            (3, Kinematics::Full3D) => true,
            _ => false,
        };
        if !ok {
            return Err(PyrucastError::Message(format!(
                "{label}: kinematics {kinematics:?} is incompatible with a {space_dim}-D space \
                 (2-D ⇒ plane_stress|plane_strain|axisymmetric, 3-D ⇒ full_3d)"
            )));
        }
        if axisymmetric != kinematics.is_axisymmetric() {
            return Err(PyrucastError::Message(if axisymmetric {
                format!(
                    "{label}: kinematics {kinematics:?} on an axisymmetric geometry — a body of \
                     revolution requires the `axisymmetric` kinematics (its integrals already \
                     carry the 2πr factor)"
                )
            } else {
                format!(
                    "{label}: the `axisymmetric` kinematics requires an axisymmetric geometry \
                     (build the Coords with Coords::axisymmetric)"
                )
            }));
        }
        let support = submesh.read().to_poi1()?;
        Ok(Self {
            fespace,
            support,
            space_dim,
            kinematics,
            measure: StrainMeasure::Linear,
        })
    }

    /// The same modelling, its law reading the strain `measure` — the choice a
    /// small-strain law makes to enter large transformations.
    ///
    /// Hooke, J2 or Mazars relate a strain to its dual without saying which:
    /// read on the Green–Lagrange `E` (small strains, large rotations) they
    /// write the second Piola–Kirchhoff `S`; read on the Hencky `H = ½ ln C`
    /// (large plastic strains) they write its dual `T`. Each pair is named for
    /// what it holds — `E_*` / `S_*`, `H_*` / `T_*` — never renamed `eps_*` /
    /// `sigma_*`, and the whole state stays on the reference configuration.
    ///
    /// Errors (`label` names the physics):
    /// - a measure that is not a law's input — `gradient`, Cauchy–Green,
    ///   Euler–Almansi are kinematic quantities, not strains a law reads;
    /// - Hencky under plane stress: `ln C` needs `C_zz`, which only the law
    ///   would know.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::ops::element_field::StrainMeasure;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStrain, "Elasticity")?
    ///     .with_measure(StrainMeasure::GreenLagrange, "Elasticity")?;
    /// // The law reads E and writes S: each component says what it holds.
    /// assert_eq!(c.strain_reads(), ["E_xx", "E_yy", "E_xy"]);
    /// assert_eq!(c.stress_names(), ["S_xx", "S_yy", "S_xy"]);
    /// // F is no strain a law reads.
    /// let plain = Continuum::new(fes.get(0)?, Kinematics::PlaneStrain, "Elasticity")?;
    /// assert!(plain.with_measure(StrainMeasure::Gradient, "Elasticity").is_err());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn with_measure(self, measure: StrainMeasure, label: &str) -> Result<Self> {
        match measure {
            StrainMeasure::Linear | StrainMeasure::GreenLagrange => {}
            StrainMeasure::Hencky if self.kinematics == Kinematics::PlaneStress => {
                return Err(PyrucastError::Message(format!(
                    "{label}: the Hencky measure ½ ln C needs C_zz, which plane stress leaves \
                     to the law — use plane_strain, or green_lagrange under plane stress"
                )));
            }
            StrainMeasure::Hencky => {}
            other => {
                return Err(PyrucastError::Message(format!(
                    "{label}: `{}` is not a strain a law reads — the measures are `linear`, \
                     `green_lagrange` and `hencky`",
                    crate::named::Named::name(other)
                )));
            }
        }
        Ok(Self { measure, ..self })
    }

    /// The strain measure the law reads.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::ops::element_field::StrainMeasure;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStrain, "Elasticity")?;
    /// assert_eq!(c.measure(), StrainMeasure::Linear);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    #[inline]
    pub fn measure(&self) -> StrainMeasure {
        self.measure
    }

    /// The prefix of the stress the law writes, the dual of its measure:
    /// `sigma` (Cauchy, small strains), `S` (second Piola–Kirchhoff, dual of
    /// Green–Lagrange) or `T` (dual of Hencky).
    pub(crate) fn stress_prefix(&self) -> &'static str {
        match self.measure {
            StrainMeasure::GreenLagrange => "S",
            StrainMeasure::Hencky => "T",
            // `with_measure` admits no other measure: anything else is linear.
            _ => "sigma",
        }
    }

    /// The FE subspace this modelling stands on.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// // The subspace returned is the one it was given: a handle, cloned, not
    /// // a new subspace.
    /// assert_eq!(c.fespace().read().cell_count(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn fespace(&self) -> Handle<SubFiniteElementSpace> {
        self.fespace.clone()
    }

    /// POI1 support over the subspace's unique nodes.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// // The POI1 support carries the subspace's unique nodes.
    /// assert_eq!(c.support().read().cell_count(), 3);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn support(&self) -> Handle<SubMesh> {
        self.support.clone()
    }

    /// Dimension of the ambient space.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// assert_eq!(c.space_dim(), 2);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    #[inline]
    pub fn space_dim(&self) -> usize {
        self.space_dim
    }

    /// The kinematic hypothesis strains are measured under.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// assert_eq!(c.kinematics(), Kinematics::PlaneStress);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    #[inline]
    pub fn kinematics(&self) -> Kinematics {
        self.kinematics
    }

    /// The strain components a law of this modelling reads, in Voigt order,
    /// under the name of its measure (`eps`, `E` or `H`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// // Three components in the plane; axisymmetry adds the hoop.
    /// assert_eq!(c.strain_reads(), ["eps_xx", "eps_yy", "eps_xy"]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn strain_reads(&self) -> Vec<String> {
        voigt::strain_reads(self.measure.prefix(), self.space_dim, self.kinematics)
    }

    /// The stress components a law of this modelling writes, in Voigt order,
    /// under the name of the dual of its measure (`sigma`, `S` or `T`).
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// # let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// assert_eq!(c.stress_names(), ["sigma_xx", "sigma_yy", "sigma_xy"]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn stress_names(&self) -> Vec<String> {
        voigt_names(self.stress_prefix(), self.space_dim, self.kinematics)
    }

    /// What a continuum-mechanics **matrix** kernel reads from the state field,
    /// by [`MatrixKind`] — the shared declaration of elasticity, plasticity and
    /// damage, which run the very same kernels.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::MatrixKind;
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
    /// let c = Continuum::new(fes.get(0)?, Kinematics::PlaneStress, "Elasticity")?;
    /// // A stiffness reads no state; the geometric stiffness reads the stress.
    /// assert!(c.element_state_reads(MatrixKind::Stiffness).is_empty());
    /// assert_eq!(c.element_state_reads(MatrixKind::Geometric),
    ///            ["sigma_xx", "sigma_xy", "sigma_yy"]);
    /// // Nor does the tangent: it is evaluated at the point, not re-read.
    /// assert!(c.element_state_reads(MatrixKind::Tangent).is_empty());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_state_reads(&self, kind: MatrixKind) -> Vec<String> {
        match kind {
            // The current Cauchy stress, Voigt-named, closed by the hoop `σ_θθ`
            // on a body of revolution — the same list `Bᵀσ` reads.
            MatrixKind::Geometric => {
                let mut names = internal_force::voigt_matrix_reads("sigma", self.space_dim);
                if self.kinematics.is_axisymmetric() {
                    names.push("sigma_zz".to_string());
                }
                names
            }
            // A stiffness, a mass and — since the tangent is evaluated at the
            // point rather than re-read from a field — a tangent read nothing
            // but the material.
            MatrixKind::Stiffness | MatrixKind::Mass | MatrixKind::Tangent => Vec::new(),
        }
    }

    /// Element kernel: local stiffness `K_e = Σ_g (Bᵀ D B) |J| w` of one cell,
    /// written into `ke` (flat row-major, side `space_dim·n_nodes`, **node-major
    /// / component-minor** dof order `dof = node·space_dim + component`). Pure
    /// and sequential — driven in parallel by
    /// [`crate::models::kernel::assemble_block`]. Law-independent: the three
    /// families call it, their iteration operator being the elastic stiffness.
    ///
    /// `D` is built at **every** Gauss point from that point's material: a
    /// material field may vary inside a cell — moduli depending on the
    /// temperature at the point, a heterogeneous `E(x)` — and the stiffness
    /// integrates what the field holds, as the law does on the residual side.
    ///
    /// ```
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::SubElementField;
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::kernel::assemble_block;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let support = zone.read().submesh().read().to_poi1().unwrap();
    /// # let vars = || (vec!["f_x".to_string(), "f_y".to_string()],
    /// #                vec!["u_x".to_string(), "u_y".to_string()]);
    /// # let mat = Handle::new(SubElementField::from_uniform_per_component(
    /// #     zone.clone(), vec!["E".into(), "nu".into()], &[210_000.0, 0.3])?);
    /// # use pyrucast::models::ElementLayout;
    /// let c = Continuum::new(zone.clone(), Kinematics::PlaneStress, "Elasticity")?;
    /// // The element kernel, as the driver calls it. The stiffness matrix of
    /// // a free solid is **singular**: its rows sum to zero, a rigid-body
    /// // motion generating no force.
    /// //
    /// // `E` then `nu`: the field is stored in the contract's order, so the
    /// // table is the identity. A real assembly would have it resolved by
    /// // `Domain::element_layout`, which accepts any order.
    /// let lay = ElementLayout { material: vec![0, 1], optional_material: vec![], state: vec![] };
    /// let (duals, primals) = vars();
    /// let bloc = assemble_block(
    ///     std::slice::from_ref(&zone), &support, &support, duals, primals,
    ///     DofOrdering::NodesThenVars, Symmetry::Full, &mat, None,
    ///     |geoms, m, _s, ke| c.element_stiffness(
    ///         &geoms[0], m, &lay, MaterialSymmetry::Isotropic, ke),
    /// )?;
    /// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
    /// assert!(total.abs() < 1e-6);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_stiffness(
        &self,
        geom: &CellGeom,
        material: &SubElementField,
        lay: &ElementLayout,
        symmetry: MaterialSymmetry,
        ke: &mut [f64],
    ) -> Result<()> {
        // The same `Bᵀ D B` loop as the tangent, `D` being the elastic one of
        // the point — read **by index**: the zone resolved the names once.
        self.element_tangent_with(
            geom,
            |g, d| {
                symmetry::elastic_constitutive_into(
                    material.row(geom.cell, g),
                    &lay.material,
                    symmetry,
                    self.kinematics,
                    geom.space_dim,
                    d,
                )?;
                Ok(())
            },
            ke,
        )
    }

    /// Element kernel: local **consistent mass** `M_e = Σ_g ρ (Nᵀ N) |J| w` of
    /// one cell, written into `ke` (same flat row-major, **node-major /
    /// component-minor** dof order as [`element_stiffness`](Self::element_stiffness)).
    /// The vector shape-function matrix is block-diagonal, so
    /// `M[(i,a),(j,b)] = δ_ab ρ ∫ N_i N_j`. Density `ρ` is read from the optional
    /// material component `rho`, at every Gauss point. Pure, sequential and
    /// law-independent.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::SubElementField;
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::kernel::assemble_block;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let support = zone.read().submesh().read().to_poi1().unwrap();
    /// # let vars = || (vec!["f_x".to_string(), "f_y".to_string()],
    /// #                vec!["u_x".to_string(), "u_y".to_string()]);
    /// # let mat = Handle::new(SubElementField::from_uniform_per_component(
    /// #     zone.clone(), vec!["rho".into()], &[2.0])?);
    /// # use pyrucast::models::ElementLayout;
    /// # use pyrucast::containers::field::ABSENT_COMPONENT;
    /// # let c = Continuum::new(zone.clone(), Kinematics::PlaneStress, "Elasticity")?;
    /// // Mass reads only `rho`, the second **optional** component of the
    /// // continuum's contract (`["alpha", "rho"]`): `alpha` is absent here.
    /// let lay = ElementLayout {
    ///     material: vec![],
    ///     optional_material: vec![ABSENT_COMPONENT, 0],
    ///     state: vec![],
    /// };
    /// // The total mass is found in the sum of the entries, once per
    /// // direction: ρ × area × space_dim.
    /// let (duals, primals) = vars();
    /// let bloc = assemble_block(
    ///     std::slice::from_ref(&zone), &support, &support, duals, primals,
    ///     DofOrdering::NodesThenVars, Symmetry::Full, &mat, None,
    ///     |geoms, m, _s, ke| c.element_mass(&geoms[0], m, &lay, ke),
    /// )?;
    /// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
    /// assert!((total - 2.0 * 0.5 * 2.0).abs() < 1e-9);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_mass(
        &self,
        geom: &CellGeom,
        material: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        let n_nodes = geom.n_nodes;
        let space_dim = geom.space_dim;
        let dofs = space_dim * n_nodes;
        // `rho` is the second optional component of the continuum contract
        // (`["alpha", "rho"]`): absent, there is no mass to integrate.
        let i_rho = lay.optional_material[RHO_SLOT];
        if i_rho == ABSENT_COMPONENT {
            return Err(PyrucastError::Message(
                "Continuum mass matrix: material component `rho` (density) is required".into(),
            ));
        }
        for g in 0..geom.n_gauss {
            let n = geom.n_at_g(g);
            let w = geom.det_j_w(g) * material.row(geom.cell, g)[i_rho as usize];
            for i in 0..n_nodes {
                for j in 0..n_nodes {
                    let m = n[i] * n[j] * w;
                    for a in 0..space_dim {
                        let r = i * space_dim + a;
                        let c = j * space_dim + a;
                        ke[r * dofs + c] += m;
                    }
                }
            }
        }
        Ok(())
    }

    /// Element kernel: local **geometric (initial-stress) stiffness**
    ///   `Kg[(i,a),(j,b)] = δ_ab Σ_g Σ_cd (∂N_i/∂x_c) σ_cd (∂N_j/∂x_e) |J| w`
    /// of one cell, written into `ke` (same flat, node-major / component-minor
    /// dof order as [`element_stiffness`](Self::element_stiffness)). The scalar
    /// `∇N_i·σ·∇N_j` is applied to each displacement component's diagonal block
    /// (`δ_ab`). The current Cauchy stress `σ` (Voigt-named) is read from
    /// `state` per Gauss point. Pure, sequential and law-independent.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::SubElementField;
    /// # use pyrucast::containers::field::SubField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::continuum::Continuum;
    /// # use pyrucast::models::kernel::assemble_block;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let support = zone.read().submesh().read().to_poi1().unwrap();
    /// # let vars = || (vec!["f_x".to_string(), "f_y".to_string()],
    /// #                vec!["u_x".to_string(), "u_y".to_string()]);
    /// # let etat = Handle::new(SubElementField::from_uniform_per_component(
    /// #     zone.clone(),
    /// #     vec!["sigma_xx".into(), "sigma_yy".into(), "sigma_xy".into()],
    /// #     &[100.0, 0.0, 0.0])?);
    /// # // The geometric stiffness reads no material; the assembler wants one,
    /// # // so it is given a useless one rather than an Option.
    /// # let bidon = Handle::new(SubElementField::from_uniform_per_component(
    /// #     zone.clone(), vec!["E".into(), "nu".into()], &[210_000.0, 0.3])?);
    /// # use pyrucast::models::ElementLayout;
    /// # let c = Continuum::new(zone.clone(), Kinematics::PlaneStress, "Elasticity")?;
    /// // The convention reads `[σ_xx, σ_xy, σ_yy]`; the field above is stored
    /// // as `[σ_xx, σ_yy, σ_xy]`. That is all the table absorbs.
    /// let lay = ElementLayout {
    ///     material: vec![],
    ///     optional_material: vec![],
    ///     state: vec![0, 2, 1],
    /// };
    /// // The **geometric** stiffness, the one of buckling: it comes from the
    /// // stress state, not from the material. Under tension it is positive
    /// // definite; its sign is what decides the critical load.
    /// let (duals, primals) = vars();
    /// let bloc = assemble_block(
    ///     std::slice::from_ref(&zone), &support, &support, duals, primals,
    ///     DofOrdering::NodesThenVars, Symmetry::Full, &bidon, Some(&etat),
    ///     |geoms, _m, s, ke| c.element_geometric(&geoms[0], s.unwrap(), &lay, ke),
    /// )?;
    /// // It too is singular: the rigid modes cost nothing in it.
    /// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
    /// assert!(total.abs() < 1e-9);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_geometric(
        &self,
        geom: &CellGeom,
        stress: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        let n_nodes = geom.n_nodes;
        let d = geom.space_dim;
        let dofs = d * n_nodes;
        // `lay.state` is the Voigt stress in `voigt_matrix_reads` order, closed
        // by the hoop `σ_θθ` on a body of revolution — resolved once for the zone.
        let lay = &lay.state;
        let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
        for g in 0..geom.n_gauss {
            let dn = &mut dn_buf[..n_nodes * d]; // [i * d + c]
            geom.dn_dx(g, dn)?;
            let w = geom.det_j_w(g);
            let row = stress.row(geom.cell, g);
            let mut sig = [0.0_f64; 9]; // [c * d + e]
            internal_force::voigt_stress_matrix(row, lay, d, &mut sig);
            // On a body of revolution the hoop strain's own non-linear part,
            // ½(u_r/r)², contributes `σ_θθ N_i N_j / r²` on the radial diagonal —
            // the initial-stress counterpart of the `N_i / r` row of `B`.
            let hoop = if geom.axisymmetric {
                let r = geom.radius(g);
                // The hoop closes the read list, exactly as it does for `Bᵀσ`.
                Some((geom.n_at_g(g), row[lay[lay.len() - 1] as usize] / (r * r)))
            } else {
                None
            };
            for i in 0..n_nodes {
                for j in 0..n_nodes {
                    // Scalar gᵢⱼ = Σ_{c,e} (∂N_i/∂x_c) σ_ce (∂N_j/∂x_e).
                    let mut gij = 0.0;
                    for c in 0..d {
                        for e in 0..d {
                            gij += dn[i * d + c] * sig[c * d + e] * dn[j * d + e];
                        }
                    }
                    gij *= w;
                    // Same scalar on every component's diagonal block (δ_ab).
                    for a in 0..d {
                        ke[(i * d + a) * dofs + (j * d + a)] += gij;
                    }
                    if let Some((n, s_hoop)) = hoop {
                        ke[(i * d) * dofs + (j * d)] += s_hoop * n[i] * n[j] * w;
                    }
                }
            }
        }
        Ok(())
    }

    /// The full delegation: `∫ Bᵀ D B` of one cell, where `D` comes from
    /// `domain`'s `tangent_point`. That is all a continuum physics has to write
    /// for its `element_tangent` — one line.
    ///
    /// Generic over `D`, hence monomorphised: the `tangent_point` called at
    /// every Gauss point is a **static** call.
    #[allow(clippy::too_many_arguments)]
    /// The full delegation: `∫ Bᵀ D B` of one cell, where `D` comes from
    /// `domain`'s `tangent_point`. That is all a continuum physics has to write
    /// for its `element_tangent` — one line.
    ///
    /// Generic over `D`, hence monomorphised: the `tangent_point` called at
    /// every Gauss point is a **static** call.
    ///
    /// ```
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::ops::element_field::StrainMeasure;
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::element_field::ElementField;
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::ops::{element_field, matrix, model};
    /// # 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()])?;
    /// # let fes = FiniteElementSpace::lagrange1(&mesh)?;
    /// # let modele = model::elasticity(&fes, Kinematics::PlaneStress, MaterialSymmetry::Isotropic, StrainMeasure::Linear)?;
    /// # let materiaux = element_field::material_field(
    /// #     &modele, &[("E", 210_000.0), ("nu", 0.3)])?;
    /// # let eps = ElementField::new(
    /// #     &fes, vec!["eps_xx".into(), "eps_yy".into(), "eps_xy".into()])?;
    /// // End to end: the tangent of a linear law **is** its stiffness, and it
    /// // reaches it by the common path — without any field of moduli having
    /// // been materialised to carry it there.
    /// # let repos = element_field::behavior::initial_state(&modele, &materiaux)?;
    /// let kt = matrix::tangent(&modele, &materiaux, &eps, &repos, None)?;
    /// let k = matrix::stiffness(&modele, &materiaux)?;
    /// assert_eq!(kt.to_dmatrix()?, k.to_dmatrix()?);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn element_tangent_of<B: crate::models::Behavior + ?Sized>(
        &self,
        behavior: &B,
        geoms: &[CellGeom],
        lay: &crate::models::ZoneLayout,
        deformation: &SubElementField,
        prev: &SubElementField,
        material: &SubElementField,
        dt: f64,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        self.element_tangent_with(
            geom,
            |g, d| {
                behavior.tangent_point(
                    geom,
                    g,
                    lay,
                    deformation.row(geom.cell, g),
                    prev.row(geom.cell, g),
                    material.row(geom.cell, g),
                    dt,
                    d,
                )
            },
            ke,
        )
    }

    pub(crate) fn element_tangent_with<F>(
        &self,
        geom: &CellGeom,
        mut d_at: F,
        ke: &mut [f64],
    ) -> Result<()>
    where
        F: FnMut(usize, &mut [[f64; 6]; 6]) -> Result<()>,
    {
        let n_nodes = geom.n_nodes;
        let space_dim = geom.space_dim;
        let dofs = space_dim * n_nodes;
        let v = voigt_size(space_dim, self.kinematics);
        // Same stack buffers as `element_stiffness`, outside the loop.
        let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
        let mut b: VoigtRows = [[0.0; MAX_CELL_DOFS]; 6];
        let mut db: VoigtRows = [[0.0; MAX_CELL_DOFS]; 6];
        let mut d = [[0.0_f64; 6]; 6];
        for g in 0..geom.n_gauss {
            // Same hoop row as `element_stiffness` on a body of revolution.
            let hoop = if self.kinematics.is_axisymmetric() {
                Some((geom.n_at_g(g), geom.radius(g)))
            } else {
                None
            };
            geom.dn_dx(g, &mut dn_buf[..n_nodes * space_dim])?;
            b_matrix_into(
                &dn_buf[..n_nodes * space_dim],
                n_nodes,
                space_dim,
                hoop,
                &mut b,
            );
            // The provider writes `D` into the caller's buffer. It is
            // **generic**, never a `&dyn Fn`: one virtual call per Gauss point
            // shows, and this kernel makes one per point.
            d_at(g, &mut d)?;
            // DB = D·B (voigt × dofs), then Kᵉ += Bᵀ (DB) · |J| w.
            for r in 0..v {
                for c in 0..dofs {
                    let mut acc = 0.0;
                    for w in 0..v {
                        acc += d[r][w] * b[w][c];
                    }
                    db[r][c] = acc;
                }
            }
            let w = geom.det_j_w(g);
            for r in 0..dofs {
                for c in 0..dofs {
                    let mut acc = 0.0;
                    for vv in 0..v {
                        acc += b[vv][r] * db[vv][c];
                    }
                    ke[r * dofs + c] += acc * w;
                }
            }
        }
        Ok(())
    }
}