pyrucast 0.9.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
//! Python wrappers for [`crate::containers::matrix::SubMatrix`] and the
//! aggregate [`crate::containers::matrix::Matrix`].

use crate::aggregate::Aggregate;
use crate::containers::matrix::{DofOrdering, Matrix, SubMatrix, Symmetry};
use crate::handle::Handle;
use crate::models::Physics;
use crate::py::mesh::submesh_handle;
use crate::py::node::PyNode;
use crate::py::node_field::PyNodeField;
use pyo3::prelude::*;

/// Flattened COO entries as exposed to Python: one
/// `(row_node, row_field, col_node, col_field, value)` tuple per entry.
type PyMatrixEntries = Vec<(u32, String, u32, String, f64)>;

/// Reject a divisor that would make every value of the result non-finite.
///
/// The Rust operator stops the program on one — a scalar operator yields the
/// value type, so it has no fallible form to return. Here a zero can actually
/// reach us from user data, so it becomes the exception Python expects.
fn check_divisor(rhs: f64, what: &str) -> PyResult<()> {
    if rhs == 0.0 {
        return Err(pyo3::exceptions::PyZeroDivisionError::new_err(format!(
            "{what} division by zero"
        )));
    }
    if !rhs.is_finite() {
        return Err(pyo3::exceptions::PyValueError::new_err(format!(
            "{what} division by {rhs}: every value of the result would be non-finite"
        )));
    }
    Ok(())
}

// ─── PySubMatrix ───────────────────────────────────────────────────────────

