onemkl 0.4.4

Safe, idiomatic Rust wrapper over Intel oneAPI Math Kernel Library (oneMKL).
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
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
// SPDX-License-Identifier: MIT OR Apache-2.0
//! PDE support — trigonometric transforms (DCT / DST) used in
//! spectral PDE solvers and signal processing.
//!
//! oneMKL exposes six trig-transform variants (sine, cosine, plus
//! four staggered combinations). The flow is:
//!
//! 1. [`TrigTransform::new`] — initialize and commit a plan for a
//!    given `n`-point transform.
//! 2. [`TrigTransform::forward`] / [`backward`](TrigTransform::backward)
//!    — run the transform on an in-place buffer.
//! 3. `Drop` releases the descriptor.
//!
//! Both single (`f32`) and double (`f64`) precision are supported via
//! the [`TrigTransformScalar`] trait. The transform is applied
//! in-place to the user-supplied buffer.
//!
//! ```ignore
//! use onemkl::pde::{TrigTransform, TrigTransformType};
//!
//! // 8-point DCT.
//! let mut f = vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 0.0];
//! //              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//! //              n+1 = 9 elements (sine / cosine transforms work on
//! //              n+1-point buffers — the boundary samples).
//! let mut plan = TrigTransform::<f64>::new(TrigTransformType::Cosine, 8).unwrap();
//! plan.forward(&mut f).unwrap();
//! ```

use core::ffi::c_int;
use core::marker::PhantomData;
use core::ptr;

use onemkl_sys::{self as sys, DFTI_DESCRIPTOR_HANDLE};

use crate::error::{Error, Result};

/// Variant of the trigonometric transform. Each maps to one of
/// MKL's `MKL_*_TRANSFORM` constants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TrigTransformType {
    /// Sine transform (DST-I).
    Sine,
    /// Cosine transform (DCT-I).
    Cosine,
    /// Staggered cosine transform (DCT-II / DCT-III pair).
    StaggeredCosine,
    /// Staggered sine transform (DST-II / DST-III pair).
    StaggeredSine,
    /// Twice-staggered cosine transform.
    Staggered2Cosine,
    /// Twice-staggered sine transform.
    Staggered2Sine,
}

impl TrigTransformType {
    #[inline]
    fn as_int(self) -> c_int {
        let v = match self {
            Self::Sine => sys::MKL_SINE_TRANSFORM,
            Self::Cosine => sys::MKL_COSINE_TRANSFORM,
            Self::StaggeredCosine => sys::MKL_STAGGERED_COSINE_TRANSFORM,
            Self::StaggeredSine => sys::MKL_STAGGERED_SINE_TRANSFORM,
            Self::Staggered2Cosine => sys::MKL_STAGGERED2_COSINE_TRANSFORM,
            Self::Staggered2Sine => sys::MKL_STAGGERED2_SINE_TRANSFORM,
        };
        v as c_int
    }

    /// Number of input samples expected for an `n`-point transform of
    /// this type. Sine and cosine work on `n + 1` boundary samples;
    /// the staggered variants work on `n` interior samples.
    #[inline]
    #[must_use]
    pub fn buffer_len(self, n: usize) -> usize {
        match self {
            Self::Sine | Self::Cosine => n + 1,
            _ => n,
        }
    }
}

/// Scalar types supported by the trig transform routines.
#[allow(missing_docs)]
pub trait TrigTransformScalar: Copy + Default + 'static {
    /// Raw `init_trig_transform` call.
    ///
    /// # Safety
    ///
    /// `n` must point to one readable `c_int` (the number of intervals, `n >= 2`) and `tt_type` to one readable `c_int` (a `MKL_*_TRANSFORM` constant). `ipar` must be valid for writes of the 128-entry integer parameter array and `dpar` for writes of the double/float parameter array MKL specifies for the transform (at least `5 * n / 2 + 2` elements; **verified** by guard-page probe, n = 64, oneMKL 2026.2, Linux x86_64: the smallest `dpar` for which init+commit+forward+backward did not fault was `n/2 + 2` (sine), `n + 2` (cosine), `3n/2 + 2` (both staggered types) and `5n/2 + 2` (both staggered2 types), so `5n/2 + 2` is the tight bound over all types; the smallest `ipar` was 15 entries, and the documented 128-entry length is kept as the safe size). `stat` must point to one writable `c_int`.
    /// Despite the `*mut` types `n` and `tt_type` are only read. The arrays must not overlap. A non-zero `*stat` reports an MKL error and the arrays must not be used further. The MKL library must be linked and usable.
    /// Transform-type constants `MKL_SINE_TRANSFORM`..`MKL_STAGGERED2_SINE_TRANSFORM` (0..=5) are declared in `mkl_trig_transforms.h`. The requirement `n >= 2` is unverified.
    unsafe fn init_trig_transform(
        n: *mut c_int,
        tt_type: *mut c_int,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    /// Raw `commit_trig_transform` call.
    ///
    /// # Safety
    ///
    /// `f` must be valid for reads of the grid values the transform defines (**verified** by the same probe: `n + 1` elements for the sine, cosine and staggered types, `n` elements for the staggered2 types, n = 64) and `handle` valid for a write of one `DFTI_DESCRIPTOR_HANDLE`. `ipar` and `dpar` must be the arrays initialised by `init_trig_transform` for the same `n` and transform type, unmodified except as MKL allows (sizes as there); `stat` must point to one writable `c_int`.
    /// On success `*handle` is owned by the caller and must be released with `free_trig_transform` exactly once; `*handle` must not be used after a failed commit. The MKL library must be linked and usable.
    unsafe fn commit_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    /// Raw `forward_trig_transform` call.
    ///
    /// # Safety
    ///
    /// `f` must be valid for reads and writes of the same number of grid elements used in `commit_trig_transform` (it is transformed in place); `handle`, `ipar`, `dpar` must be the live handle and arrays from the matching `commit_trig_transform` (handle not yet freed), and `stat` must point to one writable `c_int`.
    /// No other reference to `f` may be live during the call, and no other thread may use `handle`, `ipar` or `dpar`. The MKL library must be linked and usable.
    unsafe fn forward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    /// Raw `backward_trig_transform` call.
    ///
    /// # Safety
    ///
    /// `f` must be valid for reads and writes of the same number of grid elements used in `commit_trig_transform` (it is transformed in place); `handle`, `ipar`, `dpar` must be the live handle and arrays from the matching `commit_trig_transform` (handle not yet freed), and `stat` must point to one writable `c_int`.
    /// No other reference to `f` may be live during the call, and no other thread may use `handle`, `ipar` or `dpar`. The MKL library must be linked and usable.
    unsafe fn backward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
}

