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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Node-to-surface contact constraint via Lagrange multipliers — the
//! **unilateral** sibling of [`Embedded`](crate::models::embedded::Embedded).
//!
//! A `Contact` sub-model prevents the nodes of a **slave** mesh from
//! penetrating a **master** surface mesh. Each slave node `s` is paired at
//! build time with its closest master facet
//! ([`project_points`](crate::ops::geom::project_points())): projection weights
//! `Nᵢ(ξ)`, unit facet normal `n` and initial signed gap `g₀`. Linearised
//! around the initial geometry (small displacements, fixed pairing and
//! normal), non-penetration reads, per slave node,
//!
//! ```text
//! g₀ + n·u(s) − Σᵢ Nᵢ(ξ)·n·u(masterᵢ) ≥ 0
//! ```
//!
//! i.e. one **unilateral relation** `Σ coeffs·u ≥ −g₀` per slave node, whose
//! multiplier is `λ ≤ 0`; the contact's **reaction**, `−Cᵀλ`, is `−λ·n` on
//! the slave, spread as `+λ·Nᵢ·n` on the master facet. The
//! model is solved by the active-set operator
//! [`solve`](crate::ops::solver::solve).
//!
//! # Orientation and right-hand side
//!
//! The master surface must be **consistently oriented** with its normal
//! pointing toward the slave body (see
//! [`project_points`](crate::ops::geom::project_points())): the initial gap `g₀`
//! is then positive when separated, negative when penetrating. The relation's
//! right-hand side is `−g₀`, geometry the sub-model knows: it carries it as a
//! load, which [`external_forces`](crate::ops::node_field::external_forces())
//! returns with the other loads of the model, at each multiplier node's
//! `imposed` slot. Nobody computes it by hand, and nobody can forget it.
//!
//! # Variables
//!
//! One relation per slave node, each on a multiplier node of its own, with the
//! variable pair of every constraint relation:
//!
//! - [`MULTIPLIER`] — the primal on the multiplier node: the contact
//!   multiplier (`≤ 0` while touching, `0` when separated), whose opposite is
//!   the reaction's intensity;
//! - [`IMPOSED`] — the dual: the constraint row and the slot for the
//!   right-hand side `−g₀`.
//!
//! `variables` names the displacement components in ambient order (e.g.
//! `["u_x", "u_y"]` in 2-D), each dual read from the target — exactly one per
//! space dimension, since the normal couples them all in one scalar relation.

