slatec 0.1.0

Safe Rust interface to selected SLATEC numerical routines
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
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
//! Checked owned facades for centered-grid cylindrical and polar FISHPACK solves.
//!
//! `HWSCYL` and `HWSPLR` have the same storage and workspace ABI, but their
//! radial and second-coordinate boundary restrictions differ.  The public
//! types make those restrictions explicit and never expose FISHPACK leading
//! dimensions, dummy arrays, or reusable native work storage.

use alloc::vec::Vec;
use core::convert::TryFrom;
use core::fmt;
use core::ops::{Index, IndexMut};

use slatec_sys::FortranInteger;

use crate::runtime::lock_native;

/// A finite, strictly increasing uniformly spaced coordinate axis.
///
/// `panels` is the number of equal intervals, so the axis has `panels + 1`
/// nodes.  Centered FISHPACK cylindrical and polar drivers require at least
/// four panels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CoordinateAxis {
    lower: f32,
    upper: f32,
    panels: usize,
}

impl CoordinateAxis {
    /// Creates a checked coordinate axis.
    pub fn new(lower: f32, upper: f32, panels: usize) -> Result<Self, CurvilinearPdeError> {
        validate_axis(lower, upper, panels, false)?;
        Ok(Self {
            lower,
            upper,
            panels,
        })
    }

    /// Returns the lower coordinate.
    #[must_use]
    pub fn lower(self) -> f32 {
        self.lower
    }

    /// Returns the upper coordinate.
    #[must_use]
    pub fn upper(self) -> f32 {
        self.upper
    }

    /// Returns the number of panels.
    #[must_use]
    pub fn panels(self) -> usize {
        self.panels
    }

    /// Returns the number of grid nodes, including both endpoints.
    pub fn nodes(self) -> Result<usize, CurvilinearPdeError> {
        self.panels
            .checked_add(1)
            .ok_or(CurvilinearPdeError::DimensionOverflow)
    }
}

/// A finite, non-negative radial axis with a strictly positive span.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RadialAxis(CoordinateAxis);

impl RadialAxis {
    /// Creates a checked radial axis.  Its lower coordinate may be zero.
    pub fn new(lower: f32, upper: f32, panels: usize) -> Result<Self, CurvilinearPdeError> {
        validate_axis(lower, upper, panels, true)?;
        Ok(Self(CoordinateAxis {
            lower,
            upper,
            panels,
        }))
    }

    /// Returns the radial lower coordinate.
    #[must_use]
    pub fn lower(self) -> f32 {
        self.0.lower
    }

    /// Returns the radial upper coordinate.
    #[must_use]
    pub fn upper(self) -> f32 {
        self.0.upper
    }

    /// Returns the number of radial panels.
    #[must_use]
    pub fn panels(self) -> usize {
        self.0.panels
    }

    /// Returns the radial node count, including endpoints.
    pub fn nodes(self) -> Result<usize, CurvilinearPdeError> {
        self.0.nodes()
    }
}

/// A finite, strictly increasing coordinate interval sampled at staggered points.
///
/// `points` is the number of unknowns in the open interval.  The grid is
/// `lower + (i + 0.5) * (upper - lower) / points` for zero-based `i`, so it
/// contains neither endpoint.  The staggered FISHPACK drivers require at
/// least three points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StaggeredCoordinateAxis {
    lower: f32,
    upper: f32,
    points: usize,
}

impl StaggeredCoordinateAxis {
    /// Creates a checked staggered coordinate interval.
    pub fn new(lower: f32, upper: f32, points: usize) -> Result<Self, CurvilinearPdeError> {
        validate_staggered_axis(lower, upper, points, false)?;
        Ok(Self {
            lower,
            upper,
            points,
        })
    }

    /// Returns the lower endpoint, which is not itself a grid point.
    #[must_use]
    pub fn lower(self) -> f32 {
        self.lower
    }

    /// Returns the upper endpoint, which is not itself a grid point.
    #[must_use]
    pub fn upper(self) -> f32 {
        self.upper
    }

    /// Returns the number of staggered unknowns in the interval.
    #[must_use]
    pub fn points(self) -> usize {
        self.points
    }
}

/// A non-negative staggered radial interval.
///
/// Even when the lower endpoint is zero, the first grid point is strictly
/// positive.  [`RadialBoundary::AxisDirichlet`] and
/// [`RadialBoundary::AxisNeumann`] represent the source-defined regularity
/// condition at that omitted endpoint.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StaggeredRadialAxis(StaggeredCoordinateAxis);

impl StaggeredRadialAxis {
    /// Creates a checked staggered radial interval.
    pub fn new(lower: f32, upper: f32, points: usize) -> Result<Self, CurvilinearPdeError> {
        validate_staggered_axis(lower, upper, points, true)?;
        Ok(Self(StaggeredCoordinateAxis {
            lower,
            upper,
            points,
        }))
    }

    /// Returns the radial lower endpoint.
    #[must_use]
    pub fn lower(self) -> f32 {
        self.0.lower
    }

    /// Returns the radial upper endpoint.
    #[must_use]
    pub fn upper(self) -> f32 {
        self.0.upper
    }

    /// Returns the number of staggered radial unknowns.
    #[must_use]
    pub fn points(self) -> usize {
        self.0.points
    }
}

/// An owned first-coordinate-fast two-dimensional FISHPACK grid.
///
/// `values[second * first_nodes + first]` is the value at the corresponding
/// grid node.  This is the contiguous representation of Fortran
/// `F(IDIMF, second_nodes)` when the private `IDIMF == first_nodes`.
#[derive(Clone, Debug, PartialEq)]
pub struct FishpackGrid2 {
    values: Vec<f32>,
    first_nodes: usize,
    second_nodes: usize,
}

impl FishpackGrid2 {
    /// Creates a grid from first-coordinate-fast values.
    pub fn new(
        first_nodes: usize,
        second_nodes: usize,
        values: Vec<f32>,
    ) -> Result<Self, CurvilinearPdeError> {
        let expected = area(first_nodes, second_nodes)?;
        if values.len() != expected {
            return Err(CurvilinearPdeError::InvalidGridShape {
                expected,
                actual: values.len(),
            });
        }
        Ok(Self {
            values,
            first_nodes,
            second_nodes,
        })
    }

    /// Allocates a zero-filled grid with checked dimensions.
    pub fn zeros(first_nodes: usize, second_nodes: usize) -> Result<Self, CurvilinearPdeError> {
        let length = area(first_nodes, second_nodes)?;
        Ok(Self {
            values: zeroed(length)?,
            first_nodes,
            second_nodes,
        })
    }

    /// Returns the number of nodes on the first coordinate.
    #[must_use]
    pub fn first_nodes(&self) -> usize {
        self.first_nodes
    }

    /// Returns the number of nodes on the second coordinate.
    #[must_use]
    pub fn second_nodes(&self) -> usize {
        self.second_nodes
    }