impl TrigTransformScalar for f32 {
    unsafe fn init_trig_transform(
        n: *mut c_int,
        tt_type: *mut c_int,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::s_init_trig_transform(n, tt_type, ipar, dpar, stat) }
    }
    unsafe fn commit_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::s_commit_trig_transform(f, handle, ipar, dpar, stat) }
    }
    unsafe fn forward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::s_forward_trig_transform(f, handle, ipar, dpar, stat) }
    }
    unsafe fn backward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::s_backward_trig_transform(f, handle, ipar, dpar, stat) }
    }
}

impl TrigTransformScalar for f64 {
    unsafe fn init_trig_transform(
        n: *mut c_int,
        tt_type: *mut c_int,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::d_init_trig_transform(n, tt_type, ipar, dpar, stat) }
    }
    unsafe fn commit_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::d_commit_trig_transform(f, handle, ipar, dpar, stat) }
    }
    unsafe fn forward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::d_forward_trig_transform(f, handle, ipar, dpar, stat) }
    }
    unsafe fn backward_trig_transform(
        f: *mut Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    ) {
        unsafe { sys::d_backward_trig_transform(f, handle, ipar, dpar, stat) }
    }
}

#[inline]
fn check_tr(stat: c_int) -> Result<()> {
    // The trig transform routines return 0 on success (standard
    // convention), not TR_SUCCESS = 1501 (which is the optimization
    // routines' convention).
    if stat == 0 {
        Ok(())
    } else {
        Err(Error::LapackComputationFailure { info: stat })
    }
}

/// An owned trigonometric transform plan.
pub struct TrigTransform<T: TrigTransformScalar> {
    handle: DFTI_DESCRIPTOR_HANDLE,
    ipar: Vec<c_int>,
    dpar: Vec<T>,
    n: c_int,
    transform_type: TrigTransformType,
    _marker: PhantomData<T>,
}

unsafe impl<T: TrigTransformScalar + Send> Send for TrigTransform<T> {}