use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::matrix::{hash_name, hash_nodes, mint_pair, Symmetry, FNV_SEED};
use crate::containers::matrix::{DofOrdering, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::transfer::constrained_physics;
use crate::models::{
    Constraint, ConstraintTerm, Contribution, MatrixKind, Physics, Relation, RelationSense,
    SubModelKind, IMPOSED, MULTIPLIER,
};
use crate::ops::geom::project_points_at;
use crate::ops::mesh::barycenter;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// The master binding of one slave node: the closest facet's nodes, the
/// projection weights `Nᵢ(ξ)`, the unit facet normal and the initial gap.
#[derive(Serialize, Deserialize)]
struct Pairing {
    nodes: Vec<NodeId>,
    weights: Vec<f64>,
    normal: Vec<f64>,
    gap: f64,
}

/// One displacement component and the dual row its reaction lands in.
#[derive(Clone, Serialize, Deserialize)]
struct Component {
    variable: String,
    target_dual: String,
}

/// Node-to-surface contact constraint (frictionless, small displacements).
///
/// See the module documentation. Built by pairing each slave node with its
/// closest master facet once, at construction; the pairing, the normal and the
/// weights are then **fixed** (linearised contact).
///
/// ```
/// # 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 zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # use pyrucast::models::contact::Contact;
/// # let mut maitre = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # maitre.add_cell(&[n[0].id(), n[1].id()])?;
/// # let master = Mesh::from_submesh(maitre);
/// # let slave = mesh::poi1_from_nodes(&n[2..3])?;
/// // One **unilateral** relation per slave node, paired at construction with
/// // its nearest master facet.
/// # let cible = pyrucast::ops::model::elasticity(
/// #     &FiniteElementSpace::lagrange1(&maillage)?,
/// #     pyrucast::models::tensor::Kinematics::PlaneStress,
/// #     pyrucast::models::symmetry::MaterialSymmetry::Isotropic,
/// #     pyrucast::ops::element_field::StrainMeasure::Linear)?;
/// let c = Contact::new(&slave, &master, &cible,
///     vec!["u_x".into(), "u_y".into()])?;
/// assert_eq!(c.relations()?.len(), 1);
/// assert_eq!(c.gaps().len(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize)]
pub struct Contact {
    /// POI1 mesh of the slave nodes, one cell per relation (its cell `r` is
    /// the slave node of relation `r`).
    slave_mesh: Mesh,
    /// The oriented master surface, kept to pair the slaves again
    /// ([`update_contact`](crate::ops::model::update_contact())).
    master_mesh: Mesh,
    /// POI1 mesh of the fresh multiplier nodes, colocated with the slave nodes
    /// (paired cell-for-cell).
    multiplier_mesh: Mesh,
    /// POI1 support listing every node the constraint blocks reference — the
    /// slave nodes and every paired master node — deduplicated.
    support_mesh: Mesh,
    /// Master binding per slave node (same order as `slave_mesh`'s cells).
    pairings: Vec<Pairing>,
    /// Displacement components in ambient order (one per space dimension).
    components: Vec<Component>,
}

impl Contact {
    /// Build a contact constraint preventing the nodes of `slave` from
    /// penetrating the oriented `master` surface, coupling the displacement
    /// `variables` of `target` — one primal per space dimension, in ambient
    /// order; the dual row each reaction lands in is read from `target`
    /// ([`Model::dual_of`](crate::containers::model::Model::dual_of)).
    ///
    /// Each relation — one per slave node — gets a multiplier node of its own,
    /// minted beside its slave node.
    ///
    /// # Errors
    ///
    /// - a variable is not a primal of `target`;
    /// - `variables` is empty or does not match the space dimension;
    /// - `slave` and `master` do not share a `Coords`, or `slave` carries no
    ///   node;
    /// - `master` is not a surface mesh (facet dim ≠ `sdim − 1`), or is empty.
    ///
    /// ```
    /// # 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 zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # use pyrucast::models::contact::Contact;
    /// # let mut maitre = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # maitre.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let master = Mesh::from_submesh(maitre);
    /// # let slave = mesh::poi1_from_nodes(&n[2..3])?;
    /// // One **unilateral** relation per slave node, paired at construction with
    /// // its nearest master facet.
    /// # let cible = pyrucast::ops::model::elasticity(
    /// #     &FiniteElementSpace::lagrange1(&maillage)?,
    /// #     pyrucast::models::tensor::Kinematics::PlaneStress,
    /// #     pyrucast::models::symmetry::MaterialSymmetry::Isotropic,
    /// #     pyrucast::ops::element_field::StrainMeasure::Linear)?;
    /// let c = Contact::new(&slave, &master, &cible,
    ///     vec!["u_x".into(), "u_y".into()])?;
    /// assert_eq!(c.relations()?.len(), 1);
    /// assert_eq!(c.gaps().len(), 1);
    /// // A constraint on the mechanics, which `filter(Physics::Contact)` finds.
    /// assert_eq!(c.physics(), &[Physics::Constraint, Physics::Mechanical, Physics::Contact]);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn new(
        slave: &Mesh,
        master: &Mesh,
        target: &crate::containers::model::Model,
        variables: Vec<String>,
    ) -> Result<Self> {
        // The target's own names: each variable must be one of its primals,
        // and the dual row its reaction lands in is read from it.
        let mut components: Vec<(String, String)> = Vec::with_capacity(variables.len());
        for v in &variables {
            let dual = target.dual_of(v).ok_or_else(|| {
                PyrucastError::Message(format!(
                    "Contact: `{v}` is not a primal of the model it constrains — it declares \
                     {:?}",
                    target.primal_vars()
                ))
            })?;
            components.push((v.clone(), dual));
        }
        // The normal is that of a body: what moves along it is a displacement.
        if constrained_physics(target, variables.iter().map(String::as_str))
            != Some(Physics::Mechanical)
        {
            return Err(PyrucastError::Message(format!(
                "Contact: {variables:?} are not the displacements of a mechanical model — \
                 the exchange between two parts of a conduction or a diffusion is an \
                 interface_transfer"
            )));
        }

        // Slave and master must live in the same Coords (node ids are relative).
        let coords = slave.coords()?;
        let master_coords = master.coords()?;
        if !coords.same_object(&master_coords) {
            return Err(PyrucastError::Message(
                "Contact: slave and master meshes must share a Coords".into(),
            ));
        }
        let sdim = coords.read().dim() as usize;
        if components.len() != sdim {
            return Err(PyrucastError::Message(format!(
                "Contact: {} component(s) for a {sdim}-D space — the normal couples \
                 every displacement component, give one (variable, dual) pair per \
                 dimension, in ambient order",
                components.len()
            )));
        }

        // The slave support: one POI1 cell per unique slave node.
        let slave_ids = unique_nodes(slave);
        if slave_ids.is_empty() {
            return Err(PyrucastError::Message(
                "Contact: slave mesh carries no node".into(),
            ));
        }
        let slave_mesh =
            Mesh::from_submesh(SubMesh::poi1_from_node_ids(coords.clone(), &slave_ids)?);

        // Each slave node paired with its closest master facet, on the
        // positions as they are. A collapsed facet is the caller's mesh, and an
        // error here.
        let pairings = pair(&coords, &slave_ids, master, &HashMap::new())?;
        if pairings
            .iter()
            .any(|p| p.normal.iter().any(|v| !v.is_finite()))
        {
            return Err(PyrucastError::Message(
                "Contact: a master facet is degenerate (zero normal)".into(),
            ));
        }

        // Fresh multiplier nodes, colocated with the slave nodes.
        let multiplier_mesh = barycenter(&slave_mesh)?;
        let support_mesh = block_support(coords, &slave_ids, &pairings)?;

        let components = components
            .into_iter()
            .map(|(variable, target_dual)| Component {
                variable,
                target_dual,
            })
            .collect();

        Ok(Self {
            slave_mesh,
            master_mesh: same_zones(master)?,
            multiplier_mesh,
            support_mesh,
            pairings,
            components,
        })
    }

    /// The same contact paired again on the positions `X + u` — `X` the active
    /// configuration, `u` read in `displacement` on the contact's variables, a
    /// node or a component it lacks reading zero. Slave and master meshes,
    /// **multiplier nodes** (so the unknowns `lambda` and the rows `imposed`),
    /// variables and nature are kept; the pairings and the block support are
    /// recomputed. The gap is measured with the new pairing and normal on `X`
    /// (see [`pair`]), so that the relation is the gap linearised at `X + u`,
    /// written in total displacement. At `u = 0`, the construction again.
    ///
    /// The meshes were paired at construction: what could fail then cannot
    /// now. A master facet collapsed by the displacement is not this
    /// function's to detect; its normal is non-finite.
    pub(crate) fn updated(&self, displacement: &NodeField) -> Self {
        let coords = self
            .slave_mesh
            .coords()
            .expect("a contact's slave mesh lives in a Coords");
        let slave_ids: Vec<NodeId> = self
            .slave_mesh
            .get(0)
            .expect("a contact has its slave submesh")
            .read()
            .connectivity()
            .to_vec();
        // `u` at every node a pairing may reach — the slaves and every master
        // node — read once, before the projection.
        let mut displaced: HashMap<NodeId, Vec<f64>> = HashMap::new();
        let master_nodes: Vec<NodeId> = (&self.master_mesh)
            .into_iter()
            .flat_map(|sm| sm.read().connectivity().to_vec())
            .collect();
        for &node in slave_ids.iter().chain(&master_nodes) {
            if displaced.contains_key(&node) {
                continue;
            }
            let u: Vec<f64> = self
                .components
                .iter()
                .map(|c| displacement.value_opt(node, &c.variable).unwrap_or(0.0))
                .collect();
            if u.iter().any(|&v| v != 0.0) {
                displaced.insert(node, u);
            }
        }
        let pairings = pair(&coords, &slave_ids, &self.master_mesh, &displaced)
            .expect("the slave and master meshes were paired at construction");
        let support_mesh = block_support(coords, &slave_ids, &pairings)
            .expect("the block support is made of nodes of the paired meshes");
        Self {
            slave_mesh: same_zones(&self.slave_mesh).expect(SHARED),
            master_mesh: same_zones(&self.master_mesh).expect(SHARED),
            multiplier_mesh: same_zones(&self.multiplier_mesh).expect(SHARED),
            support_mesh,
            pairings,
            components: self.components.clone(),
        }
    }

    /// The initial signed gaps `g₀`, one per relation (slave node), in relation
    /// order — positive when separated, negative when penetrating. The
    /// relation's right-hand side is `−g₀`, the load the contact carries
    /// ([`external_forces`](crate::ops::node_field::external_forces())).
    ///
    /// ```
    /// # 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 zone = fes.get(0).unwrap();
    /// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
    /// # use pyrucast::models::contact::Contact;
    /// # let mut maitre = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # maitre.add_cell(&[n[0].id(), n[1].id()])?;
    /// # let master = Mesh::from_submesh(maitre);
    /// # let slave = mesh::poi1_from_nodes(&n[2..3])?;
    /// // One **unilateral** relation per slave node, paired at construction with
    /// // its nearest master facet.
    /// # let cible = pyrucast::ops::model::elasticity(
    /// #     &FiniteElementSpace::lagrange1(&maillage)?,
    /// #     pyrucast::models::tensor::Kinematics::PlaneStress,
    /// #     pyrucast::models::symmetry::MaterialSymmetry::Isotropic,
    /// #     pyrucast::ops::element_field::StrainMeasure::Linear)?;
    /// let c = Contact::new(&slave, &master, &cible,
    ///     vec!["u_x".into(), "u_y".into()])?;
    /// assert_eq!(c.relations()?.len(), 1);
    /// assert_eq!(c.gaps().len(), 1);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn gaps(&self) -> Vec<f64> {
        self.pairings.iter().map(|p| p.gap).collect()
    }

    /// The single POI1 submesh of multiplier nodes.
    fn multiplier_sm(&self) -> Result<Handle<SubMesh>> {
        self.multiplier_mesh.get(0)
    }

    /// The single POI1 support submesh of the constraint blocks.
    fn support_sm(&self) -> Result<Handle<SubMesh>> {
        self.support_mesh.get(0)
    }

    /// Slave node of relation `r`.
    fn slave_node(&self, r: usize) -> Result<NodeId> {
        Ok(self.slave_mesh.get(0)?.read().connectivity()[r])
    }

    /// Multiplier node of relation `r`.
    fn multiplier_node(&self, r: usize) -> Result<NodeId> {
        Ok(self.multiplier_mesh.get(0)?.read().connectivity()[r])
    }
}