/// One block (a COO sub-matrix) of a global `Matrix`, viewed by indexing
/// (`matrix[i]`) — never constructed directly. Build a block at the parent
/// level with `Matrix.block(...)` (a unit `Matrix`), composed with `|`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubMatrix")]
pub struct PySubMatrix {
    pub(crate) handle: Handle<SubMatrix>,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubMatrix {
    /// Accumulate `value` at row `(row_node, row_field)`, column
    /// `(col_node, col_field)` (COO entry).
    fn add_entry(
        &self,
        row_node: PyRef<'_, PyNode>,
        row_field: &str,
        col_node: PyRef<'_, PyNode>,
        col_field: &str,
        value: f64,
    ) -> PyResult<()> {
        let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
        self.handle
            .write()
            .add_entry(rn, row_field, cn, col_field, value)?;
        Ok(())
    }

    /// Value at row `(row_node, row_field)`, column `(col_node, col_field)`.
    fn get(
        &self,
        row_node: PyRef<'_, PyNode>,
        row_field: &str,
        col_node: PyRef<'_, PyNode>,
        col_field: &str,
    ) -> f64 {
        let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
        self.handle.read().get(rn, row_field, cn, col_field)
    }

    /// Number of rows of this block.
    fn n_rows(&self) -> usize {
        self.handle.read().n_rows()
    }

    /// Number of columns of this block.
    fn n_cols(&self) -> usize {
        self.handle.read().n_cols()
    }

    /// Number of stored COO entries.
    fn entry_count(&self) -> usize {
        self.handle.read().entry_count()
    }

    /// Whether this block is symmetric **on its own**. A block that carries only
    /// half of a symmetry — a constraint's `C` or `Cᵀ` — answers `False`: it is
    /// symmetric only paired, which `Matrix.symmetric` is what resolves.
    #[getter]
    fn is_symmetric(&self) -> bool {
        self.handle.read().is_symmetric()
    }

    /// The scalar factor applied to every value this block emits (`1.0` unless
    /// the parent `Matrix` was built via `matrix * scalar` / `matrix / scalar`).
    #[getter]
    fn factor(&self) -> f64 {
        self.handle.read().factor()
    }

    /// `sub_matrix * scalar` — a fresh block carrying the scaled `factor`
    /// (lazy: no stored value is rewritten, so it works on a *computed* block
    /// too, whose values only exist once the matrix is assembled).
    fn __mul__(&self, rhs: f64) -> PySubMatrix {
        PySubMatrix {
            handle: Handle::new(&*self.handle.read() * rhs),
        }
    }

    /// `scalar * sub_matrix` — the mirror of `sub_matrix * scalar`.
    fn __rmul__(&self, lhs: f64) -> PySubMatrix {
        self.__mul__(lhs)
    }

    /// `sub_matrix / scalar` — a fresh block carrying the divided `factor`
    /// (lazy). Raises `ZeroDivisionError` for a divisor of zero, and
    /// `ValueError` for one that is not finite: either would make every value
    /// the block emits non-finite.
    fn __truediv__(&self, rhs: f64) -> PyResult<PySubMatrix> {
        check_divisor(rhs, "sub_matrix")?;
        Ok(PySubMatrix {
            handle: Handle::new(&*self.handle.read() / rhs),
        })
    }

    /// The physics nature(s) of the sub-model that produced this block, as a list
    /// of tags (`"mechanical"`, `"thermal"`, `"constraint"`, `"other"`). **Empty**
    /// for a block built outside assembly (the "rien" case), or several tags for a
    /// coupled physics. Set by the assembler; used by `Matrix.filter`.
    fn physics(&self) -> Vec<String> {
        self.handle
            .read()
            .physics()
            .iter()
            .map(|p| p.name().to_string())
            .collect()
    }

    /// Variable (field) names this block addresses.
    fn field_names(&self) -> Vec<String> {
        self.handle.read().field_names()
    }

    /// `(node_id, field_name)` tuples for each row, in order.
    fn row_dofs(&self) -> Vec<(u32, String)> {
        self.handle
            .read()
            .row_dofs()
            .into_iter()
            .map(|(nid, name)| (nid.0, name))
            .collect()
    }

    /// `(node_id, field_name)` tuples for each column, in order.
    fn col_dofs(&self) -> Vec<(u32, String)> {
        self.handle
            .read()
            .col_dofs()
            .into_iter()
            .map(|(nid, name)| (nid.0, name))
            .collect()
    }

    /// Dense row-major buffer, length `n_rows × n_cols`.
    fn dense(&self) -> Vec<f64> {
        self.handle.read().dense()
    }

    /// `y = A · x` (dense).
    fn mul_dense(&self, x: Vec<f64>) -> PyResult<Vec<f64>> {
        Ok(self.handle.read().mul_dense(&x)?)
    }

    /// List of `(row_node, row_field, col_node, col_field, value)`
    /// tuples, in insertion order.
    fn entries(&self) -> PyMatrixEntries {
        self.handle
            .read()
            .iter_entries()
            .into_iter()
            .map(|(rn, rf, cn, cf, v)| (rn.0, rf, cn.0, cf, v))
            .collect()
    }

    fn __len__(&self) -> usize {
        self.handle.read().entry_count()
    }
}

// ─── PyMatrix (aggregate) ──────────────────────────────────────────────────

/// A global finite-element matrix, assembled from rectangular blocks
/// (`SubMatrix`).
///
/// Build blocks with `Matrix.block(...)`, compose them with `|`, then call
/// `finalize()` before solving. Index it (`matrix[i]`) to reach a block.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "Matrix")]
pub struct PyMatrix {
    pub(crate) inner: Matrix,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyMatrix {
    /// `Matrix()` — empty aggregate. Populate via `add_sub_matrix`, or
    /// build blocks with `Matrix.block(...)` and compose them with `|`.
    #[new]
    fn py_new() -> Self {
        Self {
            inner: Matrix::empty(),
        }
    }

    /// `Matrix.block(row_support, col_support, dual_vars, primal_vars, ordering="nodes_then_vars", symmetry="none")`
    /// — a single-block `Matrix` (unit aggregate). `row_support` /
    /// `col_support` may each be a `SubMesh` view or a **unitary** `Mesh`.
    /// `ordering` is `"nodes_then_vars"` (default) or `"vars_then_nodes"`.
    /// Fill entries via the block view (`block[0].add_entry(...)`) and
    /// compose several blocks with `|`, then `finalize()`.
    #[classmethod]
    #[pyo3(signature = (row_support, col_support, dual_vars, primal_vars, ordering="nodes_then_vars", symmetry=Symmetry::None))]
    fn block(
        _cls: &pyo3::Bound<'_, pyo3::types::PyType>,
        row_support: &Bound<'_, PyAny>,
        col_support: &Bound<'_, PyAny>,
        dual_vars: Vec<String>,
        primal_vars: Vec<String>,
        ordering: &str,
        symmetry: Symmetry,
    ) -> PyResult<Self> {
        let ord = match ordering {
            "nodes_then_vars" => DofOrdering::NodesThenVars,
            "vars_then_nodes" => DofOrdering::VarsThenNodes,
            other => {
                return Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "unknown ordering '{other}'; expected 'nodes_then_vars' or 'vars_then_nodes'"
                )))
            }
        };
        let row = submesh_handle(row_support)?;
        let col = submesh_handle(col_support)?;
        let sub = SubMatrix::new(row, col, dual_vars, primal_vars, ord, symmetry);
        let mut m = Matrix::empty();
        m.add_sub(Handle::new(sub))?;
        Ok(Self { inner: m })
    }

    /// Re-assemble this matrix **from its blocks alone** — no `Model` —
    /// mutating it in place. The composition path: after combining blocks of
    /// any provenance (via `+`/`-`, `|` union, `add_sub`, `filter`, …),
    /// including *computed* ones (which `finalize()` refuses — the element
    /// kernel lives outside `containers`), call this to fold everything into
    /// one CSR. Needed, for instance, to solve `(M/dt + K) u = …` :
    /// `sys = m / dt + k; sys.assemble(); pyrucast.solver.solve(sys, rhs)`.
    ///
    /// Not needed after a bare `matrix * scalar`: scaling carries the assembled
    /// CSR along, scaled.
    fn assemble(&mut self) -> PyResult<()> {
        self.inner.assemble()?;
        Ok(())
    }

    /// Build the global DOF table and CSR. Must be called before any
    /// solver-facing method (`dense`, `mul_dense`, …).
    fn finalize(&mut self) -> PyResult<()> {
        self.inner.finalize()?;
        Ok(())
    }

    /// `Matrix.filter(physics)` — a new `Matrix` holding only the blocks **whose
    /// nature set contains** the given physics (`"mechanical"`, `"thermal"`,
    /// `"constraint"`, `"other"`, `"diffusion"`, `"radiation"`). The result is
    /// **not** finalized — call `assemble` (or `finalize` for literal-only
    /// blocks) before solving.
    fn filter(&self, physics: Physics) -> PyResult<Self> {
        Ok(Self {
            inner: self.inner.filter(physics),
        })
    }

    /// `Matrix.physics()` — the list of physics natures present across the
    /// matrix's blocks (first-seen, deduplicated). Empty if no block is tagged;
    /// several tags when the matrix aggregates several physics (e.g. a heat model
    /// with a Dirichlet → `["thermal", "constraint"]`).
    fn physics(&self) -> Vec<String> {
        self.inner
            .physics()
            .iter()
            .map(|p| p.name().to_string())
            .collect()
    }

    /// Total number of rows of the (finalized) global matrix.
    fn n_rows(&self) -> PyResult<usize> {
        Ok(self.inner.n_rows()?)
    }

    /// Total number of columns of the (finalized) global matrix.
    fn n_cols(&self) -> PyResult<usize> {
        Ok(self.inner.n_cols()?)
    }

    /// Total number of stored entries across all blocks.
    fn entry_count(&self) -> usize {
        self.inner.entry_count()
    }

    /// Whether the assembled matrix satisfies `A[i][j] == A[j][i]`, by adding up
    /// what its blocks declare. A constraint's two rectangular blocks count as one
    /// symmetry when **both** are present, and as none when one has been sliced
    /// away.
    #[getter]
    fn symmetric(&self) -> bool {
        self.inner.symmetric()
    }

    /// Variable (field) names across the whole matrix.
    fn field_names(&self) -> Vec<String> {
        self.inner.field_names()
    }

    /// `(node_id, field_name)` of each global row, in order.
    fn row_dofs(&self) -> PyResult<Vec<(u32, String)>> {
        Ok(self
            .inner
            .row_dofs()?
            .into_iter()
            .map(|(n, name)| (n.0, name))
            .collect())
    }

    /// `(node_id, field_name)` of each global column, in order.
    fn col_dofs(&self) -> PyResult<Vec<(u32, String)>> {
        Ok(self
            .inner
            .col_dofs()?
            .into_iter()
            .map(|(n, name)| (n.0, name))
            .collect())
    }

    /// Value at row `(row_node, row_field)`, column `(col_node, col_field)`.
    fn get(
        &self,
        row_node: PyRef<'_, PyNode>,
        row_field: &str,
        col_node: PyRef<'_, PyNode>,
        col_field: &str,
    ) -> f64 {
        let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
        self.inner.get(rn, row_field, cn, col_field)
    }

    /// Dense row-major buffer of the finalized matrix (`n_rows × n_cols`).
    fn dense(&self) -> PyResult<Vec<f64>> {
        Ok(self.inner.dense()?)
    }

    /// `y = A · x` against a dense vector `x`.
    fn mul_dense(&self, x: Vec<f64>) -> PyResult<Vec<f64>> {
        Ok(self.inner.mul_dense(&x)?)
    }

    /// `matrix / scalar` — a fresh `Matrix` whose blocks carry the divided
    /// `factor` (lazy). Not finalized; see `__mul__`. Raises `ZeroDivisionError`
    /// for a divisor of zero, and `ValueError` for one that is not finite:
    /// either would make every value of the result non-finite.
    fn __truediv__(&self, rhs: f64) -> PyResult<PyMatrix> {
        check_divisor(rhs, "matrix")?;
        Ok(PyMatrix {
            inner: &self.inner / rhs,
        })
    }

    /// `scalar * matrix` — the mirror of `matrix * scalar`.
    fn __rmul__(&self, lhs: f64) -> PyMatrix {
        PyMatrix {
            inner: &self.inner * lhs,
        }
    }

    /// `-matrix` — a fresh `Matrix` whose blocks carry the negated `factor`
    /// (lazy). Sugar for `matrix * -1.0`.
    fn __neg__(&self) -> PyMatrix {
        PyMatrix {
            inner: -&self.inner,
        }
    }

    /// List of `(row_node, row_field, col_node, col_field, value)`
    /// tuples — every entry across every block, in block-insertion order.
    fn entries(&self) -> PyMatrixEntries {
        self.inner
            .iter_entries()
            .into_iter()
            .map(|(rn, rf, cn, cf, v)| (rn.0, rf, cn.0, cf, v))
            .collect()
    }
}

