pyrucast 0.2.1

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
//! 3-D Timoshenko frame (space frame) physics.
//!
//! A `SEG2` element in a 3-D configuration with **six** DOFs per node: the
//! displacement `u_x, u_y, u_z` and the rotation `r_x, r_y, r_z`. The local
//! 12×12 stiffness combines:
//!
//! - **axial** `E·A`,
//! - **torsion** `G·J` (about the beam axis),
//! - **bending** about the two principal axes (`E·I_z` with shear `G·A_sy`,
//!   `E·I_y` with shear `G·A_sz`), using the closed-form **Timoshenko** element
//!   (shear parameters `Φ`), which is nodally exact for end loads.
//!
//! It is rotated to the global frame by `K = Tᵀ K_loc T`. The section axes
//! (local `y'`, `z'`) are taken **automatically** from a global-Z reference
//! (global Y for a vertical beam), so no orientation data is needed — fine for
//! symmetric sections (`I_y = I_z`).
//!
//! Primal `u_x, u_y, u_z, r_x, r_y, r_z`; dual `f_x, f_y, f_z, m_x, m_y, m_z`.
//! Material components `E, A, I_y, I_z, J, G, A_sy, A_sz`. Besides the stiffness
//! it assembles the consistent **mass** (translational `ρA` + rotary
//! `ρI_p`/`ρI_y`/`ρI_z`, optional `rho`) and the **geometric stiffness** under
//! the axial force `N` — linear-element forms, rotated `Tᵀ·T`.

use crate::atoms::ElementType;
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::mesh::SubMesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use crate::store::{read, Handle};
use serde::{Deserialize, Serialize};

const MATERIAL_COMPONENTS: &[&str] = &["E", "A", "I_y", "I_z", "J", "G", "A_sy", "A_sz"];
/// Primal DOF names (displacement + rotation), per node.
const PRIMAL: [&str; 6] = ["u_x", "u_y", "u_z", "r_x", "r_y", "r_z"];
/// Dual DOF names (force + moment), per node.
const DUAL: [&str; 6] = ["f_x", "f_y", "f_z", "m_x", "m_y", "m_z"];

/// 3-D Timoshenko frame physics on a 3-D `SEG2` FE subspace.
///
/// Material data (`E, A, I_y, I_z, J, G, A_sy, A_sz`) is supplied at assembly
/// time.
#[derive(Clone, Serialize, Deserialize)]
pub struct Frame3d {
    pub(crate) fespace: Handle<SubFiniteElementSpace>,
    /// POI1 support over the unique nodes (row/col support).
    pub(crate) support: Handle<SubMesh>,
}

