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
//! Timoshenko beams — one physics, three configurations.
//!
//! The shear-deformable beam theory: plane sections stay plane but **not**
//! normal to the deflected axis, so the section rotation is a field of its own
//! and the transverse shear `γ = w' − θ` is a strain in its own right. That is
//! the whole difference from [Euler-Bernoulli](crate::models::bernoulli), where
//! `θ = w'` and no shear exists.
//!
//! ## Three configurations, no argument
//!
//! [`BeamModel`] is read from the mesh — see [`crate::models::beam`] for why
//! there is nothing to choose. What the *theory* adds on top of the shared
//! configuration is a shear compliance: material components `G` and `A_s` (the
//! shear area `κ·A`), and a shear force among the section forces.
//!
//! | `Coords` | DOFs per node | material | section forces |
//! |---|---|---|---|
//! | 1-D | `w`, `theta` | `E, I, G, A_s` | `M, V` |
//! | 2-D | `u_x, u_y, r_z` | `+ A` | `N, M, V` |
//! | 3-D | six | `E, A, I_y, I_z, J, G, A_sy, A_sz` | `N, M_y, M_z, T, V_y, V_z` |
//!
//! ## The element is exact, so the space owns no basis
//!
//! The stiffness is the closed form of the solution of the two coupled
//! equations on a span free of distributed load — [`crate::models::beam::bending_4x4`], driven
//! by `Φ = 12EI/(G·A_s·L²)`. It is **nodally exact** for end loads, so one
//! element per member suffices, and its shape functions are cubic in the
//! deflection and quadratic in the rotation.
//!
//! Those functions depend on the material through `Φ`, so no finite-element
//! space can tabulate them. The subspace therefore declares
//! [`ModelEmbedded`](crate::atoms::Interpolation::ModelEmbedded): the
//! formulation owns its interpolation, and says so rather than claiming a
//! Lagrange one it does not use.
//!
//! This replaces an earlier **linear** element with reduced shear integration,
//! which converged with mesh refinement instead of being exact. The two
//! theories now line up: Bernoulli integrates a Hermite basis it declares,
//! Timoshenko owns an exact one it declares owning.
//!
//! ## Mass
//!
//! The consistent mass is the **same element's**, integrated from the same
//! shape functions — so stiffness and mass finally describe one beam. Only the
//! axial and torsional degrees of freedom keep the linear field's
//! `(ρL/6)[[2,1],[1,2]]`, which is exact for what they actually interpolate.

use crate::atoms::ElementType;
use crate::containers::element_field::SubElementField;
use crate::containers::field::ABSENT_COMPONENT;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::matrix::Symmetry;
use crate::containers::mesh::SubMesh;
use crate::containers::model::SubModel;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::beam::{self, bending_4x4, mass_4x4, BeamModel};
use crate::models::owned_components;
use crate::models::ZoneLayout;
use crate::models::{
    frame, frame3d, Behavior, CellGeom, Domain, MatrixLayout, Physics, SubModelKind,
};
use crate::models::{ElementLayout, MatrixKind};
use serde::{Deserialize, Serialize};

/// The material a configuration needs. `G` and `A_s` are what the theory adds
/// over [Bernoulli](crate::models::bernoulli): the shear compliance.
fn material_of(model: BeamModel) -> &'static [&'static str] {
    match model {
        BeamModel::Planar1d => &["E", "I", "G", "A_s"],
        BeamModel::Frame2d => &["E", "A", "I", "G", "A_s"],
        BeamModel::Frame3d => &["E", "A", "I_y", "I_z", "J", "G", "A_sy", "A_sz"],
    }
}

/// The section forces the behaviour reports — a shear force in every one, the
/// theory having a shear strain to conjugate it with.
fn behavior_of(model: BeamModel) -> &'static [&'static str] {
    match model {
        BeamModel::Planar1d => &["M", "V"],
        BeamModel::Frame2d => &["N", "M", "V"],
        BeamModel::Frame3d => &["N", "M_y", "M_z", "T", "V_y", "V_z"],
    }
}

