pyrucast 0.9.1

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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
//! Python wrappers for the mesher operations in [`crate::ops::mesh`].
//!
//! 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::atoms::ElementType;
use crate::containers::mesh::Mesh;
use crate::ops::mesh::{FrontRelax, GmshBlock};
use crate::py::coords::PyCoords;
use crate::py::element_field::{PyElementField, PySubElementField};
use crate::py::mesh::PyMesh;
use crate::py::node::PyNode;
use crate::py::node_field::{PyNodeField, PySubNodeField};
use crate::py::signals::PySignals;
use pyo3::exceptions::PyTypeError;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
use pyrucast_macros::py_op;

/// 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::mesh::from_live_nodes(coords.handle.clone())?;
    Ok(PyMesh { inner: mesh })
}

/// Build a points (POI1) mesh with one point per node in `nodes`.
///
/// The `Coords` comes from the nodes themselves — every `Node` carries its
/// own — so no `Coords` argument is needed. Errors 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<crate::atoms::Node> = nodes.iter().map(|n| n.as_node().clone()).collect();
    let mesh = crate::ops::mesh::poi1_from_nodes(&ns)?;
    Ok(PyMesh { inner: mesh })
}

/// 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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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`.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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`.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.**
#[py_op(method_on = PyMesh)]
#[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::mesh::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.**
#[py_op(method_on = PyMesh)]
#[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::mesh::points_on_torus(
        &mesh.inner,
        &center,
        &axis,
        major_radius,
        minor_radius,
        tol,
    )?;
    Ok(PyMesh { inner: result })
}

/// Fuse submeshes of the same element type into one, dropping duplicate cells
/// (identical node sequences).
///
/// Types appear in their first-seen order; the face colour of the first
/// submesh of each type is kept. `mesh` itself is left untouched.
///
/// Errors if `mesh` has no submesh (no `Coords` to attach to).
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(name = "consolidate_mesh")]
pub fn consolidate(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    Ok(PyMesh {
        inner: crate::ops::mesh::consolidate(&mesh.inner)?,
    })
}

/// 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.
///
/// A cluster is a connected component of the « closer than `tol` » relation:
/// the weld propagates from node to node, so on a chain a—b—c where a and c
/// are further apart than `tol`, all three still end up as one — which is why
/// a `tol` of the order of the element size collapses a whole region rather
/// than a seam.
///
/// With `in_place=True` the connectivity of `mesh`'s **own** submeshes is
/// rewritten instead — the assumed side effect — and the very same mesh object
/// is returned. Since the union `mesh_a | mesh_b` shares its submeshes rather
/// than copying them, welding that union in place welds `mesh_a` and `mesh_b`
/// themselves: afterwards they really do share their interface nodes. The mesh
/// structure is preserved (same submeshes, same cells in the same order), so a
/// cell that *would* collapse is an error here instead of being dropped, as is
/// a submesh already sealed by a finite-element space, field or matrix. Both
/// are checked before anything is written: a rejected call changes nothing.
///
/// Every call prints a one-line tally on stdout once the weld is done — nodes
/// welded, cells dropped, tolerance used.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, tol, in_place=false))]
pub fn merge_nodes(
    py: Python<'_>,
    mesh: Py<PyMesh>,
    tol: f64,
    in_place: bool,
) -> PyResult<Py<PyMesh>> {
    let result = crate::ops::mesh::merge_nodes(&mesh.borrow(py).inner, tol, in_place)?;
    if in_place {
        // The operator welded `mesh`'s own submeshes and handed the same mesh
        // back; return the caller's object itself, so `out is mesh` holds.
        return Ok(mesh);
    }
    Py::new(py, 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.
#[py_op(method_on = PyMesh)]
#[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::mesh::border(&mesh.inner, angle_deg)?;
    Ok(PyMesh { inner: result })
}

/// Extract the boundary surface (skin) of a volume mesh, split by flat face.
///
/// Works on every volume type — TET4, PYRA5, PENTA6, HEX8 and their quadratic
/// counterparts TET10, PENTA15, HEX20, HEX27.
///
/// A volume-element facet (TET4 → 4 triangles, HEX8 → 6 quads, PENTA6 → 2
/// triangles + 3 quads, PYRA5 → 1 quad + 4 triangles) used by exactly one cell
/// lies on the boundary; sharing is decided on the facet's corners, so cells of
/// different degrees still cancel. 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°).
///
/// **A facet is emitted in its own type**: a HEX8 yields QUA4, a TET10 yields
/// TRI6, a HEX27 yields QUA9 — so the skin of a quadratic mesh is quadratic
/// and keeps its mid-side nodes. Returns a Mesh with one submesh per flat face
/// and per facet type — e.g. 6 submeshes for a cube, 5 for a prism (2 caps +
/// 3 sides), 5 for a pyramid (base + 4 triangles). Facets keep their outward
/// orientation; the original nodes are reused.
#[py_op(method_on = PyMesh)]
#[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> {
    // Python's optional kwarg is flattened **here**, at the boundary: past
    // this point the operator receives an angle, not an absence to test for.
    let angle_deg = angle_deg.unwrap_or(crate::ops::mesh::skin::DEFAULT_ANGLE_DEG);
    let result = crate::ops::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::orient(&mesh.inner)?;
    Ok(PyMesh { inner: result })
}