impl SubModelKind for Contact {
    fn primal_vars(&self) -> Vec<String> {
        vec![MULTIPLIER.to_string()]
    }

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

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

    /// Its right-hand side: `−g` at each relation's multiplier node, component
    /// `imposed` — the gap is geometry this sub-model knows, so it carries it as
    /// a load rather than leave it to be remembered.
    fn external_force_contribution(&self) -> Vec<crate::models::ResidualContribution> {
        let mult_sm = self
            .multiplier_sm()
            .expect("a contact has its multiplier mesh");
        let mut gaps = SubNodeField::from_poi1(&mult_sm, vec![IMPOSED.to_string()])
            .expect("the multipliers of a contact are a POI1 support");
        // The support's node order is the relations' order: a positional write.
        for (value, pairing) in gaps.values_mut().iter_mut().zip(&self.pairings) {
            *value = -pairing.gap;
        }
        vec![crate::models::ResidualContribution::Literal(
            NodeField::from_sub(gaps),
        )]
    }

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

    /// Like the other constraints, `Contact` fills its `C` / `Cᵀ` blocks
    /// directly (no `stiffness_layout`). One block pair for the whole
    /// sub-model: the row of relation `r` couples **every** displacement
    /// component through the normal — the slave node carries `+n_c`, each
    /// master node `−Nᵢ·n_c`.
    fn contributions(
        &self,
        kind: MatrixKind,
        _material: Option<&Handle<SubElementField>>,
    ) -> Result<Vec<Contribution>> {
        // A constraint only enters the global (stiffness) matrix — no mass or
        // geometric term. A tangent request reaches it as a stiffness one
        // (`tangent_is_stiffness`), so it never arrives here.
        if kind != MatrixKind::Stiffness {
            return Ok(Vec::new());
        }
        let mult_sm = self.multiplier_sm()?;
        let support_sm = self.support_sm()?;
        let variables: Vec<String> = self.components.iter().map(|c| c.variable.clone()).collect();
        let duals: Vec<String> = self
            .components
            .iter()
            .map(|c| c.target_dual.clone())
            .collect();

        // Neither block is symmetric alone; the pair is. The identity folds in
        // both supports and every component's pair of names — which is what
        // tells one contact from another.
        let (id_c, id_ct) = {
            let (mult_g, sup_g) = (mult_sm.read(), support_sm.read());
            let mut h = FNV_SEED;
            h = hash_nodes(h, mult_g.connectivity());
            h = hash_nodes(h, sup_g.connectivity());
            for comp in &self.components {
                h = hash_name(h, &comp.variable);
                h = hash_name(h, &comp.target_dual);
            }
            mint_pair(h)
        };
        // C: rows (multiplier, IMPOSED), cols (support, every variable).
        let mut c = SubMatrix::new(
            mult_sm.clone(),
            support_sm.clone(),
            vec![IMPOSED.to_string()],
            variables,
            DofOrdering::NodesThenVars,
            Symmetry::Half(id_c),
        )?;
        // Every row is a unilateral relation: the solver reads it here.
        c.set_row_sense(RelationSense::GreaterEqual);
        // Cᵀ: rows (support, every dual), cols (multiplier, MULTIPLIER).
        let mut ct = SubMatrix::new(
            support_sm,
            mult_sm,
            duals,
            vec![MULTIPLIER.to_string()],
            DofOrdering::NodesThenVars,
            Symmetry::Half(id_ct),
        )?;
        for (r, p) in self.pairings.iter().enumerate() {
            let m = self.multiplier_node(r)?;
            let s = self.slave_node(r)?;
            for (comp, &n_c) in self.components.iter().zip(&p.normal) {
                // +n_c on the slave node.
                c.add_entry(m, IMPOSED, s, &comp.variable, n_c)?;
                ct.add_entry(s, &comp.target_dual, m, MULTIPLIER, n_c)?;
                // −Nᵢ·n_c on each master node.
                for (node, w) in p.nodes.iter().zip(p.weights.iter()) {
                    c.add_entry(m, IMPOSED, *node, &comp.variable, -w * n_c)?;
                    ct.add_entry(*node, &comp.target_dual, m, MULTIPLIER, -w * n_c)?;
                }
            }
        }
        Ok(vec![Contribution::Literal(vec![c, ct])])
    }

