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
//! The exchange law `h(a − b)` — what a boundary and an interface share.
//!
//! One law, two situations, and the only difference is **which side of the
//! equals sign the far medium lives on**:
//!
//! | | the far side is… | where it goes |
//! |---|---|---|
//! | [boundary](crate::models::boundary_transfer) | a **datum** (an ambient value) | the right-hand side, `h·a_ext ∫N dΓ` |
//! | [interface](crate::models::interface_transfer) | an **unknown** (the other mesh's field) | the matrix, as a coupling block |
//!
//! The off-diagonal block *is* the right-hand side made implicit. That is why
//! the two physics share this module rather than each carrying a copy of
//! `∫NᵢNⱼ`: the boundary kernel is the interface kernel with both sides on the
//! same cell.
//!
//! ## What is transferred is the caller's to say
//!
//! Neither physics knows what it transports. It is given a list of
//! `(primal, dual)` pairs — the same shape
//! [`embedded`](crate::models::embedded) and [`contact`](crate::models::contact)
//! take, the two other laws that tie meshes together — and everything else
//! follows from it:
//!
//! ```text
//! transferred material behaviour input behaviour output
//! ("T", "q") h_T T / jump_T flux_T
//! ("c_H2","j_H2") h_c_H2 c_H2 / jump_c_H2 flux_c_H2
//! ("u_x", "f_x") h_u_x u_x / jump_u_x flux_u_x
//! ```
//!
//! One coefficient per transferred quantity, named after it. A surface exchange
//! on displacements is then a **Winkler elastic foundation**, and an interface
//! one a joint of finite stiffness — neither needed a line of new physics.
//!
//! ## When *not* to use it on displacements
//!
//! Tying two surfaces by making `h` large is a penalty method, and a
//! [`Mpc`](crate::models::mpc) does it exactly, without degrading the
//! conditioning. The test is where the number comes from: **if `h` comes from a
//! measurement this is physics; if `h` was chosen "large enough", it wanted a
//! constraint.**
use crateSubElementField;
use crateSubField;
use crate;
use crate;
/// The material component carrying the exchange coefficient of one transferred
/// quantity — `h_T`, `h_c_H2`, `h_u_x`.
///
/// Derived rather than tabulated, which is what made
/// [`Domain::material_components`](crate::models::Domain::material_components)
/// owned: the name is not known until the caller says what is transferred.
///
/// ```
/// # use pyrucast::models::transfer;
/// // Le nom n'est pas tabulé : il se déduit de ce que l'appelant transporte.
/// assert_eq!(transfer::coefficient_name("T"), "h_T");
/// assert_eq!(transfer::coefficient_name("c_H2"), "h_c_H2");
/// ```
/// The behaviour **output** component of one transferred quantity: the exchanged
/// flux density `h·(a − b)`.
///
/// ```
/// # use pyrucast::models::transfer;
/// // La **sortie** de la loi : la densité de flux échangée.
/// assert_eq!(transfer::flux_name("T"), "flux_T");
/// ```
/// The behaviour **input** component of an interface law: the jump of one
/// transferred quantity across it, `a₁ − a₂`.
///
/// A boundary law needs no such name — its input is the field itself, the far
/// side being a datum rather than a second unknown.
///
/// ```
/// # use pyrucast::models::transfer;
/// // L'**entrée** d'une loi d'interface : le saut a₁ − a₂. Une loi de bord
/// // n'en a pas besoin — son entrée est le champ lui-même.
/// assert_eq!(transfer::jump_name("T"), "jump_T");
/// ```
/// Check a caller's transferred list, and return the material contract it
/// implies. An empty list is a caller error: a law that transfers nothing has no
/// matrix to assemble and no coefficient to read.
///
/// ```
/// # use pyrucast::models::transfer;
/// let paires = vec![("T".to_string(), "q".to_string())];
/// assert_eq!(transfer::material_contract("BoundaryTransfer", &paires)?,
/// vec!["h_T".to_string()]);
/// // Une loi qui ne transporte rien n'a ni matrice ni coefficient : c'est
/// // une erreur d'appel, pas un cas dégénéré à laisser passer.
/// assert!(transfer::material_contract("BoundaryTransfer", &[]).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// The `'static` singleton slice of one nature, so a physics whose nature is
/// **stored** can still answer [`SubModelKind::physics`](crate::models::SubModelKind::physics)
/// without the trait
/// having to hand out owned data.
///
/// A transfer law's nature cannot be deduced from its variable names, which the
/// caller chooses freely, so it is declared and kept; but there are finitely
/// many natures, and each has exactly one slice.
///
/// ```
/// # use pyrucast::models::transfer;
/// # use pyrucast::models::Physics;
/// // La nature d'une loi de transfert ne se déduit pas des noms de
/// // variables, que l'appelant choisit : elle est déclarée, puis rendue
/// // ici sous la forme d'une tranche `'static`.
/// assert_eq!(transfer::physics_slice(Physics::Thermal), &[Physics::Thermal]);
/// ```
/// Resolve each transferred quantity's coefficient to a **component index**,
/// once, before any loop.
///
/// [`SubElementField::value`] looks its component up by a linear scan over the
/// names, so calling it inside the Gauss loop — as both physics used to — pays a
/// string comparison per point. Hoisting it here is why the multi-component form
/// costs less than the scalar one it replaces, rather than more.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::DofOrdering;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::transfer;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["h_T".into()], &[2.0]).unwrap());
/// // Les index sont **hissés hors de la boucle de Gauss** : `value` cherche
/// // son nom par balayage linéaire, et le payer par point coûtait plus que
/// // la forme scalaire qu'on remplace.
/// let paires = vec![("T".to_string(), "q".to_string())];
/// assert_eq!(transfer::coefficient_indices(&mat.read(), &paires)?, vec![0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// `sign · h ∫_Γ N_i^row N_j^col dΓ`, one uncoupled sub-block per transferred
/// quantity.
///
/// The four blocks of an interface come from this one function: the two diagonal
/// ones with `row_geom == col_geom` and `sign = +1`, the two off-diagonal ones
/// with the facing cell and `sign = −1`. A boundary term is the diagonal case
/// alone.
///
/// `ke` is laid out [`NodesThenVars`](crate::containers::matrix::DofOrdering),
/// so a node's variables are contiguous. Quantities do **not** couple to each
/// other — heat crossing a joint does not drive hydrogen across it — which is
/// why only the diagonal in the variable index is written.
///
/// The measure comes from the **row** side: on a conforming interface the two
/// carry the same surface, so either would do, and taking the row side keeps the
/// four blocks integrated identically — which is what makes them sum to a
/// consistent operator.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::DofOrdering;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::transfer;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["h_T".into()], &[2.0]).unwrap());
/// let paires = vec![("T".to_string(), "q".to_string())];
/// let idx = transfer::coefficient_indices(&mat.read(), &paires)?;
/// // h ∫ N_i N_j dΓ : la mesure vient du côté **ligne**, ce qui fait que
/// // les quatre blocs d'une interface s'intègrent identiquement.
/// let bloc = assemble_block(
/// std::slice::from_ref(&zone), &support, &support,
/// vec!["q".into()], vec!["T".into()], DofOrdering::NodesThenVars, true,
/// Some(&mat), None,
/// |geoms, m, _s, ke| {
/// transfer::exchange_matrix(&geoms[0], &geoms[0], m.unwrap(), &idx, 1.0, ke)
/// },
/// )?;
/// // La somme des entrées vaut h × la longueur du segment.
/// let total: f64 = bloc.iter_entries().into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!((total - 2.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// `f_i = ∫ N_i · flux dΓ` — the internal nodal fluxes of an exchange law,
/// weighted by `N` and not by `Bᵀ`.
///
/// A film integrand is a flux **density**, not a gradient-conjugate quantity, so
/// the continuum default would be wrong here. For a linear law this equals
/// `(K·u)_i`, which is the invariant the internal forces must satisfy.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::DofOrdering;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::transfer;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["h_T".into()], &[2.0]).unwrap());
/// # let flux = SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["flux_T".into()], &[1.0])?;
/// # let paires = vec![("T".to_string(), "q".to_string())];
/// # let fe = std::sync::Mutex::new(vec![0.0; 2]);
/// // ∫ Nᵀ · flux dΓ — le résidu d'une loi de transfert, du côté nodal.
/// // Une densité unité sur un segment de longueur 1 se partage en deux.
/// pyrucast::models::kernel::reduce_cells(&zone, |geom| {
/// transfer::internal_force(geom, &flux, &paires, &mut fe.lock().unwrap())?;
/// Ok(0.0)
/// })?;
/// assert!((fe.lock().unwrap().iter().sum::<f64>() - 1.0).abs() < 1e-12);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```