    /// Returns the contiguous first-coordinate-fast values.
    #[must_use]
    pub fn values(&self) -> &[f32] {
        &self.values
    }

    /// Returns the mutable contiguous first-coordinate-fast values.
    #[must_use]
    pub fn values_mut(&mut self) -> &mut [f32] {
        &mut self.values
    }

    /// Returns the value at `(first, second)` when it is in range.
    #[must_use]
    pub fn get(&self, first: usize, second: usize) -> Option<&f32> {
        self.offset(first, second)
            .map(|offset| &self.values[offset])
    }

    /// Returns the mutable value at `(first, second)` when it is in range.
    pub fn get_mut(&mut self, first: usize, second: usize) -> Option<&mut f32> {
        self.offset(first, second)
            .map(|offset| &mut self.values[offset])
    }

    fn offset(&self, first: usize, second: usize) -> Option<usize> {
        (first < self.first_nodes && second < self.second_nodes)
            .then_some(second * self.first_nodes + first)
    }
}

impl Index<(usize, usize)> for FishpackGrid2 {
    type Output = f32;

    fn index(&self, index: (usize, usize)) -> &Self::Output {
        self.get(index.0, index.1)
            .expect("FishpackGrid2 indices satisfy the documented dimensions")
    }
}

impl IndexMut<(usize, usize)> for FishpackGrid2 {
    fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
        self.get_mut(index.0, index.1)
            .expect("FishpackGrid2 indices satisfy the documented dimensions")
    }
}

/// Boundary conditions for a regular axial or angular coordinate.
///
/// Derivatives use the increasing-coordinate direction.  Every supplied edge
/// contains all nodes of the other coordinate, corners included.
#[derive(Clone, Debug, PartialEq)]
pub enum CoordinateBoundary {
    /// Identify the lower and upper coordinate planes periodically.
    Periodic,
    /// Prescribe values at both endpoints.
    Dirichlet {
        /// Values at the lower endpoint.
        lower: Vec<f32>,
        /// Values at the upper endpoint.
        upper: Vec<f32>,
    },
    /// Prescribe a lower value and upper increasing-coordinate derivative.
    DirichletNeumann {
        /// Values at the lower endpoint.
        lower: Vec<f32>,
        /// Increasing-coordinate derivatives at the upper endpoint.
        upper_derivative: Vec<f32>,
    },
    /// Prescribe increasing-coordinate derivatives at both endpoints.
    Neumann {
        /// Increasing-coordinate derivatives at the lower endpoint.
        lower_derivative: Vec<f32>,
        /// Increasing-coordinate derivatives at the upper endpoint.
        upper_derivative: Vec<f32>,
    },
    /// Prescribe a lower increasing-coordinate derivative and upper value.
    NeumannDirichlet {
        /// Increasing-coordinate derivatives at the lower endpoint.
        lower_derivative: Vec<f32>,
        /// Values at the upper endpoint.
        upper: Vec<f32>,
    },
}

/// Boundary conditions for the radial coordinate.
///
/// `Axis*` variants represent the documented `R = 0` unspecified-axis modes;
/// they are not a request for an arbitrary value at the origin.
#[derive(Clone, Debug, PartialEq)]
pub enum RadialBoundary {
    /// Prescribe values at both radial endpoints.
    Dirichlet {
        /// Values at the inner radius.
        lower: Vec<f32>,
        /// Values at the outer radius.
        upper: Vec<f32>,
    },
    /// Prescribe a lower value and upper radial derivative.
    DirichletNeumann {
        /// Values at the inner radius.
        lower: Vec<f32>,
        /// Radial derivatives at the outer radius.
        upper_derivative: Vec<f32>,
    },
    /// Prescribe radial derivatives at both endpoints.
    Neumann {
        /// Radial derivatives at the inner radius.
        lower_derivative: Vec<f32>,
        /// Radial derivatives at the outer radius.
        upper_derivative: Vec<f32>,
    },
    /// Prescribe a lower radial derivative and upper value.
    NeumannDirichlet {
        /// Radial derivatives at the inner radius.
        lower_derivative: Vec<f32>,
        /// Values at the outer radius.
        upper: Vec<f32>,
    },
    /// Use FISHPACK's unspecified-axis condition at `R = 0` and prescribe the outer value.
    AxisDirichlet {
        /// Values at the outer radius.
        outer: Vec<f32>,
    },
    /// Use FISHPACK's unspecified-axis condition at `R = 0` and prescribe the outer derivative.
    AxisNeumann {
        /// Radial derivatives at the outer radius.
        outer_derivative: Vec<f32>,
    },
}

/// A checked centered-grid cylindrical Helmholtz problem.
///
/// The native operation is `HWSCYL`, which approximates
/// `(1/r)(r u_r)_r + u_zz + lambda/r^2 u = rhs` on an `r × z` grid.
#[derive(Clone, Debug, PartialEq)]
pub struct CylindricalHelmholtz2d(CenteredProblem);

impl CylindricalHelmholtz2d {
    /// Validates and owns a centered-grid cylindrical problem.
    pub fn new(
        radius: RadialAxis,
        axial: CoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        axial_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        CenteredProblem::new(
            ProblemKind::Cylindrical,
            radius,
            axial,
            coefficient,
            rhs,
            radial_boundary,
            axial_boundary,
        )
        .map(Self)
    }

    /// Solves through the reviewed single-precision `HWSCYL` driver.
    pub fn solve(self) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        self.0.solve(slatec_sys::pde::fishpack::hwscyl)
    }
}

/// A checked centered-grid polar Helmholtz problem.
///
/// The native operation is `HWSPLR`, which approximates
/// `(1/r)(r u_r)_r + (1/r^2)u_theta_theta + lambda u = rhs`.
#[derive(Clone, Debug, PartialEq)]
pub struct PolarHelmholtz2d(CenteredProblem);

impl PolarHelmholtz2d {
    /// Validates and owns a centered-grid polar problem.
    pub fn new(
        radius: RadialAxis,
        angle: CoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        angular_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        CenteredProblem::new(
            ProblemKind::Polar,
            radius,
            angle,
            coefficient,
            rhs,
            radial_boundary,
            angular_boundary,
        )
        .map(Self)
    }

    /// Solves through the reviewed single-precision `HWSPLR` driver.
    pub fn solve(self) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        self.0.solve(slatec_sys::pde::fishpack::hwsplr)
    }
}

/// A checked staggered-grid cylindrical Helmholtz problem.
///
/// The native operation is `HSTCYL`, which samples both coordinates at
/// open-interval staggered points.  Endpoint values and derivatives belong in
/// the boundary objects; unlike [`CylindricalHelmholtz2d`], they are not
/// stored in the right-hand-side grid.
#[derive(Clone, Debug, PartialEq)]
pub struct StaggeredCylindricalHelmholtz2d(StaggeredProblem);