/// Re-order the cells of a line mesh into a continuous chain.
///
/// The complement of `orient`: where `orient` fixes the *direction* of the
/// cells, `chain` fixes their *order* — each SEG2/SEG3 submesh is sorted so
/// that consecutive cells share a node (and flipped where needed), so reading
/// the connectivity walks the curve from one end to the other. Each submesh is
/// chained on its own and must be one continuous chain, open or closed: a node
/// carrying three segments (branching) or disjoint pieces raise an error.
/// Returns a fresh mesh sharing the input's nodes.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn chain(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::chain(&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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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=None))]
pub fn line(
    a: PyRef<PyNode>,
    b: PyRef<PyNode>,
    n_elems: usize,
    element_type: Option<ElementType>,
) -> PyResult<PyMesh> {
    let element_type = element_type.unwrap_or(ElementType::SEG2);
    let mesh = crate::ops::mesh::line(a.as_node(), b.as_node(), n_elems, element_type)?;
    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=None))]
pub fn circle(
    center: PyRef<PyNode>,
    normal: Vec<f64>,
    radius: f64,
    n_elems: usize,
    element_type: Option<ElementType>,
) -> PyResult<PyMesh> {
    let element_type = element_type.unwrap_or(ElementType::SEG2);
    let mesh = crate::ops::mesh::circle(center.as_node(), &normal, radius, n_elems, element_type)?;
    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=None))]
pub fn arc(
    a: PyRef<PyNode>,
    center: PyRef<PyNode>,
    b: PyRef<PyNode>,
    n_elems: usize,
    element_type: Option<ElementType>,
) -> PyResult<PyMesh> {
    let element_type = element_type.unwrap_or(ElementType::SEG2);
    let mesh = crate::ops::mesh::arc(
        a.as_node(),
        center.as_node(),
        b.as_node(),
        n_elems,
        element_type,
    )?;
    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`).
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh_a, mesh_b, n_layers, element_type=None))]
pub fn sweep(
    mesh_a: PyRef<PyMesh>,
    mesh_b: PyRef<PyMesh>,
    n_layers: usize,
    element_type: Option<ElementType>,
) -> PyResult<PyMesh> {
    let element_type = element_type.unwrap_or(ElementType::QUA4);
    let mesh = crate::ops::mesh::sweep(&mesh_a.inner, &mesh_b.inner, n_layers, element_type)?;
    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`.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (side1, side2, side3, side4, element_type=None))]