/// The shear ratios the state carries beside the section forces — one per
/// bending plane, `Φ = 12EI/(G·A_s·L²)`.
fn shear_ratios_of(model: BeamModel) -> &'static [&'static str] {
    match model {
        BeamModel::Frame3d => &["phi_y", "phi_z"],
        _ => &["phi"],
    }
}

/// Timoshenko beam physics on a `SEG2` FE subspace.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Interpolation, 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::{Domain, SubModelKind};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = [[0.0], [1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&n.iter().map(|x| x.id()).collect::<Vec<_>>()).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::new(&maillage, Interpolation::ModelEmbedded).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # use pyrucast::models::timoshenko::Timoshenko;
/// // The exact beam: its interpolation depends on the material through Φ, so
/// // it belongs to the formulation, not to the space.
/// let t = Timoshenko::new(zone.clone())?;
/// assert!(t.material_components().contains(&"A_s".to_string()));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Serialize, Deserialize)]
pub struct Timoshenko {
    pub(crate) fespace: Handle<SubFiniteElementSpace>,
    /// POI1 support over the unique nodes (row/col support of the block).
    pub(crate) support: Handle<SubMesh>,
    pub(crate) model: BeamModel,
}

impl Timoshenko {
    /// Timoshenko beam on a `SEG2` FE subspace. The configuration follows the
    /// dimension of the mesh; the subspace must be `MODEL_EMBEDDED`.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Interpolation, 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::{Domain, SubModelKind};
    /// # let coords = Handle::new(Coords::new(1).unwrap());
    /// # let n: Vec<Node> = [[0.0], [1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # sm.add_cell(&n.iter().map(|x| x.id()).collect::<Vec<_>>()).unwrap();
    /// # let maillage = Mesh::from_submesh(sm);
    /// # let fes = FiniteElementSpace::new(&maillage, Interpolation::ModelEmbedded).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # use pyrucast::models::timoshenko::Timoshenko;
    /// // The exact beam: its interpolation depends on the material through Φ, so
    /// // it belongs to the formulation, not to the space.
    /// let t = Timoshenko::new(zone.clone())?;
    /// assert!(t.material_components().contains(&"A_s".to_string()));
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        let (submesh, space_dim, et, axisymmetric, interpolation) = {
            let s = fespace.read();
            (
                s.submesh(),
                s.space_dim(),
                s.element_type(),
                s.is_axisymmetric(),
                s.interpolation(),
            )
        };
        if et != ElementType::SEG2 {
            return Err(PyrucastError::Message(format!(
                "Timoshenko: a beam needs SEG2 elements, got {et}"
            )));
        }
        if !interpolation.is_model_embedded() {
            return Err(PyrucastError::Message(format!(
                "Timoshenko: this element is the exact beam, whose interpolation is \
                 cubic/quadratic and depends on the material through Φ = 12EI/(G·A_s·L²) — it is \
                 owned by the formulation, not by the space. Build the subspace with \
                 `Interpolation::ModelEmbedded`; got {interpolation}."
            )));
        }
        if axisymmetric {
            return Err(PyrucastError::Message(
                "Timoshenko: a segment in a meridian plane is a shell of revolution, not a beam"
                    .into(),
            ));
        }
        let model = BeamModel::from_space_dim(space_dim)
            .map_err(|e| PyrucastError::Message(format!("Timoshenko: {e}")))?;
        let support = submesh.read().to_poi1()?;
        Ok(Self {
            fespace,
            support,
            model,
        })
    }

    /// The layout every block of this physics shares.
    fn layout(&self) -> MatrixLayout {
        MatrixLayout {
            fespaces: vec![self.fespace.clone()],
            support: self.support.clone(),
            dual_vars: self.dual_vars(),
            primal_vars: self.primal_vars(),
            ordering: DofOrdering::NodesThenVars,
            symmetry: Symmetry::Full,
        }
    }
}

impl SubModelKind for Timoshenko {
    fn primal_vars(&self) -> Vec<String> {
        self.model.primal().iter().map(|s| s.to_string()).collect()
    }

