pyrucast 0.9.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
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
//! Multi-point constraint (MPC) via Lagrange multipliers.
//!
//! An MPC sub-model imposes one or more **linear relations** between degrees of
//! freedom: for each relation `r`,
//!
//! ```text
//! Σₖ aₖ · u(nodeₖ, varₖ) = g
//! ```
//!
//! It is a *constraint*, not a volumetric physics: it carries no material and no
//! constitutive law, and it creates no node (it never mutates the
//! [`Coords`](crate::coords::Coords)). It is the **generalisation of
//! [`Dirichlet`](crate::models::dirichlet::Dirichlet)**, which is the single-term
//! relation `1·u = u_d`.
//!
//! # Mesh-per-term layout
//!
//! Each term is a [`MpcTerm`] = (POI1 mesh, primal variable, dual variable,
//! scalar coefficient). All term meshes and the `multiplier_mesh` are paired
//! **element-for-element**: relation `r` links the `r`-th cell of *every* term
//! mesh to the `r`-th multiplier node. So a periodicity between two surfaces of
//! `N` nodes is `N` relations at once, vectorised over the cells (no per-node
//! loop). Consistent ordering of the paired meshes is the **user's
//! responsibility** (cell `r` of each mesh must be geometric partners).
//!
//! # Variables
//!
//! Like `Dirichlet`, an MPC owns a pair of variables shared by all its relations:
//!
//! - `multiplier` (default `lambda_mpc`) — this sub-model's **primal**: the
//!   Lagrange multiplier `λ`, an unknown of the augmented system, whose solved
//!   value is the **reaction**;
//! - `imposed_value` (default `mpc_rhs`) — this sub-model's **dual**: the
//!   constraint-equation row, and the **slot** at which the user writes the
//!   right-hand side `g` in the load `SubNodeField` (on the multiplier node).
//!
//! Each term's `target_dual` is the dual (residual) variable of the term's own
//! physics — the row into which its reaction `aₖ·λ` is added. Find it easily with
//! [`Model::dual_of`](crate::containers::model::Model::dual_of).

use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::containers::element_field::SubElementField;
use crate::containers::mesh::Mesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::{
    constraint_block_pair, Constraint, ConstraintTerm, Contribution, MatrixKind, Physics, Relation,
    RelationSense, SubModelKind,
};
use serde::{Deserialize, Serialize};

/// Default multiplier (primal) name shared by every relation of an MPC.
///
/// ```
/// # 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::{Constraint, Physics, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// # use pyrucast::models::mpc;
/// // Derived rather than tabulated: `multiplier` and `imposed_value` left at
/// // `None` take these values.
/// assert_eq!(
///     (mpc::default_multiplier().as_str(),
///      mpc::default_imposed_value().as_str()),
///     ("lambda_mpc", "mpc_rhs"));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn default_multiplier() -> String {
    "lambda_mpc".to_string()
}

/// Default imposed-value (dual) name — the constraint-equation row and `g` slot.
///
/// ```
/// # 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::{Constraint, Physics, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// # use pyrucast::models::mpc;
/// // Derived rather than tabulated: `multiplier` and `imposed_value` left at
/// // `None` take these values.
/// assert_eq!(
///     (mpc::default_multiplier().as_str(),
///      mpc::default_imposed_value().as_str()),
///     ("lambda_mpc", "mpc_rhs"));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn default_imposed_value() -> String {
    "mpc_rhs".to_string()
}

/// One term `coefficient · u(node, variable)` shared by every relation of an
/// [`Mpc`]. Its mesh is POI1: cell `r` holds the node of relation `r`.
///
/// ```
/// # 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::{Constraint, Physics, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// # use pyrucast::models::mpc::{self, Mpc, MpcTerm};
/// # let a = mesh::poi1_from_nodes(&n[..1])?;
/// # let b = mesh::poi1_from_nodes(&n[1..2])?;
/// # let cible = pyrucast::ops::model::heat_conduction(&fes)?;
/// // "Both nodes have the same temperature": Σ aₖ·uₖ = g, with one λ per
/// // relation.
/// let m = Mpc::new(
///     vec![MpcTerm::new(&cible, &a, "T", 1.0)?,
///          MpcTerm::new(&cible, &b, "T", -1.0)?],
///     &mult, RelationSense::Equality)?;
/// assert_eq!(m.relations()?.len(), 1);
/// assert_eq!(m.relations()?[0].terms.len(), 2);
/// assert_eq!(m.relations()?[0].imposed_value, mpc::default_imposed_value());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct MpcTerm {
    /// POI1 mesh, paired element-for-element with the other terms and the
    /// multiplier mesh (cell `r` = the node of relation `r` for this term).
    pub(crate) mesh: Mesh,
    /// Constrained primal variable (a *column* of the target's stiffness), e.g. `"u_x"`.
    pub(crate) variable: String,
    /// The term physics's dual; the *row* where the reaction `coefficient·λ`
    /// lands (e.g. `"f_x"`). Find it with `Model::dual_of`.
    pub(crate) target_dual: String,
    /// Scalar coefficient `aₖ` (v1).
    pub(crate) coefficient: f64,
}