    /// Linear relations on the active set: their tangent blocks **are** their stiffness blocks.
    fn tangent_is_stiffness(&self) -> bool {
        true
    }

    /// A constraint on the mechanics, and a contact.
    fn physics(&self) -> &'static [Physics] {
        &[Physics::Constraint, Physics::Mechanical, Physics::Contact]
    }

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

    fn display(&self) -> String {
        format!(
            "SubModel<Contact>: {} slave node(s), {} component(s)",
            self.pairings.len(),
            self.components.len()
        )
    }

    fn render(&self, _opts: &DumpOptions) -> String {
        let mut out = format!(
            "SubModel<Contact>\n  primal var(s): {MULTIPLIER} (multiplier)\n  dual var(s):   \
             {IMPOSED} (imposed value / −g₀)\n  slave nodes: {}\n  components:",
            self.pairings.len()
        );
        for c in &self.components {
            out.push_str(&format!("\n    {} (dual {})", c.variable, c.target_dual));
        }
        out
    }
}

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

    /// One **unilateral** [`Relation`] (`≥`) per slave node: the slave terms
    /// with coefficients `+n_c` (one per component), then one term per
    /// (master node × component) with coefficient `−Nᵢ·n_c`.
    fn relations(&self) -> Result<Vec<Relation>> {
        let mut relations = Vec::with_capacity(self.pairings.len());
        for (r, p) in self.pairings.iter().enumerate() {
            let m = self.multiplier_node(r)?;
            let s = self.slave_node(r)?;
            let mut terms = Vec::with_capacity((1 + p.nodes.len()) * self.components.len());
            for (comp, &n_c) in self.components.iter().zip(&p.normal) {
                terms.push(ConstraintTerm {
                    node: s,
                    variable: comp.variable.clone(),
                    target_dual: comp.target_dual.clone(),
                    coefficient: n_c,
                });
                for (node, w) in p.nodes.iter().zip(p.weights.iter()) {
                    terms.push(ConstraintTerm {
                        node: *node,
                        variable: comp.variable.clone(),
                        target_dual: comp.target_dual.clone(),
                        coefficient: -w * n_c,
                    });
                }
            }
            relations.push(Relation {
                multiplier_node: m,
                terms,
                sense: RelationSense::GreaterEqual,
            });
        }
        Ok(relations)
    }
}