    fn dual_vars(&self) -> Vec<String> {
        self.model.dual().iter().map(|s| s.to_string()).collect()
    }

    fn as_domain(&self) -> Option<&dyn Domain> {
        Some(self)
    }

    fn as_behavior(&self) -> Option<&dyn Behavior> {
        Some(self)
    }

    fn stiffness_layout(&self) -> Option<MatrixLayout> {
        Some(self.layout())
    }

    fn mass_layout(&self) -> Option<MatrixLayout> {
        Some(self.layout())
    }

    /// The geometric stiffness needs an axial force to be stiffened by, which a
    /// pure-bending configuration does not have.
    fn geometric_layout(&self) -> Option<MatrixLayout> {
        match self.model {
            BeamModel::Planar1d => None,
            _ => Some(self.layout()),
        }
    }

    /// Internal forces `f = ∫ Bᵀ σ dx` — the **transpose** of the very `B` this
    /// physics' deformation operator applies
    /// ([`crate::models::beam::b_into`]), integrated against the section
    /// forces. The continuum default reads a Voigt stress tensor, which a field
    /// carrying `N`, `M` and `V` has never had.
    ///
    /// The read list is the behaviour's own output, in its own order: the
    /// section forces first, conjugate to the leading rows of `B`, then the
    /// shear ratios its interpolation is built on.
    fn internal_force_reads(&self) -> Vec<String> {
        Behavior::behavior_output_components(self)
    }

    fn internal_force_element(
        &self,
        geoms: &[CellGeom],
        stress: &SubElementField,
        lay: &[u32],
        _material: &SubElementField,
        _mat: &[u32],
        fe: &mut [f64],
    ) -> Result<()> {
        let forces = behavior_of(self.model).len();
        beam::internal_force_into(
            self.model,
            &geoms[0],
            stress,
            &lay[..forces],
            &lay[forces..],
            fe,
        );
        Ok(())
    }

    fn physics(&self) -> &'static [Physics] {
        &[Physics::Mechanical]
    }

    fn label(&self) -> &'static str {
        "Timoshenko"
    }

    fn render(&self, _opts: &DumpOptions) -> String {
        let primal = self.primal_vars().join(", ");
        let dual = self.dual_vars().join(", ");
        let n = self.support.read().cell_count();
        format!(
            "SubModel<Timoshenko({})>\n  primal var(s): {primal}\n  dual var(s):   {dual}\n  \
             support: {n} node(s)",
            self.model
        )
    }
}