// Polymorphic product — **closed block**, undecorated on purpose (see
// `impl_aggregate_pymethods!`): its `.pyi` entries are the hand-written
// overloads submitted just below.
#[pymethods]
impl PyMatrix {
    /// `matrix * x` — either a matrix-vector product against a `NodeField` (`x`
    /// read at the matrix's column DOFs, result a fresh `NodeField` over its row
    /// DOFs) or, for a `float`, a scalar scale: a fresh `Matrix` whose blocks
    /// carry the scaled `factor` (lazy — no value is rewritten). The scaled
    /// result is **not** finalized; call `finalize()` (or `assemble` for computed
    /// blocks) before solving or querying it.
    fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
        let py = rhs.py();
        if let Ok(field) = rhs.extract::<PyRef<'_, PyNodeField>>() {
            let inner = self.inner.mul_field(&field.inner)?;
            return Ok(Py::new(py, PyNodeField { inner })?.into_any());
        }
        let s: f64 = rhs.extract()?;
        let inner = &self.inner * s;
        Ok(Py::new(py, PyMatrix { inner })?.into_any())
    }
}

/// The right-hand side of a matrix sum, as a `Matrix` or a `SubMatrix`.
///
/// Kept as the borrowed alternatives rather than a materialised `Matrix`: the
/// sum shares its operands' blocks, and an aggregate is not cloneable anyway
/// (it carries the factorization cache).
enum SumOperand<'py> {
    Aggregate(PyRef<'py, PyMatrix>),
    Block(PyRef<'py, PySubMatrix>),
}

impl<'py> SumOperand<'py> {
    fn extract(rhs: &Bound<'py, PyAny>, op: &str) -> PyResult<Self> {
        if let Ok(m) = rhs.extract::<PyRef<'py, PyMatrix>>() {
            return Ok(Self::Aggregate(m));
        }
        if let Ok(b) = rhs.extract::<PyRef<'py, PySubMatrix>>() {
            return Ok(Self::Block(b));
        }
        Err(pyo3::exceptions::PyTypeError::new_err(format!(
            "{op}: the right-hand side must be a Matrix or a SubMatrix"
        )))
    }
}