impl MpcTerm {
    /// Build a term. `mesh` must be POI1 (one node per relation); it is shared
    /// (its submeshes are increfed so the nodes stay alive).
    ///
    /// ```
    /// # 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::{Constraint, Physics, RelationSense, SubModelKind};
    /// # use pyrucast::ops::mesh;
    /// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::models::mpc::{self, Mpc, MpcTerm};
    /// # let a = mesh::poi1_from_nodes(&n[..1])?;
    /// # let b = mesh::poi1_from_nodes(&n[1..2])?;
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes)?;
    /// // "Both nodes have the same temperature": Σ aₖ·uₖ = g, with one λ per
    /// // relation.
    /// let m = Mpc::new(
    ///     vec![MpcTerm::new(&cible, &a, "T", 1.0)?,
    ///          MpcTerm::new(&cible, &b, "T", -1.0)?],
    ///     &mult, RelationSense::Equality)?;
    /// assert_eq!(m.relations()?.len(), 1);
    /// assert_eq!(m.relations()?[0].terms.len(), 2);
    /// assert_eq!(m.relations()?[0].imposed_value, mpc::default_imposed_value());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(
        target: &crate::containers::model::Model,
        mesh: &Mesh,
        variable: &str,
        coefficient: f64,
    ) -> Result<Self> {
        // The dual row this term's reaction lands in is the target's business,
        // read from it rather than retyped.
        let target_dual = target.dual_of(variable).ok_or_else(|| {
            PyrucastError::Message(format!(
                "MpcTerm: `{variable}` is not a primal of the model it constrains — it \
                 declares {:?}",
                target.primal_vars()
            ))
        })?;
        Ok(Self {
            mesh: share(mesh)?,
            variable: variable.to_string(),
            target_dual,
            coefficient,
        })
    }
}

/// Multi-point constraint imposed via Lagrange multipliers.
///
/// See the module documentation for the meaning of the two variable names, the
/// mesh-per-term layout and the element-for-element pairing. The right-hand side
/// `g` is **not** stored here: the user supplies it through the load
/// `SubNodeField` at the multiplier node's `imposed_value` component (default
/// `g = 0`).
///
/// ```
/// # 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::{Constraint, Physics, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let mult = mesh::barycenter(&impose).unwrap();
/// # use pyrucast::models::mpc::{self, Mpc, MpcTerm};
/// # let a = mesh::poi1_from_nodes(&n[..1])?;
/// # let b = mesh::poi1_from_nodes(&n[1..2])?;
/// # let cible = pyrucast::ops::model::heat_conduction(&fes)?;
/// // "Both nodes have the same temperature": Σ aₖ·uₖ = g, with one λ per
/// // relation.
/// let m = Mpc::new(
///     vec![MpcTerm::new(&cible, &a, "T", 1.0)?,
///          MpcTerm::new(&cible, &b, "T", -1.0)?],
///     &mult, RelationSense::Equality)?;
/// assert_eq!(m.relations()?.len(), 1);
/// assert_eq!(m.relations()?[0].terms.len(), 2);
/// assert_eq!(m.relations()?[0].imposed_value, mpc::default_imposed_value());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct Mpc {
    /// The terms summed on the left-hand side of every relation (at least one).
    pub(crate) terms: Vec<MpcTerm>,
    /// POI1 mesh of the multiplier nodes (one node `λ` per relation).
    pub(crate) multiplier_mesh: Mesh,
    /// This sub-model's primal — the Lagrange multiplier (e.g. `"lambda_mpc"`).
    pub(crate) multiplier: String,
    /// This sub-model's dual — constraint row + `g` slot (e.g. `"mpc_rhs"`).
    pub(crate) imposed_value: String,
    /// Equality (default) or unilateral inequality (`Σ aₖ·uₖ ≥ g` / `≤ g`),
    /// solved by the active-set operator.
    #[serde(default)]
    pub(crate) sense: RelationSense,
}

