pyrucast 0.15.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
//! Multi-point constraints (MPC) exercised end-to-end through the public API.
//!
//! A 1-D heat-conduction bar `-u'' = 0` on `[0, 1]` (SEG2 grid, `k = 1`) whose
//! analytical solution is linear. MPCs are imposed by Lagrange multipliers on the
//! same augmented system as Dirichlet, so a well-posed set of relations recovers
//! `u(x) = x` and the equivalence with Dirichlet holds for the single-term case.

use pyrucast::aggregate::Aggregate;
use pyrucast::atoms::{ElementType, Node};
use pyrucast::containers::element_field::{ElementField, SubElementField};
use pyrucast::containers::field::{Field, SubField};
use pyrucast::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use pyrucast::containers::matrix::Matrix;
use pyrucast::containers::mesh::{Mesh, SubMesh};
use pyrucast::containers::model::{Model, SubModel};
use pyrucast::containers::node_field::{NodeField, SubNodeField};
use pyrucast::coords::Coords;
use pyrucast::handle::Handle;
use pyrucast::models::symmetry::MaterialSymmetry;
use pyrucast::ops::matrix::stiffness;
use pyrucast::ops::solver::{solve, solve_with_options, RelationMethod, SolveOptions};
use pyrucast::Result;

const N_ELEMS: usize = 4;
const H: f64 = 1.0 / N_ELEMS as f64;
const TOL: f64 = 1e-10;

/// The system solved by master/slave elimination instead of multipliers.
fn eliminate(k: &Matrix, rhs: &NodeField) -> Result<NodeField> {
    solve_with_options(
        k,
        rhs,
        &SolveOptions {
            relations: RelationMethod::Eliminate,
            ..Default::default()
        },
    )
}

/// Build the `[0, 1]` SEG2 bar with a `k = 1` heat-conduction sub-model already
/// added; returns the nodes, the base model and the material field.
fn heat_bar() -> Result<(Vec<Node>, Handle<Coords>, Model, ElementField)> {
    let coords = Handle::new(Coords::new(1)?);
    let nodes: Vec<Node> = (0..=N_ELEMS)
        .map(|i| Node::create_in(coords.clone(), &[i as f64 * H]))
        .collect::<Result<_>>()?;

    let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
    for i in 0..N_ELEMS {
        mesh.add_cell(&[nodes[i].id(), nodes[i + 1].id()])?;
    }
    let fes = FiniteElementSpace::lagrange1(&mesh)?;
    let sub: Handle<SubFiniteElementSpace> = fes.get(0)?;

    let mut mat = SubElementField::new(sub.clone(), vec!["k".into()])?;
    mat.set_uniform("k", 1.0)?;
    let mut materials = ElementField::empty();
    materials.add_sub(Handle::new(mat))?;

    let mut model = Model::empty();
    model.add_sub(Handle::new(SubModel::heat_conduction(
        sub,
        MaterialSymmetry::Isotropic,
    )?))?;

    Ok((nodes, coords, model, materials))
}

/// A POI1 mesh carrying a single node.
fn poi1(node: &Node) -> Result<Mesh> {
    Ok(Mesh::from_submesh(SubMesh::poi1_from_nodes(
        std::slice::from_ref(node),
    )?))
}

