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
//! Python wrappers for [`crate::containers::model::SubModel`] and [`crate::containers::model::Model`].
use crate::atoms::NodeId;
use crate::containers::model::{Model, SubModel};
use crate::handle::Handle;
use crate::models::Physics;
use crate::py::finite_element_space::{PyFiniteElementSpace, PySubFiniteElementSpace};
use crate::py::mesh::PyMesh;
use crate::py::node::PyNode;
use crate::py::node_field::PyNodeField;
use pyo3::prelude::*;
/// A **view** into one sub-model of a `Model`, obtained by indexing
/// (`model[i]`) — never constructed directly. Build physics at the parent
/// level instead: `model.heat_conduction(fes)` or `model.dirichlet(...)`,
/// composed with `|`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubModel")]
pub struct PySubModel {
pub(crate) handle: Handle<SubModel>,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubModel {
/// Names of the primal (primary) variables of this sub-model.
fn primal_vars(&self) -> Vec<String> {
self.handle.read().primal_vars()
}
/// Names of the dual variables of this sub-model.
fn dual_vars(&self) -> Vec<String> {
self.handle.read().dual_vars()
}
/// `sub.fespace()` — the `SubFiniteElementSpace` this sub-model integrates
/// on, its law included when it has one; side A for an interface
/// transfer. `None` for a constraint sub-model (Dirichlet, MPC…, which
/// integrate nothing).
fn fespace(&self) -> Option<PySubFiniteElementSpace> {
self.handle
.read()
.material_fespace()
.map(|handle| PySubFiniteElementSpace { handle })
}
/// The physics nature(s) of this sub-model as a list of tags among
/// `"mechanical"`, `"thermal"`, `"diffusion"`, `"radiation"`,
/// `"constraint"` and `"contact"`. A flux or an exchange takes the nature
/// of the model it targets; a constraint carries `"constraint"` plus that
/// nature, or alone when its relation spans two physics; radiation carries
/// `"thermal"` and `"radiation"`; a contact carries `"constraint"`,
/// `"mechanical"` and `"contact"`.
fn physics(&self) -> Vec<String> {
self.handle
.read()
.physics()
.iter()
.map(|p| p.name().to_string())
.collect()
}
/// The kind of this sub-model, named — `"Dirichlet"`, `"Contact"`,
/// `"Elasticity"`… The question its natures cannot answer: a contact and a
/// Dirichlet on displacements are both constraint and mechanical.
fn label(&self) -> &'static str {
self.handle.read().label()
}
/// POI1 `Mesh` of the multiplier nodes (Lagrange physics only — empty
/// otherwise). Build a load `SubNodeField` on `mesh[0]` to impose the
/// constrained values, or read the nodes via `mesh.node(0, i, 0)`.
fn multiplier_mesh(&self) -> PyResult<PyMesh> {
let mesh = self.handle.read().multiplier_mesh()?;
Ok(PyMesh { inner: mesh })
}
/// Names of the material components this sub-model expects, or
/// `None` for physics that don't need material data (Dirichlet, …).
fn material_components(&self) -> Option<Vec<String>> {
self.handle
.read()
.material_components()
.map(|c| c.iter().map(|s| s.to_string()).collect())
}
/// Whether this sub-model carries a constitutive behaviour that can be
/// integrated with `strain` / `integrate_behavior`: `True` for the
/// physics with a law, `False` for constraints like Dirichlet and for the
/// exchanges and the flux, which integrate on a subspace without a law.
#[getter]
fn has_behavior(&self) -> bool {
self.handle.read().has_behavior()
}
}
/// A physics problem: a collection of sub-models (heat conduction,
/// Dirichlet BCs, ...) over finite-element spaces.
///
/// Build sub-models with the operators of `pyrucast.model`
/// (`model.heat_conduction(fes)`, `model.dirichlet(...)`) and compose them
/// with `|`; assemble with `stiffness` / `mass`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "Model")]
pub struct PyModel {
pub(crate) inner: Model,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyModel {
/// Names of the primal (primary) variables across the whole model.
fn primal_vars(&self) -> Vec<String> {
self.inner.primal_vars()
}
/// Names of the dual variables across the whole model.
fn dual_vars(&self) -> Vec<String> {
self.inner.dual_vars()
}
/// `Model.dual_of(variable)` — the dual (residual) variable conjugate to a
/// primal `variable` (e.g. `"u_x" -> "f_x"`, `"T" -> "q"`), searched across
/// all sub-models, or `None`. A helper to fill an MPC term's `target_dual`.
fn dual_of(&self, variable: &str) -> Option<String> {
self.inner.dual_of(variable)
}
/// `Model.fespace()` — the `FiniteElementSpace` this model integrates on:
/// the behaviour subspace of each domain sub-model (constraints skipped), in
/// order, one per sub-model — two physics on one subspace list it twice.
/// The subspaces are shared, not copied. Raises if the model has no domain
/// sub-model. Combined with `FiniteElementSpace.mesh()`, lets a caller
/// recover the FE space and mesh from the model alone.
fn fespace(&self) -> PyResult<PyFiniteElementSpace> {
Ok(PyFiniteElementSpace {
inner: self.inner.fespace()?,
})
}
/// `Model.filter(physics)` — a new `Model` holding only the sub-models **whose
/// nature set contains** the given physics. `physics` is a tag: `"mechanical"`,
/// `"thermal"`, `"constraint"`, `"other"`, `"diffusion"`, `"radiation"` or
/// `"contact"`. Sub-model order is preserved; the result may be empty.
///
/// A coupled physics declares several natures and is therefore returned by
/// each of its filters — a radiation boundary is both `"thermal"` and
/// `"radiation"`, a contact both `"constraint"` and `"contact"`.
fn filter(&self, physics: Physics) -> Self {
Self {
inner: self.inner.filter(physics),
}
}
/// `Model.exclude(physics)` — the complement of `filter`: a new `Model`
/// holding only the sub-models **whose nature set does not contain** the
/// given physics. The two compose, one condition each: a constraint also
/// carries the nature of the physics it pins, so
/// `model.filter("mechanical")` is the mechanics **with** its supports and
/// `model.filter("mechanical").exclude("constraint")` the mechanics alone.
fn exclude(&self, physics: Physics) -> Self {
Self {
inner: self.inner.exclude(physics),
}
}
/// `Model.multiplier_mesh()` — POI1 `Mesh` of the constraint multiplier
/// nodes across the model (empty for a model with no constraint). Each
/// constraint mints its own, one per relation: read them via
/// `mesh.node(0, i, 0)` or build a load `SubNodeField` on `mesh[0]`.
fn multiplier_mesh(&self) -> PyResult<PyMesh> {
Ok(PyMesh {
inner: self.inner.multiplier_mesh()?,
})
}
/// `Model.constraint_rhs(imposed)` — build the constraint load (right-hand
/// side) of this model's constraint from `(node, g)` pairs.
///
/// `imposed` is a list of `(Node, value)`: each node **keys the relation it
/// belongs to** (for `dirichlet` the constrained node itself, for `mpc` any
/// of the relation's term nodes), and `value` is the right-hand side `g`.
/// Returns a fresh `NodeField` over the multiplier nodes, carrying the
/// `imposed` component, with `g` at each cited relation and `0` elsewhere. Union it
/// into the global load with `|`, e.g. `load | model.constraint_rhs([...])`.
///
/// The model must hold exactly one constraint sub-model (the `dirichlet` /
/// `mpc` object). Raises if a node constrains none of its relations, or keys
/// several of them (ambiguous — drop it).
fn constraint_rhs(
&self,
py: Python<'_>,
imposed: Vec<(Py<PyNode>, f64)>,
) -> PyResult<PyNodeField> {
// The relations' nodes live in the multipliers' `Coords`; a model with
// no constraint has none, and `constraint_rhs` says so itself.
let coords = self.inner.multiplier_mesh()?.coords().ok();
let pairs = imposed
.iter()
.map(|(node, g)| Ok((node.borrow(py).id_in(coords.as_ref())?, *g)))
.collect::<PyResult<Vec<(NodeId, f64)>>>()?;
let inner = self.inner.constraint_rhs(&pairs)?;
Ok(PyNodeField { inner })
}
/// `Model.constraint_rhs_by_index(imposed)` — like `constraint_rhs` but each
/// relation is keyed by its **index** (0-based, in `relations()` order)
/// instead of a node.
///
/// `imposed` is a list of `(relation_index, g)`. Use this when a node
/// participates in several relations, where node keying would be ambiguous.
/// Returns the same kind of `NodeField` over the multiplier nodes; union it
/// with `|`. Raises if an index is out of range.
fn constraint_rhs_by_index(&self, imposed: Vec<(usize, f64)>) -> PyResult<PyNodeField> {
let inner = self.inner.constraint_rhs_by_index(&imposed)?;
Ok(PyNodeField { inner })
}
}
crate::impl_aggregate_pymethods!(
PyModel,
PySubModel,
"Model",
sub_model,
Model,
r#"
class PyModel:
@overload
def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubModel"]:
"""`model[i]` → the `SubModel` view of term i (a physics term, a
Dirichlet condition, an MPC, ...)."""
@overload
def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyModel"]:
"""`model[i:j:k]` → a fresh `Model` holding the sliced terms, shared
with this one (no deep copy)."""
def __or__(self, other: pyo3_stub_gen.RustType["PyModel"] | pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
"""`model | other` → a fresh `Model` holding the terms of both, in
first-seen order and deduplicated by object identity. This is how a problem
is composed: physics | boundary conditions | constraints."""
def __ror__(self, other: pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
"""`sub_model | model` — the mirror of `model | sub_model`, differing
only in that the lone term comes first."""
"#,
r#"
class PySubModel:
def __or__(self, other: pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
"""`sub_model | sub_model` → a fresh `Model` holding both terms."""
"#
);
crate::impl_dump_pymethod!(handle PySubModel, handle);