impl Mpc {
    /// Build a multi-point constraint imposing, for each relation `r`,
    /// `Σₖ aₖ·u(nodeₖ, varₖ) ⋈ g` (`⋈` is `sense`, `=` by default) — the `r`-th
    /// cell of every term mesh paired with the `r`-th multiplier node.
    ///
    /// `multiplier` / `imposed_value` default to `lambda_mpc` / `mpc_rhs` when
    /// `None`. Every term mesh and `multiplier_mesh` must be POI1, share one
    /// [`Coords`](crate::coords::Coords), and pair element-for-element
    /// (same number of submeshes, same cell count per submesh).
    ///
    /// A non-equality `sense` turns the relations unilateral (enforced only
    /// while active); such a model is solved by the active-set operator
    /// [`unilateral`](crate::ops::solver::unilateral).
    ///
    /// ```
    /// # 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::{Constraint, Physics, RelationSense, SubModelKind};
    /// # use pyrucast::ops::mesh;
    /// # 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 cible = pyrucast::ops::model::heat_conduction(&fes).unwrap();
    /// # let zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # let mult = mesh::barycenter(&impose).unwrap();
    /// # use pyrucast::models::mpc::{self, Mpc, MpcTerm};
    /// # let a = mesh::poi1_from_nodes(&n[..1])?;
    /// # let b = mesh::poi1_from_nodes(&n[1..2])?;
    /// # let cible = pyrucast::ops::model::heat_conduction(&fes)?;
    /// // "Both nodes have the same temperature": Σ aₖ·uₖ = g, with one λ per
    /// // relation.
    /// let m = Mpc::new(
    ///     vec![MpcTerm::new(&cible, &a, "T", 1.0)?,
    ///          MpcTerm::new(&cible, &b, "T", -1.0)?],
    ///     &mult, RelationSense::Equality)?;
    /// assert_eq!(m.relations()?.len(), 1);
    /// assert_eq!(m.relations()?[0].terms.len(), 2);
    /// assert_eq!(m.relations()?[0].imposed_value, mpc::default_imposed_value());
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(terms: Vec<MpcTerm>, multiplier_mesh: &Mesh, sense: RelationSense) -> Result<Self> {
        // Derived, never overridden: `None` chose no behaviour, it chose a
        // default, and `default_multiplier` is public for whoever needs the
        // name. Two relations do not collide either — their DOFs differ by
        // multiplier *node*, not by name.
        if terms.is_empty() {
            return Err(PyrucastError::Message(
                "Mpc: at least one term is required".into(),
            ));
        }
        if multiplier_mesh.cell_count() == 0 {
            return Err(PyrucastError::Message(
                "Mpc: multiplier_mesh must carry at least one node".into(),
            ));
        }
        let n_sub = multiplier_mesh.len();
        // NodeIds are Coords-relative: every mesh must share it.
        let coords_m = multiplier_mesh.coords()?;

        // Reference: multiplier submesh element types + cell counts (all POI1).
        let mut mult_counts = Vec::with_capacity(n_sub);
        for i in 0..n_sub {
            let mult_sm = multiplier_mesh.get(i)?;
            let (met, mcount) = {
                let s = mult_sm.read();
                (s.element_type(), s.cell_count())
            };
            if met != ElementType::POI1 {
                return Err(PyrucastError::Message(format!(
                    "Mpc: multiplier_mesh submesh {i} must be POI1, got {met}"
                )));
            }
            mult_counts.push(mcount);
        }

        // Every term: shared Coords, same submesh count, POI1 + equal cell counts.
        for (t_idx, t) in terms.iter().enumerate() {
            let coords_t = t.mesh.coords()?;
            if !coords_t.same_object(&coords_m) {
                return Err(PyrucastError::Message(format!(
                    "Mpc: term {t_idx} mesh and multiplier_mesh must share a Coords"
                )));
            }
            if t.mesh.len() != n_sub {
                return Err(PyrucastError::Message(format!(
                    "Mpc: multiplier_mesh has {n_sub} submesh(es) but term {t_idx} has {}",
                    t.mesh.len()
                )));
            }
            for i in 0..n_sub {
                let term_sm = t.mesh.get(i)?;
                let (tet, tcount) = {
                    let s = term_sm.read();
                    (s.element_type(), s.cell_count())
                };
                if tet != ElementType::POI1 {
                    return Err(PyrucastError::Message(format!(
                        "Mpc: term {t_idx} submesh {i} must be POI1, got {tet}"
                    )));
                }
                if tcount != mult_counts[i] {
                    return Err(PyrucastError::Message(format!(
                        "Mpc: term {t_idx} submesh {i} has {tcount} node(s) but \
                         multiplier has {}",
                        mult_counts[i]
                    )));
                }
            }
        }

        Ok(Self {
            terms,
            multiplier_mesh: share(multiplier_mesh)?,
            multiplier: default_multiplier(),
            imposed_value: default_imposed_value(),
            sense,
        })
    }
}