impl Domain for Timoshenko {
    fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
        self.fespace.clone()
    }

    fn material_components(&self) -> Vec<String> {
        owned_components(material_of(self.model))
    }

    /// `rho` for the mass, and — in the 1-D configuration — the full area `A`,
    /// which only the mass needs (the stiffness uses the shear area).
    fn optional_material_components(&self) -> &'static [&'static str] {
        match self.model {
            BeamModel::Planar1d => &["A", "rho"],
            _ => &["rho"],
        }
    }

    /// The beam's geometric stiffness reads its axial force.
    fn element_state_reads(&self, kind: MatrixKind) -> Vec<String> {
        match kind {
            MatrixKind::Geometric => vec!["N".to_string()],
            _ => Vec::new(),
        }
    }

    fn element_matrix(
        &self,
        geoms: &[CellGeom],
        material: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        // Every configuration has its contract (`material_of`); the constants are read
        // through the indices the zone resolved, in that order.
        let m = |k: usize| material.row(geom.cell, 0)[lay.material[k] as usize];
        match self.model {
            // [E, I, G, A_s]
            BeamModel::Planar1d => planar_stiffness(geom, m(0) * m(1), m(2) * m(3), ke),
            // [E, A, I, G, A_s]
            BeamModel::Frame2d => {
                frame::element_stiffness(geom, m(0) * m(1), m(0) * m(2), m(3) * m(4), ke)
            }
            // [E, A, I_y, I_z, J, G, A_sy, A_sz]
            BeamModel::Frame3d => frame3d::element_stiffness(
                geom,
                m(0) * m(1),
                m(5) * m(4),
                m(0),
                m(2),
                m(3),
                m(5),
                m(6),
                m(7),
                ke,
            ),
        }
    }

    fn element_mass(
        &self,
        geoms: &[CellGeom],
        material: &SubElementField,
        lay: &ElementLayout,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        let row = material.row(geom.cell, 0);
        let m = |k: usize| row[lay.material[k] as usize];
        // `rho` closes each configuration's list of optional components; without it
        // there is no mass to integrate.
        let rho = optional(row, lay, lay.optional_material.len() - 1, "rho")?;
        match self.model {
            // [E, I, G, A_s] + facultatives [A, rho]
            BeamModel::Planar1d => {
                let a = optional(row, lay, 0, "A")?;
                planar_mass(geom, rho * a, rho * m(1), m(0) * m(1), m(2) * m(3), ke)
            }
            // [E, A, I, G, A_s]
            BeamModel::Frame2d => frame::element_mass(
                geom,
                rho * m(1),
                rho * m(2),
                m(0) * m(2),
                Some(m(3) * m(4)),
                ke,
            ),
            // [E, A, I_y, I_z, J, G, A_sy, A_sz]
            BeamModel::Frame3d => frame3d::element_mass(
                geom,
                rho,
                m(1),
                m(2),
                m(3),
                m(0),
                Some(m(5)),
                Some(m(6)),
                Some(m(7)),
                ke,
            ),
        }
    }

    fn element_geometric(
        &self,
        geoms: &[CellGeom],
        _material: &SubElementField,
        lay: &ElementLayout,
        state: &SubElementField,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        match self.model {
            BeamModel::Planar1d => Err(PyrucastError::Message(
                "Timoshenko: a pure-bending beam carries no axial force, so it has no geometric \
                 stiffness — use a 2-D or 3-D configuration"
                    .into(),
            )),
            _ => {
                let n = state.row(geom.cell, 0)[lay.state[0] as usize];
                match self.model {
                    BeamModel::Frame2d => frame::element_geometric(geom, n, ke),
                    _ => frame3d::element_geometric(geom, n, ke),
                }
            }
        }
    }
}