/// A two-term difference relation `1·T(node4) − 1·T(node0) = 1`, combined with a
/// Dirichlet `T(node0) = 0`, must recover `u(x) = x` (so `T(node4) = 1`). This
/// exercises a genuine multi-term MPC with a non-zero right-hand side `g`.
#[test]
fn mpc_difference_relation_recovers_linear_solution() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    // Dirichlet T(node0) = 0.
    let imposed0 = poi1(&nodes[0])?;
    let dir = SubModel::dirichlet(&imposed0, &model, "T", Default::default())?;
    let dir_mult = dir.multiplier_nodes()[0];
    model.add_sub(Handle::new(dir))?;

    // MPC: T(node4) − T(node0) = 1. `dual_of` finds "q" for us.
    assert_eq!(model.dual_of("T").as_deref(), Some("q"));
    let mesh_last = poi1(&nodes[N_ELEMS])?;
    let mesh_first = poi1(&nodes[0])?;
    let mpc = SubModel::mpc(
        &[(&mesh_last, "T", 1.0), (&mesh_first, "T", -1.0)],
        &model,
        Default::default(),
    )?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    // RHS: imposed = 0 at the Dirichlet multiplier, 1 (g) at the MPC one.
    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[dir_mult])?;
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    let mut rhs = SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?;
    rhs.set_value(dir_mult, "imposed", 0.0)?;
    rhs.set_value(mpc_mult, "imposed", 1.0)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let solution = solve(&k, &rhs)?;

    for (i, node) in nodes.iter().enumerate() {
        let got = solution.value(node.id(), "T")?;
        let expected = i as f64 * H;
        assert!(
            (got - expected).abs() < TOL,
            "T at node {i}: got {got}, expected {expected}"
        );
    }
    // The relation itself holds exactly.
    let t_last = solution.value(nodes[N_ELEMS].id(), "T")?;
    let t_first = solution.value(nodes[0].id(), "T")?;
    assert!((t_last - t_first - 1.0).abs() < TOL);
    Ok(())
}

/// The reaction of a multi-term relation is **spread by its coefficients**, and
/// the multiplier alone does not give it.
///
/// λ is a single scalar for the whole relation. The nodal reaction of term `k`
/// is `aₖ·λ`, in the dual row of *its* variable — so for a relation
/// `2·T(a) − 3·T(b) = g` the two nodes carry `2λ` and `−3λ`, neither of which is
/// λ. For a Dirichlet of one term with coefficient 1 the two coincide, which is
/// why nothing ever seemed to be missing.
#[test]
fn a_multi_term_reaction_is_spread_by_its_coefficients() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    // T(node0) = 0, so the bar is held.
    let imposed0 = poi1(&nodes[0])?;
    let dir = SubModel::dirichlet(&imposed0, &model, "T", Default::default())?;
    let dir_mult = dir.multiplier_nodes()[0];
    model.add_sub(Handle::new(dir))?;

    // 2·T(node4) − 3·T(node2) = 1 — coefficients deliberately unequal.
    let (a, b) = (2.0_f64, -3.0_f64);
    let mesh_last = poi1(&nodes[N_ELEMS])?;
    let mesh_mid = poi1(&nodes[N_ELEMS / 2])?;
    let mpc = SubModel::mpc(
        &[(&mesh_last, "T", a), (&mesh_mid, "T", b)],
        &model,
        Default::default(),
    )?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    let mpc_h = Handle::new(mpc);
    let mpc_h_names = mpc_h.clone();
    model.add_sub(mpc_h.clone())?;

    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[dir_mult])?;
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    // Every relation names its row alike: one component, two multiplier nodes.
    let mut rhs = SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?;
    rhs.set_value(dir_mult, "imposed", 0.0)?;
    rhs.set_value(mpc_mult, "imposed", 1.0)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let solution = solve(&k, &rhs)?;

    // The selector is the sub-model: point at the relation, get its
    // reaction — without crossing the conduction, which has nothing to say here.
    let mut relation_seule = Model::empty();
    relation_seule.add_sub(mpc_h)?;
    let state = ElementField::empty();
    let f_int =
        pyrucast::ops::node_field::internal_forces(&relation_seule, &state, &solution, &materials)?;

    // The names are asked of the sub-model rather than guessed.
    let (mult_name, imposed_name) = {
        let k = mpc_h_names.read();
        let k = k.as_kind();
        (k.primal_vars()[0].clone(), k.dual_vars()[0].clone())
    };
    let lambda = solution.value(mpc_mult, &mult_name)?;
    let at_last = f_int.value(nodes[N_ELEMS].id(), "q")?;
    let at_mid = f_int.value(nodes[N_ELEMS / 2].id(), "q")?;

    // Each node carries its own coefficient times the one multiplier.
    assert!(
        (at_last - a * lambda).abs() < TOL,
        "{at_last} vs {}",
        a * lambda
    );
    assert!(
        (at_mid - b * lambda).abs() < TOL,
        "{at_mid} vs {}",
        b * lambda
    );
    // And λ alone is neither of them — the point of the whole exercise.
    assert!(lambda.abs() > TOL);
    assert!((at_last - lambda).abs() > TOL);
    assert!((at_mid - lambda).abs() > TOL);

    // The constraint's own row holds its equation: C·u, whose imposed half is g.
    let cu = f_int.value(mpc_mult, &imposed_name)?;
    assert!((cu - 1.0).abs() < TOL, "C·u = {cu}, attendu g = 1");
    Ok(())
}