impl StaggeredCylindricalHelmholtz2d {
    /// Validates and owns a staggered cylindrical problem.
    pub fn new(
        radius: StaggeredRadialAxis,
        axial: StaggeredCoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        axial_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        StaggeredProblem::new(
            ProblemKind::StaggeredCylindrical,
            radius,
            axial,
            coefficient,
            rhs,
            radial_boundary,
            axial_boundary,
        )
        .map(Self)
    }

    /// Solves through the reviewed single-precision `HSTCYL` driver.
    pub fn solve(self) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        self.0.solve(slatec_sys::pde::fishpack::hstcyl)
    }
}

/// A checked staggered-grid polar Helmholtz problem.
///
/// The native operation is `HSTPLR`.  Its unknowns are at open-interval
/// radial and angular points, while endpoint data remain private native
/// boundary buffers owned by this problem.
#[derive(Clone, Debug, PartialEq)]
pub struct StaggeredPolarHelmholtz2d(StaggeredProblem);

impl StaggeredPolarHelmholtz2d {
    /// Validates and owns a staggered polar problem.
    pub fn new(
        radius: StaggeredRadialAxis,
        angle: StaggeredCoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        angular_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        StaggeredProblem::new(
            ProblemKind::StaggeredPolar,
            radius,
            angle,
            coefficient,
            rhs,
            radial_boundary,
            angular_boundary,
        )
        .map(Self)
    }

    /// Solves through the reviewed single-precision `HSTPLR` driver.
    pub fn solve(self) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        self.0.solve(slatec_sys::pde::fishpack::hstplr)
    }
}

/// An owned solution returned by a centered curvilinear FISHPACK driver.
#[derive(Clone, Debug, PartialEq)]
pub struct CurvilinearPdeSolution {
    values: FishpackGrid2,
    perturbation: f32,
    native_status: NativeCurvilinearPdeStatus,
}

impl CurvilinearPdeSolution {
    #[cfg(feature = "fishpack-spherical")]
    pub(super) fn from_native(
        values: FishpackGrid2,
        perturbation: f32,
        native_status: NativeCurvilinearPdeStatus,
    ) -> Self {
        Self {
            values,
            perturbation,
            native_status,
        }
    }

    /// Returns the solution on every grid node, including boundary nodes.
    #[must_use]
    pub fn values(&self) -> &FishpackGrid2 {
        &self.values
    }

    /// Consumes this result and returns the owned solution grid.
    #[must_use]
    pub fn into_values(self) -> FishpackGrid2 {
        self.values
    }

    /// Returns FISHPACK's compatibility correction subtracted from the RHS.
    ///
    /// A nonzero value means the selected singular Poisson system was solved
    /// after the documented correction; callers can compare its magnitude to
    /// the original RHS before accepting the result.
    #[must_use]
    pub fn perturbation(&self) -> f32 {
        self.perturbation
    }

    /// Returns the native completion status.
    #[must_use]
    pub fn native_status(&self) -> NativeCurvilinearPdeStatus {
        self.native_status
    }
}

/// The native completion state after a checked centered-grid solve.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NativeCurvilinearPdeStatus {
    /// The driver returned `IERROR = 0`.
    Success,
    /// The driver returned its documented attempted-solve coefficient warning.
    ///
    /// The meaning of the coefficient warning differs between the cylindrical
    /// and polar source prologues; the safe API preserves the exact code
    /// without over-generalizing that mathematical condition.
    CoefficientWarning {
        /// Exact native `IERROR` warning code.
        code: i32,
    },
}

impl NativeCurvilinearPdeStatus {
    /// Returns the exact native `IERROR` code.
    #[must_use]
    pub fn code(self) -> i32 {
        match self {
            Self::Success => 0,
            Self::CoefficientWarning { code } => code,
        }
    }
}

/// Validation, allocation, or unexpected native failure for these facades.
#[derive(Clone, Debug, PartialEq)]
pub enum CurvilinearPdeError {
    /// An axis endpoint was non-finite, unordered, or an invalid radial lower bound.
    InvalidAxis,
    /// A grid axis has fewer than the documented four panels.
    GridTooSmall {
        /// Requested panel count.
        panels: usize,
        /// Documented lower bound.
        minimum: usize,
    },
    /// A checked dimension or workspace computation overflowed Rust or Fortran storage.
    DimensionOverflow,
    /// The supplied RHS grid did not have the exact node dimensions.
    InvalidGridShape {
        /// Required element count.
        expected: usize,
        /// Supplied element count.
        actual: usize,
    },
    /// An input scalar, RHS, or boundary vector contains a non-finite value.
    NonFiniteInput {
        /// Human-readable input category.
        field: &'static str,
    },
    /// A supplied derivative or value edge did not span the other coordinate.
    InvalidBoundaryLength {
        /// Affected coordinate category.
        axis: &'static str,
        /// Required edge length.
        expected: usize,
        /// Supplied edge length.
        actual: usize,
    },
    /// Two Dirichlet edge values assigned the same corner inconsistently.
    InconsistentCornerValues,
    /// Periodic duplicate endpoint RHS samples differed.
    InconsistentPeriodicRightHandSide,
    /// The selected driver forbids the supplied radial/second-coordinate boundary pairing.
    UnsupportedBoundaryCombination {
        /// FISHPACK driver rejecting this pairing.
        routine: &'static str,
    },
    /// An unspecified radial-axis boundary was used away from `R = 0`.
    AxisBoundaryRequiresZeroRadius,
    /// A lower radial derivative was requested at `R = 0`.
    RadialDerivativeAtAxis,
    /// `HWSCYL` requires a zero coefficient for its unspecified-axis modes.
    AxisBoundaryRequiresZeroCoefficient,
    /// An owned workspace allocation failed.
    AllocationFailed,
    /// The native driver reported an invalid workspace requirement in `W(1)`.
    InconsistentNativeWorkspace {
        /// Value reported in native `W(1)`.
        reported: f32,
        /// Private workspace allocation length.
        allocated: usize,
    },
    /// A prevalidated call returned an unexpected `IERROR` code.
    NativeFailure {
        /// FISHPACK driver returning the code.
        routine: &'static str,
        /// Exact native `IERROR` value.
        code: i32,
    },
}