impl Behavior for Timoshenko {
    fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
        self.fespace.clone()
    }

    /// The section forces — **and** the shear ratio `Φ` of each bending plane.
    ///
    /// `Φ` is not a section force, and nothing else in this crate keeps in the
    /// state a quantity its consumer could recompute. It is the one exception,
    /// and a deliberate one. The exact element's *interpolation* depends on the
    /// material through `Φ`, so its `B` — and with it `∫ Bᵀσ` — cannot be
    /// written without it; but the internal-force kernel is handed the state and
    /// not the material, that seam having never needed one (a continuum's `B` is
    /// the symmetric gradient, and knows nothing of any modulus). Carrying `Φ`
    /// in the state is what lets a beam's residual exist without giving every
    /// physics in the crate a material argument it would ignore.
    ///
    /// It earns its place in the field rather than being recomputed because the
    /// residual re-reads it at **every** Newton iteration — which is the same
    /// test the consistent tangent was measured against before it stopped being
    /// stored.
    fn behavior_output_components(&self) -> Vec<String> {
        behavior_of(self.model)
            .iter()
            .chain(shear_ratios_of(self.model))
            .map(|s| s.to_string())
            .collect()
    }

    /// The section forces from the generalised strains — a **linear** law, as
    /// for every structural element.
    fn deformation_reads(&self) -> Vec<String> {
        owned_components(match self.model {
            BeamModel::Planar1d => &["kappa", "gamma"][..],
            BeamModel::Frame2d => &["eps", "kappa", "gamma"][..],
            BeamModel::Frame3d => {
                &["eps", "kappa_y", "kappa_z", "torsion", "gamma_y", "gamma_z"][..]
            }
        })
    }

    fn integrate_point(
        &self,
        geom: &CellGeom,
        _g: usize,
        lay: &ZoneLayout,
        deformation: &[f64],
        _prev: &[f64],
        material: &[f64],
        _dt: f64,
        out: &mut [f64],
    ) -> Result<()> {
        let m = |k: usize| material[lay.material[k] as usize];
        let e = |k: usize| deformation[lay.deformation[k] as usize];
        // The span: the only geometry `Φ` needs, and it is right there.
        let l = beam::span(geom.node_coord(0), geom.node_coord(1));
        match self.model {
            // [E, I, G, A_s] × [κ, γ]
            BeamModel::Planar1d => {
                out[0] = m(0) * m(1) * e(0); // E·I·κ
                out[1] = m(2) * m(3) * e(1); // G·A_s·γ
                out[2] = beam::phi(m(0) * m(1), Some(m(2) * m(3)), l);
            }
            // [E, A, I, G, A_s] × [ε, κ, γ]
            BeamModel::Frame2d => {
                out[0] = m(0) * m(1) * e(0); // E·A·ε
                out[1] = m(0) * m(2) * e(1); // E·I·κ
                out[2] = m(3) * m(4) * e(2); // G·A_s·γ
                out[3] = beam::phi(m(0) * m(2), Some(m(3) * m(4)), l);
            }
            // [E, A, I_y, I_z, J, G, A_sy, A_sz] × [ε, κ_y, κ_z, torsion, γ_y, γ_z]
            BeamModel::Frame3d => {
                out[0] = m(0) * m(1) * e(0); // E·A·ε
                out[1] = m(0) * m(2) * e(1); // E·I_y·κ_y
                out[2] = m(0) * m(3) * e(2); // E·I_z·κ_z
                out[3] = m(5) * m(4) * e(3); // G·J·torsion
                out[4] = m(5) * m(6) * e(4); // G·A_sy·γ_y
                out[5] = m(5) * m(7) * e(5); // G·A_sz·γ_z
                                             // One bending plane per `Φ`, each with its inertia and its pair — the pairing
                                             // section réduite : x'-y' porte `I_z` et `A_sy`, x'-z' l'autre
                                             // `b_into` expects.
                out[6] = beam::phi(m(0) * m(3), Some(m(5) * m(6)), l);
                out[7] = beam::phi(m(0) * m(2), Some(m(5) * m(7)), l);
            }
        }
        Ok(())
    }
}

// ─── The 1-D configuration's own kernels ────────────────────────────────────
//
// The plane and space frames delegate to [`crate::models::frame`] and
// [`crate::models::frame3d`], which hold the rotations to the global axes. A
// 1-D beam has no rotation to make, so its kernels are the bare blocks.

/// The exact bending stiffness of a 1-D beam, on `[w_A, θ_A, w_B, θ_B]`.
/// An optional component, read through the index the zone resolved — when
/// missing, it names itself in the error rather than silently being zero.
fn optional(row: &[f64], lay: &ElementLayout, slot: usize, name: &str) -> Result<f64> {
    match lay.optional_material[slot] {
        ABSENT_COMPONENT => Err(PyrucastError::Message(format!(
            "Timoshenko mass matrix: material component `{name}` is required"
        ))),
        i => Ok(row[i as usize]),
    }
}

fn planar_stiffness(geom: &CellGeom, ei: f64, gas: f64, ke: &mut [f64]) -> Result<()> {
    let (xa, xb) = (geom.node_coord(0), geom.node_coord(1));
    let l = (xb[0] - xa[0]).abs();
    if l <= f64::EPSILON {
        return Err(PyrucastError::Message(format!(
            "Timoshenko: cell {} has zero length",
            geom.cell
        )));
    }
    let k = bending_4x4(ei, Some(gas), l);
    for (r, row) in k.iter().enumerate() {
        for (c, v) in row.iter().enumerate() {
            ke[r * 4 + c] += v;
        }
    }
    Ok(())
}