pub fn transfinite(
    side1: PyRef<PyMesh>,
    side2: PyRef<PyMesh>,
    side3: PyRef<PyMesh>,
    side4: PyRef<PyMesh>,
    element_type: Option<ElementType>,
) -> PyResult<PyMesh> {
    let element_type = element_type.unwrap_or(ElementType::QUA4);
    let mesh = crate::ops::mesh::transfinite(
        &side1.inner,
        &side2.inner,
        &side3.inner,
        &side4.inner,
        element_type,
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Extrude `mesh` by `n_layers` layers along `direction` (the total
/// displacement vector). SEG2 → QUA4, TRI3 → PENTA6, QUA4 → HEX8.
#[py_op(method_on = PyMesh)]
#[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::mesh::extrude(&mesh.inner, &direction, n_layers)?;
    Ok(PyMesh { inner: result })
}

/// Revolve `mesh` by `n_layers` layers over a total `angle` (radians) — the
/// rotational companion of `extrude`. SEG2 → QUA4, TRI3 → PENTA6,
/// QUA4 → HEX8.
///
/// In 2-D the revolution is about the point `center` (counterclockwise for a
/// positive `angle`) and `axis` is ignored; in 3-D it is about the line
/// through `center` directed by `axis` (right-handed), which is then
/// required. `|angle|` may not exceed a full turn, and a full turn closes the
/// ring: the last node layer is the first one again, so there is no seam. No
/// node may lie on the axis — it would collapse the cells touching it.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, angle, n_layers, center, axis=None))]
pub fn revolve(
    mesh: PyRef<PyMesh>,
    angle: f64,
    n_layers: usize,
    center: Vec<f64>,
    axis: Option<Vec<f64>>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::revolve(&mesh.inner, angle, n_layers, &center, axis.as_deref())?;
    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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn convert(mesh: PyRef<PyMesh>, element_type: ElementType) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::convert(&mesh.inner, element_type)?;
    Ok(PyMesh { inner: result })
}

/// Copy `mesh`, either onto **fresh nodes** placed at the same spots
/// (`new_nodes=True`, the default) or onto the very same nodes
/// (`new_nodes=False`, only the connectivity is copied).
///
/// Both modes keep the submesh order, element types, cell order and face
/// colours, and hand back a mesh that is **never sealed** — editable even
/// when the source has been frozen by a finite-element space, a field or a
/// matrix. The original is left untouched.
///
/// With `new_nodes=True` each distinct node of `mesh` yields one fresh node at
/// the same position (nodes shared between cells stay shared), so the two
/// meshes no longer move together. With `new_nodes=False` they share their
/// nodes: moving one moves it in both.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, new_nodes=true))]
pub fn copy(mesh: PyRef<PyMesh>, new_nodes: bool) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::copy(&mesh.inner, new_nodes)?;
    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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::rotate(&mesh.inner, angle, &center, axis.as_deref())?;
    Ok(PyMesh { inner: result })
}

/// Mirror `mesh` through the point `center` (Cast3m `SYME … POINT`),
/// returning a fresh copy with its own nodes (the original is left
/// untouched). Every node goes to `2·center − x`.
///
/// In 3-D the map reverses orientation, so the cells are re-ordered (as
/// `invert` does) to keep the copy's Jacobians positive; in 2-D it is a plain
/// half-turn and nothing is re-ordered.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn symmetry_point(mesh: PyRef<PyMesh>, center: Vec<f64>) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::symmetry_point(&mesh.inner, &center)?;
    Ok(PyMesh { inner: result })
}

/// Mirror `mesh` through the infinite line running through `a` and `b`
/// (Cast3m `SYME … DROIT`), returning a fresh copy with its own nodes (the
/// original is left untouched).
///
/// In 2-D this is the mirror image about the line; in 3-D it is the half-turn
/// about it (for the mirror image through a plane, use `symmetry_plane`).
/// Orientation-reversing in 2-D only, where the cells are re-ordered (as
/// `invert` does) to keep the copy's Jacobians positive.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn symmetry_line(mesh: PyRef<PyMesh>, a: Vec<f64>, b: Vec<f64>) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::symmetry_line(&mesh.inner, &a, &b)?;
    Ok(PyMesh { inner: result })
}

/// Mirror `mesh` through the plane running through the three points `a`, `b`
/// and `c` (Cast3m `SYME … PLAN`), returning a fresh copy with its own nodes
/// (the original is left untouched). Only the plane the three points span
/// matters, not their order; they must not be aligned.
///
/// 3-D only — in 2-D the mirror about a line is `symmetry_line`. Always
/// orientation-reversing, so the cells are re-ordered (as `invert` does) to
/// keep the copy's Jacobians positive.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn symmetry_plane(
    mesh: PyRef<PyMesh>,
    a: Vec<f64>,
    b: Vec<f64>,
    c: Vec<f64>,
) -> PyResult<PyMesh> {
    let result = crate::ops::mesh::symmetry_plane(&mesh.inner, &a, &b, &c)?;
    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).