impl SubModelKind for Mpc {
    fn primal_vars(&self) -> Vec<String> {
        vec![self.multiplier.clone()]
    }

    fn dual_vars(&self) -> Vec<String> {
        vec![self.imposed_value.clone()]
    }

    /// Its relations, applied to the solution: the reaction `Cᵀ λ` on the
    /// constrained nodes, and `C·u` on its own row.
    fn internal_force_contribution(&self) -> Vec<crate::models::ResidualContribution> {
        vec![crate::models::ResidualContribution::Relations]
    }

    fn as_constraint(&self) -> Option<&dyn Constraint> {
        Some(self)
    }

    /// Like `Dirichlet`, MPC has no [`stiffness_layout`](SubModelKind::stiffness_layout)
    /// (nothing is integrated on a cell): it returns its filled `C` / `Cᵀ` blocks
    /// directly, one pair per `(submesh, term)`, via the shared
    /// `constraint_block_pair` builder (coefficient `aₖ` instead of `1`). All
    /// terms of a relation share the same multiplier node and `imposed_value` row,
    /// which is what sums them into one equation.
    fn contributions(
        &self,
        kind: MatrixKind,
        _material: Option<&crate::handle::Handle<SubElementField>>,
    ) -> Result<Vec<Contribution>> {
        // A constraint only enters the global (stiffness) matrix — no
        // mass/geometric/tangent term.
        if kind != MatrixKind::Stiffness {
            return Ok(Vec::new());
        }
        let n_sub = self.multiplier_mesh.len();
        let mut blocks = Vec::with_capacity(n_sub * self.terms.len() * 2);
        for i in 0..n_sub {
            let mult_sm = self.multiplier_mesh.get(i)?;
            for t in &self.terms {
                let term_sm = t.mesh.get(i)?;
                let (c_block, ct_block) = constraint_block_pair(
                    &mult_sm,
                    &term_sm,
                    &t.variable,
                    &t.target_dual,
                    &self.multiplier,
                    &self.imposed_value,
                    t.coefficient,
                )?;
                blocks.push(c_block);
                blocks.push(ct_block);
            }
        }
        Ok(vec![Contribution::Literal(blocks)])
    }

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

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

    fn display(&self) -> String {
        let n = self.multiplier_mesh.cell_count();
        format!(
            "SubModel<Mpc>: {} relation(s), {} term(s) each",
            n,
            self.terms.len()
        )
    }

    fn render(&self, _opts: &DumpOptions) -> String {
        let n = self.multiplier_mesh.cell_count();
        let mut out = format!(
            "SubModel<Mpc>\n  primal var(s): {} (multiplier)\n  dual var(s):   {} \
             (imposed value / g)\n  sense: {}\n  relations: {n}\n  terms:",
            self.multiplier, self.imposed_value, self.sense,
        );
        for t in &self.terms {
            out.push_str(&format!(
                "\n    {:+} · {} (dual {})",
                t.coefficient, t.variable, t.target_dual
            ));
        }
        out
    }
}

impl Constraint for Mpc {
    fn multiplier_mesh(&self) -> &Mesh {
        &self.multiplier_mesh
    }