/// Consistent **mass** of a 1-D beam — translations `(ρAL/6)[[2,1],[1,2]]` and
/// rotary inertia `(ρIL/6)[[2,1],[1,2]]`, in DOF order `[w0, θ0, w1, θ1]`.
///
/// This is the *linear* element's mass, kept as it was; see the module note.
fn planar_mass(
    geom: &CellGeom,
    rho_a: f64,
    rho_i: f64,
    ei: f64,
    gas: f64,
    ke: &mut [f64],
) -> Result<()> {
    let (xa, xb) = (geom.node_coord(0), geom.node_coord(1));
    let l = (xb[0] - xa[0]).abs();
    let m = mass_4x4(rho_a, rho_i, ei, Some(gas), l);
    for (r, row) in m.iter().enumerate() {
        for (c, v) in row.iter().enumerate() {
            ke[r * 4 + c] += v;
        }
    }
    Ok(())
}

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

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

    /// One `SEG2` from `a` to `b`, in whatever dimension the coordinates have.
    fn one_beam(a: &[f64], b: &[f64]) -> (Timoshenko, NodeId, NodeId) {
        let coords = Handle::new(Coords::new(a.len() as u8).unwrap());
        let na = Node::create_in(coords.clone(), a).unwrap();
        let nb = Node::create_in(coords.clone(), b).unwrap();
        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[na.id(), nb.id()]).unwrap();
        let fes = FiniteElementSpace::new(&mesh, Interpolation::ModelEmbedded).unwrap();
        let beam = Timoshenko::new(fes.get(0).unwrap()).unwrap();
        (beam, na.id(), nb.id())
    }

    fn material(beam: &Timoshenko, pairs: &[(&str, f64)]) -> Handle<SubElementField> {
        let names: Vec<String> = pairs.iter().map(|(c, _)| (*c).to_string()).collect();
        let mut m = SubElementField::new(beam.fespace.clone(), names).unwrap();
        for (c, v) in pairs {
            m.set_uniform(c, *v).unwrap();
        }
        Handle::new(m)
    }

    /// The configuration is read from the mesh, and with it every DOF name.
    #[test]
    fn the_configuration_follows_the_dimension() {
        let (b1, _, _) = one_beam(&[0.0], &[2.0]);
        assert_eq!(b1.primal_vars(), ["w", "theta"]);
        let (b2, _, _) = one_beam(&[0.0, 0.0], &[2.0, 0.0]);
        assert_eq!(b2.primal_vars(), ["u_x", "u_y", "r_z"]);
        let (b3, _, _) = one_beam(&[0.0, 0.0, 0.0], &[2.0, 0.0, 0.0]);
        assert_eq!(b3.primal_vars().len(), 6);
    }

    /// A Lagrange subspace is refused, and the message says why rather than
    /// leaving the caller to guess which space a beam wants.
    #[test]
    fn a_lagrange_subspace_is_refused() {
        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 err = match Timoshenko::new(fes.get(0).unwrap()) {
            Err(e) => e.to_string(),
            Ok(_) => panic!("a Lagrange subspace should be refused"),
        };
        assert!(err.contains("ModelEmbedded"), "message: {err}");
    }

    /// The exact element combines the bending and shear compliances **in
    /// series** — bend the member and shear it, and the two give way one after
    /// the other. That is the physical content of the `Φ` correction, and it
    /// holds in every configuration.
    #[test]
    fn the_tip_stiffness_is_the_two_compliances_in_series() {
        let l = 2.0;
        let (e, i, g, a_s) = (3.0, 2.0, 5.0, 2.0);
        let (ei, gas) = (e * i, g * a_s);
        let series = 1.0 / (l * l * l / (12.0 * ei) + l / gas);

        // 1-D: the bare block.
        let (beam, a, _) = one_beam(&[0.0], &[l]);
        let mat = material(&beam, &[("E", e), ("I", i), ("G", g), ("A_s", a_s)]);
        let k = &beam.build_stiffness_blocks(&mat).unwrap()[0];
        assert!((k.get(a, "f_w", a, "w") - series).abs() < 1e-9);

        // 2-D: the same block, rotated, and decoupled from the axial term.
        let (frame, a2, _) = one_beam(&[0.0, 0.0], &[l, 0.0]);
        let mat = material(
            &frame,
            &[("E", e), ("A", 4.0), ("I", i), ("G", g), ("A_s", a_s)],
        );
        let k = &frame.build_stiffness_blocks(&mat).unwrap()[0];
        assert!((k.get(a2, "f_y", a2, "u_y") - series).abs() < 1e-9);
        assert!((k.get(a2, "f_x", a2, "u_x") - e * 4.0 / l).abs() < 1e-9);
        assert!(k.get(a2, "f_x", a2, "u_y").abs() < 1e-9);
    }

    /// A vertical member puts the axial term on `u_y` — the local axes are read
    /// from the geometry, with no orientation data to supply.
    #[test]
    fn a_vertical_member_finds_its_own_axes() {
        let l = 2.0;
        let (e, area) = (3.0, 4.0);
        let (frame, a, _) = one_beam(&[0.0, 0.0], &[0.0, l]);
        let mat = material(
            &frame,
            &[("E", e), ("A", area), ("I", 2.0), ("G", 5.0), ("A_s", 2.0)],
        );
        let k = &frame.build_stiffness_blocks(&mat).unwrap()[0];
        assert!((k.get(a, "f_y", a, "u_y") - e * area / l).abs() < 1e-9);
        assert!(k.get(a, "f_y", a, "u_x").abs() < 1e-9);
    }

    /// A pure-bending beam has no axial force, so it declares no geometric
    /// stiffness — rather than assembling an empty one that would read as "this
    /// member cannot buckle".
    #[test]
    fn a_pure_bending_beam_declares_no_geometric_stiffness() {
        let (b1, _, _) = one_beam(&[0.0], &[2.0]);
        assert!(b1.geometric_layout().is_none());
        let (b2, _, _) = one_beam(&[0.0, 0.0], &[2.0, 0.0]);
        assert!(b2.geometric_layout().is_some());
    }
}