impl fmt::Display for CurvilinearPdeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidAxis => formatter.write_str("axis endpoints are invalid"),
            Self::GridTooSmall { panels, minimum } => {
                write!(
                    formatter,
                    "axis has {panels} panels; at least {minimum} are required"
                )
            }
            Self::DimensionOverflow => formatter.write_str("PDE dimension or workspace overflowed"),
            Self::InvalidGridShape { expected, actual } => {
                write!(formatter, "grid has {actual} values; expected {expected}")
            }
            Self::NonFiniteInput { field } => write!(formatter, "{field} must be finite"),
            Self::InvalidBoundaryLength {
                axis,
                expected,
                actual,
            } => write!(
                formatter,
                "{axis} boundary has length {actual}; expected {expected}"
            ),
            Self::InconsistentCornerValues => {
                formatter.write_str("two prescribed boundary values disagree at a corner")
            }
            Self::InconsistentPeriodicRightHandSide => {
                formatter.write_str("periodic duplicate endpoint RHS samples must agree")
            }
            Self::UnsupportedBoundaryCombination { routine } => {
                write!(
                    formatter,
                    "the supplied boundary combination is not accepted by {routine}"
                )
            }
            Self::AxisBoundaryRequiresZeroRadius => formatter
                .write_str("an unspecified axis boundary requires a radial lower endpoint of zero"),
            Self::RadialDerivativeAtAxis => {
                formatter.write_str("a radial derivative boundary cannot be used at r = 0")
            }
            Self::AxisBoundaryRequiresZeroCoefficient => {
                formatter.write_str("HWSCYL requires a zero coefficient with an unspecified axis")
            }
            Self::AllocationFailed => formatter.write_str("PDE workspace allocation failed"),
            Self::InconsistentNativeWorkspace {
                reported,
                allocated,
            } => write!(
                formatter,
                "native workspace report {reported} is invalid for allocation {allocated}"
            ),
            Self::NativeFailure { routine, code } => {
                write!(
                    formatter,
                    "{routine} returned unexpected native error code {code}"
                )
            }
        }
    }
}

impl std::error::Error for CurvilinearPdeError {}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ProblemKind {
    Cylindrical,
    Polar,
    StaggeredCylindrical,
    StaggeredPolar,
}

#[derive(Clone, Debug, PartialEq)]
struct CenteredProblem {
    kind: ProblemKind,
    radius: RadialAxis,
    second: CoordinateAxis,
    coefficient: f32,
    rhs: FishpackGrid2,
    radial_boundary: RadialBoundary,
    second_boundary: CoordinateBoundary,
}

#[derive(Clone, Debug, PartialEq)]
struct StaggeredProblem {
    kind: ProblemKind,
    radius: StaggeredRadialAxis,
    second: StaggeredCoordinateAxis,
    coefficient: f32,
    rhs: FishpackGrid2,
    radial_boundary: RadialBoundary,
    second_boundary: CoordinateBoundary,
}

type CenteredDriver = unsafe extern "C" fn(
    *mut f32,
    *mut f32,
    *mut FortranInteger,
    *mut FortranInteger,
    *mut f32,
    *mut f32,
    *mut f32,
    *mut f32,
    *mut FortranInteger,
    *mut FortranInteger,
    *mut f32,
    *mut f32,
    *mut f32,
    *mut f32,
    *mut FortranInteger,
    *mut f32,
    *mut FortranInteger,
    *mut f32,
);

impl CenteredProblem {
    fn new(
        kind: ProblemKind,
        radius: RadialAxis,
        second: CoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        second_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        if !coefficient.is_finite() {
            return Err(CurvilinearPdeError::NonFiniteInput {
                field: "Helmholtz coefficient",
            });
        }
        let first_nodes = radius.nodes()?;
        let second_nodes = second.nodes()?;
        let expected = area(first_nodes, second_nodes)?;
        if rhs.first_nodes != first_nodes || rhs.second_nodes != second_nodes {
            return Err(CurvilinearPdeError::InvalidGridShape {
                expected,
                actual: area(rhs.first_nodes, rhs.second_nodes)?,
            });
        }
        if rhs.values.iter().any(|value| !value.is_finite()) {
            return Err(CurvilinearPdeError::NonFiniteInput {
                field: "right-hand side",
            });
        }
        radial_boundary.validate(second_nodes)?;
        second_boundary.validate(first_nodes)?;
        validate_radial_boundary(
            kind,
            radius,
            coefficient,
            &radial_boundary,
            &second_boundary,
        )?;
        validate_periodic_rhs(&rhs, &second_boundary)?;
        validate_corners(
            &radial_boundary,
            &second_boundary,
            first_nodes,
            second_nodes,
        )?;
        Ok(Self {
            kind,
            radius,
            second,
            coefficient,
            rhs,
            radial_boundary,
            second_boundary,
        })
    }

    fn solve(self, driver: CenteredDriver) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        let first_nodes = self.radius.nodes()?;
        let second_nodes = self.second.nodes()?;
        let mut first_panels = FortranInteger::try_from(self.radius.panels())
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut second_panels = FortranInteger::try_from(self.second.panels())
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut first_dimension = FortranInteger::try_from(first_nodes)
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut radial_code = self.radial_boundary.code();
        let mut second_code = self.second_boundary.code();
        let mut lower_radius = self.radius.lower();
        let mut upper_radius = self.radius.upper();
        let mut lower_second = self.second.lower();
        let mut upper_second = self.second.upper();
        let mut coefficient = self.coefficient;
        let mut values = self.rhs.values;
        apply_dirichlet_edges(
            first_nodes,
            second_nodes,
            &mut values,
            &self.radial_boundary,
            &self.second_boundary,
        );
        let dummy = [0.0_f32];
        let lower_radial_derivative = self.radial_boundary.lower_derivative().unwrap_or(&dummy);
        let upper_radial_derivative = self.radial_boundary.upper_derivative().unwrap_or(&dummy);
        let lower_second_derivative = self.second_boundary.lower_derivative().unwrap_or(&dummy);
        let upper_second_derivative = self.second_boundary.upper_derivative().unwrap_or(&dummy);
        let workspace_length = workspace_len(first_nodes, second_nodes)?;
        let mut workspace = zeroed(workspace_length)?;
        let mut perturbation = 0.0;
        let mut native_code = 0;
        let _native = lock_native();
        // SAFETY: both reviewed drivers use the same GNU-Fortran ABI and
        // documented F(IDIMF, N+1) layout.  All private buffers are
        // contiguous, non-null, correctly sized, and remain live for the
        // entire native call.  Only the owned RHS/solution and workspace are
        // mutable native arrays.
        unsafe {
            driver(
                &mut lower_radius,
                &mut upper_radius,
                &mut first_panels,
                &mut radial_code,
                lower_radial_derivative.as_ptr().cast_mut(),
                upper_radial_derivative.as_ptr().cast_mut(),
                &mut lower_second,
                &mut upper_second,
                &mut second_panels,
                &mut second_code,
                lower_second_derivative.as_ptr().cast_mut(),
                upper_second_derivative.as_ptr().cast_mut(),
                &mut coefficient,
                values.as_mut_ptr(),
                &mut first_dimension,
                &mut perturbation,
                &mut native_code,
                workspace.as_mut_ptr(),
            );
        }
        if native_code != 0 && native_code != 11 {
            return Err(CurvilinearPdeError::NativeFailure {
                routine: self.kind.routine(),
                code: native_code,
            });
        }
        if !perturbation.is_finite() {
            return Err(CurvilinearPdeError::NativeFailure {
                routine: self.kind.routine(),
                code: native_code,
            });
        }
        let reported = workspace[0];
        if !reported.is_finite() || reported < 1.0 || reported > workspace_length as f32 {
            return Err(CurvilinearPdeError::InconsistentNativeWorkspace {
                reported,
                allocated: workspace_length,
            });
        }
        Ok(CurvilinearPdeSolution {
            values: FishpackGrid2 {
                values,
                first_nodes,
                second_nodes,
            },
            perturbation,
            native_status: if native_code == 0 {
                NativeCurvilinearPdeStatus::Success
            } else {
                NativeCurvilinearPdeStatus::CoefficientWarning { code: native_code }
            },
        })
    }
}