/// Each slave node paired with its closest master facet on the positions
/// `X + u` — `X` the active configuration, `u` given per node in `displaced`
/// (empty: the positions `X` themselves). The gap is measured with that pairing
/// and that normal **on `X`**, `g̃ = n·(X_s − Σ Nᵢ X_mᵢ)`: then `g̃ + C·u` is
/// the gap of `X + u` to first order, the relation linearised there and written
/// in total displacement from `X`.
fn pair(
    coords: &Handle<crate::coords::Coords>,
    slave_ids: &[NodeId],
    master: &Mesh,
    displaced: &HashMap<NodeId, Vec<f64>>,
) -> Result<Vec<Pairing>> {
    let at = |c: &crate::coords::Coords, n: NodeId| -> Result<Vec<f64>> {
        let mut x = c.position(n)?.to_vec();
        if let Some(u) = displaced.get(&n) {
            for (xa, ua) in x.iter_mut().zip(u) {
                *xa += ua;
            }
        }
        Ok(x)
    };
    // The guard is released before the projection, which takes its own.
    let points: Vec<Vec<f64>> = {
        let c = coords.read();
        slave_ids
            .iter()
            .map(|&n| at(&c, n))
            .collect::<Result<_>>()?
    };
    let projections = project_points_at(master, &points, at)?;
    if displaced.is_empty() {
        return Ok(projections
            .into_iter()
            .map(|p| Pairing {
                nodes: p.nodes,
                weights: p.weights,
                normal: p.normal,
                gap: p.gap,
            })
            .collect());
    }
    let c = coords.read();
    projections
        .into_iter()
        .zip(slave_ids)
        .map(|(p, &s)| {
            let x_s = c.position(s)?;
            let mut point = vec![0.0; x_s.len()];
            for (&n, &w) in p.nodes.iter().zip(&p.weights) {
                for (pa, xa) in point.iter_mut().zip(c.position(n)?) {
                    *pa += w * xa;
                }
            }
            let gap = (0..x_s.len())
                .map(|a| (x_s[a] - point[a]) * p.normal[a])
                .sum();
            Ok(Pairing {
                nodes: p.nodes,
                weights: p.weights,
                normal: p.normal,
                gap,
            })
        })
        .collect()
}