impl<T: TrigTransformScalar> TrigTransform<T> {
    /// Build a plan for an `n`-point transform of the given type.
    /// Sine and cosine transforms operate on `n + 1`-element buffers
    /// (boundary samples included); the staggered variants operate
    /// on `n`-element buffers (interior samples). See
    /// [`TrigTransformType::buffer_len`].
    pub fn new(transform_type: TrigTransformType, n: usize) -> Result<Self> {
        if n == 0 {
            return Err(Error::InvalidArgument("n must be ≥ 1"));
        }
        let mut n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
        let mut tt_int: c_int = transform_type.as_int();
        // Allocate ipar of size 128 and dpar generously sized to fit
        // the largest variant's workspace.
        let mut ipar: Vec<c_int> = vec![0; 128];
        let mut dpar: Vec<T> = vec![T::default(); 5 * n + 2];
        let mut stat: c_int = 0;

        unsafe {
            T::init_trig_transform(
                &mut n_i,
                &mut tt_int,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;

        let mut handle: DFTI_DESCRIPTOR_HANDLE = ptr::null_mut();
        // commit_trig_transform takes f as input; it inspects the
        // first element to determine alignment / size. We can pass a
        // throwaway buffer here.
        let mut probe: Vec<T> = vec![T::default(); transform_type.buffer_len(n)];
        unsafe {
            T::commit_trig_transform(
                probe.as_mut_ptr(),
                &mut handle,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;

        Ok(Self {
            handle,
            ipar,
            dpar,
            n: n_i,
            transform_type,
            _marker: PhantomData,
        })
    }

    /// Length of the buffer this plan expects on each transform call.
    #[inline]
    #[must_use]
    pub fn buffer_len(&self) -> usize {
        self.transform_type.buffer_len(self.n as usize)
    }

    /// Apply the forward transform in place. `f` must have at least
    /// [`buffer_len`](Self::buffer_len) elements.
    pub fn forward(&mut self, f: &mut [T]) -> Result<()> {
        let need = self.buffer_len();
        if f.len() < need {
            return Err(Error::InvalidArgument(
                "buffer too small for the trig transform",
            ));
        }
        let mut stat: c_int = 0;
        unsafe {
            T::forward_trig_transform(
                f.as_mut_ptr(),
                &mut self.handle,
                self.ipar.as_mut_ptr(),
                self.dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)
    }

    /// Apply the backward / inverse transform in place.
    pub fn backward(&mut self, f: &mut [T]) -> Result<()> {
        let need = self.buffer_len();
        if f.len() < need {
            return Err(Error::InvalidArgument(
                "buffer too small for the trig transform",
            ));
        }
        let mut stat: c_int = 0;
        unsafe {
            T::backward_trig_transform(
                f.as_mut_ptr(),
                &mut self.handle,
                self.ipar.as_mut_ptr(),
                self.dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)
    }
}

impl<T: TrigTransformScalar> Drop for TrigTransform<T> {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            let mut stat: c_int = 0;
            unsafe {
                sys::free_trig_transform(&mut self.handle, self.ipar.as_mut_ptr(), &mut stat);
            }
        }
    }
}

// ---------------------------------------------------------------
// Cartesian Helmholtz / Poisson solver (2-D)
// ---------------------------------------------------------------

/// Boundary condition on one side of the rectangle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Boundary {
    /// Dirichlet: `u` is prescribed (the boundary values are supplied
    /// to [`Helmholtz2D::solve`]).
    Dirichlet,
    /// Neumann: the outward-pointing-axis derivative `du/dn` is
    /// prescribed (values supplied to [`Helmholtz2D::solve`]).
    Neumann,
    /// Periodic: the side is identified with the opposite one; both
    /// sides of the pair must be `Periodic`.
    Periodic,
}

impl Boundary {
    fn as_char(self) -> u8 {
        match self {
            Self::Dirichlet => b'D',
            Self::Neumann => b'N',
            Self::Periodic => b'P',
        }
    }
}

/// Scalar types supported by the Helmholtz solver.
#[allow(missing_docs, clippy::missing_safety_doc, clippy::too_many_arguments)]
pub trait HelmholtzScalar: Copy + Default + 'static {
    fn to_f64(self) -> f64;
    fn from_f64(v: f64) -> Self;
    unsafe fn init_2d(
        ax: *const Self,
        bx: *const Self,
        ay: *const Self,
        by: *const Self,
        nx: *const c_int,
        ny: *const c_int,
        bc: *const core::ffi::c_char,
        q: *const Self,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn commit_2d(
        f: *mut Self,
        bd_ax: *const Self,
        bd_bx: *const Self,
        bd_ay: *const Self,
        bd_by: *const Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn solve_2d(
        f: *mut Self,
        bd_ax: *const Self,
        bd_bx: *const Self,
        bd_ay: *const Self,
        bd_by: *const Self,
        handle: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *const Self,
        stat: *mut c_int,
    );
    unsafe fn init_3d(
        lim: [*const Self; 6],
        n: [*const c_int; 3],
        bc: *const core::ffi::c_char,
        q: *const Self,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn commit_3d(
        f: *mut Self,
        bd: [*const Self; 6],
        xh: *mut DFTI_DESCRIPTOR_HANDLE,
        yh: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn solve_3d(
        f: *mut Self,
        bd: [*const Self; 6],
        xh: *mut DFTI_DESCRIPTOR_HANDLE,
        yh: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *const Self,
        stat: *mut c_int,
    );
    unsafe fn init_sph(
        lim: [*const Self; 4],
        np: *const c_int,
        nt: *const c_int,
        q: *const Self,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn commit_sph(
        f: *mut Self,
        h1: *mut DFTI_DESCRIPTOR_HANDLE,
        h2: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn solve_sph(
        f: *mut Self,
        h1: *mut DFTI_DESCRIPTOR_HANDLE,
        h2: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn init_sph_np(
        lim: [*const Self; 4],
        np: *const c_int,
        nt: *const c_int,
        q: *const Self,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn commit_sph_np(
        f: *mut Self,
        h: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn solve_sph_np(
        f: *mut Self,
        h: *mut DFTI_DESCRIPTOR_HANDLE,
        ipar: *mut c_int,
        dpar: *mut Self,
        stat: *mut c_int,
    );
    unsafe fn free_sph_np(h: *mut DFTI_DESCRIPTOR_HANDLE, ipar: *mut c_int, stat: *mut c_int);
}

macro_rules! impl_helmholtz_scalar {
    ($t:ty, $init:ident, $commit:ident, $solve:ident, $init3:ident, $commit3:ident, $solve3:ident, $inits:ident, $commits:ident, $solves:ident, $initn:ident, $commitn:ident, $solven:ident) => {
        impl HelmholtzScalar for $t {
            fn to_f64(self) -> f64 {
                self as f64
            }
            fn from_f64(v: f64) -> Self {
                v as $t
            }
            unsafe fn init_2d(
                ax: *const Self,
                bx: *const Self,
                ay: *const Self,
                by: *const Self,
                nx: *const c_int,
                ny: *const c_int,
                bc: *const core::ffi::c_char,
                q: *const Self,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$init(ax, bx, ay, by, nx, ny, bc, q, ipar, dpar, stat) }
            }
            unsafe fn commit_2d(
                f: *mut Self,
                bd_ax: *const Self,
                bd_bx: *const Self,
                bd_ay: *const Self,
                bd_by: *const Self,
                handle: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$commit(f, bd_ax, bd_bx, bd_ay, bd_by, handle, ipar, dpar, stat) }
            }
            unsafe fn solve_2d(
                f: *mut Self,
                bd_ax: *const Self,
                bd_bx: *const Self,
                bd_ay: *const Self,
                bd_by: *const Self,
                handle: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *const Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$solve(f, bd_ax, bd_bx, bd_ay, bd_by, handle, ipar, dpar, stat) }
            }
            unsafe fn init_3d(
                l: [*const Self; 6],
                n: [*const c_int; 3],
                bc: *const core::ffi::c_char,
                q: *const Self,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe {
                    sys::$init3(
                        l[0], l[1], l[2], l[3], l[4], l[5], n[0], n[1], n[2], bc, q, ipar, dpar,
                        stat,
                    )
                }
            }
            unsafe fn commit_3d(
                f: *mut Self,
                b: [*const Self; 6],
                xh: *mut DFTI_DESCRIPTOR_HANDLE,
                yh: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe {
                    sys::$commit3(
                        f, b[0], b[1], b[2], b[3], b[4], b[5], xh, yh, ipar, dpar, stat,
                    )
                }
            }
            unsafe fn solve_3d(
                f: *mut Self,
                b: [*const Self; 6],
                xh: *mut DFTI_DESCRIPTOR_HANDLE,
                yh: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *const Self,
                stat: *mut c_int,
            ) {
                unsafe {
                    sys::$solve3(
                        f, b[0], b[1], b[2], b[3], b[4], b[5], xh, yh, ipar, dpar, stat,
                    )
                }
            }
            unsafe fn init_sph(
                l: [*const Self; 4],
                np: *const c_int,
                nt: *const c_int,
                q: *const Self,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$inits(l[0], l[1], l[2], l[3], np, nt, q, ipar, dpar, stat) }
            }
            unsafe fn commit_sph(
                f: *mut Self,
                h1: *mut DFTI_DESCRIPTOR_HANDLE,
                h2: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$commits(f, h1, h2, ipar, dpar, stat) }
            }
            unsafe fn solve_sph(
                f: *mut Self,
                h1: *mut DFTI_DESCRIPTOR_HANDLE,
                h2: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$solves(f, h1, h2, ipar, dpar, stat) }
            }
            unsafe fn init_sph_np(
                l: [*const Self; 4],
                np: *const c_int,
                nt: *const c_int,
                q: *const Self,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$initn(l[0], l[1], l[2], l[3], np, nt, q, ipar, dpar, stat) }
            }
            unsafe fn commit_sph_np(
                f: *mut Self,
                h: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$commitn(f, h, ipar, dpar, stat) }
            }
            unsafe fn solve_sph_np(
                f: *mut Self,
                h: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                dpar: *mut Self,
                stat: *mut c_int,
            ) {
                unsafe { sys::$solven(f, h, ipar, dpar, stat) }
            }
            unsafe fn free_sph_np(
                h: *mut DFTI_DESCRIPTOR_HANDLE,
                ipar: *mut c_int,
                stat: *mut c_int,
            ) {
                unsafe { sys::free_sph_np(h, ipar, stat) }
            }
        }
    };
}
impl_helmholtz_scalar!(
    f32,
    s_init_helmholtz_2d,
    s_commit_helmholtz_2d,
    s_helmholtz_2d,
    s_init_helmholtz_3d,
    s_commit_helmholtz_3d,
    s_helmholtz_3d,
    s_init_sph_p,
    s_commit_sph_p,
    s_sph_p,
    s_init_sph_np,
    s_commit_sph_np,
    s_sph_np
);
impl_helmholtz_scalar!(
    f64,
    d_init_helmholtz_2d,
    d_commit_helmholtz_2d,
    d_helmholtz_2d,
    d_init_helmholtz_3d,
    d_commit_helmholtz_3d,
    d_helmholtz_3d,
    d_init_sph_p,
    d_commit_sph_p,
    d_sph_p,
    d_init_sph_np,
    d_commit_sph_np,
    d_sph_np
);

/// Index range of the unknown nodes along one axis of `n` intervals
/// for the boundary pair `(lo, hi)`: Dirichlet nodes are fixed,
/// Neumann boundary nodes are unknowns, a periodic axis has `n` unknowns
/// (node `n` repeats node 0).
fn unknown_range(lo: Boundary, hi: Boundary, n: usize) -> (usize, usize) {
    if lo == Boundary::Periodic {
        return (0, n - 1);
    }
    (
        if lo == Boundary::Dirichlet { 1 } else { 0 },
        if hi == Boundary::Dirichlet { n - 1 } else { n },
    )
}

/// Right-hand-side adjustment for one axis at node index `i`:
/// returns `(subtract, halvings)` where `subtract` is the amount to
/// subtract from the rhs (Dirichlet lift `g/h²`, Neumann `2g/h`) and
/// `halvings` is 1 on a Neumann boundary node (MKL weights those rows
/// by 2, measured), else 0.
fn axis_lift<T: HelmholtzScalar>(
    bc: [Boundary; 2],
    n: usize,
    i: usize,
    h: f64,
    g_lo: impl Fn() -> T,
    g_hi: impl Fn() -> T,
) -> (f64, u32) {
    let mut sub = 0.0;
    let mut halv = 0;
    if bc[0] == Boundary::Dirichlet && i == 1 {
        sub += g_lo().to_f64() / (h * h);
    }
    if bc[1] == Boundary::Dirichlet && i == n - 1 {
        sub += g_hi().to_f64() / (h * h);
    }
    if bc[0] == Boundary::Neumann && i == 0 {
        sub += 2.0 * g_lo().to_f64() / h;
        halv += 1;
    }
    if bc[1] == Boundary::Neumann && i == n {
        sub += 2.0 * g_hi().to_f64() / h;
        halv += 1;
    }
    (sub, halv)
}

fn check_pairs(bc: &[Boundary]) -> Result<()> {
    for pair in bc.chunks(2) {
        if (pair[0] == Boundary::Periodic) != (pair[1] == Boundary::Periodic) {
            return Err(Error::InvalidArgument(
                "periodic boundary must be set on both sides of the pair",
            ));
        }
    }
    Ok(())
}

/// Fast solver for the 2-D Helmholtz equation `Δu − q·u = f` on the
/// rectangle `[ax, bx] × [ay, by]` (`q = 0` gives Poisson), on a
/// uniform `nx × ny` grid of intervals (second-order finite
/// differences, FFT-based).
///
/// Grid values are stored column-by-x: node `(i, j)` lives at
/// `f[i + j * (nx + 1)]`, `0 ≤ i ≤ nx`, `0 ≤ j ≤ ny`.
/// [`solve`](Self::solve) takes the right-hand side in `f` and
/// overwrites it with the solution (Dirichlet boundary nodes are set
/// to the supplied boundary data).
///
/// Boundary data: Dirichlet sides take the value of `u`, Neumann sides
/// the outward normal derivative `∂u/∂n`, periodic sides nothing.
/// Neumann boundary nodes are unknowns, discretised with a reflected
/// ghost node. All-Neumann/periodic with `q = 0` is singular and MKL
/// reports it as an error.
///
/// **Measured MKL behaviour** (oneMKL 2026.2.1, Linux x86_64, LP64; fitted
/// to 10 digits against a dense reference): MKL returns
/// `(−Δ + q)⁻¹ f / hy²` instead of the documented `(Δ − q)⁻¹ f`, weights
/// Neumann boundary rows by 2, and ignores the boundary-data arrays, so
/// this wrapper moves the boundary data to the right-hand side itself and
/// rescales the result.
pub struct Helmholtz2D<T: HelmholtzScalar> {
    handle: DFTI_DESCRIPTOR_HANDLE,
    ipar: Vec<c_int>,
    dpar: Vec<T>,
    nx: usize,
    ny: usize,
    bc: [Boundary; 4],
    hx: f64,
    hy: f64,
    committed: bool,
}

unsafe impl<T: HelmholtzScalar + Send> Send for Helmholtz2D<T> {}

impl<T: HelmholtzScalar> Helmholtz2D<T> {
    /// Build a solver. `bc` is ordered `[x = ax, x = bx, y = ay, y = by]`;
    /// a periodic pair must be periodic on both sides. `nx` and `ny`
    /// must be even and at least 4 (MKL requirement). `q ≥ 0` is the
    /// Helmholtz coefficient.
    pub fn new(
        (ax, bx): (T, T),
        (ay, by): (T, T),
        nx: usize,
        ny: usize,
        bc: [Boundary; 4],
        q: T,
    ) -> Result<Self> {
        if nx < 4 || ny < 4 || !nx.is_multiple_of(2) || !ny.is_multiple_of(2) {
            return Err(Error::InvalidArgument(
                "nx and ny must be even and at least 4",
            ));
        }
        check_pairs(&bc)?;
        let nx_i: c_int = nx.try_into().map_err(|_| Error::DimensionOverflow)?;
        let ny_i: c_int = ny.try_into().map_err(|_| Error::DimensionOverflow)?;
        let bc_c: [core::ffi::c_char; 5] = [
            bc[0].as_char() as _,
            bc[1].as_char() as _,
            bc[2].as_char() as _,
            bc[3].as_char() as _,
            0,
        ];
        let mut ipar: Vec<c_int> = vec![0; 128];
        // MKL documents 5*nx/2 + 7*ny/2 + 9 for dpar; pad generously.
        let mut dpar: Vec<T> = vec![T::default(); 5 * nx / 2 + 7 * ny / 2 + 64];
        let mut stat: c_int = 0;
        unsafe {
            T::init_2d(
                &ax,
                &bx,
                &ay,
                &by,
                &nx_i,
                &ny_i,
                bc_c.as_ptr(),
                &q,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        Ok(Self {
            handle: ptr::null_mut(),
            ipar,
            dpar,
            nx,
            ny,
            bc,
            hx: (bx.to_f64() - ax.to_f64()) / nx as f64,
            hy: (by.to_f64() - ay.to_f64()) / ny as f64,
            committed: false,
        })
    }

    /// Required length of the grid buffer, `(nx + 1) * (ny + 1)`.
    #[must_use]
    pub fn grid_len(&self) -> usize {
        (self.nx + 1) * (self.ny + 1)
    }

    /// Solve in place. `f` holds the right-hand side on entry and the
    /// solution on exit. `bd_ax`/`bd_bx` (length `ny + 1`) and
    /// `bd_ay`/`bd_by` (length `nx + 1`) carry the Dirichlet values or
    /// outward Neumann derivatives of the corresponding side; for a
    /// periodic side pass an empty slice (ignored).
    pub fn solve(
        &mut self,
        f: &mut [T],
        bd_ax: &[T],
        bd_bx: &[T],
        bd_ay: &[T],
        bd_by: &[T],
    ) -> Result<()> {
        if f.len() < self.grid_len() {
            return Err(Error::InvalidArgument("grid buffer too small"));
        }
        let (nx, ny) = (self.nx, self.ny);
        let w = nx + 1;
        let bd = [bd_ax, bd_bx, bd_ay, bd_by];
        let need = [ny + 1, ny + 1, nx + 1, nx + 1];
        for k in 0..4 {
            if self.bc[k] != Boundary::Periodic && bd[k].len() < need[k] {
                return Err(Error::InvalidArgument("boundary data slice too short"));
            }
        }
        let g = |k: usize, idx: usize| {
            move || {
                if bd[k].is_empty() {
                    T::default()
                } else {
                    bd[k][idx]
                }
            }
        };
        let (ilo, ihi) = unknown_range(self.bc[0], self.bc[1], nx);
        let (jlo, jhi) = unknown_range(self.bc[2], self.bc[3], ny);
        // MKL applies no boundary lift: do it here (see the type docs).
        for j in jlo..=jhi {
            for i in ilo..=ihi {
                let (sx, hx_) =
                    axis_lift([self.bc[0], self.bc[1]], nx, i, self.hx, g(0, j), g(1, j));
                let (sy, hy_) =
                    axis_lift([self.bc[2], self.bc[3]], ny, j, self.hy, g(2, i), g(3, i));
                let v = &mut f[i + j * w];
                let r = v.to_f64() - sx - sy;
                *v = T::from_f64(r / f64::from(1u32 << (hx_ + hy_)));
            }
        }
        // A periodic axis repeats its first node in the last one.
        if self.bc[0] == Boundary::Periodic {
            for j in 0..=ny {
                f[nx + j * w] = f[j * w];
            }
        }
        if self.bc[2] == Boundary::Periodic {
            for i in 0..=nx {
                f[i + ny * w] = f[i];
            }
        }
        let zeros: Vec<T> = vec![T::default(); nx.max(ny) + 1];
        let zp = zeros.as_ptr();
        let mut stat: c_int = 0;
        if !self.committed {
            let mut probe: Vec<T> = f[..self.grid_len()].to_vec();
            unsafe {
                T::commit_2d(
                    probe.as_mut_ptr(),
                    zp,
                    zp,
                    zp,
                    zp,
                    &mut self.handle,
                    self.ipar.as_mut_ptr(),
                    self.dpar.as_mut_ptr(),
                    &mut stat,
                );
            }
            check_tr(stat)?;
            self.committed = true;
        }
        unsafe {
            T::solve_2d(
                f.as_mut_ptr(),
                zp,
                zp,
                zp,
                zp,
                &mut self.handle,
                self.ipar.as_mut_ptr(),
                self.dpar.as_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        // Undo MKL's sign and 1/hy² scaling; Dirichlet nodes get the data.
        let hy2 = self.hy * self.hy;
        for j in 0..=ny {
            for i in 0..=nx {
                let d = if i == 0 && self.bc[0] == Boundary::Dirichlet {
                    Some(bd[0][j])
                } else if i == nx && self.bc[1] == Boundary::Dirichlet {
                    Some(bd[1][j])
                } else if j == 0 && self.bc[2] == Boundary::Dirichlet {
                    Some(bd[2][i])
                } else if j == ny && self.bc[3] == Boundary::Dirichlet {
                    Some(bd[3][i])
                } else {
                    None
                };
                let v = &mut f[i + j * w];
                *v = match d {
                    Some(d) => d,
                    None => T::from_f64(-hy2 * v.to_f64()),
                };
            }
        }
        Ok(())
    }
}

impl<T: HelmholtzScalar> Drop for Helmholtz2D<T> {
    fn drop(&mut self) {
        if self.handle.is_null() {
            return;
        }
        let mut stat: c_int = 0;
        unsafe {
            sys::free_helmholtz_2d(&mut self.handle, self.ipar.as_mut_ptr(), &mut stat);
        }
    }
}

/// Fast solver for the 3-D Helmholtz equation `Δu − q·u = f` on a box
/// with a uniform `nx × ny × nz` grid. Boundary types, data meaning and
/// the measured MKL behaviour the wrapper corrects are those of
/// [`Helmholtz2D`] (the 3-D result is `(−Δ + q)⁻¹ f / hz²`).
///
/// Node `(i, j, k)` is `f[i + j*(nx+1) + k*(nx+1)*(ny+1)]`. Boundary
/// data per face, in the order `[ax, bx, ay, by, az, bz]`: x faces are
/// `(ny+1)*(nz+1)` long (`j + k*(ny+1)`), y faces `(nx+1)*(nz+1)`
/// (`i + k*(nx+1)`), z faces `(nx+1)*(ny+1)` (`i + j*(nx+1)`); periodic
/// faces take empty slices.
pub struct Helmholtz3D<T: HelmholtzScalar> {
    xh: DFTI_DESCRIPTOR_HANDLE,
    yh: DFTI_DESCRIPTOR_HANDLE,
    ipar: Vec<c_int>,
    dpar: Vec<T>,
    n: [usize; 3],
    h: [f64; 3],
    bc: [Boundary; 6],
    committed: bool,
}

unsafe impl<T: HelmholtzScalar + Send> Send for Helmholtz3D<T> {}

impl<T: HelmholtzScalar> Helmholtz3D<T> {
    /// Build a solver; `nx`, `ny`, `nz` must be even and at least 4.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        (ax, bx): (T, T),
        (ay, by): (T, T),
        (az, bz): (T, T),
        nx: usize,
        ny: usize,
        nz: usize,
        bc: [Boundary; 6],
        q: T,
    ) -> Result<Self> {
        if [nx, ny, nz].iter().any(|&n| n < 4 || !n.is_multiple_of(2)) {
            return Err(Error::InvalidArgument(
                "nx, ny, nz must be even and at least 4",
            ));
        }
        check_pairs(&bc)?;
        let nx_i: c_int = nx.try_into().map_err(|_| Error::DimensionOverflow)?;
        let ny_i: c_int = ny.try_into().map_err(|_| Error::DimensionOverflow)?;
        let nz_i: c_int = nz.try_into().map_err(|_| Error::DimensionOverflow)?;
        let bc_c: [core::ffi::c_char; 7] = [
            bc[0].as_char() as _,
            bc[1].as_char() as _,
            bc[2].as_char() as _,
            bc[3].as_char() as _,
            bc[4].as_char() as _,
            bc[5].as_char() as _,
            0,
        ];
        let mut ipar: Vec<c_int> = vec![0; 128];
        // MKL's 3-D dpar size is quadratic in the grid; cover the largest
        // face product generously (not MKL's documented formula).
        let face = ((nx + 1) * (ny + 1))
            .max((ny + 1) * (nz + 1))
            .max((nx + 1) * (nz + 1));
        let mut dpar: Vec<T> = vec![T::default(); 7 * face + 40 * (nx + ny + nz) + 200];
        let mut stat: c_int = 0;
        unsafe {
            T::init_3d(
                [&ax, &bx, &ay, &by, &az, &bz],
                [&nx_i, &ny_i, &nz_i],
                bc_c.as_ptr(),
                &q,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        let step = |a: T, b: T, n: usize| (b.to_f64() - a.to_f64()) / n as f64;
        Ok(Self {
            xh: ptr::null_mut(),
            yh: ptr::null_mut(),
            ipar,
            dpar,
            n: [nx, ny, nz],
            h: [step(ax, bx, nx), step(ay, by, ny), step(az, bz, nz)],
            bc,
            committed: false,
        })
    }

    /// Required grid length, `(nx + 1) * (ny + 1) * (nz + 1)`.
    #[must_use]
    pub fn grid_len(&self) -> usize {
        (self.n[0] + 1) * (self.n[1] + 1) * (self.n[2] + 1)
    }

    /// Solve in place; `bd` holds the boundary data of the faces
    /// `[ax, bx, ay, by, az, bz]` (layouts in the type docs).
    pub fn solve(&mut self, f: &mut [T], bd: [&[T]; 6]) -> Result<()> {
        let [nx, ny, nz] = self.n;
        let (wx, wy) = (nx + 1, ny + 1);
        if f.len() < self.grid_len() {
            return Err(Error::InvalidArgument("grid buffer too small"));
        }
        let need = [
            wy * (nz + 1),
            wy * (nz + 1),
            wx * (nz + 1),
            wx * (nz + 1),
            wx * wy,
            wx * wy,
        ];
        for k in 0..6 {
            if self.bc[k] != Boundary::Periodic && bd[k].len() < need[k] {
                return Err(Error::InvalidArgument("boundary data slice too short"));
            }
        }
        let at = |i: usize, j: usize, k: usize| i + j * wx + k * wx * wy;
        let g = |f_: usize, idx: usize| {
            move || {
                if bd[f_].is_empty() {
                    T::default()
                } else {
                    bd[f_][idx]
                }
            }
        };
        let (ilo, ihi) = unknown_range(self.bc[0], self.bc[1], nx);
        let (jlo, jhi) = unknown_range(self.bc[2], self.bc[3], ny);
        let (klo, khi) = unknown_range(self.bc[4], self.bc[5], nz);
        for k in klo..=khi {
            for j in jlo..=jhi {
                for i in ilo..=ihi {
                    let (sx, hx_) = axis_lift(
                        [self.bc[0], self.bc[1]],
                        nx,
                        i,
                        self.h[0],
                        g(0, j + k * wy),
                        g(1, j + k * wy),
                    );
                    let (sy, hy_) = axis_lift(
                        [self.bc[2], self.bc[3]],
                        ny,
                        j,
                        self.h[1],
                        g(2, i + k * wx),
                        g(3, i + k * wx),
                    );
                    let (sz, hz_) = axis_lift(
                        [self.bc[4], self.bc[5]],
                        nz,
                        k,
                        self.h[2],
                        g(4, i + j * wx),
                        g(5, i + j * wx),
                    );
                    let v = &mut f[at(i, j, k)];
                    let r = v.to_f64() - sx - sy - sz;
                    *v = T::from_f64(r / f64::from(1u32 << (hx_ + hy_ + hz_)));
                }
            }
        }
        // A periodic axis repeats its first node in the last one.
        if self.bc[0] == Boundary::Periodic {
            for k in 0..=nz {
                for j in 0..=ny {
                    f[at(nx, j, k)] = f[at(0, j, k)];
                }
            }
        }
        if self.bc[2] == Boundary::Periodic {
            for k in 0..=nz {
                for i in 0..=nx {
                    f[at(i, ny, k)] = f[at(i, 0, k)];
                }
            }
        }
        if self.bc[4] == Boundary::Periodic {
            for j in 0..=ny {
                for i in 0..=nx {
                    f[at(i, j, nz)] = f[at(i, j, 0)];
                }
            }
        }
        let zeros: Vec<T> = vec![T::default(); wx.max(wy) * (nz + 1).max(wx.max(wy))];
        let zp = [zeros.as_ptr(); 6];
        let mut stat: c_int = 0;
        if !self.committed {
            let mut probe: Vec<T> = f[..self.grid_len()].to_vec();
            unsafe {
                T::commit_3d(
                    probe.as_mut_ptr(),
                    zp,
                    &mut self.xh,
                    &mut self.yh,
                    self.ipar.as_mut_ptr(),
                    self.dpar.as_mut_ptr(),
                    &mut stat,
                );
            }
            check_tr(stat)?;
            self.committed = true;
        }
        unsafe {
            T::solve_3d(
                f.as_mut_ptr(),
                zp,
                &mut self.xh,
                &mut self.yh,
                self.ipar.as_mut_ptr(),
                self.dpar.as_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        // Undo MKL's sign and 1/hz² scaling; Dirichlet nodes get the data.
        let hz2 = self.h[2] * self.h[2];
        for k in 0..=nz {
            for j in 0..=ny {
                for i in 0..=nx {
                    let d = if i == 0 && self.bc[0] == Boundary::Dirichlet {
                        Some(bd[0][j + k * wy])
                    } else if i == nx && self.bc[1] == Boundary::Dirichlet {
                        Some(bd[1][j + k * wy])
                    } else if j == 0 && self.bc[2] == Boundary::Dirichlet {
                        Some(bd[2][i + k * wx])
                    } else if j == ny && self.bc[3] == Boundary::Dirichlet {
                        Some(bd[3][i + k * wx])
                    } else if k == 0 && self.bc[4] == Boundary::Dirichlet {
                        Some(bd[4][i + j * wx])
                    } else if k == nz && self.bc[5] == Boundary::Dirichlet {
                        Some(bd[5][i + j * wx])
                    } else {
                        None
                    };
                    let v = &mut f[at(i, j, k)];
                    *v = match d {
                        Some(d) => d,
                        None => T::from_f64(-hz2 * v.to_f64()),
                    };
                }
            }
        }
        Ok(())
    }
}

impl<T: HelmholtzScalar> Drop for Helmholtz3D<T> {
    fn drop(&mut self) {
        if self.xh.is_null() && self.yh.is_null() {
            return;
        }
        let mut stat: c_int = 0;
        unsafe {
            sys::free_helmholtz_3d(
                &mut self.xh,
                &mut self.yh,
                self.ipar.as_mut_ptr(),
                &mut stat,
            );
        }
    }
}

/// Fast Helmholtz solver `Δ_S u − q·u = F` on the unit sphere surface
/// (`φ ∈ [0, 2π]` periodic, `θ ∈ [0, π]` pole to pole), wrapping MKL's
/// periodic spherical solver (`?_sph_p`).
///
/// Node `(i, j)` (`φ = 2π·i/np`, `θ = π·j/nt`) is `f[i + j*(np+1)]`;
/// the nodes `i = np` repeat `i = 0`, and the pole rows `j = 0`, `j = nt`
/// should hold a single value per ring (the ring average is what the
/// solver uses). `q > 0` makes the problem well posed; with `q = 0` MKL
/// reports the constant null space as a warning, surfaced here as an error.
///
/// **Measured MKL behaviour** (oneMKL 2026.2.1, Linux x86_64, LP64): the
/// argument order is `(ap, bp, at, bt)`, and for each `φ`-mode MKL solves
/// `hθ²·sinθⱼ·(−Δ_h + q)u = f` with the conservative θ stencil built from
/// averaged node sines, and weight 1 (not `sinθ`) on the pole rows; the
/// wrapper maps `F` to `f = −hθ²·sinθⱼ·F` (weight 1 at the poles).
pub struct SphericalHelmholtz<T: HelmholtzScalar> {
    h1: DFTI_DESCRIPTOR_HANDLE,
    h2: DFTI_DESCRIPTOR_HANDLE,
    ipar: Vec<c_int>,
    dpar: Vec<T>,
    np: usize,
    nt: usize,
    committed: bool,
}

unsafe impl<T: HelmholtzScalar + Send> Send for SphericalHelmholtz<T> {}

impl<T: HelmholtzScalar> SphericalHelmholtz<T> {
    /// Build a solver for `np` intervals in `φ` (even, ≥ 4) and `nt`
    /// intervals in `θ` (≥ 2).
    pub fn new(np: usize, nt: usize, q: T) -> Result<Self> {
        if np < 4 || !np.is_multiple_of(2) || nt < 2 {
            return Err(Error::InvalidArgument("np must be even and ≥ 4, nt ≥ 2"));
        }
        let np_i: c_int = np.try_into().map_err(|_| Error::DimensionOverflow)?;
        let nt_i: c_int = nt.try_into().map_err(|_| Error::DimensionOverflow)?;
        let lim = [
            T::from_f64(0.0),
            T::from_f64(2.0 * core::f64::consts::PI),
            T::from_f64(0.0),
            T::from_f64(core::f64::consts::PI),
        ];
        let mut ipar: Vec<c_int> = vec![0; 128];
        // Documented size is 5*np/2 + nt + 10; pad generously.
        let mut dpar: Vec<T> = vec![T::default(); 4 * (5 * np / 2 + nt + 10) + 200];
        let mut stat: c_int = 0;
        unsafe {
            T::init_sph(
                [&lim[0], &lim[1], &lim[2], &lim[3]],
                &np_i,
                &nt_i,
                &q,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        Ok(Self {
            h1: ptr::null_mut(),
            h2: ptr::null_mut(),
            ipar,
            dpar,
            np,
            nt,
            committed: false,
        })
    }

    /// Required grid length, `(np + 1) * (nt + 1)`.
    #[must_use]
    pub fn grid_len(&self) -> usize {
        (self.np + 1) * (self.nt + 1)
    }

    /// Solve in place: `f` holds `F` on entry and `u` on exit.
    pub fn solve(&mut self, f: &mut [T]) -> Result<()> {
        if f.len() < self.grid_len() {
            return Err(Error::InvalidArgument("grid buffer too small"));
        }
        let (np, nt) = (self.np, self.nt);
        let w = np + 1;
        let ht = core::f64::consts::PI / nt as f64;
        for j in 0..=nt {
            let weight = if j == 0 || j == nt {
                1.0
            } else {
                (j as f64 * ht).sin()
            };
            for i in 0..=np {
                let v = &mut f[i + j * w];
                *v = T::from_f64(-ht * ht * weight * v.to_f64());
            }
        }
        let mut stat: c_int = 0;
        if !self.committed {
            let mut probe: Vec<T> = f[..self.grid_len()].to_vec();
            unsafe {
                T::commit_sph(
                    probe.as_mut_ptr(),
                    &mut self.h1,
                    &mut self.h2,
                    self.ipar.as_mut_ptr(),
                    self.dpar.as_mut_ptr(),
                    &mut stat,
                );
            }
            check_tr(stat)?;
            self.committed = true;
        }
        unsafe {
            T::solve_sph(
                f.as_mut_ptr(),
                &mut self.h1,
                &mut self.h2,
                self.ipar.as_mut_ptr(),
                self.dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)
    }
}

impl<T: HelmholtzScalar> Drop for SphericalHelmholtz<T> {
    fn drop(&mut self) {
        if self.h1.is_null() && self.h2.is_null() {
            return;
        }
        let mut stat: c_int = 0;
        unsafe {
            sys::free_sph_p(
                &mut self.h1,
                &mut self.h2,
                self.ipar.as_mut_ptr(),
                &mut stat,
            );
        }
    }
}

/// Helmholtz solver `Δ_S u − q·u = F` on a patch of the sphere surface,
/// `φ ∈ [ap, bp]`, `θ ∈ [at, bt]` with `0 < at < bt < π` (no pole), with
/// Dirichlet data on all four sides, wrapping MKL's non-periodic spherical
/// solver (`?_sph_np`).
///
/// Node `(i, j)` (`φ = ap + (bp−ap)·i/np`, `θ = at + (bt−at)·j/nt`) is
/// `f[i + j*(np+1)]`. On entry the interior nodes hold `F` and the boundary
/// nodes (`i = 0`, `i = np`, `j = 0`, `j = nt`) hold the Dirichlet data `g`;
/// on exit the interior holds `u` and the boundary is unchanged.
///
/// **Measured MKL behaviour** (oneMKL 2026.2.1, Linux x86_64, LP64): argument
/// order `(ap, bp, at, bt)`; the interior block (`1 ≤ i < np`, `1 ≤ j < nt`)
/// of the solver matrix is the inverse of
/// `hθ²·sinθⱼ·q + (sₚ + sₘ)` on the diagonal, `−sₚ`/`−sₘ` to the θ
/// neighbours (`sₚ`, `sₘ` the averaged node sines at `θⱼ ± hθ/2`) and
/// `2hθ²/(sinθⱼ·hφ²)` on the diagonal / `−hθ²/(sinθⱼ·hφ²)` to the φ
/// neighbours (agreement with a dense model 1e-15 on 2 domains at
/// np = 6, nt = 4). MKL treats the boundary rows and columns as decoupled
/// lines carrying no usable boundary condition (`j = 0, nt` pass `f`
/// through; `i = 0, np` are solved as θ-only problems), so the wrapper moves
/// the Dirichlet data into the right-hand side itself and never uses MKL's
/// boundary output. The mapping is `f = −hθ²·sinθⱼ·F` plus that lift.
pub struct SphericalPatchHelmholtz<T: HelmholtzScalar> {
    h: DFTI_DESCRIPTOR_HANDLE,
    ipar: Vec<c_int>,
    dpar: Vec<T>,
    np: usize,
    nt: usize,
    hp: f64,
    ht: f64,
    at: f64,
    committed: bool,
}

unsafe impl<T: HelmholtzScalar + Send> Send for SphericalPatchHelmholtz<T> {}

impl<T: HelmholtzScalar> SphericalPatchHelmholtz<T> {
    /// Build a solver for the patch `[ap, bp] × [at, bt]` with `np` × `nt`
    /// intervals (`np ≥ 2`, `nt ≥ 2`, `0 < at < bt < π`, `ap < bp`).
    pub fn new(ap: f64, bp: f64, at: f64, bt: f64, np: usize, nt: usize, q: T) -> Result<Self> {
        if np < 2 || nt < 2 {
            return Err(Error::InvalidArgument("np and nt must be at least 2"));
        }
        if ap.partial_cmp(&bp) != Some(core::cmp::Ordering::Less)
            || !(0.0 < at && at < bt && bt < core::f64::consts::PI)
        {
            return Err(Error::InvalidArgument("need ap < bp and 0 < at < bt < pi"));
        }
        let np_i: c_int = np.try_into().map_err(|_| Error::DimensionOverflow)?;
        let nt_i: c_int = nt.try_into().map_err(|_| Error::DimensionOverflow)?;
        let lim = [
            T::from_f64(ap),
            T::from_f64(bp),
            T::from_f64(at),
            T::from_f64(bt),
        ];
        let mut ipar: Vec<c_int> = vec![0; 128];
        let mut dpar: Vec<T> = vec![T::default(); 4 * (5 * np / 2 + nt + 10) + 200];
        let mut stat: c_int = 0;
        unsafe {
            T::init_sph_np(
                [&lim[0], &lim[1], &lim[2], &lim[3]],
                &np_i,
                &nt_i,
                &q,
                ipar.as_mut_ptr(),
                dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        Ok(Self {
            h: ptr::null_mut(),
            ipar,
            dpar,
            np,
            nt,
            hp: (bp - ap) / np as f64,
            ht: (bt - at) / nt as f64,
            at,
            committed: false,
        })
    }

    /// Required grid length, `(np + 1) * (nt + 1)`.
    #[must_use]
    pub fn grid_len(&self) -> usize {
        (self.np + 1) * (self.nt + 1)
    }

    /// Solve in place (see the type docs for what `f` holds on entry / exit).
    pub fn solve(&mut self, f: &mut [T]) -> Result<()> {
        if f.len() < self.grid_len() {
            return Err(Error::InvalidArgument("grid buffer too small"));
        }
        let (np, nt) = (self.np, self.nt);
        let w = np + 1;
        let (hp, ht) = (self.hp, self.ht);
        let sin_at = |j: usize| (self.at + j as f64 * ht).sin();
        let g: Vec<f64> = f[..self.grid_len()].iter().map(|v| v.to_f64()).collect();
        let mut rhs = vec![T::default(); self.grid_len()];
        for j in 1..nt {
            let sj = sin_at(j);
            let sp = 0.5 * (sj + sin_at(j + 1));
            let sm = 0.5 * (sj + sin_at(j - 1));
            let c = ht * ht / (sj * hp * hp);
            for i in 1..np {
                let mut v = -ht * ht * sj * g[i + j * w];
                if j == 1 {
                    v += sm * g[i];
                }
                if j == nt - 1 {
                    v += sp * g[i + nt * w];
                }
                if i == 1 {
                    v += c * g[j * w];
                }
                if i == np - 1 {
                    v += c * g[np + j * w];
                }
                rhs[i + j * w] = T::from_f64(v);
            }
        }
        let mut stat: c_int = 0;
        if !self.committed {
            let mut probe = rhs.clone();
            unsafe {
                T::commit_sph_np(
                    probe.as_mut_ptr(),
                    &mut self.h,
                    self.ipar.as_mut_ptr(),
                    self.dpar.as_mut_ptr(),
                    &mut stat,
                );
            }
            check_tr(stat)?;
            self.committed = true;
        }
        unsafe {
            T::solve_sph_np(
                rhs.as_mut_ptr(),
                &mut self.h,
                self.ipar.as_mut_ptr(),
                self.dpar.as_mut_ptr(),
                &mut stat,
            );
        }
        check_tr(stat)?;
        for j in 1..nt {
            for i in 1..np {
                f[i + j * w] = rhs[i + j * w];
            }
        }
        Ok(())
    }
}

impl<T: HelmholtzScalar> Drop for SphericalPatchHelmholtz<T> {
    fn drop(&mut self) {
        if self.h.is_null() {
            return;
        }
        let mut stat: c_int = 0;
        unsafe { T::free_sph_np(&mut self.h, self.ipar.as_mut_ptr(), &mut stat) };
    }
}