    /// One [`Relation`] per multiplier node, each with one [`ConstraintTerm`] per
    /// [`MpcTerm`]. Flattens the mesh-per-term layout into the method-neutral view
    /// a future master/slave elimination consumes.
    fn relations(&self) -> Result<Vec<Relation>> {
        let n_sub = self.multiplier_mesh.len();
        let mut relations = Vec::new();
        for i in 0..n_sub {
            let mult = self.multiplier_mesh.get(i)?.read();
            // One **guard** per term for this submesh, all held together, so the
            // relation at index r reads the r-th node of each in place. Two terms
            // may name the same submesh: two read guards on one object, which the
            // lock allows (see `handle.rs`, Concurrency).
            let term_guards: Vec<crate::handle::ReadGuard<crate::containers::mesh::SubMesh>> = self
                .terms
                .iter()
                .map(|t| Ok(t.mesh.get(i)?.read()))
                .collect::<Result<Vec<_>>>()?;
            for (r, mult_node) in mult.connectivity().iter().enumerate() {
                let terms = self
                    .terms
                    .iter()
                    .zip(&term_guards)
                    .map(|(t, g)| ConstraintTerm {
                        node: g.connectivity()[r],
                        variable: t.variable.clone(),
                        target_dual: t.target_dual.clone(),
                        coefficient: t.coefficient,
                    })
                    .collect();
                relations.push(Relation {
                    multiplier_node: *mult_node,
                    imposed_value: self.imposed_value.clone(),
                    terms,
                    sense: self.sense,
                });
            }
        }
        Ok(relations)
    }
}

/// Clone a mesh by sharing its submeshes — increfs each submesh handle so the
/// nodes stay alive for the lifetime of the sub-model.
fn share(mesh: &Mesh) -> Result<Mesh> {
    let mut out = Mesh::empty();
    for sm in mesh {
        out.add_sub(sm.clone())?;
    }
    Ok(out)
}

#[cfg(test)]
mod tests {

    /// A conduction on a segment: the target a relation constrains.
    fn cible_conduction(coords: &Handle<Coords>, a: &Node) -> crate::containers::model::Model {
        let b = Node::create_in(coords.clone(), &[2.0]).unwrap();
        let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        sm.add_cell(&[a.id(), b.id()]).unwrap();
        let fes = crate::containers::finite_element_space::FiniteElementSpace::lagrange1(
            &Mesh::from_submesh(sm),
        )
        .unwrap();
        crate::ops::model::heat_conduction(&fes).unwrap()
    }
    use super::*;
    use crate::atoms::Node;
    use crate::containers::mesh::SubMesh;
    use crate::coords::Coords;
    use crate::handle::Handle;
    use crate::ops::mesh::barycenter;

    fn poi1(node: &Node) -> Mesh {
        Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(node)).unwrap())
    }

    #[test]
    fn empty_terms_rejected() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let n = Node::create_in(coords, &[0.0]).unwrap();
        let mult = barycenter(&poi1(&n)).unwrap();
        assert!(Mpc::new(vec![], &mult, Default::default()).is_err());
    }

    #[test]
    fn mismatched_cell_count_rejected() {
        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();
        // Term mesh with two nodes, but the multiplier mesh has one → rejected.
        let mut term_sm = SubMesh::new(coords, ElementType::POI1);
        term_sm.add_cell(&[a.id()]).unwrap();
        term_sm.add_cell(&[b.id()]).unwrap();
        let term_mesh = Mesh::from_submesh(term_sm);
        let mult = barycenter(&poi1(&a)).unwrap();
        let cible = cible_conduction(&a.coords(), &a);
        let term = MpcTerm::new(&cible, &term_mesh, "T", 1.0).unwrap();
        assert!(Mpc::new(vec![term], &mult, Default::default()).is_err());
    }

    #[test]
    fn relations_flatten_terms() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords, &[1.0]).unwrap();
        let mesh_a = poi1(&a);
        let mesh_b = poi1(&b);
        let mult = barycenter(&mesh_a).unwrap();
        let cible = cible_conduction(&a.coords(), &a);
        let terms = vec![
            MpcTerm::new(&cible, &mesh_a, "T", 2.0).unwrap(),
            MpcTerm::new(&cible, &mesh_b, "T", -3.0).unwrap(),
        ];
        let mpc = Mpc::new(terms, &mult, Default::default()).unwrap();

        // Default variable names.
        assert_eq!(mpc.primal_vars(), vec!["lambda_mpc".to_string()]);
        assert_eq!(mpc.dual_vars(), vec!["mpc_rhs".to_string()]);

        // One relation carrying both terms, in order, with their coefficients.
        let rels = mpc.relations().unwrap();
        assert_eq!(rels.len(), 1);
        assert_eq!(rels[0].terms.len(), 2);
        assert_eq!(rels[0].terms[0].node, a.id());
        assert_eq!(rels[0].terms[0].coefficient, 2.0);
        assert_eq!(rels[0].terms[1].node, b.id());
        assert_eq!(rels[0].terms[1].coefficient, -3.0);
    }
}