#[py_op(method_on = PyMesh)]
#[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: ElementType,
    size: Option<f64>,
) -> PyResult<PyMesh> {
    // Poll Python signals while meshing so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesh::triangulate_surface_cancellable(
        &contour.inner,
        element_type,
        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.
///
/// `relax` chooses what the front is allowed to do to itself between two rows.
/// After each row the fresh chain is smoothed, which keeps the front from
/// kinking — and, being a Laplacian, rounds its corners off. That costs more
/// than it looks: a front sheds nodes only at its **corners**, so once they are
/// rounded away it keeps every node it has while its perimeter shrinks, and the
/// middle of the domain comes out finer than asked. A plain 20 × 20 square at
/// size 1 gives 600 cells instead of 400.
///
/// - `"free"` (the default) — the historical behaviour: a node moves wherever
///   the smoothing points. The only mode that never lets the front kink.
/// - `"along"` — the same step, kept only **along** the front: the spacing is
///   evened out, the shape is not. The square then comes out as the 400 exact
///   squares anyone would draw.
/// - `"none"` — the front stays exactly where the row put it.
///
/// There is no best answer, which is why it is a choice: `"along"` and
/// `"none"` win on anything with corners to keep and can kink on a curve, where
/// there is nothing to preserve and everything to straighten. A run that fails
/// to converge raises rather than grinding on.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (contour, element_type, size=None, all_quad=false, relax=None))]
pub fn pave_surface(
    py: Python<'_>,
    contour: PyRef<PyMesh>,
    element_type: ElementType,
    size: Option<f64>,
    all_quad: bool,
    relax: Option<FrontRelax>,
) -> PyResult<PyMesh> {
    // Poll Python signals while paving so a long run stays Ctrl+C-able.
    let mesh = crate::ops::mesh::pave_surface_cancellable(
        &contour.inner,
        element_type,
        size,
        all_quad,
        relax.unwrap_or_default(),
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Move the interior nodes of a surface mesh to improve its cells, leaving the
/// connectivity and the boundary exactly as they are.
///
/// `sweeps` is how many passes to run. `angular=True` (the default) uses
/// angle-based smoothing, which aims at the right angles a quadrangle wants;
/// `False` uses the plain Laplacian, which aims at the one-ring's barycentre
/// and knows nothing about angles. `in_place=True` writes the new positions
/// onto your own nodes and hands the same mesh back; otherwise the moved nodes
/// are duplicated and a fresh mesh comes out, the boundary's nodes being
/// shared since they never moved.
///
/// Two guarantees hold whatever the rule: **no node on the boundary ever
/// moves**, and a position is taken only when every incident cell stays valid
/// and the worst incident quality does not get worse.
///
/// Smoothing cannot change who is next to whom, so it cannot fix a node with
/// the wrong number of cells around it — the angles around a node sum to 2π
/// whatever the positions. That is `cleanup`'s job, and running it first is
/// usually what unlocks the smoothing.
///
/// TRI3 and QUA4 only, in 2-D. POI1 and SEG2 submeshes are ignored.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (mesh, sweeps=20, angular=true, in_place=false))]
pub fn regularize(
    mesh: PyRef<PyMesh>,
    sweeps: usize,
    angular: bool,
    in_place: bool,
) -> PyResult<PyMesh> {
    let out = crate::ops::mesh::regularize(&mesh.inner, sweeps, angular, in_place)?;
    Ok(PyMesh { inner: out })
}

/// Fix the connectivity of a surface mesh: remove its doublets, give up the
/// nodes that have only three cells around them, and switch the diagonals that
/// lower the valence error.
///
/// **No node of the contour ever moves**, and none is ever given up: the mesh
/// keeps exactly the boundary it came with.
///
/// A **doublet** is an interior node with only two quadrangles around it,
/// which therefore share two edges; the node sits in a wedge no smoothing can
/// open. A node of the **wrong valence** wants four cells and has three or
/// five, giving corners of 120° or 72° on average — and the angles around a
/// node sum to 2π whatever the positions, so smoothing will never square them.
///
/// Two moves answer that:
///
/// - the **diagonal switch**, for a node of valence five or more: two
///   quadrangles sharing an edge form a hexagon, which splits across any of
///   its three diagonals. It changes no node and no boundary, and is applied
///   only when it strictly lowers the valence error and leaves both cells
///   convex.
/// - the **collapse**, for an interior node with only three cells: round a
///   node carrying `q` quadrangles and `t` triangles the star is bounded by a
///   polygon of `n = 2q + t` sides, and an `n`-gon decomposes with no interior
///   node into `q'` quadrangles and `t'` triangles such that `2q' + t' = n - 2`
///   — always a cell fewer than the star. So the node is given up along with
///   that cell: 3 quadrangles become 2, and 1 quadrangle with 2 triangles
///   becomes a single quadrangle. It is the only move that removes a node,
///   changes how many cells there are, or moves anything: removing a node
///   leaves the ring round it stretched, so the move is judged after relaxing
///   that ring, and the relaxation is kept along with it. A move that does not
///   improve the neighbourhood's worst cell is undone whole.
///
/// - the **pair collapse**, for two interior nodes sharing an edge with at
///   least one short of a cell: neither can be given up alone without trading
///   one irregular node for two, but together they carry `val(a) + val(b) - 2`
///   cells — a hexagon's worth at 3-3, a heptagon's at 3-4 — and both re-cut
///   with two cells fewer. Two nodes and two cells go at once, and a triangle
///   in the star is carried across rather than created.
///
/// Triangles are read for incidence and reshaped, and they only ever leave two
/// at a time — their number has the parity of the boundary's edge count, which
/// nothing here may change. Turning a lone triangle into a quadrangle is
/// `merge_triangles`'s job.
///
/// Your own nodes come back untouched apart from those on a ring a collapse
/// relaxed, which are duplicated — the mesh you hand in is never modified. The
/// result comes back wound the way it went in, clockwise or not.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn cleanup(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let out = crate::ops::mesh::cleanup(&mesh.inner)?;
    Ok(PyMesh { inner: out })
}

/// Remove the triangles from a quadrangle-dominant mesh, in pairs.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn merge_triangles(mesh: PyRef<PyMesh>) -> PyResult<PyMesh> {
    let out = crate::ops::mesh::merge_triangles(&mesh.inner)?;
    Ok(PyMesh { inner: out })
}

/// Mesh the inside of a closed contour with a structured grid core and a
/// frontal band — the regular-mesh companion of `pave_surface`.
///
/// Same input, same output, same promise that the contour is untouchable: only
/// the interior is obtained differently. `pave_surface` walks a front inward
/// until two of its rows meet, and that meeting line carries the valence
/// defects, the leftover triangles and the flattest cells — even on a plain
/// rectangle, which comes out as an onion with four diagonal seams.
/// `grid_surface` lays a tensor grid instead, and leaves the front only what
/// the grid could not reach.
///
/// The grid's lines are taken from the contour: every axis-aligned edge long
/// enough to be a feature pins a line, and the gaps are subdivided at about
/// `size`. A grid node landing on a contour node **is** that node, so the core
/// reaches the boundary rather than stopping short of it. On a rectilinear
/// domain laid out for the grid there is no band at all and the mesh is the
/// grid: every cell a rectangle, every Jacobian 1, no triangle.
///
/// That last part is the one thing asked of the caller. A grid can only meet a
/// contour whose nodes fall on grid lines, so **break every side at the
/// shape's own corners and let each piece take a whole number of cells**. A
/// contour that does not is not an error — it just gets more band and less
/// grid, down to the quality of `pave_surface` in the worst case.
///
/// `band` is extra clearance in cells between the core and the contour. Zero
/// is the useful value; raise it only for a contour the grid cannot meet, such
/// as a curve, where giving the front a couple of cells to work in beats
/// letting it fight for a sliver.
///
/// `relax` chooses what the front may do to itself between two rows: `"free"`
/// (the default, and the historical behaviour), `"along"` — the smoothing kept
/// only along the front, which keeps its corners and with them the front's
/// ability to shed nodes as it contracts — or `"none"`. See `pave_surface`,
/// which shares the band with this operator and where the choice is spelled
/// out.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (contour, element_type, size=None, band=0, all_quad=false, relax=None))]
pub fn grid_surface(
    py: Python<'_>,
    contour: PyRef<PyMesh>,
    element_type: ElementType,
    size: Option<f64>,
    band: usize,
    all_quad: bool,
    relax: Option<FrontRelax>,
) -> PyResult<PyMesh> {
    let mesh = crate::ops::mesh::grid_surface_cancellable(
        &contour.inner,
        element_type,
        size,
        band,
        all_quad,
        relax.unwrap_or_default(),
        &PySignals(py),
    )?;
    Ok(PyMesh { inner: mesh })
}

/// Mesh the inside of a closed contour with a structured grid core and a
/// frontal band, taking the grid's lines **one per contour node**.
///
/// The second of the two grid meshers, and the sibling of `grid_surface`, which
/// it does not replace: same input, same output, same untouchable contour, and
/// neither wins everywhere.
///
/// `grid_surface` pins a line on the coordinate each aligned side lies on, and
/// subdivides between two lines by whichever side spans them end to end. Every
/// line is straight. `grid_surface2` gives every node of the contour the line
/// that crosses it, collapses the bands too thin to be cells — welding each of
/// their edges onto the contour node at one end, or onto its midpoint — and
/// lets a grid node within a quarter cell of a contour node move onto it.
///
/// A row is therefore a polyline rather than a line, and that is the point: one
/// row can meet two facing walls at two different heights, so a wall cut into
/// ten can face a wall cut into eleven. `grid_surface` has to pick one of them
/// and sends the other to the band.
///
/// **Reach for `grid_surface2` on a rectilinear shape**, all the more so when
/// its sides were not cut at the corners facing them; **reach for
/// `grid_surface` on anything curved**, where the contour's nodes only tell you
/// where its vertices happened to fall. Measured worst cell, `grid_surface`
/// then `grid_surface2`: plate with a step off the grid 0.405 / 0.963, L with
/// arbitrary dimensions 0.437 / 0.979, crenellated profile with its base in one
/// run 0.323 / 0.651, house with a pitched roof 0.420 / 0.548. On a **circle**
/// the order reverses hard — 0.288 against 0.005 — and `grid_surface2` should
/// not be used: nothing dictates a grid line over most of a curve. The book's
/// *Mailler une géométrie* page puts all four surface meshers side by side.
///
/// `size`, `band` and `relax` mean what they mean for `grid_surface`.
#[py_op(method_on = PyMesh)]
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (contour, element_type, size=None, band=0, all_quad=false, relax=None))]
pub fn grid_surface2(
    py: Python<'_>,
    contour: PyRef<PyMesh>,
    element_type: ElementType,
    size: Option<f64>,
    band: usize,
    all_quad: bool,
    relax: Option<FrontRelax>,
) -> PyResult<PyMesh> {
    let mesh = crate::ops::mesh::grid_surface2_cancellable(
        &contour.inner,
        element_type,
        size,
        band,
        all_quad,
        relax.unwrap_or_default(),
        &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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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.
#[py_op(method_on = PyMesh)]
#[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::mesh::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)
}

/// Build meshes from a gmsh mesh **already in memory** — the node table and
/// the element blocks — instead of from a file.
///
/// This is the low-level operator behind `pyrucast.mesh.from_gmsh`, which is
/// what you normally want: it asks the live gmsh model for these arrays
/// itself. Call this one when you hold the arrays already, or when you want
/// to choose exactly what to import.
///
/// - `node_tags` — gmsh's node tags, as `gmsh.model.mesh.getNodes()` returns
///   them (first of the triple);
/// - `node_coords` — three coordinates per tag, in the same order (second of
///   the triple);
/// - `blocks` — a sequence of `(element_type, node_tags, groups)`, one per
///   homogeneous block: the gmsh type code (`2` for a triangle, `4` for a
///   tetrahedron, …), that block's flat connectivity, and the physical-group
///   names its cells belong to.
///
/// numpy arrays are read **without being copied**, through the buffer
/// protocol; plain Python lists work too, at the cost of a conversion.
///
/// Same rules and same result as `read_gmsh`: a `dict` from group name to
/// `Mesh`, all sharing the `coords` you pass, whose dimension decides how many
/// of gmsh's three coordinates are kept. Raises if a block is not a whole
/// number of cells, if a cell names a tag absent from `node_tags`, or if a
/// gmsh element type has no pyrucast counterpart.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
pub fn from_gmsh_arrays<'py>(
    py: Python<'py>,
    coords: PyRef<PyCoords>,
    node_tags: &Bound<'py, PyAny>,
    node_coords: &Bound<'py, PyAny>,
    blocks: &Bound<'py, PyAny>,
) -> PyResult<Bound<'py, PyDict>> {
    // Unpack every block first, so the Python objects holding the buffers stay
    // alive for as long as the slices that borrow from them.
    let mut codes: Vec<u32> = Vec::new();
    let mut tag_objects: Vec<Bound<'py, PyAny>> = Vec::new();
    let mut names: Vec<Vec<String>> = Vec::new();
    for (i, item) in blocks.try_iter()?.enumerate() {
        let item = item?;
        let unpack = |k: usize| {
            item.get_item(k).map_err(|_| {
                PyValueError::new_err(format!(
                    "block {i}: expected a (element_type, node_tags, groups) triple"
                ))
            })
        };
        codes.push(unpack(0)?.extract()?);
        tag_objects.push(unpack(1)?);
        names.push(unpack(2)?.extract()?);
    }

    let tags = crate::py::arrays::borrow::<u64>(node_tags)?;
    let xyz = crate::py::arrays::borrow::<f64>(node_coords)?;
    let block_tags = tag_objects
        .iter()
        .map(crate::py::arrays::borrow::<u64>)
        .collect::<PyResult<Vec<_>>>()?;

    let blocks: Vec<GmshBlock<'_>> = codes
        .iter()
        .zip(&block_tags)
        .zip(&names)
        .map(|((&element_type, tags), groups)| GmshBlock {
            element_type,
            node_tags: tags.as_slice(),
            groups,
        })
        .collect();

    let groups = crate::ops::mesh::from_gmsh_arrays(
        coords.handle.clone(),
        tags.as_slice(),
        xyz.as_slice(),
        &blocks,
    )?;
    groups_to_dict(py, groups)
}

