pyrucast 0.1.4

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
//! Python wrappers for the mesher operations in [`crate::ops::mesher`].
//!
//! Free functions that build or transform a [`PyMesh`]. Kept here —
//! mirroring `src/ops/mesher/` — rather than on the `Mesh` class, per the
//! `py/ops/` convention (operations live with operations).

use crate::containers::mesh::ElementType;
use crate::containers::mesh::{Mesh, Node, SubMesh};
use crate::py::coords::PyCoords;
use crate::py::mesh::PyMesh;
use crate::py::node::PyNode;
use crate::py::signals::PySignals;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;

/// Build a points (POI1) mesh holding every live node of `coords`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn from_live_nodes(coords: PyRef<PyCoords>) -> PyResult<PyMesh> {
    let mesh = crate::ops::mesher::from_live_nodes(coords.handle.clone())?;
    Ok(PyMesh { inner: mesh })
}

/// Build a points (POI1) mesh with one point per node in `nodes`.
///
/// The Coords is taken from the nodes themselves (every `Node`
/// carries its own), so no Coords argument is needed. Returns a
/// Mesh with a single POI1 submesh; raises if `nodes` is empty.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn poi1_from_nodes(nodes: Vec<PyRef<PyNode>>) -> PyResult<PyMesh> {
    let ns: Vec<Node> = nodes.iter().map(|n| n.as_node().clone()).collect();
    let sm = SubMesh::poi1_from_nodes(&ns)?;
    Ok(PyMesh {
        inner: Mesh::from_submesh(sm),
    })
}

/// Convert a mesh to POI1, submesh by submesh.
///
/// Returns a new mesh with the same number of submeshes; each output
/// submesh is a POI1 submesh holding the de-duplicated nodes of the
/// corresponding input submesh, in order of first appearance.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn to_poi1(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::to_poi1(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Build a POI1 mesh of per-element centroids (centres of gravity), submesh
/// by submesh.
///
/// Returns a new mesh with the same number of submeshes; each output submesh
/// is a POI1 submesh with one **fresh** node per element of the corresponding
/// input submesh, placed at the element's centroid. A POI1 input is therefore
/// copied to colocated fresh nodes — handy to mint Lagrange-multiplier support
/// nodes from a set of constrained points.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn barycenter(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::barycenter(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Keep the elements of `mesh` resting on the nodes of `points`
/// (Cast3m `ELEM … APPUYE`).
///
/// Only the node set referenced by `points` matters (typically a POI1
/// points mesh). With `strict=True` a cell is kept when **all** its nodes
/// are in the set (`APPUYE STRICTEMENT`); with `strict=False` when **at
/// least one** is (`APPUYE`). The result mirrors `mesh` submesh by submesh
/// (same types, possibly-empty zones). Both meshes must share the same
/// `Coords`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, points, strict=true))]
pub fn elements_on(mesh: PyRef<PyMesh>, points: PyRef<PyMesh>, strict: bool) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::elements_on(&mesh.inner, &points.inner, strict)?;
    Ok(PyMesh { inner: result })
}

// --- Node selection by geometric region (Cast3m `POIN … SPHE / CYLI / …`) ---
//
// One operator per (shape, side). They all return a POI1 mesh mirroring
// `mesh` submesh by submesh — one zone per input zone, possibly empty — and
// all take the same `tol`, the geometric precision of the test as a distance
// to the region's surface; `tol=None` means `1e-6 ×` the bounding-box
// diagonal. The odd one out is the *nearest* node, which returns a single
// node and lives on the class: `mesh.nearest_node(point)`.