impl StaggeredProblem {
    fn new(
        kind: ProblemKind,
        radius: StaggeredRadialAxis,
        second: StaggeredCoordinateAxis,
        coefficient: f32,
        rhs: FishpackGrid2,
        radial_boundary: RadialBoundary,
        second_boundary: CoordinateBoundary,
    ) -> Result<Self, CurvilinearPdeError> {
        if !coefficient.is_finite() {
            return Err(CurvilinearPdeError::NonFiniteInput {
                field: "Helmholtz coefficient",
            });
        }
        let first_points = radius.points();
        let second_points = second.points();
        let expected = area(first_points, second_points)?;
        if rhs.first_nodes != first_points || rhs.second_nodes != second_points {
            return Err(CurvilinearPdeError::InvalidGridShape {
                expected,
                actual: area(rhs.first_nodes, rhs.second_nodes)?,
            });
        }
        if rhs.values.iter().any(|value| !value.is_finite()) {
            return Err(CurvilinearPdeError::NonFiniteInput {
                field: "right-hand side",
            });
        }
        radial_boundary.validate(second_points)?;
        second_boundary.validate(first_points)?;
        validate_staggered_radial_boundary(
            kind,
            radius,
            coefficient,
            &radial_boundary,
            &second_boundary,
        )?;
        Ok(Self {
            kind,
            radius,
            second,
            coefficient,
            rhs,
            radial_boundary,
            second_boundary,
        })
    }

    fn solve(self, driver: CenteredDriver) -> Result<CurvilinearPdeSolution, CurvilinearPdeError> {
        let first_points = self.radius.points();
        let second_points = self.second.points();
        let mut first_points_native = FortranInteger::try_from(first_points)
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut second_points_native = FortranInteger::try_from(second_points)
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut first_dimension = FortranInteger::try_from(first_points)
            .map_err(|_| CurvilinearPdeError::DimensionOverflow)?;
        let mut radial_code = self.radial_boundary.code();
        let mut second_code = self.second_boundary.code();
        let mut lower_radius = self.radius.lower();
        let mut upper_radius = self.radius.upper();
        let mut lower_second = self.second.lower();
        let mut upper_second = self.second.upper();
        let mut coefficient = self.coefficient;
        let mut values = self.rhs.values;
        let dummy = [0.0_f32];
        let lower_radial = self.radial_boundary.lower_data().unwrap_or(&dummy);
        let upper_radial = self.radial_boundary.upper_data().unwrap_or(&dummy);
        let lower_second_data = self.second_boundary.lower_data().unwrap_or(&dummy);
        let upper_second_data = self.second_boundary.upper_data().unwrap_or(&dummy);
        let workspace_length = staggered_workspace_len(first_points, second_points)?;
        let mut workspace = zeroed(workspace_length)?;
        let mut perturbation = 0.0;
        let mut native_code = 0;
        let _native = lock_native();
        // SAFETY: both reviewed staggered drivers share this source-verified
        // GNU-Fortran ABI.  Private buffers are non-null and exactly sized for
        // their documented M, N, and IDIMF contracts; no pointer is retained.
        unsafe {
            driver(
                &mut lower_radius,
                &mut upper_radius,
                &mut first_points_native,
                &mut radial_code,
                lower_radial.as_ptr().cast_mut(),
                upper_radial.as_ptr().cast_mut(),
                &mut lower_second,
                &mut upper_second,
                &mut second_points_native,
                &mut second_code,
                lower_second_data.as_ptr().cast_mut(),
                upper_second_data.as_ptr().cast_mut(),
                &mut coefficient,
                values.as_mut_ptr(),
                &mut first_dimension,
                &mut perturbation,
                &mut native_code,
                workspace.as_mut_ptr(),
            );
        }
        if native_code != 0 && native_code != 11 {
            return Err(CurvilinearPdeError::NativeFailure {
                routine: self.kind.routine(),
                code: native_code,
            });
        }
        if !perturbation.is_finite() {
            return Err(CurvilinearPdeError::NativeFailure {
                routine: self.kind.routine(),
                code: native_code,
            });
        }
        let reported = workspace[0];
        if !reported.is_finite() || reported < 1.0 || reported > workspace_length as f32 {
            return Err(CurvilinearPdeError::InconsistentNativeWorkspace {
                reported,
                allocated: workspace_length,
            });
        }
        Ok(CurvilinearPdeSolution {
            values: FishpackGrid2 {
                values,
                first_nodes: first_points,
                second_nodes: second_points,
            },
            perturbation,
            native_status: if native_code == 0 {
                NativeCurvilinearPdeStatus::Success
            } else {
                NativeCurvilinearPdeStatus::CoefficientWarning { code: native_code }
            },
        })
    }
}

impl ProblemKind {
    fn routine(self) -> &'static str {
        match self {
            Self::Cylindrical => "HWSCYL",
            Self::Polar => "HWSPLR",
            Self::StaggeredCylindrical => "HSTCYL",
            Self::StaggeredPolar => "HSTPLR",
        }
    }
}

impl CoordinateBoundary {
    pub(super) fn code(&self) -> FortranInteger {
        match self {
            Self::Periodic => 0,
            Self::Dirichlet { .. } => 1,
            Self::DirichletNeumann { .. } => 2,
            Self::Neumann { .. } => 3,
            Self::NeumannDirichlet { .. } => 4,
        }
    }

    pub(super) fn lower_value(&self) -> Option<&[f32]> {
        match self {
            Self::Dirichlet { lower, .. } | Self::DirichletNeumann { lower, .. } => Some(lower),
            Self::Periodic | Self::Neumann { .. } | Self::NeumannDirichlet { .. } => None,
        }
    }

    pub(super) fn upper_value(&self) -> Option<&[f32]> {
        match self {
            Self::Dirichlet { upper, .. } | Self::NeumannDirichlet { upper, .. } => Some(upper),
            Self::Periodic | Self::DirichletNeumann { .. } | Self::Neumann { .. } => None,
        }
    }

    pub(super) fn lower_derivative(&self) -> Option<&[f32]> {
        match self {
            Self::Neumann {
                lower_derivative, ..
            }
            | Self::NeumannDirichlet {
                lower_derivative, ..
            } => Some(lower_derivative),
            Self::Periodic | Self::Dirichlet { .. } | Self::DirichletNeumann { .. } => None,
        }
    }