/// 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.
///
/// Every element type pyrucast knows is read: POI1, SEG2, TRI3, QUA4, TET4,
/// PYRA5, PENTA6, HEX8 and the quadratic SEG3, TRI6, QUA8, QUA9, TET10,
/// PENTA15, HEX20, HEX27. Any other gmsh type raises, naming the codes it
/// does accept.
#[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::mesh::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::mesh::read_gmsh_str(coords.handle.clone(), text)?;
    groups_to_dict(py, groups)
}

/// Select the part of a field's support passing a value band, zone by zone —
/// a value-range filter returning a `Mesh`.
///
/// `field` may be a `NodeField` / `SubNodeField` (→ POI1 submeshes of the
/// passing **nodes**) or an `ElementField` / `SubElementField` (→ submeshes
/// of the passing **cells**, each of its zone's element type; a cell passes
/// only when *all* its Gauss points do). The result has one submesh per
/// processed zone.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a point/cell is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component of each zone. A `components`
/// list tests **only** those components, and only on the zones carrying
/// **all** of them — a zone missing any listed component is skipped (no
/// submesh). Errors if no bound is given, or the lower one exceeds the upper.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
#[allow(clippy::too_many_arguments)]
pub fn select(
    field: &Bound<'_, PyAny>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    if let Ok(f) = field.extract::<PyRef<PyNodeField>>() {
        select_nodes(f, ge, gt, le, lt, components)
    } else if let Ok(f) = field.extract::<PyRef<PyElementField>>() {
        select_cells(f, ge, gt, le, lt, components)
    } else if let Ok(f) = field.extract::<PyRef<PySubNodeField>>() {
        select_sub_nodes(f, ge, gt, le, lt, components)
    } else if let Ok(f) = field.extract::<PyRef<PySubElementField>>() {
        select_sub_cells(f, ge, gt, le, lt, components)
    } else {
        Err(PyTypeError::new_err(
            "expected a NodeField, SubNodeField, ElementField or SubElementField",
        ))
    }
}