/// Nodes **inside** the sphere of centre `center` and radius `radius`.
///
/// Keeps the nodes at a distance `≤ radius + tol` from `center`. In 2-D the
/// sphere is a disc — `center` just has to match the mesh dimension.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, center, radius, tol=None))]
pub fn points_in_sphere(
    mesh: PyRef<PyMesh>,
    center: Vec<f64>,
    radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_in_sphere(&mesh.inner, &center, radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the sphere of centre `center` and radius `radius`
/// (Cast3m `POIN … SPHE`).
///
/// Keeps the nodes whose distance to `center` is within `tol` of `radius`, on
/// either side. In 2-D this selects a circle.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, center, radius, tol=None))]
pub fn points_on_sphere(
    mesh: PyRef<PyMesh>,
    center: Vec<f64>,
    radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_on_sphere(&mesh.inner, &center, radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the plane through `origin` with normal `normal`
/// (Cast3m `POIN … PLAN`).
///
/// Keeps the nodes within `tol` of the plane — the usual way to grab a
/// boundary face of a box mesh. `normal` need not be normalized; in 2-D the
/// plane is a line.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, origin, normal, tol=None))]
pub fn points_on_plane(
    mesh: PyRef<PyMesh>,
    origin: Vec<f64>,
    normal: Vec<f64>,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_on_plane(&mesh.inner, &origin, &normal, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **below** the plane through `origin` with normal `normal` — the
/// half-space the normal points away from, plane included.
///
/// There is no `points_above_plane`: flip the normal and this is the other
/// half-space.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, origin, normal, tol=None))]
pub fn points_below_plane(
    mesh: PyRef<PyMesh>,
    origin: Vec<f64>,
    normal: Vec<f64>,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_below_plane(&mesh.inner, &origin, &normal, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the infinite line through `a` and `b`
/// (Cast3m `POIN … DROIT`).
///
/// Keeps the nodes at a distance `≤ tol` from the line, with no bound along
/// it — use `points_in_cylinder` with a small radius for a selection clipped
/// to the `a → b` segment.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, a, b, tol=None))]
pub fn points_on_line(
    mesh: PyRef<PyMesh>,
    a: Vec<f64>,
    b: Vec<f64>,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_on_line(&mesh.inner, &a, &b, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **inside** the finite cylinder of axis `base → top` and radius
/// `radius`.
///
/// The cylinder is capped: a node is kept when it is within `radius + tol` of
/// the axis **and** its axial coordinate falls between the two end sections.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, base, top, radius, tol=None))]
pub fn points_in_cylinder(
    mesh: PyRef<PyMesh>,
    base: Vec<f64>,
    top: Vec<f64>,
    radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_in_cylinder(&mesh.inner, &base, &top, radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the lateral surface of the finite cylinder of axis
/// `base → top` and radius `radius` (Cast3m `POIN … CYLI`).
///
/// The end discs are **not** part of the selection — they are flat faces, and
/// `points_on_plane` cuts those. This is how you grab the bore of a tube.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, base, top, radius, tol=None))]
pub fn points_on_cylinder(
    mesh: PyRef<PyMesh>,
    base: Vec<f64>,
    top: Vec<f64>,
    radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_on_cylinder(&mesh.inner, &base, &top, radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **inside** the cone of axis `base → top`, radius `base_radius` at
/// `base` and `top_radius` at `top`.
///
/// The shape is a truncated cone: `top_radius=0` (the default) gives a true
/// cone whose apex is `top`, `top_radius=base_radius` a cylinder. Capped like
/// `points_in_cylinder`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, base, top, base_radius, top_radius=0.0, tol=None))]
pub fn points_in_cone(
    mesh: PyRef<PyMesh>,
    base: Vec<f64>,
    top: Vec<f64>,
    base_radius: f64,
    top_radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result =
        crate::ops::mesher::points_in_cone(&mesh.inner, &base, &top, base_radius, top_radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the lateral surface of the cone of axis `base → top`, radius
/// `base_radius` at `base` and `top_radius` at `top` (Cast3m `POIN … CONE`).
///
/// The distance to the slanted surface is the perpendicular one, so the band
/// stays `tol` wide however steep the cone is. As for `points_on_cylinder`,
/// the end discs are not part of the selection.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, base, top, base_radius, top_radius=0.0, tol=None))]
pub fn points_on_cone(
    mesh: PyRef<PyMesh>,
    base: Vec<f64>,
    top: Vec<f64>,
    base_radius: f64,
    top_radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result =
        crate::ops::mesher::points_on_cone(&mesh.inner, &base, &top, base_radius, top_radius, tol)?;
    Ok(PyMesh { inner: result })
}

/// Nodes **inside** the torus of centre `center`, axis `axis`, major radius
/// `major_radius` and minor radius `minor_radius`.
///
/// The section is circular: the torus is the set of points at a distance
/// `≤ minor_radius` from the circle of radius `major_radius` drawn around
/// `center` in the plane normal to `axis`. **3-D only.**
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, center, axis, major_radius, minor_radius, tol=None))]
pub fn points_in_torus(
    mesh: PyRef<PyMesh>,
    center: Vec<f64>,
    axis: Vec<f64>,
    major_radius: f64,
    minor_radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_in_torus(
        &mesh.inner,
        &center,
        &axis,
        major_radius,
        minor_radius,
        tol,
    )?;
    Ok(PyMesh { inner: result })
}

/// Nodes **on** the torus of centre `center`, axis `axis`, major radius
/// `major_radius` and minor radius `minor_radius`.
///
/// Keeps the nodes within `tol` of the tube's surface. The torus being
/// closed, there is no cap to worry about here. **3-D only.**
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, center, axis, major_radius, minor_radius, tol=None))]
pub fn points_on_torus(
    mesh: PyRef<PyMesh>,
    center: Vec<f64>,
    axis: Vec<f64>,
    major_radius: f64,
    minor_radius: f64,
    tol: Option<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::points_on_torus(
        &mesh.inner,
        &center,
        &axis,
        major_radius,
        minor_radius,
        tol,
    )?;
    Ok(PyMesh { inner: result })
}

// `consolidate(mesh)` is exposed by the type-dispatching top-level
// wrapper in `crate::py::ops::consolidate` (shared with NodeField).

/// Weld together nodes closer than `tol`, redirecting the connectivity to one
/// representative per cluster.
///
/// Returns a new mesh mirroring `mesh` (same submeshes, types and colours)
/// with welded-away nodes redirected to their cluster representative — the
/// smallest-id node of the cluster, which keeps its own coordinates (no
/// averaging). Cells that collapse onto a repeated node (a degenerate segment,
/// triangle, …) are dropped. `tol` must be ≥ 0; `tol = 0` welds only exactly
/// coincident nodes. `mesh` itself is left untouched.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn merge_nodes(mesh: PyRef<PyMesh>, tol: f64) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::merge_nodes(&mesh.inner, tol)?;
    Ok(PyMesh { inner: result })
}

/// Extract the boundary of a surface mesh (TRI3/QUA4) as SEG2 loops.
///
/// An element edge used by exactly one cell is a boundary edge; the boundary
/// edges (pooled across all surface submeshes) are chained into closed loops.
/// Returns a Mesh with one SEG2 submesh per loop — a single loop for a
/// simply-connected domain, several when the domain has holes or disjoint
/// pieces. Loops keep the CCW boundary orientation (outer loop CCW, holes
/// CW), so the result can feed straight back into `triangulate_surface`.
///
/// With `angle_deg` given, each loop is further split into open **arêtes** at
/// its corner nodes — where the boundary turns by more than `angle_deg`
/// degrees — one SEG2 submesh per arête (as `skin` splits a volume's skin into
/// flat faces). A loop with no such corner stays a single closed loop.
/// `angle_deg=None` (the default) keeps every boundary as one closed loop.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, angle_deg=None))]
pub fn border(mesh: PyRef<PyMesh>, angle_deg: Option<f64>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::border(&mesh.inner, angle_deg)?;
    Ok(PyMesh { inner: result })
}

/// Extract the boundary surface (skin) of a volume mesh, split by flat face.
///
/// A volume-element facet (TET4 → 4 triangles, HEX8 → 6 quads, PENTA6 → 2
/// triangles + 3 quads) used by exactly one cell lies on the boundary; the
/// boundary facets (pooled across all volume submeshes) are grouped into flat
/// faces by flooding across shared edges as long as neighbouring facets stay
/// coplanar (their normals differ by at most `angle_deg`, default 1°).
/// Returns a Mesh with one TRI3/QUA4 submesh per flat face — e.g. 6 submeshes
/// for a cube, 5 for a prism (2 caps + 3 sides). Facets keep their
/// outward orientation; the original nodes are reused.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, angle_deg=None))]
pub fn skin(mesh: PyRef<PyMesh>, angle_deg: Option<f64>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::skin(&mesh.inner, angle_deg)?;
    Ok(PyMesh { inner: result })
}

/// Harmonise the orientation of a mesh's cells (cast3m `ORIE`).
///
/// Cells sharing a facet are made consistently oriented — all normals of a
/// surface point the same way, all segments of a curve run head-to-tail, all
/// volume cells share one handedness — in any dimension (SEG/TRI/QUA/TET/
/// PENTA/HEX, linear or quadratic). Each connected component is seeded by its
/// lowest-indexed cell, which keeps its orientation; the absolute sense is not
/// chosen (use `invert` to flip a whole mesh, e.g. a hole's boundary). Returns
/// a fresh mesh sharing the input's nodes.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn orient(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::orient(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Reverse the orientation of every cell of a mesh (cast3m `INVE`).
///
/// Flips each cell's winding/traversal/handedness (POI1 cells are unchanged),
/// in any dimension. Combined with `orient`, this selects the inside/outside
/// sense of a closed contour or surface. Returns a fresh mesh sharing the
/// input's nodes.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn invert(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::invert(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Build a line of `n_elems` elements from node `a` to node `b`.
///
/// `element_type` is `"SEG2"` (default) or `"SEG3"`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (a, b, n_elems, element_type="SEG2"))]
pub fn line(
    a: PyRef<PyNode>,
    b: PyRef<PyNode>,
    n_elems: usize,
    element_type: &str,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let mesh = crate::ops::mesher::line(a.as_node(), b.as_node(), n_elems, et)?;
    Ok(PyMesh { inner: mesh })
}

/// Build a closed circle mesh of `n_elems` elements, centred on `center`,
/// lying in the plane defined by the 3-component `normal`, with the given
/// `radius`.
///
/// `element_type` is `"SEG2"` (default) or `"SEG3"`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (center, normal, radius, n_elems, element_type="SEG2"))]
pub fn circle(
    center: PyRef<PyNode>,
    normal: Vec<f64>,
    radius: f64,
    n_elems: usize,
    element_type: &str,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let mesh = crate::ops::mesher::circle(center.as_node(), &normal, radius, n_elems, et)?;
    Ok(PyMesh { inner: mesh })
}

/// Build an open arc of `n_elems` elements from `a` to `b`, following the
/// circle centred on `center` that passes through both (the shorter arc is
/// built).
///
/// `element_type` is `"SEG2"` (default) or `"SEG3"`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (a, center, b, n_elems, element_type="SEG2"))]
pub fn arc(
    a: PyRef<PyNode>,
    center: PyRef<PyNode>,
    b: PyRef<PyNode>,
    n_elems: usize,
    element_type: &str,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let mesh = crate::ops::mesher::arc(a.as_node(), center.as_node(), b.as_node(), n_elems, et)?;
    Ok(PyMesh { inner: mesh })
}

/// Sweep two SEG2 line meshes into a mesh of `element_type`, building
/// `n_layers` layers between `mesh_a` and `mesh_b`.
///
/// `element_type` is `"QUA4"` (default), `"TRI3"`, `"QUA8"`, `"QUA9"` or
/// `"TRI6"` — a `QUA4` mesh is always built first, then converted (diagonal
/// split for the triangles, promoted to quadratic for `QUA8`/`QUA9`/`TRI6`).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh_a, mesh_b, n_layers, element_type="QUA4"))]
pub fn sweep(
    mesh_a: PyRef<PyMesh>,
    mesh_b: PyRef<PyMesh>,
    n_layers: usize,
    element_type: &str,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let mesh = crate::ops::mesher::sweep(&mesh_a.inner, &mesh_b.inner, n_layers, et)?;
    Ok(PyMesh { inner: mesh })
}

/// Build a structured surface bounded by four `SEG2` sides, by transfinite
/// interpolation (the Coons-patch generalization of `sweep` from two lines
/// to four). `side1`/`side3` and `side2`/`side4` are the two pairs of
/// **opposite** sides and must each have the same element count; the four
/// sides must form a closed contour, `side1 → side2 → side3 → side4 →
/// side1`, each sharing its end node with the next side's start node.
///
/// `element_type` is `"QUA4"` (default), `"TRI3"`, `"QUA8"`, `"QUA9"` or
/// `"TRI6"` — same conversion path as `sweep`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (side1, side2, side3, side4, element_type="QUA4"))]
pub fn transfinite(
    side1: PyRef<PyMesh>,
    side2: PyRef<PyMesh>,
    side3: PyRef<PyMesh>,
    side4: PyRef<PyMesh>,
    element_type: &str,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let mesh = crate::ops::mesher::transfinite(
        &side1.inner,
        &side2.inner,
        &side3.inner,
        &side4.inner,
        et,
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Extrude `mesh` by `n_layers` layers along `direction` (the total
/// displacement vector). SEG2 → QUA4, TRI3 → PENTA6, QUA4 → HEX8.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn extrude(mesh: PyRef<PyMesh>, direction: Vec<f64>, n_layers: usize) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::extrude(&mesh.inner, &direction, n_layers)?;
    Ok(PyMesh { inner: result })
}

/// Sweep two matching surface meshes into a solid mesh, building `n_layers`
/// layers between `mesh_a` and `mesh_b`. The 3-D companion of `sweep`:
/// TRI3 faces → PENTA6 prisms, QUA4 faces → HEX8 hexahedra.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn sweep_solid(
    mesh_a: PyRef<PyMesh>,
    mesh_b: PyRef<PyMesh>,
    n_layers: usize,
) -> PyResult<PyMesh> {
    let mesh = crate::ops::mesher::sweep_solid(&mesh_a.inner, &mesh_b.inner, n_layers)?;
    Ok(PyMesh { inner: mesh })
}

/// Build the **quadratic** (Lagrange-2) copy of a linear mesh: each element
/// type is bumped to its quadratic sibling (TRI3→TRI6, HEX8→HEX20, …). Corner
/// nodes are re-used; one mid-edge node is created per edge (at the midpoint)
/// and shared between the cells that use it. The original mesh is untouched.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn to_quadratic(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::to_quadratic(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Convert every submesh of `mesh` to `element_type`, splitting each cell into
/// cells of the target type **without moving or adding any node** on the
/// existing corners. Supported: identity (already the target type — copied
/// verbatim), `"QUA4"` → `"TRI3"` (two triangles per quad, `(0,2)` diagonal),
/// and `"HEX8"` → `"TET4"` (six tetrahedra per hex, a conforming space-filling
/// split). Corner nodes are re-used; face colours are preserved. To promote to
/// a quadratic type (`TRI3`→`TRI6`, …), which creates mid-edge nodes, use
/// `to_quadratic`. The original mesh is untouched.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn convert(mesh: PyRef<PyMesh>, element_type: &str) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    let result = crate::ops::mesher::convert(&mesh.inner, et)?;
    Ok(PyMesh { inner: result })
}

/// Translate `mesh` by `vector`, returning a fresh copy with its own nodes
/// (the original is left untouched). `vector` matches the mesh dimension.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn translate(mesh: PyRef<PyMesh>, vector: Vec<f64>) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::translate(&mesh.inner, &vector)?;
    Ok(PyMesh { inner: result })
}

/// Rotate `mesh` by `angle` (radians) about `center`, returning a fresh copy
/// with its own nodes (the original is left untouched).
///
/// In 2-D, `center` is a point and `axis` is ignored. In 3-D, the rotation is
/// about the line through `center` directed by `axis` (right-handed); `axis`
/// is required.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, angle, center, axis=None))]
pub fn rotate(
    mesh: PyRef<PyMesh>,
    angle: f64,
    center: Vec<f64>,
    axis: Option<Vec<f64>>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesher::rotate(&mesh.inner, angle, &center, axis.as_deref())?;
    Ok(PyMesh { inner: result })
}

/// Mesh the interior of a closed SEG2 `contour` with `element_type` cells
/// using a constrained-Delaunay + Ruppert-refinement mesher.
///
/// `contour` holds **one or more** closed SEG2 loops, each oriented by the
/// caller: a **counter-clockwise** loop is a domain's outer boundary, a
/// **clockwise** loop is a hole (contained in an outer loop). Several
/// disjoint CCW loops mesh several independent domains at once. `size` sets
/// the target element edge length; `None` uses the mean boundary edge length
/// per domain. `element_type` is "TRI3" or "QUA4" (QUA4 is quad-dominant:
/// the result may also carry a few boundary triangles). The contour may be
/// 2-D or a planar loop in 3-D (meshed in its best-fit plane, lifted back).
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (contour, element_type, size=None))]
pub fn triangulate_surface(
    py: Python<'_>,
    contour: PyRef<PyMesh>,
    element_type: &str,
    size: Option<f64>,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    // Poll Python signals while meshing so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesher::triangulate_surface_cancellable(
        &contour.inner,
        et,
        size,
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Pave the inside of a closed contour with quadrangles, in rows walking
/// inward from the boundary.
///
/// The quadrangle-oriented companion of `triangulate_surface`, and the one to
/// reach for when the mesh is going to be computed on: paving lays QUA4 cells
/// down directly, in rows that follow the contour, instead of triangulating
/// and pairing triangles up afterwards.
///
/// `contour` holds **one or more** closed SEG2 loops, oriented by the caller
/// exactly as for `triangulate_surface`: a **counter-clockwise** loop is a
/// domain's outer boundary, a **clockwise** loop is a hole. Several disjoint
/// CCW loops pave several independent domains at once. `size` sets the target
/// element edge length; `None` uses the mean boundary edge length per domain.
/// `element_type` is "QUA4", "QUA8" or "QUA9". The contour may be 2-D or a
/// planar loop in 3-D (paved in its best-fit plane, then lifted back).
///
/// The contour is untouchable: its nodes come back at their own positions and
/// no node is ever added on a boundary edge. A contour the paver cannot work
/// with is therefore reported rather than worked around — `all_quad=True` on a
/// loop with an odd number of segments raises, since a polygon with an odd
/// number of sides has no filling by quadrangles alone and evening the count
/// out would mean adding a boundary node; so does a contour so coarse for the
/// requested size that the front folds onto itself.
///
/// With `all_quad=False` (the default) an odd loop simply costs one triangle,
/// returned in a separate TRI3 submesh, along with the few cells a distorted
/// leftover polygon could not make square.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (contour, element_type, size=None, all_quad=false))]
pub fn pave_surface(
    py: Python<'_>,
    contour: PyRef<PyMesh>,
    element_type: &str,
    size: Option<f64>,
    all_quad: bool,
) -> PyResult<PyMesh> {
    let et = ElementType::from_name(element_type)
        .ok_or_else(|| PyValueError::new_err(format!("unknown element type: {element_type}")))?;
    // Poll Python signals while paving so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesher::pave_surface_cancellable(
        &contour.inner,
        et,
        size,
        all_quad,
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Mesh the inside of a closed envelope with a hexahedral boundary layer over
/// a tetrahedral core — the 3-D companion of `pave_surface`.
///
/// Puts hexahedra where they matter, in the layer against the boundary where
/// gradients are steepest and an element's shape decides the accuracy, and
/// leaves the smooth interior to tetrahedra.
///
/// `layers` boundary layers are grown inward, each `thickness` deep;
/// `thickness=None` takes the envelope's mean edge length, which gives roughly
/// cube-shaped cells. `size` is the target element size for the tetrahedral
/// core. The envelope is a closed surface of QUA4 and/or TRI3 facets whose
/// normals point **out of the material**, exactly as for `triangulate_volume`;
/// its nodes are reused as they are.
///
/// The result carries a QUA4-born HEX8 submesh, a TRI3-born PENTA6 one, a
/// PYRA5 one and a TET4 one, each present only if non-empty. The pyramids are
/// the junction: the layer's inner faces are squares and a tetrahedron has
/// none, so without them the mesh could not be conforming.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (envelope, layers=1, thickness=None, size=None))]
pub fn pave_volume(
    py: Python<'_>,
    envelope: PyRef<PyMesh>,
    layers: usize,
    thickness: Option<f64>,
    size: Option<f64>,
) -> PyResult<PyMesh> {
    // Poll Python signals while meshing so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesher::pave_volume_cancellable(
        &envelope.inner,
        layers,
        thickness,
        size,
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Fill the inside of a closed `TRI3` `envelope` with `TET4` cells — the 3-D
/// companion of `triangulate_surface`.
///
/// The envelope's normals must point **out of the material**; a concave
/// shape is fine, and an internal cavity is simply another closed surface
/// whose normals point into the hole. Its nodes are reused as they are, and
/// nodes are added inside the solid so the cells come out well shaped.
///
/// `size` is the target edge length; `None` takes the mean edge length of
/// the envelope. `allow_surface_nodes` lets the mesher cut the envelope
/// finer where it cannot otherwise fit it or make it usable: the shape is
/// kept — every added node lies on the edge or facet it divides — but the
/// skin of the result no longer matches the surface handed in, and a warning
/// on stderr says how many were added. Without it, such a surface is
/// refused rather than meshed badly.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (envelope, size=None, allow_surface_nodes=false))]
pub fn triangulate_volume(
    py: Python<'_>,
    envelope: PyRef<PyMesh>,
    size: Option<f64>,
    allow_surface_nodes: bool,
) -> PyResult<PyMesh> {
    // Poll Python signals while meshing so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesher::triangulate_volume_cancellable(
        &envelope.inner,
        size,
        allow_surface_nodes,
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Turn an ordered list of `(group name, Mesh)` pairs into a `dict` that
/// keeps the file order (Python dicts are insertion-ordered).
fn groups_to_dict<'py>(
    py: Python<'py>,
    groups: Vec<(String, Mesh)>,
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    for (name, mesh) in groups {
        dict.set_item(name, Py::new(py, PyMesh { inner: mesh })?)?;
    }
    Ok(dict)
}

/// Read a gmsh `.msh` file (ASCII or binary, MSH 2.2 or 4.1) into a `dict`
/// mapping each physical group name to a `Mesh`, adding the nodes to `coords`.
///
/// The nodes land in the `coords` you pass, so you keep the handle needed to
/// pose boundary conditions on a named region. Its dimension decides how
/// many of gmsh's three coordinates are kept (a 2-D `Coords` flattens onto
/// `xy`). All returned meshes share that single `Coords`, so a node on the
/// boundary between two named groups is the same node on both sides. Inside
/// a group's mesh there is one submesh per element type; elements with no
/// physical group land under the key `"<ungrouped>"`. The dict preserves the
/// file order.
///
/// Supported element types: POI1, SEG2, TRI3, QUA4, TET4, HEX8; any other
/// gmsh type raises.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn read_gmsh<'py>(
    py: Python<'py>,
    coords: PyRef<PyCoords>,
    path: &str,
) -> PyResult<Bound<'py, PyDict>> {
    let groups = crate::ops::mesher::read_gmsh(coords.handle.clone(), std::path::Path::new(path))?;
    groups_to_dict(py, groups)
}

/// Like `read_gmsh`, but parsing the `.msh` text already held in a string
/// instead of reading from a path. Same `dict[str, Mesh]` result.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn read_gmsh_str<'py>(
    py: Python<'py>,
    coords: PyRef<PyCoords>,
    text: &str,
) -> PyResult<Bound<'py, PyDict>> {
    let groups = crate::ops::mesher::read_gmsh_str(coords.handle.clone(), text)?;
    groups_to_dict(py, groups)
}