    pub(super) fn upper_derivative(&self) -> Option<&[f32]> {
        match self {
            Self::DirichletNeumann {
                upper_derivative, ..
            }
            | Self::Neumann {
                upper_derivative, ..
            } => Some(upper_derivative),
            Self::Periodic | Self::Dirichlet { .. } | Self::NeumannDirichlet { .. } => None,
        }
    }

    pub(super) fn lower_data(&self) -> Option<&[f32]> {
        self.lower_value().or_else(|| self.lower_derivative())
    }

    pub(super) fn upper_data(&self) -> Option<&[f32]> {
        self.upper_value().or_else(|| self.upper_derivative())
    }

    pub(super) fn validate(&self, expected: usize) -> Result<(), CurvilinearPdeError> {
        validate_edges(
            [
                self.lower_value(),
                self.upper_value(),
                self.lower_derivative(),
                self.upper_derivative(),
            ],
            expected,
            "second-coordinate",
        )
    }
}

impl RadialBoundary {
    pub(super) fn code(&self) -> FortranInteger {
        match self {
            Self::Dirichlet { .. } => 1,
            Self::DirichletNeumann { .. } => 2,
            Self::Neumann { .. } => 3,
            Self::NeumannDirichlet { .. } => 4,
            Self::AxisDirichlet { .. } => 5,
            Self::AxisNeumann { .. } => 6,
        }
    }

    pub(super) fn lower_value(&self) -> Option<&[f32]> {
        match self {
            Self::Dirichlet { lower, .. } | Self::DirichletNeumann { lower, .. } => Some(lower),
            Self::Neumann { .. }
            | Self::NeumannDirichlet { .. }
            | Self::AxisDirichlet { .. }
            | Self::AxisNeumann { .. } => None,
        }
    }

    pub(super) fn upper_value(&self) -> Option<&[f32]> {
        match self {
            Self::Dirichlet { upper, .. }
            | Self::NeumannDirichlet { upper, .. }
            | Self::AxisDirichlet { outer: upper } => Some(upper),
            Self::DirichletNeumann { .. } | Self::Neumann { .. } | Self::AxisNeumann { .. } => None,
        }
    }

    pub(super) fn lower_derivative(&self) -> Option<&[f32]> {
        match self {
            Self::Neumann {
                lower_derivative, ..
            }
            | Self::NeumannDirichlet {
                lower_derivative, ..
            } => Some(lower_derivative),
            Self::Dirichlet { .. }
            | Self::DirichletNeumann { .. }
            | Self::AxisDirichlet { .. }
            | Self::AxisNeumann { .. } => None,
        }
    }

    pub(super) fn upper_derivative(&self) -> Option<&[f32]> {
        match self {
            Self::DirichletNeumann {
                upper_derivative, ..
            }
            | Self::Neumann {
                upper_derivative, ..
            }
            | Self::AxisNeumann {
                outer_derivative: upper_derivative,
            } => Some(upper_derivative),
            Self::Dirichlet { .. } | Self::NeumannDirichlet { .. } | Self::AxisDirichlet { .. } => {
                None
            }
        }
    }

    pub(super) fn lower_data(&self) -> Option<&[f32]> {
        self.lower_value().or_else(|| self.lower_derivative())
    }

    pub(super) fn upper_data(&self) -> Option<&[f32]> {
        self.upper_value().or_else(|| self.upper_derivative())
    }

    pub(super) fn is_axis(&self) -> bool {
        matches!(self, Self::AxisDirichlet { .. } | Self::AxisNeumann { .. })
    }

    pub(super) fn validate(&self, expected: usize) -> Result<(), CurvilinearPdeError> {
        validate_edges(
            [
                self.lower_value(),
                self.upper_value(),
                self.lower_derivative(),
                self.upper_derivative(),
            ],
            expected,
            "radial",
        )
    }
}

fn validate_axis(
    lower: f32,
    upper: f32,
    panels: usize,
    radial: bool,
) -> Result<(), CurvilinearPdeError> {
    if !lower.is_finite() || !upper.is_finite() || lower >= upper || (radial && lower < 0.0) {
        return Err(CurvilinearPdeError::InvalidAxis);
    }
    if panels < 4 {
        return Err(CurvilinearPdeError::GridTooSmall { panels, minimum: 4 });
    }
    Ok(())
}

fn validate_staggered_axis(
    lower: f32,
    upper: f32,
    points: usize,
    radial: bool,
) -> Result<(), CurvilinearPdeError> {
    if !lower.is_finite() || !upper.is_finite() || lower >= upper || (radial && lower < 0.0) {
        return Err(CurvilinearPdeError::InvalidAxis);
    }
    if points < 3 {
        return Err(CurvilinearPdeError::GridTooSmall {
            panels: points,
            minimum: 3,
        });
    }
    Ok(())
}

fn validate_edges(
    edges: [Option<&[f32]>; 4],
    expected: usize,
    axis: &'static str,
) -> Result<(), CurvilinearPdeError> {
    for values in edges.into_iter().flatten() {
        if values.len() != expected {
            return Err(CurvilinearPdeError::InvalidBoundaryLength {
                axis,
                expected,
                actual: values.len(),
            });
        }
        if values.iter().any(|value| !value.is_finite()) {
            return Err(CurvilinearPdeError::NonFiniteInput {
                field: "boundary data",
            });
        }
    }
    Ok(())
}

fn validate_radial_boundary(
    kind: ProblemKind,
    radius: RadialAxis,
    coefficient: f32,
    radial: &RadialBoundary,
    second: &CoordinateBoundary,
) -> Result<(), CurvilinearPdeError> {
    if radial.is_axis() && radius.lower() != 0.0 {
        return Err(CurvilinearPdeError::AxisBoundaryRequiresZeroRadius);
    }
    if radius.lower() == 0.0
        && matches!(
            radial,
            RadialBoundary::Neumann { .. } | RadialBoundary::NeumannDirichlet { .. }
        )
    {
        return Err(CurvilinearPdeError::RadialDerivativeAtAxis);
    }
    if kind == ProblemKind::Cylindrical && radial.is_axis() && coefficient != 0.0 {
        return Err(CurvilinearPdeError::AxisBoundaryRequiresZeroCoefficient);
    }
    if kind == ProblemKind::Polar
        && radial.is_axis()
        && !matches!(
            second,
            CoordinateBoundary::Periodic | CoordinateBoundary::Neumann { .. }
        )
    {
        return Err(CurvilinearPdeError::UnsupportedBoundaryCombination { routine: "HWSPLR" });
    }
    Ok(())
}