// Polymorphic sum and difference — **closed block**, undecorated on purpose
// (see `impl_aggregate_pymethods!`): the `.pyi` entries are the hand-written
// overloads submitted below.
#[pymethods]
impl PyMatrix {
    /// `matrix + other` — a fresh `Matrix` holding the blocks of both, shared
    /// and **not** deduplicated: unlike `|`, a block handed over twice counts
    /// twice, so `k + k` is `2k` where `k | k` is `k`. Nothing is computed here;
    /// the assembler sums whatever lands on the same global `(row, col)`. **Not**
    /// finalized: call `assemble()` before solving.
    fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
        let inner = match SumOperand::extract(rhs, "matrix + x")? {
            SumOperand::Aggregate(m) => &self.inner + &m.inner,
            SumOperand::Block(b) => &self.inner + &*b.handle.read(),
        };
        Ok(PyMatrix { inner })
    }

    /// `matrix - other` — as `+`, with the right-hand side's blocks negated
    /// (which copies them, the factor living in the block).
    fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
        let inner = match SumOperand::extract(rhs, "matrix - x")? {
            SumOperand::Aggregate(m) => &self.inner - &m.inner,
            SumOperand::Block(b) => &self.inner - &*b.handle.read(),
        };
        Ok(PyMatrix { inner })
    }
}