crate::physics_operator! {
    /// Timoshenko-beam `Model` spanning **every** subspace of `fes`.
    /// Parent-level operator; material (`E`, `I`, `G`, `A_s`) is
    /// supplied at assembly time.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::containers::model::{Model, SubModel};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # use pyrucast::models::tensor::Kinematics;
    /// # use pyrucast::models::symmetry::MaterialSymmetry;
    /// # use pyrucast::models::{Physics, RelationSense};
    /// # use pyrucast::ops::mesh;
    /// # 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 zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::atoms::Interpolation;
    /// # let mut b = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # b.add_cell(&[n[0].id(), n[1].id()])?;
    /// let poutres =
    ///     FiniteElementSpace::new(&Mesh::from_submesh(b), Interpolation::ModelEmbedded)?;
    /// let m = model::timoshenko(&poutres)?;
    /// assert_eq!(m.len(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn timoshenko(fes) via SubModel::timoshenko;
    python: "`model.timoshenko(fespace)` — the **shear-deformable** beam, in whichever\nconfiguration the mesh puts it (`SEG2` throughout):\n\n| `Coords` | DOFs per node | material | section forces |\n|---|---|---|---|\n| 1-D | `w`, `theta` | `E, I, G, A_s` | `M, V` |\n| 2-D | `u_x, u_y, r_z` | `+ A` | `N, M, V` |\n| 3-D | six | `E, A, I_y, I_z, J, G, A_sy, A_sz` | `N, M_y, M_z, T, V_y, V_z` |\n\nThis replaces `model.frame` and `model.frame3d`, which were the same\nphysics in 2-D and 3-D. Read the DOF names back with\n`model.primal_vars()`.\n\nThe element is the **exact** one — the closed form driven by\n`Φ = 12EI/(G·A_s·L²)` — so one element per member suffices. Its shape\nfunctions depend on the material through `Φ`, hence no space can tabulate\nthem: build the subspace with\n`FiniteElementSpace(mesh, interpolation=\"MODEL_EMBEDDED\")`.\n\nPrefer `bernoulli` for a slender member, where the shear compliance is\nnegligible."
}