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
//! Linear solvers for an assembled [`Matrix`] and a right-hand side.
//!
//! One entry, [`solve`]: the matrix carries everything the solve needs. A
//! constraint relation is a row named [`IMPOSED`](crate::models::IMPOSED), its
//! coefficients are that row, its multiplier is the column
//! [`MULTIPLIER`](crate::models::MULTIPLIER) of the same node, and its sense
//! (`=`, `≥`, `≤`) is declared by the block that built it
//! ([`SubMatrix::row_sense`](crate::containers::matrix::SubMatrix::row_sense)).
//! No model is passed alongside, so none can contradict the matrix.
//!
//! [`SolveOptions::relations`] chooses how the relations are enforced:
//!
//! - [`RelationMethod::Lagrange`] (default) — the saddle-point as assembled,
//! factorized by a sparse LU (or Cholesky); as soon as the matrix carries an
//! inequality, the **active-set** method decides which relations are
//! saturated ([`ActiveSetMethod`]);
//! - [`RelationMethod::Eliminate`] — every equality relation eliminates one
//! unknown (master/slave condensation), and the smaller system left carries
//! no multiplier but those of the inequalities, which the same active-set
//! loop resolves on it.
//!
//! Whatever is costly — the factorization, the condensation, the active-set
//! state — is cached on the matrix ([`SolveOptions::cache`]) and cleared when
//! the matrix changes.
//!
//! ```
//! # use pyrucast::models::symmetry::MaterialSymmetry;
//! # use pyrucast::aggregate::Aggregate;
//! # use pyrucast::atoms::{ElementType, Node};
//! # use pyrucast::containers::field::SubField;
//! # use pyrucast::containers::finite_element_space::FiniteElementSpace;
//! # use pyrucast::containers::mesh::{Mesh, SubMesh};
//! # use pyrucast::containers::node_field::NodeField;
//! # use pyrucast::coords::Coords;
//! # use pyrucast::handle::Handle;
//! # use pyrucast::models::RelationSense;
//! # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
//! # let coords = Handle::new(Coords::new(1).unwrap());
//! # let n: Vec<Node> = (0..3)
//! # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
//! # .collect();
//! # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
//! # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
//! # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
//! # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
//! let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
//! let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::Equality)?)?;
//! # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
//! let k = matrix::stiffness(&modele, &materiaux)?;
//! # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
//! # vec!["imposed".into()])?;
//! # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
//! // A bar held at 100 °C on its left end, with no other load: 100 °C
//! // everywhere — by multipliers or by elimination alike.
//! let u = solver::solve(&k, &charge)?;
//! assert!((u.value(n[2].id(), "T")? - 100.0).abs() < 1e-9);
//! let par_elimination = solver::solve_with_options(&k, &charge, &solver::SolveOptions {
//! relations: solver::RelationMethod::Eliminate, ..Default::default() })?;
//! assert!((par_elimination.value(n[2].id(), "T")? - 100.0).abs() < 1e-9);
//! # Ok::<(), pyrucast::PyrucastError>(())
//! ```
use crateMatrix;
use crateNodeField;
use crateResult;
use crate;
pub use ;
pub use ActiveSetMethod;
/// How a solve enforces the constraint relations of the matrix.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::named::Named;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # use pyrucast::ops::solver::{RelationMethod, SolveOptions};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// # .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::Equality)?)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// # let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// # vec!["imposed".into()])?;
/// # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
/// assert_eq!(RelationMethod::default(), RelationMethod::Lagrange);
/// assert_eq!(RelationMethod::parse("eliminate")?, RelationMethod::Eliminate);
/// // By elimination, the multiplier is gone from the solution: the reaction is
/// // read in the dual row of the eliminated unknown instead.
/// let elimine = solver::solve_with_options(&k, &charge, &SolveOptions {
/// relations: RelationMethod::Eliminate, ..Default::default() })?;
/// assert!(elimine.value(n[0].id(), "q").is_ok());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// Options for [`solve_with_options`]. The defaults are those of the Python
/// face: `method="lu"`, `relations="lagrange"`, `active_set="schur"`,
/// `cache=True`, `max_iter=100`, `tol=1e-10`, `verbosity="silent"`.
///
/// ```
/// # use pyrucast::ops::solver::{ActiveSetMethod, RelationMethod, SolveMethod, SolveOptions};
/// let d = SolveOptions::default();
/// assert_eq!(d.method, SolveMethod::Lu);
/// assert_eq!(d.relations, RelationMethod::Lagrange);
/// assert_eq!(d.active_set, ActiveSetMethod::SchurComplement);
/// assert!(d.cache && d.max_iter == 100 && d.tol == 1e-10);
/// ```
/// Solve `matrix · x = rhs` with the default options.
///
/// `matrix` is assembled and square; `rhs` is read at every row DOF of the
/// matrix, a DOF no zone defines reading zero — the imposed value of a
/// relation lives at its multiplier node, component `imposed`. A relation is
/// enforced by its multiplier, and an inequality relation (`≥`, `≤`) by the
/// active-set loop: an active relation holds as an equation and its multiplier
/// carries the reaction (`λ ≤ 0` for `≥`, `λ ≥ 0` for `≤`), an inactive one
/// reports `λ = 0`.
///
/// The solution has one zone per distinct column support of the matrix's
/// blocks, each sharing that block's POI1 support — the multipliers included.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// # .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// // A floor: T(0) ≥ 100 °C, nothing else.
/// let plancher = model::dirichlet(&impose, &barre, "T", RelationSense::GreaterEqual)?;
/// let modele = barre.union(&plancher)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// # vec!["imposed".into()])?;
/// # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
/// // The matrix knows the relation is an inequality: the active set finds it
/// // saturated, and the bar sits on its floor.
/// let u = solver::solve(&k, &charge)?;
/// assert!((u.value(n[2].id(), "T")? - 100.0).abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// Like [`solve`], with explicit [`SolveOptions`].
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # use pyrucast::ops::solver::{SolveMethod, SolveOptions};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// # .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::Equality)?)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// # let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// # vec!["imposed".into()])?;
/// # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
/// // A Lagrange saddle-point is symmetric but indefinite: Cholesky refuses it,
/// // and says so.
/// let cholesky = SolveOptions { method: SolveMethod::Cholesky, cache: false, ..Default::default() };
/// let err = solver::solve_with_options(&k, &charge, &cholesky).unwrap_err().to_string();
/// assert!(err.contains("positive definite"), "{err}");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// Like [`solve`], but polls `cancel` at each phase boundary so the call can be
/// stopped early (returning [`PyrucastError::Interrupted`](crate::PyrucastError::Interrupted)).
///
/// **Granularity.** A sparse factorization is a single library call with no
/// cooperative checkpoint: `cancel` is polled *around* the heavy steps and at
/// each status iteration of the active-set loop, so a `Ctrl+C` lands at the
/// next phase boundary, not inside a factorization.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # use std::sync::atomic::{AtomicBool, Ordering};
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// # .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::Equality)?)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// # let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// # vec!["imposed".into()])?;
/// let stop = AtomicBool::new(false);
/// assert!(solver::solve_cancellable(&k, &charge, &stop).is_ok());
/// // A token armed in advance: the stop lands at the first phase boundary.
/// stop.store(true, Ordering::Relaxed);
/// assert!(solver::solve_cancellable(&k, &charge, &stop).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// [`solve_cancellable`] with explicit [`SolveOptions`] — the full form the
/// Python binding routes to.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::RelationSense;
/// # use pyrucast::ops::{element_field, matrix, mesh, model, solver};
/// # use pyrucast::ops::solver::{ActiveSetMethod, SolveOptions};
/// # use std::sync::atomic::AtomicBool;
/// # let coords = Handle::new(Coords::new(1).unwrap());
/// # let n: Vec<Node> = (0..3)
/// # .map(|i| Node::create_in(coords.clone(), &[i as f64 / 2.0]).unwrap())
/// # .collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # for i in 0..2 { sm.add_cell(&[n[i].id(), n[i + 1].id()]).unwrap(); }
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let barre = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let modele = barre.union(&model::dirichlet(&impose, &barre, "T", RelationSense::GreaterEqual)?)?;
/// # let materiaux = element_field::material_field(&modele, &[("k", 1.0)])?;
/// # let k = matrix::stiffness(&modele, &materiaux)?;
/// # let charge = NodeField::from_submesh(&modele.multiplier_mesh()?.get(0)?,
/// # vec!["imposed".into()])?;
/// # charge.get(0)?.write().add_to_component("imposed", 100.0)?;
/// let stop = AtomicBool::new(false);
/// let refacto = SolveOptions { active_set: ActiveSetMethod::Refactorize, ..Default::default() };
/// let u = solver::solve_cancellable_with_options(&k, &charge, &refacto, &stop)?;
/// assert!((u.value(n[2].id(), "T")? - 100.0).abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```