fn validate_staggered_radial_boundary(
    kind: ProblemKind,
    radius: StaggeredRadialAxis,
    coefficient: f32,
    radial: &RadialBoundary,
    second: &CoordinateBoundary,
) -> Result<(), CurvilinearPdeError> {
    if radial.is_axis() && radius.lower() != 0.0 {
        return Err(CurvilinearPdeError::AxisBoundaryRequiresZeroRadius);
    }
    if radius.lower() > 0.0 && radial.is_axis() {
        return Err(CurvilinearPdeError::AxisBoundaryRequiresZeroRadius);
    }
    match kind {
        ProblemKind::StaggeredCylindrical => {
            if radius.lower() == 0.0 && !radial.is_axis() {
                return Err(CurvilinearPdeError::UnsupportedBoundaryCombination {
                    routine: "HSTCYL",
                });
            }
            if radial.is_axis() && coefficient != 0.0 {
                return Err(CurvilinearPdeError::AxisBoundaryRequiresZeroCoefficient);
            }
        }
        ProblemKind::StaggeredPolar => {
            if radius.lower() == 0.0
                && matches!(
                    radial,
                    RadialBoundary::Neumann { .. } | RadialBoundary::NeumannDirichlet { .. }
                )
            {
                return Err(CurvilinearPdeError::RadialDerivativeAtAxis);
            }
            if radial.is_axis()
                && !matches!(
                    second,
                    CoordinateBoundary::Periodic | CoordinateBoundary::Neumann { .. }
                )
            {
                return Err(CurvilinearPdeError::UnsupportedBoundaryCombination {
                    routine: "HSTPLR",
                });
            }
        }
        ProblemKind::Cylindrical | ProblemKind::Polar => {
            unreachable!("centered kinds use their own validator")
        }
    }
    Ok(())
}

fn validate_periodic_rhs(
    grid: &FishpackGrid2,
    boundary: &CoordinateBoundary,
) -> Result<(), CurvilinearPdeError> {
    if matches!(boundary, CoordinateBoundary::Periodic)
        && (0..grid.first_nodes)
            .any(|first| grid[(first, 0)] != grid[(first, grid.second_nodes - 1)])
    {
        return Err(CurvilinearPdeError::InconsistentPeriodicRightHandSide);
    }
    Ok(())
}

fn validate_corners(
    radial: &RadialBoundary,
    second: &CoordinateBoundary,
    first_nodes: usize,
    second_nodes: usize,
) -> Result<(), CurvilinearPdeError> {
    for (radial_value, second_value) in [
        (
            radial.lower_value().map(|values| values[0]),
            second.lower_value().map(|values| values[0]),
        ),
        (
            radial.upper_value().map(|values| values[0]),
            second.lower_value().map(|values| values[first_nodes - 1]),
        ),
        (
            radial.lower_value().map(|values| values[second_nodes - 1]),
            second.upper_value().map(|values| values[0]),
        ),
        (
            radial.upper_value().map(|values| values[second_nodes - 1]),
            second.upper_value().map(|values| values[first_nodes - 1]),
        ),
    ] {
        if let (Some(radial_value), Some(second_value)) = (radial_value, second_value) {
            if radial_value != second_value {
                return Err(CurvilinearPdeError::InconsistentCornerValues);
            }
        }
    }
    Ok(())
}

fn apply_dirichlet_edges(
    first_nodes: usize,
    second_nodes: usize,
    values: &mut [f32],
    radial: &RadialBoundary,
    second: &CoordinateBoundary,
) {
    if let Some(lower) = radial.lower_value() {
        for second_index in 0..second_nodes {
            values[second_index * first_nodes] = lower[second_index];
        }
    }
    if let Some(upper) = radial.upper_value() {
        for second_index in 0..second_nodes {
            values[second_index * first_nodes + first_nodes - 1] = upper[second_index];
        }
    }
    if let Some(lower) = second.lower_value() {
        values[..first_nodes].copy_from_slice(lower);
    }
    if let Some(upper) = second.upper_value() {
        values[(second_nodes - 1) * first_nodes..].copy_from_slice(upper);
    }
}

fn workspace_len(first_nodes: usize, second_nodes: usize) -> Result<usize, CurvilinearPdeError> {
    let log2_second = (usize::BITS - 1 - second_nodes.leading_zeros()) as usize;
    second_nodes
        .checked_mul(4)
        .and_then(|first| {
            log2_second
                .checked_add(13)
                .and_then(|factor| factor.checked_mul(first_nodes))
                .and_then(|second| first.checked_add(second))
        })
        .ok_or(CurvilinearPdeError::DimensionOverflow)
}

fn staggered_workspace_len(
    first_points: usize,
    second_points: usize,
) -> Result<usize, CurvilinearPdeError> {
    let log2_second = (usize::BITS - 1 - second_points.leading_zeros()) as usize;
    first_points
        .checked_mul(13)
        .and_then(|value| {
            second_points
                .checked_mul(4)
                .and_then(|other| value.checked_add(other))
        })
        .and_then(|value| {
            first_points
                .checked_mul(log2_second)
                .and_then(|other| value.checked_add(other))
        })
        .ok_or(CurvilinearPdeError::DimensionOverflow)
}

fn area(first: usize, second: usize) -> Result<usize, CurvilinearPdeError> {
    first
        .checked_mul(second)
        .ok_or(CurvilinearPdeError::DimensionOverflow)
}

fn zeroed(length: usize) -> Result<Vec<f32>, CurvilinearPdeError> {
    let mut values = Vec::new();
    values
        .try_reserve_exact(length)
        .map_err(|_| CurvilinearPdeError::AllocationFailed)?;
    values.resize(length, 0.0);
    Ok(values)
}

#[cfg(test)]
mod tests {
    use alloc::vec;
    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    use alloc::vec::Vec;

    use super::{
        CoordinateAxis, CoordinateBoundary, CurvilinearPdeError, CylindricalHelmholtz2d,
        FishpackGrid2, PolarHelmholtz2d, RadialAxis, RadialBoundary,
    };

    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    use super::{
        StaggeredCoordinateAxis, StaggeredCylindricalHelmholtz2d, StaggeredPolarHelmholtz2d,
        StaggeredRadialAxis,
    };

    #[test]
    fn radial_axis_and_boundary_restrictions_are_checked() {
        assert!(matches!(
            RadialAxis::new(-1.0, 1.0, 4),
            Err(CurvilinearPdeError::InvalidAxis)
        ));
        let radius = RadialAxis::new(0.0, 1.0, 4).unwrap();
        let second = CoordinateAxis::new(0.0, 1.0, 4).unwrap();
        let grid = FishpackGrid2::zeros(5, 5).unwrap();
        assert!(matches!(
            CylindricalHelmholtz2d::new(
                radius,
                second,
                1.0,
                grid,
                RadialBoundary::AxisDirichlet {
                    outer: vec![0.0; 5]
                },
                CoordinateBoundary::Periodic,
            ),
            Err(CurvilinearPdeError::AxisBoundaryRequiresZeroCoefficient)
        ));
    }