// The four flavours of `select`, each documented for its sole receiver. Not
// registered in the module — the free function above remains the polymorphic
// entry point — they give `#[py_op]` the method of each flavour.
// `#[pyfunction]` serves only to make valid the pyo3 signature that `#[py_op]`
// copies.

/// Select the **nodes** of this field passing a value band, zone by zone —
/// a value-range filter returning a `Mesh` with one POI1 submesh per
/// processed zone.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a node is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component of each zone. A `components`
/// list tests **only** those components, and only on the zones carrying
/// **all** of them — a zone missing any listed component is skipped (no
/// submesh). Errors if no bound is given, or the lower one exceeds the upper.
#[py_op(method_on = PyNodeField, name = "select")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn select_nodes(
    field: PyRef<PyNodeField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    Ok(PyMesh {
        inner: crate::ops::mesh::select_nodes(&field.inner, &band, components)?,
    })
}

/// Select the **cells** of this field passing a value band, zone by zone —
/// a value-range filter returning a `Mesh` with one submesh per processed
/// zone, each of its zone's element type. A cell passes only when *all* its
/// Gauss points do.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a cell is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component of each zone. A `components`
/// list tests **only** those components, and only on the zones carrying
/// **all** of them — a zone missing any listed component is skipped (no
/// submesh). Errors if no bound is given, or the lower one exceeds the upper.
#[py_op(method_on = PyElementField, name = "select")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn select_cells(
    field: PyRef<PyElementField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    Ok(PyMesh {
        inner: crate::ops::mesh::select_cells(&field.inner, &band, components)?,
    })
}