/// A single-term MPC `1·T = u_d` (coefficient 1, `g = u_d`) must produce exactly
/// the same solution as an equivalent Dirichlet — the MPC generalises Dirichlet.
#[test]
fn single_term_mpc_matches_dirichlet() -> Result<()> {
    // Reference: two Dirichlet conditions T(0) = 0, T(1) = 1.
    let solve_dirichlet = || -> Result<NodeField> {
        let (nodes, coords, mut model, materials) = heat_bar()?;
        let left = poi1(&nodes[0])?;
        let right = poi1(&nodes[N_ELEMS])?;
        let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
        let dr = SubModel::dirichlet(&right, &model, "T", Default::default())?;
        let (nl, nr) = (dl.multiplier_nodes()[0], dr.multiplier_nodes()[0]);
        model.add_sub(Handle::new(dl))?;
        model.add_sub(Handle::new(dr))?;
        let mut sm = SubMesh::new(coords, ElementType::POI1);
        sm.add_cell(&[nl])?;
        sm.add_cell(&[nr])?;
        let sm = Handle::new(sm);
        let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
        rhs.set_value(nl, "imposed", 0.0)?;
        rhs.set_value(nr, "imposed", 1.0)?;
        let k = stiffness(&model, &materials)?;
        solve(&k, &NodeField::from_sub(rhs))
    };

    // MPC variant: Dirichlet T(0) = 0 + single-term MPC 1·T(node4) = 1.
    let solve_mpc = || -> Result<NodeField> {
        let (nodes, coords, mut model, materials) = heat_bar()?;
        let left = poi1(&nodes[0])?;
        let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
        let nl = dl.multiplier_nodes()[0];
        model.add_sub(Handle::new(dl))?;

        let right = poi1(&nodes[N_ELEMS])?;
        let mpc = SubModel::mpc(&[(&right, "T", 1.0)], &model, Default::default())?;
        let nm = mpc.multiplier_nodes()[0];
        model.add_sub(Handle::new(mpc))?;

        let mut sm = SubMesh::new(coords, ElementType::POI1);
        sm.add_cell(&[nl])?;
        sm.add_cell(&[nm])?;
        let sm = Handle::new(sm);
        let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
        rhs.set_value(nl, "imposed", 0.0)?;
        rhs.set_value(nm, "imposed", 1.0)?;
        let k = stiffness(&model, &materials)?;
        solve(&k, &NodeField::from_sub(rhs))
    };

    let (nodes, ..) = heat_bar()?;
    let dir = solve_dirichlet()?;
    let mpc = solve_mpc()?;
    for node in &nodes {
        let a = dir.value(node.id(), "T")?;
        let b = mpc.value(node.id(), "T")?;
        assert!(
            (a - b).abs() < TOL,
            "node {:?}: dirichlet {a} vs mpc {b}",
            node.id()
        );
    }
    Ok(())
}