// Same, on a block: `sub_matrix + x` yields the two-block `Matrix`.
#[pymethods]
impl PySubMatrix {
    /// `sub_matrix + other` — a fresh `Matrix` holding this block and the
    /// other operand's, as `Matrix.__add__` does.
    fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
        let inner = match SumOperand::extract(rhs, "sub_matrix + x")? {
            SumOperand::Aggregate(m) => &*self.handle.read() + &m.inner,
            // One guard at a time: `b + b` hands over the same block twice, and
            // a second read on a lock this thread already holds may deadlock
            // against a queued writer.
            SumOperand::Block(b) => {
                let other = (*b.handle.read()).clone();
                &*self.handle.read() + &other
            }
        };
        Ok(PyMatrix { inner })
    }

    /// `sub_matrix - other` — as `+`, with the right-hand side negated.
    fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
        let inner = match SumOperand::extract(rhs, "sub_matrix - x")? {
            SumOperand::Aggregate(m) => &*self.handle.read() - &m.inner,
            SumOperand::Block(b) => {
                let other = (*b.handle.read()).clone();
                &*self.handle.read() - &other
            }
        };
        Ok(PyMatrix { inner })
    }

    /// `-sub_matrix` — a fresh block carrying the negated `factor` (lazy). No
    /// value is rewritten.
    fn __neg__(&self) -> PySubMatrix {
        PySubMatrix {
            handle: Handle::new(-&*self.handle.read()),
        }
    }
}

#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
    pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PyMatrix:
    @overload
    def __mul__(self, rhs: pyo3_stub_gen.RustType["PyNodeField"]) -> pyo3_stub_gen.RustType["PyNodeField"]:
        """`matrix * x` → the matrix-vector product: `x` is read at the column
        DOFs, the result is a fresh `NodeField` over the row DOFs."""
    @overload
    def __mul__(self, rhs: float) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`matrix * scalar` → a fresh `Matrix` whose blocks carry the scaled
        `factor` (lazy — no value is rewritten). **Not** finalized: call
        `finalize()` (or `assemble` for computed blocks) before solving."""
    "# }
}

#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
    pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PyMatrix:
    def __add__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`matrix + other` → a fresh `Matrix` holding the blocks of both,
        shared and **not** deduplicated: `k + k` is `2k` where `k | k` is `k`.
        Reach for `|` to compose one operator out of distinct parts, for `+` to
        add two operators. **Not** finalized: call `assemble()` before solving."""
    def __sub__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`matrix - other` → as `+`, with the right-hand side's blocks
        negated (which copies them, the factor living in the block)."""
    "# }
}

#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
    pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PySubMatrix:
    def __add__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`sub_matrix + other` → a fresh `Matrix` holding this block and the
        other operand's, as `Matrix.__add__` does."""
    def __sub__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`sub_matrix - other` → as `+`, with the right-hand side negated."""
    def __neg__(self) -> pyo3_stub_gen.RustType["PySubMatrix"]:
        """`-sub_matrix` → a fresh block carrying the negated `factor`
        (lazy — no value is rewritten)."""
    "# }
}

crate::impl_aggregate_pymethods!(
    PyMatrix,
    PySubMatrix,
    "Matrix",
    sub_matrix,
    Matrix,
    r#"
class PyMatrix:
    @overload
    def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubMatrix"]:
        """`matrix[i]` → the `SubMatrix` view of block i (one rectangular COO
        block, with its row and column supports)."""
    @overload
    def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`matrix[i:j:k]` → a fresh `Matrix` holding the sliced blocks, shared
        with this one (no deep copy)."""
    def __or__(self, other: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`matrix | other` → a fresh `Matrix` holding the blocks of both, in
        first-seen order and deduplicated by object identity. Assemble the global
        operator this way, then call `finalize()` before solving."""
    def __ror__(self, other: pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`sub_matrix | matrix` — the mirror of `matrix | sub_matrix`,
        differing only in that the lone block comes first."""
    "#,
    r#"
class PySubMatrix:
    def __or__(self, other: pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
        """`sub_matrix | sub_matrix` → a fresh `Matrix` holding both blocks."""
    "#
);
crate::impl_dump_pymethod!(handle PySubMatrix, handle);