/// Select the **nodes** of this sub-field passing a value band — a
/// value-range filter returning a `Mesh` with a single POI1 submesh.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a node is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component. A `components` list tests
/// **only** those components; if the sub-field lacks any of them, nothing is
/// tested and the result is an **empty** `Mesh`. Errors if no bound is given,
/// or the lower one exceeds the upper.
#[py_op(method_on = PySubNodeField, name = "select")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn select_sub_nodes(
    field: PyRef<PySubNodeField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    Ok(PyMesh {
        inner: crate::ops::mesh::select_sub_nodes(&field.handle.read(), &band, components)?,
    })
}

/// Select the **cells** of this sub-field passing a value band — a
/// value-range filter returning a `Mesh` with a single submesh of the
/// sub-field's element type. A cell passes only when *all* its Gauss points
/// do.
///
/// The band is set by the four comparison bounds — `ge` (`≥`), `gt` (`>`),
/// `le` (`≤`), `lt` (`<`); give at most one lower (`ge`/`gt`) and one upper
/// (`le`/`lt`), at least one overall. With several components in play they
/// are combined with **AND**: a cell is kept only when *every* tested
/// component is in band.
///
/// `components=None` tests every component. A `components` list tests
/// **only** those components; if the sub-field lacks any of them, nothing is
/// tested and the result is an **empty** `Mesh`. Errors if no bound is given,
/// or the lower one exceeds the upper.
#[py_op(method_on = PySubElementField, name = "select")]
#[pyfunction]
#[pyo3(signature = (field, ge=None, gt=None, le=None, lt=None, components=None))]
pub fn select_sub_cells(
    field: PyRef<PySubElementField>,
    ge: Option<f64>,
    gt: Option<f64>,
    le: Option<f64>,
    lt: Option<f64>,
    components: Option<Vec<String>>,
) -> PyResult<PyMesh> {
    let band = crate::atoms::Band::new(ge, gt, le, lt)?;
    Ok(PyMesh {
        inner: crate::ops::mesh::select_sub_cells(&field.handle.read(), &band, components)?,
    })
}