/// The **elimination** solver must reproduce the Lagrange solution on a genuine
/// two-term MPC combined with a Dirichlet — with disjoint slaves (non-chained,
/// the v1 scope). `2·T(node4) − 1·T(node2) = 1.5` (slave node4, master node2)
/// plus `T(node0) = 0` (slave node0). Both methods solve the same constrained
/// energy minimisation, so their fields coincide node-for-node and the relation
/// holds exactly. (The field is *not* `u = x`: a multi-term relation injects
/// reactions at both term nodes, so the minimiser bends.)
#[test]
fn mpc_elimination_matches_lagrange() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    // Dirichlet T(node0) = 0.
    let imposed0 = poi1(&nodes[0])?;
    let dir = SubModel::dirichlet(&imposed0, &model, "T", Default::default())?;
    let dir_mult = dir.multiplier_nodes()[0];
    model.add_sub(Handle::new(dir))?;

    // MPC: 2·T(node4) − 1·T(node2) = 1.5 (slave = node4, master = node2).
    let mesh4 = poi1(&nodes[N_ELEMS])?;
    let mesh2 = poi1(&nodes[N_ELEMS / 2])?;
    let mpc = SubModel::mpc(
        &[(&mesh4, "T", 2.0), (&mesh2, "T", -1.0)],
        &model,
        Default::default(),
    )?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    // RHS: imposed = 0 at the Dirichlet multiplier, 1.5 (= 2·1 − 1·0.5) at the MPC one.
    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[dir_mult])?;
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    let mut rhs = SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?;
    rhs.set_value(dir_mult, "imposed", 0.0)?;
    rhs.set_value(mpc_mult, "imposed", 1.5)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let lagrange = solve(&k, &rhs)?;
    let elim = eliminate(&k, &rhs)?;

    // The two methods produce the same field, node-for-node.
    for (i, node) in nodes.iter().enumerate() {
        let a = lagrange.value(node.id(), "T")?;
        let b = elim.value(node.id(), "T")?;
        assert!(
            (a - b).abs() < TOL,
            "node {i}: lagrange {a} vs elimination {b}"
        );
    }
    // The Dirichlet and the MPC relation hold exactly on the elimination field.
    let t0 = elim.value(nodes[0].id(), "T")?;
    let t2 = elim.value(nodes[N_ELEMS / 2].id(), "T")?;
    let t4 = elim.value(nodes[N_ELEMS].id(), "T")?;
    assert!(t0.abs() < TOL, "Dirichlet T(0) = {t0}");
    assert!(
        (2.0 * t4 - t2 - 1.5).abs() < TOL,
        "relation: 2·{t4} − {t2} ≠ 1.5"
    );
    Ok(())
}

/// A single-term MPC solved by **elimination** matches the equivalent Dirichlet:
/// `1·T(node4) = 1` (with Dirichlet `T(node0) = 0`) gives the same field as two
/// Dirichlet conditions. The single-term relation is `a_s = 1`, masters = ∅.
#[test]
fn single_term_mpc_elimination_equals_dirichlet() -> Result<()> {
    // Reference: two Dirichlet T(0) = 0, T(1) = 1 (Lagrange).
    let reference = || -> Result<NodeField> {
        let (nodes, coords, mut model, materials) = heat_bar()?;
        let left = poi1(&nodes[0])?;
        let right = poi1(&nodes[N_ELEMS])?;
        let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
        let dr = SubModel::dirichlet(&right, &model, "T", Default::default())?;
        let (nl, nr) = (dl.multiplier_nodes()[0], dr.multiplier_nodes()[0]);
        model.add_sub(Handle::new(dl))?;
        model.add_sub(Handle::new(dr))?;
        let mut sm = SubMesh::new(coords, ElementType::POI1);
        sm.add_cell(&[nl])?;
        sm.add_cell(&[nr])?;
        let sm = Handle::new(sm);
        let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
        rhs.set_value(nl, "imposed", 0.0)?;
        rhs.set_value(nr, "imposed", 1.0)?;
        let k = stiffness(&model, &materials)?;
        solve(&k, &NodeField::from_sub(rhs))
    };

    // Dirichlet T(0) = 0 + single-term MPC 1·T(node4) = 1, solved by elimination.
    let by_elimination = || -> Result<NodeField> {
        let (nodes, coords, mut model, materials) = heat_bar()?;
        let left = poi1(&nodes[0])?;
        let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
        let nl = dl.multiplier_nodes()[0];
        model.add_sub(Handle::new(dl))?;

        let right = poi1(&nodes[N_ELEMS])?;
        let mpc = SubModel::mpc(&[(&right, "T", 1.0)], &model, Default::default())?;
        let nm = mpc.multiplier_nodes()[0];
        model.add_sub(Handle::new(mpc))?;

        let mut sm = SubMesh::new(coords, ElementType::POI1);
        sm.add_cell(&[nl])?;
        sm.add_cell(&[nm])?;
        let sm = Handle::new(sm);
        let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
        rhs.set_value(nl, "imposed", 0.0)?;
        rhs.set_value(nm, "imposed", 1.0)?;
        let k = stiffness(&model, &materials)?;
        eliminate(&k, &NodeField::from_sub(rhs))
    };

    let (nodes, ..) = heat_bar()?;
    let dir = reference()?;
    let mpc = by_elimination()?;
    for node in &nodes {
        let a = dir.value(node.id(), "T")?;
        let b = mpc.value(node.id(), "T")?;
        assert!(
            (a - b).abs() < TOL,
            "node {:?}: dirichlet {a} vs elimination {b}",
            node.id()
        );
    }
    Ok(())
}