impl Frame3d {
    /// 3-D frame physics on a 3-D `SEG2` FE subspace. Errors unless the
    /// subspace is `SEG2` in a 3-D configuration.
    pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
        let (submesh, space_dim, et) = {
            let s = read(&fespace)?;
            (s.submesh(), s.space_dim(), s.element_type()?)
        };
        if et != ElementType::SEG2 {
            return Err(PyrucastError::Message(format!(
                "Frame3d: expected SEG2 elements, got {et}"
            )));
        }
        if space_dim != 3 {
            return Err(PyrucastError::Message(format!(
                "Frame3d: space frame requires a 3-D configuration, got {space_dim}-D"
            )));
        }
        let support = read(&submesh)?.to_poi1()?;
        Ok(Self { fespace, support })
    }
}

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

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

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

    fn stiffness_layout(&self) -> Option<MatrixLayout> {
        Some(MatrixLayout {
            fespaces: vec![self.fespace.clone()],
            support: self.support.clone(),
            dual_vars: self.dual_vars(),
            primal_vars: self.primal_vars(),
            ordering: DofOrdering::NodesThenVars,
            symmetric: true,
        })
    }

    /// Mass and geometric-stiffness blocks share the stiffness layout.
    fn mass_layout(&self) -> Option<MatrixLayout> {
        self.stiffness_layout()
    }

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

    fn element_matrix(
        &self,
        geoms: &[CellGeom],
        material: Option<&SubElementField>,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        element_stiffness(
            geom,
            material.expect("Frame3d requires a material field"),
            ke,
        )
    }

    fn element_mass(
        &self,
        geoms: &[CellGeom],
        material: Option<&SubElementField>,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        element_mass(
            geom,
            material.expect("Frame3d requires a material field"),
            ke,
        )
    }

    fn element_geometric(
        &self,
        geoms: &[CellGeom],
        _material: Option<&SubElementField>,
        state: Option<&SubElementField>,
        ke: &mut [f64],
    ) -> Result<()> {
        let geom = &geoms[0];
        let stress = state.expect("frame3d geometric stiffness requires the axial force `N`");
        element_geometric(geom, stress, ke)
    }

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

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

    fn render(&self, _opts: &DumpOptions) -> String {
        let n = read(&self.support).map(|s| s.cell_count()).unwrap_or(0);
        format!(
            "SubModel<Frame3d>\n  primal var(s): u_x, u_y, u_z, r_x, r_y, r_z\n  \
             dual var(s):   f_x, f_y, f_z, m_x, m_y, m_z\n  support: {n} node(s)"
        )
    }
}

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

    fn material_components(&self) -> Option<&'static [&'static str]> {
        Some(MATERIAL_COMPONENTS)
    }

    /// `rho` (density) — required only by the mass matrix.
    fn optional_material_components(&self) -> &'static [&'static str] {
        &["rho"]
    }

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

    /// Section forces `N, M_y, M_z, T, V_y, V_z` — the linear law on the
    /// generalised strains `(eps, kappa_y, kappa_z, torsion, gamma_y, gamma_z)`
    /// produced by
    /// [`crate::ops::element_field::frame_deformation`](fn@crate::ops::element_field::frame_deformation).
    fn behavior_output_components(&self) -> Result<Vec<String>> {
        Ok(vec![
            "N".into(),
            "M_y".into(),
            "M_z".into(),
            "T".into(),
            "V_y".into(),
            "V_z".into(),
        ])
    }

    /// `N = E·A·ε`, `M_y = E·I_y·κ_y`, `M_z = E·I_z·κ_z`, `T = G·J·torsion`,
    /// `V_y = G·A_sy·γ_y`, `V_z = G·A_sz·γ_z` at one Gauss point.
    fn integrate_point(
        &self,
        geom: &CellGeom,
        input: &SubElementField,
        _prev: Option<&SubElementField>,
        material: Option<&SubElementField>,
        g: usize,
        _dt: Option<f64>,
        out: &mut [f64],
    ) -> Result<()> {
        let mat = material.expect("Frame3d declares a material_fespace ⇒ material is supplied");
        let cell = geom.cell;
        let v = |c| mat.value(cell, 0, c);
        let e = v("E")?;
        let gg = v("G")?;
        out[0] = e * v("A")? * input.value(cell, g, "eps")?;
        out[1] = e * v("I_y")? * input.value(cell, g, "kappa_y")?;
        out[2] = e * v("I_z")? * input.value(cell, g, "kappa_z")?;
        out[3] = gg * v("J")? * input.value(cell, g, "torsion")?;
        out[4] = gg * v("A_sy")? * input.value(cell, g, "gamma_y")?;
        out[5] = gg * v("A_sz")? * input.value(cell, g, "gamma_z")?;
        Ok(())
    }
}

// ─── Geometry helpers ────────────────────────────────────────────────────────

fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
    [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]
}
fn norm(a: [f64; 3]) -> f64 {
    (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt()
}
fn normalize(a: [f64; 3]) -> [f64; 3] {
    let n = norm(a);
    [a[0] / n, a[1] / n, a[2] / n]
}

/// Local axes `R = [x'; y'; z']` (rows, in global coords) from the beam
/// direction `d`. `x'` is along the beam; `y'`/`z'` come from a global-Z
/// reference (global Y if the beam is ~vertical) — automatic orientation.
fn local_axes(d: [f64; 3]) -> [[f64; 3]; 3] {
    let x = normalize(d);
    let z_ref = if x[2].abs() > 0.999 {
        [0.0, 1.0, 0.0]
    } else {
        [0.0, 0.0, 1.0]
    };
    let y = normalize(cross(z_ref, x)); // ⟂ x' and ref
    let z = cross(x, y); // completes the right-handed triad
    [x, y, z]
}

/// Local 12×12 Timoshenko frame stiffness, DOF order per node
/// `[u', v', w', θx', θy', θz']`.
#[allow(clippy::too_many_arguments)]
fn local_stiffness(
    ea: f64,
    gj: f64,
    e: f64,
    iy: f64,
    iz: f64,
    g: f64,
    asy: f64,
    asz: f64,
    l: f64,
) -> [[f64; 12]; 12] {
    let mut k = [[0.0_f64; 12]; 12];
    let a = ea / l; // axial
    let t = gj / l; // torsion
                    // Shear parameters for the two bending planes.
    let phi_y = 12.0 * e * iz / (g * asy * l * l); // x'-y' plane (I_z, A_sy)
    let phi_z = 12.0 * e * iy / (g * asz * l * l); // x'-z' plane (I_y, A_sz)

    let kv1 = 12.0 * e * iz / (l * l * l * (1.0 + phi_y));
    let kv2 = 6.0 * e * iz / (l * l * (1.0 + phi_y));
    let kv3 = (4.0 + phi_y) * e * iz / (l * (1.0 + phi_y));
    let kv4 = (2.0 - phi_y) * e * iz / (l * (1.0 + phi_y));

    let kw1 = 12.0 * e * iy / (l * l * l * (1.0 + phi_z));
    let kw2 = 6.0 * e * iy / (l * l * (1.0 + phi_z));
    let kw3 = (4.0 + phi_z) * e * iy / (l * (1.0 + phi_z));
    let kw4 = (2.0 - phi_z) * e * iy / (l * (1.0 + phi_z));

    // Upper triangle (then mirrored). DOFs: u'=0/6, v'=1/7, w'=2/8,
    // θx'=3/9, θy'=4/10, θz'=5/11.
    k[0][0] = a;
    k[0][6] = -a;
    k[6][6] = a;
    k[3][3] = t;
    k[3][9] = -t;
    k[9][9] = t;
    // x'-y' plane: v' (1, 7), θz' (5, 11).
    k[1][1] = kv1;
    k[1][5] = kv2;
    k[1][7] = -kv1;
    k[1][11] = kv2;
    k[5][5] = kv3;
    k[5][7] = -kv2;
    k[5][11] = kv4;
    k[7][7] = kv1;
    k[7][11] = -kv2;
    k[11][11] = kv3;
    // x'-z' plane: w' (2, 8), θy' (4, 10) — sign-flipped coupling.
    k[2][2] = kw1;
    k[2][4] = -kw2;
    k[2][8] = -kw1;
    k[2][10] = -kw2;
    k[4][4] = kw3;
    k[4][8] = kw2;
    k[4][10] = kw4;
    k[8][8] = kw1;
    k[8][10] = kw2;
    k[10][10] = kw3;

    for i in 0..12 {
        for j in (i + 1)..12 {
            k[j][i] = k[i][j];
        }
    }
    k
}

/// Rotation `T` (12×12): block-diagonal repetition of `R` over the four DOF
/// triples `[u_A], [θ_A], [u_B], [θ_B]`.
fn rotation(r: &[[f64; 3]; 3]) -> [[f64; 12]; 12] {
    let mut t = [[0.0_f64; 12]; 12];
    for blk in 0..4 {
        let o = blk * 3;
        for i in 0..3 {
            for j in 0..3 {
                t[o + i][o + j] = r[i][j];
            }
        }
    }
    t
}

fn matmul(a: &[[f64; 12]; 12], b: &[[f64; 12]; 12]) -> [[f64; 12]; 12] {
    let mut out = [[0.0_f64; 12]; 12];
    for i in 0..12 {
        for j in 0..12 {
            let mut acc = 0.0;
            for k in 0..12 {
                acc += a[i][k] * b[k][j];
            }
            out[i][j] = acc;
        }
    }
    out
}

fn transpose(a: &[[f64; 12]; 12]) -> [[f64; 12]; 12] {
    let mut out = [[0.0_f64; 12]; 12];
    for i in 0..12 {
        for j in 0..12 {
            out[i][j] = a[j][i];
        }
    }
    out
}

/// Assemble `K = Tᵀ K_loc T` of every 3-D frame element into `k`, at
/// `(NodeId_i, dual_a) × (NodeId_j, primal_b)`.
/// Element kernel: local 3-D frame stiffness `K = Tᵀ K_loc T` of one 2-node
/// element, written into `ke` (flat row-major 12×12, **node-major /
/// variable-minor** dof order `dof = node·6 + var`). Pure and sequential —
/// driven in parallel by [`crate::models::kernel::assemble_block`].
pub fn element_stiffness(
    geom: &CellGeom,
    material: &SubElementField,
    ke: &mut [f64],
) -> Result<()> {
    let cell = geom.cell;
    let xa = geom.node_coord(0)?;
    let xb = geom.node_coord(1)?;
    let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
    let l = norm(d);
    // [E·A, G·J, E, I_y, I_z, G, A_sy, A_sz].
    let v = |c| material.value(cell, 0, c);
    let kl = local_stiffness(
        v("E")? * v("A")?,
        v("G")? * v("J")?,
        v("E")?,
        v("I_y")?,
        v("I_z")?,
        v("G")?,
        v("A_sy")?,
        v("A_sz")?,
        l,
    );
    let t = rotation(&local_axes(d));
    let kg = matmul(&transpose(&t), &matmul(&kl, &t)); // Tᵀ K_loc T

    for r in 0..12 {
        for c in 0..12 {
            ke[r * 12 + c] = kg[r][c];
        }
    }
    Ok(())
}

/// Local 12×12 **consistent mass** (linear element): `(ρAL/6)[[2,1],[1,2]]` on
/// each translation `u',v',w'`, and rotary inertia `(ρI L/6)[[2,1],[1,2]]` on
/// each rotation — polar `I_p = I_y + I_z` for the torsion `θx'`, `I_y` for
/// `θy'`, `I_z` for `θz'`. No translation–rotation coupling for the linear
/// kinematics.
fn local_mass(rho: f64, area: f64, iy: f64, iz: f64, l: f64) -> [[f64; 12]; 12] {
    let mut m = [[0.0_f64; 12]; 12];
    // (local dof, rotary second-moment) for each of the six per-node DOFs.
    let inertia = [area, area, area, iy + iz, iy, iz];
    for (var, &sec) in inertia.iter().enumerate() {
        let ms = rho * sec * l / 6.0;
        let (i, j) = (var, var + 6); // node A / node B
        m[i][i] += 2.0 * ms;
        m[j][j] += 2.0 * ms;
        m[i][j] += ms;
        m[j][i] += ms;
    }
    m
}

/// Local 12×12 **geometric stiffness** under axial force `N`:
/// `(N/L)[[1,−1],[−1,1]]` on each transverse translation `v'` (1, 7) and `w'`
/// (2, 8); the axial, torsion and bending-rotation DOFs carry no term for the
/// linear element.
fn local_geometric(n: f64, l: f64) -> [[f64; 12]; 12] {
    let mut k = [[0.0_f64; 12]; 12];
    let g = n / l;
    for &(i, j) in &[(1usize, 7usize), (2, 8)] {
        k[i][i] += g;
        k[j][j] += g;
        k[i][j] -= g;
        k[j][i] -= g;
    }
    k
}

/// Element kernel: local 3-D frame **consistent mass** `M = Tᵀ M_loc T` (Cast3M
/// `MASS`), from density `rho`, area `A` and second moments `I_y`, `I_z`. Same
/// `ke` layout as [`element_stiffness`].
pub fn element_mass(geom: &CellGeom, material: &SubElementField, ke: &mut [f64]) -> Result<()> {
    let cell = geom.cell;
    let xa = geom.node_coord(0)?;
    let xb = geom.node_coord(1)?;
    let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
    let l = norm(d);
    let rho = material.value(cell, 0, "rho").map_err(|_| {
        PyrucastError::Message(
            "Frame3d mass matrix: material component `rho` (density) is required".into(),
        )
    })?;
    let ml = local_mass(
        rho,
        material.value(cell, 0, "A")?,
        material.value(cell, 0, "I_y")?,
        material.value(cell, 0, "I_z")?,
        l,
    );
    let t = rotation(&local_axes(d));
    write_12x12(ke, &matmul(&transpose(&t), &matmul(&ml, &t)));
    Ok(())
}

/// Element kernel: local 3-D frame **geometric stiffness** `K_g = Tᵀ K_loc T`
/// (Cast3M `KSIG`), from the axial force `N` (state component `N`). Same `ke`
/// layout as [`element_stiffness`].
pub fn element_geometric(geom: &CellGeom, state: &SubElementField, ke: &mut [f64]) -> Result<()> {
    let cell = geom.cell;
    let xa = geom.node_coord(0)?;
    let xb = geom.node_coord(1)?;
    let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
    let l = norm(d);
    let n = state.value(cell, 0, "N")?;
    let kl = local_geometric(n, l);
    let t = rotation(&local_axes(d));
    write_12x12(ke, &matmul(&transpose(&t), &matmul(&kl, &t)));
    Ok(())
}

/// Scatter a 12×12 matrix into the flat row-major `ke` (accumulating).
fn write_12x12(ke: &mut [f64], m: &[[f64; 12]; 12]) {
    for (r, row) in m.iter().enumerate() {
        for (col, v) in row.iter().enumerate() {
            ke[r * 12 + col] += v;
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::aggregate::Aggregate;
    use crate::atoms::{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::store::insert;

    fn one_beam(bx: f64, by: f64, bz: f64) -> (Frame3d, NodeId, NodeId) {
        let coords = insert(Coords::new(3).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[bx, by, bz]).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 frame = Frame3d::new(fes.get(0).unwrap()).unwrap();
        (frame, a.id(), b.id())
    }

    fn material(frame: &Frame3d) -> Handle<SubElementField> {
        let mut m = SubElementField::new(
            frame.fespace.clone(),
            MATERIAL_COMPONENTS.iter().map(|s| s.to_string()).collect(),
        )
        .unwrap();
        for (c, v) in [
            ("E", 2.0),
            ("A", 3.0),
            ("I_y", 1.5),
            ("I_z", 2.5),
            ("J", 1.2),
            ("G", 0.8),
            ("A_sy", 4.0),
            ("A_sz", 5.0),
        ] {
            m.set_uniform(c, v).unwrap();
        }
        insert(m)
    }

    /// Horizontal X-beam (local = global): axial on x, torsion on r_x, the two
    /// bending planes decoupled from axial.
    #[test]
    fn horizontal_beam_axial_torsion_decoupled() {
        let l = 2.0;
        let (frame, a, b) = one_beam(l, 0.0, 0.0);
        let mat = material(&frame);
        let blocks = frame.build_stiffness_blocks(Some(&mat)).unwrap();
        let k = &blocks[0];
        let tol = 1e-9;
        // E·A = 6, G·J = 0.96.
        assert!((k.get(a, "f_x", a, "u_x") - 6.0 / l).abs() < tol); // axial
        assert!((k.get(a, "f_x", b, "u_x") + 6.0 / l).abs() < tol);
        assert!((k.get(a, "m_x", a, "r_x") - 0.96 / l).abs() < tol); // torsion
                                                                     // Axial ⟂ everything else; the two bending planes are decoupled.
        assert!(k.get(a, "f_x", a, "u_y").abs() < tol);
        assert!(k.get(a, "f_x", a, "r_x").abs() < tol);
        assert!(k.get(a, "f_y", a, "u_z").abs() < tol);
        assert!(k.get(a, "f_y", a, "r_y").abs() < tol);
    }

    /// A beam along global Y: the rotation puts the axial term on `u_y`.
    #[test]
    fn vertical_beam_axial_is_along_y() {
        let l = 2.0;
        let (frame, a, _b) = one_beam(0.0, l, 0.0);
        let mat = material(&frame);
        let blocks = frame.build_stiffness_blocks(Some(&mat)).unwrap();
        let k = &blocks[0];
        assert!((k.get(a, "f_y", a, "u_y") - 6.0 / l).abs() < 1e-9); // axial on y
        assert!(k.get(a, "f_y", a, "u_x").abs() < 1e-9);
    }
}