/// The POI1 support of the constraint blocks: the slave nodes, then every
/// paired master node, deduplicated.
fn block_support(
    coords: Handle<crate::coords::Coords>,
    slave_ids: &[NodeId],
    pairings: &[Pairing],
) -> Result<Mesh> {
    let mut support_ids = slave_ids.to_vec();
    let mut seen: HashSet<NodeId> = support_ids.iter().copied().collect();
    for p in pairings {
        for &n in &p.nodes {
            if seen.insert(n) {
                support_ids.push(n);
            }
        }
    }
    Ok(Mesh::from_submesh(SubMesh::poi1_from_node_ids(
        coords,
        &support_ids,
    )?))
}

/// Why sharing the zones of one of the contact's own meshes cannot fail.
const SHARED: &str = "the zones of one mesh go together";

/// A mesh of the same zones as `mesh` — the same handles, nothing copied.
fn same_zones(mesh: &Mesh) -> Result<Mesh> {
    let mut out = Mesh::empty();
    for sm in mesh {
        out.add_sub(sm.clone())?;
    }
    Ok(out)
}

/// Unique node ids of a mesh, in order of first appearance across submeshes.
fn unique_nodes(mesh: &Mesh) -> Vec<NodeId> {
    let mut seen: HashSet<NodeId> = HashSet::new();
    let mut out: Vec<NodeId> = Vec::new();
    for sm in mesh {
        for &nid in sm.read().connectivity() {
            if seen.insert(nid) {
                out.push(nid);
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {

    /// A bar on the master mesh: the target the contact constrains, whose duals it
    /// reads. A SEG2 in a plane is a manifold, not a solid — a structural physics
    /// is what lives there.
    fn cible_mecanique(master: &Mesh) -> crate::containers::model::Model {
        let fes =
            crate::containers::finite_element_space::FiniteElementSpace::lagrange1(master).unwrap();
        crate::ops::model::truss(&fes, crate::ops::element_field::StrainMeasure::Linear).unwrap()
    }
    use super::*;
    use crate::atoms::{ElementType, Node};
    use crate::coords::Coords;
    use crate::handle::Handle;

    /// A slave node above a single SEG2 master (2-D): pairing, relation
    /// structure, sense and gap.
    fn seg_and_node(height: f64) -> (Mesh, Mesh) {
        let coords = Handle::new(Coords::new(2).unwrap());
        // Master from (0,0) to (2,0), normal (0,−1) (tangent +x).
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let mut msm = SubMesh::new(coords.clone(), ElementType::SEG2);
        msm.add_cell(&[a.id(), b.id()]).unwrap();
        let master = Mesh::from_submesh(msm);
        // Slave node above the middle.
        let s = Node::create_in(coords.clone(), &[0.5, height]).unwrap();
        let mut ssm = SubMesh::new(coords, ElementType::POI1);
        ssm.add_cell(&[s.id()]).unwrap();
        let slave = Mesh::from_submesh(ssm);
        (slave, master)
    }

    #[test]
    fn relations_couple_all_components_through_the_normal() {
        let (slave, master) = seg_and_node(0.25);
        let contact = Contact::new(
            &slave,
            &master,
            &cible_mecanique(&master),
            vec!["u_x".into(), "u_y".into()],
        )
        .unwrap();

        let rels = contact.relations().unwrap();
        assert_eq!(rels.len(), 1);
        let rel = &rels[0];
        assert_eq!(rel.sense, RelationSense::GreaterEqual);
        // (1 slave + 2 master nodes) × 2 components.
        assert_eq!(rel.terms.len(), 6);
        // Normal (0,−1): u_x coefficients vanish, u_y are ∓.
        let sum_abs_x: f64 = rel
            .terms
            .iter()
            .filter(|t| t.variable == "u_x")
            .map(|t| t.coefficient.abs())
            .sum();
        assert!(sum_abs_x < 1e-12);
        let slave_y = rel
            .terms
            .iter()
            .find(|t| t.variable == "u_y" && t.coefficient < 0.0)
            .expect("slave term −1 on u_y");
        assert!((slave_y.coefficient + 1.0).abs() < 1e-12);
        // Master weights sum to +1 on u_y (−(−1)·Nᵢ), gap = −0.25 (behind n).
        let master_y: f64 = rel
            .terms
            .iter()
            .filter(|t| t.variable == "u_y" && t.coefficient > 0.0)
            .map(|t| t.coefficient)
            .sum();
        assert!((master_y - 1.0).abs() < 1e-12);
        assert!((contact.gaps()[0] + 0.25).abs() < 1e-12);
    }

    #[test]
    fn component_count_must_match_dimension() {
        let (slave, master) = seg_and_node(0.25);
        assert!(Contact::new(
            &slave,
            &master,
            &cible_mecanique(&master),
            vec!["u_y".into()], // 1 component in 2-D
        )
        .is_err());
    }
}