/// Elimination recovers each relation's multiplier in post-processing: on
/// `-u'' = 0` with `T(0) = 0`, `T(1) = 1`, the `lambda` at each multiplier
/// node equals the Lagrange one, `+1` at x=0, `-1` at x=1 — and the whole
/// solution is the Lagrange one, the same DOFs on the same supports.
#[test]
fn elimination_recovers_the_multipliers() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;
    let left = poi1(&nodes[0])?;
    let right = poi1(&nodes[N_ELEMS])?;
    let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
    let dr = SubModel::dirichlet(&right, &model, "T", Default::default())?;
    let (nl, nr) = (dl.multiplier_nodes()[0], dr.multiplier_nodes()[0]);
    model.add_sub(Handle::new(dl))?;
    model.add_sub(Handle::new(dr))?;

    let mut sm = SubMesh::new(coords, ElementType::POI1);
    sm.add_cell(&[nl])?;
    sm.add_cell(&[nr])?;
    let sm = Handle::new(sm);
    let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
    rhs.set_value(nl, "imposed", 0.0)?;
    rhs.set_value(nr, "imposed", 1.0)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let lagrange = solve(&k, &rhs)?;
    let elim = eliminate(&k, &rhs)?;

    // Lagrange multipliers (reference boundary fluxes).
    let lambda_l = lagrange.value(nl, "lambda")?;
    let lambda_r = lagrange.value(nr, "lambda")?;
    assert!((lambda_l - 1.0).abs() < TOL);
    assert!((lambda_r + 1.0).abs() < TOL);

    // The elimination returns them where the Lagrange path does: at the
    // multiplier nodes, nothing in the dual rows.
    for (m, lambda) in [(nl, lambda_l), (nr, lambda_r)] {
        let eliminated = elim.value(m, "lambda")?;
        assert!(
            (eliminated - lambda).abs() < TOL,
            "{eliminated} vs λ {lambda}"
        );
    }
    assert_eq!(Field::components(&elim), Field::components(&lagrange));
    assert!(elim.value_opt(nodes[0].id(), "q").is_none());
    Ok(())
}

/// Periodicity by elimination: `T(node4) − T(node0) = 0` (a disjoint slave) forces
/// both ends equal; anchored by `T(node1) = 0.5`, the `-u'' = 0` solution is the
/// constant field `u ≡ 0.5`.
#[test]
fn elimination_periodicity_constant_field() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    // Dirichlet T(node1) = 0.5 (interior anchor).
    let anchor = poi1(&nodes[1])?;
    let dir = SubModel::dirichlet(&anchor, &model, "T", Default::default())?;
    let dir_mult = dir.multiplier_nodes()[0];
    model.add_sub(Handle::new(dir))?;

    // Periodicity T(node4) − T(node0) = 0.
    let mesh4 = poi1(&nodes[N_ELEMS])?;
    let mesh0 = poi1(&nodes[0])?;
    let mpc = SubModel::mpc(
        &[(&mesh4, "T", 1.0), (&mesh0, "T", -1.0)],
        &model,
        Default::default(),
    )?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    // RHS: imposed = 0.5 at the anchor, 0 at the MPC multiplier.
    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[dir_mult])?;
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    let mut rhs = SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?;
    rhs.set_value(dir_mult, "imposed", 0.5)?;
    rhs.set_value(mpc_mult, "imposed", 0.0)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let elim = eliminate(&k, &rhs)?;

    for node in &nodes {
        let got = elim.value(node.id(), "T")?;
        assert!(
            (got - 0.5).abs() < TOL,
            "T at {:?}: got {got}, expected 0.5",
            node.id()
        );
    }
    Ok(())
}