    #[test]
    fn polar_axis_requires_periodic_or_derivative_angle_boundary() {
        let radius = RadialAxis::new(0.0, 1.0, 4).unwrap();
        let angle = CoordinateAxis::new(0.0, 1.0, 4).unwrap();
        let grid = FishpackGrid2::zeros(5, 5).unwrap();
        assert!(matches!(
            PolarHelmholtz2d::new(
                radius,
                angle,
                0.0,
                grid,
                RadialBoundary::AxisDirichlet {
                    outer: vec![0.0; 5]
                },
                CoordinateBoundary::Dirichlet {
                    lower: vec![0.0; 5],
                    upper: vec![0.0; 5]
                },
            ),
            Err(CurvilinearPdeError::UnsupportedBoundaryCombination { .. })
        ));
    }

    #[test]
    fn grid_uses_first_coordinate_fast_layout() {
        let grid = FishpackGrid2::new(3, 2, vec![0.0, 1.0, 2.0, 10.0, 11.0, 12.0]).unwrap();
        assert_eq!(grid[(2, 0)], 2.0);
        assert_eq!(grid[(1, 1)], 11.0);
    }

    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    #[test]
    fn native_cylindrical_and_polar_constant_solutions_are_manufactured() {
        let radius = RadialAxis::new(1.0, 2.0, 8).unwrap();
        let second = CoordinateAxis::new(0.0, 1.0, 8).unwrap();
        let zeros = || FishpackGrid2::zeros(9, 9).unwrap();
        let radial = || RadialBoundary::Dirichlet {
            lower: vec![1.0; 9],
            upper: vec![1.0; 9],
        };
        let cylindrical = CylindricalHelmholtz2d::new(
            radius,
            second,
            0.0,
            zeros(),
            radial(),
            CoordinateBoundary::Dirichlet {
                lower: vec![1.0; 9],
                upper: vec![1.0; 9],
            },
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!(
            cylindrical
                .values()
                .values()
                .iter()
                .all(|value| (*value - 1.0).abs() < 1.0e-4)
        );

        let polar = PolarHelmholtz2d::new(
            radius,
            second,
            0.0,
            zeros(),
            radial(),
            CoordinateBoundary::Periodic,
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!(
            polar
                .values()
                .values()
                .iter()
                .all(|value| (*value - 1.0).abs() < 1.0e-4)
        );
    }

    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    #[test]
    fn native_staggered_cylindrical_and_polar_constant_solutions_are_manufactured() {
        let radius = StaggeredRadialAxis::new(1.0, 2.0, 8).unwrap();
        let second = StaggeredCoordinateAxis::new(0.0, 1.0, 8).unwrap();
        let zeros = || FishpackGrid2::zeros(8, 8).unwrap();
        let radial = || RadialBoundary::Dirichlet {
            lower: vec![1.0; 8],
            upper: vec![1.0; 8],
        };
        let cylindrical = StaggeredCylindricalHelmholtz2d::new(
            radius,
            second,
            0.0,
            zeros(),
            radial(),
            CoordinateBoundary::Dirichlet {
                lower: vec![1.0; 8],
                upper: vec![1.0; 8],
            },
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!(
            cylindrical
                .values()
                .values()
                .iter()
                .all(|value| (*value - 1.0).abs() < 1.0e-4)
        );

        let polar = StaggeredPolarHelmholtz2d::new(
            radius,
            second,
            0.0,
            zeros(),
            radial(),
            CoordinateBoundary::Periodic,
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!(
            polar
                .values()
                .values()
                .iter()
                .all(|value| (*value - 1.0).abs() < 1.0e-4)
        );
    }

    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    #[test]
    fn native_cylindrical_nonconstant_boundary_and_singular_perturbation_are_verified() {
        let radius = RadialAxis::new(1.0, 2.0, 12).unwrap();
        let axial = CoordinateAxis::new(0.0, 1.0, 12).unwrap();
        let z_values = (0..=12)
            .map(|index| index as f32 / 12.0)
            .collect::<Vec<_>>();
        let zero = vec![0.0; 13];
        let one = vec![1.0; 13];
        let solution = CylindricalHelmholtz2d::new(
            radius,
            axial,
            0.0,
            FishpackGrid2::zeros(13, 13).unwrap(),
            RadialBoundary::Dirichlet {
                lower: z_values.clone(),
                upper: z_values,
            },
            CoordinateBoundary::Dirichlet {
                lower: zero,
                upper: one,
            },
        )
        .unwrap()
        .solve()
        .unwrap();
        for second in 0..=12 {
            let expected = second as f32 / 12.0;
            for first in 0..=12 {
                assert!((solution.values()[(first, second)] - expected).abs() < 3.0e-4);
            }
        }

        let singular = CylindricalHelmholtz2d::new(
            RadialAxis::new(1.0, 2.0, 8).unwrap(),
            CoordinateAxis::new(0.0, 1.0, 8).unwrap(),
            0.0,
            FishpackGrid2::new(9, 9, vec![2.5; 81]).unwrap(),
            RadialBoundary::Neumann {
                lower_derivative: vec![0.0; 9],
                upper_derivative: vec![0.0; 9],
            },
            CoordinateBoundary::Neumann {
                lower_derivative: vec![0.0; 9],
                upper_derivative: vec![0.0; 9],
            },
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!((singular.perturbation() - 2.5).abs() < 2.0e-4);
    }

    #[cfg(feature = "fishpack-cylindrical-polar-native-tests")]
    #[test]
    fn native_polar_nonzero_coefficient_and_singular_perturbation_are_verified() {
        let coefficient = 1.75;
        let solution = PolarHelmholtz2d::new(
            RadialAxis::new(1.0, 2.0, 8).unwrap(),
            CoordinateAxis::new(0.0, core::f32::consts::TAU, 8).unwrap(),
            coefficient,
            FishpackGrid2::new(9, 9, vec![coefficient; 81]).unwrap(),
            RadialBoundary::Dirichlet {
                lower: vec![1.0; 9],
                upper: vec![1.0; 9],
            },
            CoordinateBoundary::Periodic,
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!(
            solution
                .values()
                .values()
                .iter()
                .all(|value| (*value - 1.0).abs() < 2.0e-4)
        );

        let singular = PolarHelmholtz2d::new(
            RadialAxis::new(1.0, 2.0, 8).unwrap(),
            CoordinateAxis::new(0.0, core::f32::consts::TAU, 8).unwrap(),
            0.0,
            FishpackGrid2::new(9, 9, vec![1.25; 81]).unwrap(),
            RadialBoundary::Neumann {
                lower_derivative: vec![0.0; 9],
                upper_derivative: vec![0.0; 9],
            },
            CoordinateBoundary::Periodic,
        )
        .unwrap()
        .solve()
        .unwrap();
        assert!((singular.perturbation() - 1.25).abs() < 2.0e-4);
    }
}