// ─── Méthodes de délégation ────────────────────────────────────────────────
//
// The "subject" face of the operators above (`CONVENTIONS.md`, § "Le verbe
// exposé aussi en méthode"). They now come from `#[py_op]`, placed on the free
// function: the method is derived from its signature, and its documentation
// **copied** rather than pointed at — which is what makes it appear in full
// in `help()` as in the stub the IDEs read.
//
// This block therefore keeps only what breaks the mould. `merge_nodes` does:
// its receiver is a `Py<Self>` and its return a `Py<PyMesh>` — the object
// itself, not a borrowed view. `#[py_op]` emits only a `PyRef` receiver, and
// bending it for a single case would cost more than this very method.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyMesh {
    /// 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.
    ///
    /// A cluster is a connected component of the « closer than `tol` » relation:
    /// the weld propagates from node to node, so on a chain a—b—c where a and c
    /// are further apart than `tol`, all three still end up as one — which is why
    /// a `tol` of the order of the element size collapses a whole region rather
    /// than a seam.
    ///
    /// With `in_place=True` the connectivity of `mesh`'s **own** submeshes is
    /// rewritten instead — the assumed side effect — and the very same mesh object
    /// is returned. Since the union `mesh_a | mesh_b` shares its submeshes rather
    /// than copying them, welding that union in place welds `mesh_a` and `mesh_b`
    /// themselves: afterwards they really do share their interface nodes. The mesh
    /// structure is preserved (same submeshes, same cells in the same order), so a
    /// cell that *would* collapse is an error here instead of being dropped, as is
    /// a submesh already sealed by a finite-element space, field or matrix. Both
    /// are checked before anything is written: a rejected call changes nothing.
    ///
    /// Every call prints a one-line tally on stdout once the weld is done — nodes
    /// welded, cells dropped, tolerance used.
    #[pyo3(signature = (tol, in_place=false))]
    fn merge_nodes(
        slf: Py<Self>,
        py: Python<'_>,
        tol: f64,
        in_place: bool,
    ) -> PyResult<Py<PyMesh>> {
        super::mesh::merge_nodes(py, slf, tol, in_place)
    }
}