/// Chaining is out of v1 scope: two relations that would eliminate the **same**
/// DOF (a Dirichlet and a single-term MPC both on node0) must be rejected.
#[test]
fn elimination_rejects_chaining() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    let imposed0 = poi1(&nodes[0])?;
    let dir = SubModel::dirichlet(&imposed0, &model, "T", Default::default())?;
    let dir_mult = dir.multiplier_nodes()[0];
    model.add_sub(Handle::new(dir))?;

    // A single-term MPC on the *same* node0 — its only DOF is already a slave.
    let mesh0 = poi1(&nodes[0])?;
    let mpc = SubModel::mpc(&[(&mesh0, "T", 1.0)], &model, Default::default())?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[dir_mult])?;
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    let rhs = NodeField::from_sub(SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?);

    let k = stiffness(&model, &materials)?;
    assert!(eliminate(&k, &rhs).is_err());
    Ok(())
}

/// A relation whose only term has a zero coefficient has no valid denominator
/// `a_s` and must be rejected.
#[test]
fn elimination_rejects_zero_coefficient() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    let mesh4 = poi1(&nodes[N_ELEMS])?;
    let mpc = SubModel::mpc(&[(&mesh4, "T", 0.0)], &model, Default::default())?;
    let mpc_mult = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    let mut rhs_sm = SubMesh::new(coords, ElementType::POI1);
    rhs_sm.add_cell(&[mpc_mult])?;
    let rhs_sm = Handle::new(rhs_sm);
    let rhs = NodeField::from_sub(SubNodeField::from_poi1(&rhs_sm, vec!["imposed".into()])?);

    let k = stiffness(&model, &materials)?;
    assert!(eliminate(&k, &rhs).is_err());
    Ok(())
}

/// A second elimination solve on the same matrix gives the same result — the
/// condensation is reused from the matrix's cache (the cache itself is checked
/// where its type lives, in the elimination path's own tests).
#[test]
fn elimination_resolve_gives_the_same_result() -> Result<()> {
    let (nodes, coords, mut model, materials) = heat_bar()?;

    let left = poi1(&nodes[0])?;
    let dl = SubModel::dirichlet(&left, &model, "T", Default::default())?;
    let nl = dl.multiplier_nodes()[0];
    model.add_sub(Handle::new(dl))?;

    let right = poi1(&nodes[N_ELEMS])?;
    let mpc = SubModel::mpc(&[(&right, "T", 1.0)], &model, Default::default())?;
    let nm = mpc.multiplier_nodes()[0];
    model.add_sub(Handle::new(mpc))?;

    let mut sm = SubMesh::new(coords, ElementType::POI1);
    sm.add_cell(&[nl])?;
    sm.add_cell(&[nm])?;
    let sm = Handle::new(sm);
    let mut rhs = SubNodeField::from_poi1(&sm, vec!["imposed".into()])?;
    rhs.set_value(nl, "imposed", 0.0)?;
    rhs.set_value(nm, "imposed", 1.0)?;
    let rhs = NodeField::from_sub(rhs);

    let k = stiffness(&model, &materials)?;
    let s1 = eliminate(&k, &rhs)?;
    let s2 = eliminate(&k, &rhs)?;
    for node in &nodes {
        assert_eq!(s1.value(node.id(), "T")?, s2.value(node.id(), "T")?);
    }
    // T = x on the bar: the relations hold.
    assert!((s1.value(nodes[N_ELEMS].id(), "T")? - 1.0).abs() < 1e-12);
    Ok(())
}