copp 0.2.1

Convex-objective path parameterization for robotic trajectory planning.
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
//! Python object wrappers for path construction and path evaluation.
//!
//! The Rust path API uses [`DMatrix`] in `(dim, n_samples)` layout. This module
//! exposes a Python-friendly facade with explicit [`PyMatrixLayout`] conversion,
//! [`PySplineConfig`] ownership, and [`PyPathDerivatives`] result objects.

use crate::diag::PathError;
use crate::ffi::python::array::{array_like_to_vec_f64, array_like_to_vec2_f64};
use crate::ffi::python::error::to_py_err;
use crate::path::{
    OutOfRangeMode as RustOutOfRangeMode, Parametrization as RustParametrization, Path as RustPath,
    PathEvaluator2nd, PathEvaluator3rd, SplineConfig as RustSplineConfig,
};
use nalgebra::DMatrix;
use numpy::{PyArray1, PyArray2, PyArrayMethods};
use pyo3::Borrowed;
use pyo3::exceptions::{PyAttributeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyAnyMethods, PyTuple, PyTupleMethods};
use std::sync::{Arc, Mutex};

/// Register path-related classes on the native [`PyModule`].
pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyOutOfRangeMode>()?;
    m.add_class::<PyParametrization>()?;
    m.add_class::<PyMatrixLayout>()?;
    m.add_class::<PySplineConfig>()?;
    m.add_class::<PyPathDerivatives>()?;
    m.add_class::<PyPath>()?;
    Ok(())
}

/// Python enum mirroring [`RustOutOfRangeMode`].
#[pyclass(
    name = "OutOfRangeMode",
    module = "copp_py._native",
    eq,
    eq_int,
    rename_all = "SCREAMING_SNAKE_CASE",
    from_py_object
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PyOutOfRangeMode {
    /// Reject out-of-range path parameters with a core [`crate::diag::PathError`].
    Error,
    /// Clamp out-of-range path parameters into the configured path range.
    Clamp,
}

impl PyOutOfRangeMode {
    /// Convert the Python wrapper enum into [`RustOutOfRangeMode`].
    fn to_rust(self) -> RustOutOfRangeMode {
        match self {
            Self::Error => RustOutOfRangeMode::Error,
            Self::Clamp => RustOutOfRangeMode::Clamp,
        }
    }
}

/// Python enum mirroring [`RustParametrization`].
#[pyclass(
    name = "Parametrization",
    module = "copp_py._native",
    eq,
    eq_int,
    rename_all = "SCREAMING_SNAKE_CASE",
    from_py_object
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PyParametrization {
    /// Uniformly distribute waypoints over the configured path range.
    Uniform,
}

impl PyParametrization {
    /// Convert the Python wrapper enum into [`RustParametrization`].
    fn to_rust(self) -> RustParametrization {
        match self {
            Self::Uniform => RustParametrization::Uniform,
        }
    }
}

/// Matrix layout contract used by Python path inputs and outputs.
#[pyclass(
    name = "MatrixLayout",
    module = "copp_py._native",
    eq,
    eq_int,
    rename_all = "SCREAMING_SNAKE_CASE",
    from_py_object
)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PyMatrixLayout {
    /// Python-style layout: rows are samples/waypoints, columns are dimensions.
    SampleMajor,
    /// Dimension-major layout: rows are dimensions, columns are samples/waypoints.
    DimMajor,
}

/// Internal parser for `OutOfRangeMode | str | None` Python arguments.
#[derive(Clone, Copy)]
struct OutOfRangeArg(
    /// Parsed out-of-range mode used by [`pyo3`] method arguments.
    PyOutOfRangeMode,
);

impl FromPyObject<'_, '_> for OutOfRangeArg {
    /// [`PyErr`] returned when parsing fails.
    type Error = PyErr;

    /// Parse enum values, accepted strings, or `None` into an out-of-range mode.
    fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
        if obj.is_none() {
            return Ok(Self(PyOutOfRangeMode::Error));
        }

        if let Ok(mode) = obj.extract::<PyOutOfRangeMode>() {
            return Ok(Self(mode));
        }

        if let Ok(text) = obj.extract::<&str>() {
            return match normalize_token(text).as_str() {
                "error" => Ok(Self(PyOutOfRangeMode::Error)),
                "clamp" => Ok(Self(PyOutOfRangeMode::Clamp)),
                _ => Err(PyValueError::new_err(
                    "`out_of_range` must be OutOfRangeMode.ERROR, OutOfRangeMode.CLAMP, \"error\", or \"clamp\"",
                )),
            };
        }

        Err(PyValueError::new_err(
            "`out_of_range` must be an OutOfRangeMode value or a string",
        ))
    }
}

/// Internal parser for `Parametrization | str | None` Python arguments.
#[derive(Clone, Copy)]
struct ParametrizationArg(
    /// Parsed waypoint parametrization used by [`pyo3`] method arguments.
    PyParametrization,
);

impl FromPyObject<'_, '_> for ParametrizationArg {
    /// [`PyErr`] returned when parsing fails.
    type Error = PyErr;

    /// Parse enum values, accepted strings, or `None` into a parametrization.
    fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
        if obj.is_none() {
            return Ok(Self(PyParametrization::Uniform));
        }

        if let Ok(parametrization) = obj.extract::<PyParametrization>() {
            return Ok(Self(parametrization));
        }

        if let Ok(text) = obj.extract::<&str>() {
            return match normalize_token(text).as_str() {
                "uniform" => Ok(Self(PyParametrization::Uniform)),
                _ => Err(PyValueError::new_err(
                    "`parametrization` must be Parametrization.UNIFORM or \"uniform\"",
                )),
            };
        }

        Err(PyValueError::new_err(
            "`parametrization` must be a Parametrization value or a string",
        ))
    }
}

/// Internal parser for `MatrixLayout | str | None` Python arguments.
#[derive(Clone, Copy)]
struct MatrixLayoutArg(
    /// Parsed matrix layout used by [`pyo3`] method arguments.
    PyMatrixLayout,
);

impl FromPyObject<'_, '_> for MatrixLayoutArg {
    /// [`PyErr`] returned when parsing fails.
    type Error = PyErr;

    /// Parse enum values, accepted strings, or `None` into a matrix layout.
    fn extract(obj: Borrowed<'_, '_, PyAny>) -> Result<Self, Self::Error> {
        if obj.is_none() {
            return Ok(Self(PyMatrixLayout::SampleMajor));
        }

        if let Ok(layout) = obj.extract::<PyMatrixLayout>() {
            return Ok(Self(layout));
        }

        if let Ok(text) = obj.extract::<&str>() {
            return match normalize_token(text).as_str() {
                "sample_major" | "samplemajor" => Ok(Self(PyMatrixLayout::SampleMajor)),
                "dim_major" | "dimmajor" => Ok(Self(PyMatrixLayout::DimMajor)),
                _ => Err(PyValueError::new_err(
                    "`layout` must be MatrixLayout.SAMPLE_MAJOR, MatrixLayout.DIM_MAJOR, \"sample_major\", or \"dim_major\"",
                )),
            };
        }

        Err(PyValueError::new_err(
            "`layout` must be a MatrixLayout value or a string",
        ))
    }
}

/// Python-owned waypoint spline configuration backed by [`RustSplineConfig`].
#[pyclass(name = "SplineConfig", module = "copp_py._native")]
pub(crate) struct PySplineConfig {
    /// Odd spline order, at least 3 when passed to the Rust core.
    order: usize,
    /// Waypoint parameter assignment policy.
    parametrization: PyParametrization,
    /// Lower endpoint of the path parameter range.
    s_min: f64,
    /// Upper endpoint of the path parameter range.
    s_max: f64,
    /// Runtime behavior for path evaluation outside `[s_min, s_max]`.
    out_of_range: PyOutOfRangeMode,
    /// Optional endpoint derivative [`DMatrix`] at `s_min`, shape `(dim, m)`.
    start_state: Option<DMatrix<f64>>,
    /// Optional endpoint derivative [`DMatrix`] at `s_max`, shape `(dim, m)`.
    end_state: Option<DMatrix<f64>>,
}

#[pymethods]
impl PySplineConfig {
    /// Configuration for waypoint-spline path construction.
    ///
    /// Parameters
    /// ----------
    /// order : int, default=5
    ///     Odd spline order, at least 3. Common values are 3, 5, and 7.
    /// s_min : float, default=0.0
    ///     Lower endpoint of the path parameter range.
    /// s_max : float, default=1.0
    ///     Upper endpoint of the path parameter range. Must be greater than
    ///     ``s_min`` when building a path.
    /// out_of_range : OutOfRangeMode | str, default=OutOfRangeMode.ERROR
    ///     Behavior when evaluating outside ``[s_min, s_max]``. Strings
    ///     ``"error"`` and ``"clamp"`` are accepted for convenience.
    /// parametrization : Parametrization | str, default=Parametrization.UNIFORM
    ///     Waypoint parameter assignment policy. Only uniform spacing is
    ///     currently supported.
    /// start_state, end_state : ArrayLike | None
    ///     Optional boundary derivative matrices convertible to float64 with shape
    ///     ``(dim, (order - 1) // 2)``. ``None`` means zero endpoint
    ///     derivatives.
    #[new]
    #[pyo3(
        signature = (*, order = 5, s_min = 0.0, s_max = 1.0, out_of_range = OutOfRangeArg(PyOutOfRangeMode::Error), parametrization = ParametrizationArg(PyParametrization::Uniform), start_state = None, end_state = None),
        text_signature = "(*, order=5, s_min=0.0, s_max=1.0, out_of_range='error', parametrization='uniform', start_state=None, end_state=None)"
    )]
    fn new<'py>(
        order: usize,
        s_min: f64,
        s_max: f64,
        out_of_range: OutOfRangeArg,
        parametrization: ParametrizationArg,
        start_state: Option<&Bound<'py, PyAny>>,
        end_state: Option<&Bound<'py, PyAny>>,
    ) -> PyResult<Self> {
        Ok(Self {
            order,
            parametrization: parametrization.0,
            s_min,
            s_max,
            out_of_range: out_of_range.0,
            start_state: optional_boundary_matrix("start_state", start_state)?,
            end_state: optional_boundary_matrix("end_state", end_state)?,
        })
    }

    /// Return the spline order stored in this Python config object.
    #[getter]
    fn order(&self) -> usize {
        self.order
    }

    /// Set the spline order without validating core-level spline constraints.
    ///
    /// The Rust core validates oddness and minimum order when a [`RustPath`] is
    /// constructed, keeping setter behavior lightweight and Pythonic.
    #[setter]
    fn set_order(&mut self, order: usize) {
        self.order = order;
    }

    /// Return the lower endpoint of the path parameter range.
    #[getter]
    fn s_min(&self) -> f64 {
        self.s_min
    }

    /// Set the lower endpoint of the path parameter range.
    #[setter]
    fn set_s_min(&mut self, s_min: f64) {
        self.s_min = s_min;
    }

    /// Return the upper endpoint of the path parameter range.
    #[getter]
    fn s_max(&self) -> f64 {
        self.s_max
    }

    /// Set the upper endpoint of the path parameter range.
    #[setter]
    fn set_s_max(&mut self, s_max: f64) {
        self.s_max = s_max;
    }

    /// Return the out-of-range evaluation policy.
    #[getter]
    fn out_of_range(&self) -> PyOutOfRangeMode {
        self.out_of_range
    }

    /// Set the out-of-range evaluation policy from an enum value or string.
    #[setter]
    fn set_out_of_range(&mut self, value: &Bound<'_, PyAny>) -> PyResult<()> {
        self.out_of_range = parse_out_of_range(value)?;
        Ok(())
    }

    /// Return the waypoint parametrization policy.
    #[getter]
    fn parametrization(&self) -> PyParametrization {
        self.parametrization
    }

    /// Set the waypoint parametrization policy from an enum value or string.
    #[setter]
    fn set_parametrization(&mut self, value: &Bound<'_, PyAny>) -> PyResult<()> {
        self.parametrization = parse_parametrization(value)?;
        Ok(())
    }

    /// Return a copy of the start boundary derivative matrix, if present.
    #[getter]
    fn start_state<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyArray2<f64>>>> {
        optional_boundary_matrix_to_pyarray2(py, self.start_state.as_ref())
    }

    /// Set or clear the start boundary derivative matrix.
    #[setter]
    fn set_start_state(&mut self, value: &Bound<'_, PyAny>) -> PyResult<()> {
        self.start_state = parse_optional_boundary_value("start_state", value)?;
        Ok(())
    }

    /// Return a copy of the end boundary derivative matrix, if present.
    #[getter]
    fn end_state<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyArray2<f64>>>> {
        optional_boundary_matrix_to_pyarray2(py, self.end_state.as_ref())
    }

    /// Set or clear the end boundary derivative matrix.
    #[setter]
    fn set_end_state(&mut self, value: &Bound<'_, PyAny>) -> PyResult<()> {
        self.end_state = parse_optional_boundary_value("end_state", value)?;
        Ok(())
    }

    /// Return a compact representation for interactive Python sessions.
    fn __repr__(&self) -> String {
        format!(
            "SplineConfig(order={}, s_min={}, s_max={}, out_of_range={:?}, parametrization={:?})",
            self.order, self.s_min, self.s_max, self.out_of_range, self.parametrization
        )
    }
}

impl PySplineConfig {
    /// Convert the owned Python configuration into [`RustSplineConfig`].
    fn to_rust(&self) -> RustSplineConfig {
        RustSplineConfig {
            order: self.order,
            parametrization: self.parametrization.to_rust(),
            s_min: self.s_min,
            s_max: self.s_max,
            out_of_range_mode: self.out_of_range.to_rust(),
            start_state: self.start_state.clone(),
            end_state: self.end_state.clone(),
        }
    }
}

/// Python-visible path evaluation result container.
#[pyclass(name = "PathDerivatives", module = "copp_py._native")]
pub(crate) struct PyPathDerivatives {
    /// Position samples as a [`PyArray2`] in the path's selected output layout.
    #[pyo3(get)]
    q: Py<PyArray2<f64>>,
    /// First derivative samples, or `None` when not requested.
    #[pyo3(get)]
    dq: Option<Py<PyArray2<f64>>>,
    /// Second derivative samples, or `None` when not requested.
    #[pyo3(get)]
    ddq: Option<Py<PyArray2<f64>>>,
    /// Third derivative samples, or `None` when not requested.
    #[pyo3(get)]
    dddq: Option<Py<PyArray2<f64>>>,
}

#[pymethods]
impl PyPathDerivatives {
    /// Return a compact representation without printing array contents.
    fn __repr__(&self) -> &'static str {
        "PathDerivatives(q=<numpy.ndarray>, dq=..., ddq=..., dddq=...)"
    }
}

/// Python-owned wrapper around the Rust [`RustPath`] object.
#[pyclass(name = "Path", module = "copp_py._native")]
pub(crate) struct PyPath {
    /// The core [`RustPath`] object that owns spline/evaluator data.
    inner: RustPath,
    /// Preferred Python matrix layout for inputs and derivative outputs.
    layout: PyMatrixLayout,
    /// Shared Python callback state for evaluator-backed paths.
    callback_state: Option<Arc<PyCallbackState>>,
}

#[pymethods]
impl PyPath {
    /// Build a waypoint spline path.
    ///
    /// Parameters
    /// ----------
    /// waypoints : ArrayLike
    ///     Waypoint matrix convertible to float64. With the default
    ///     ``MatrixLayout.SAMPLE_MAJOR``, shape is ``(n_points, dim)`` and
    ///     each row is one waypoint. With ``MatrixLayout.DIM_MAJOR``, shape is
    ///     ``(dim, n_points)`` and each column is one waypoint.
    /// config : SplineConfig | None, default=None
    ///     Spline construction options. When omitted, keyword arguments build
    ///     an equivalent temporary ``SplineConfig``.
    /// order : int, default=5
    ///     Odd spline order used only when ``config`` is omitted.
    /// s_min, s_max : float, default=0.0, 1.0
    ///     Path-parameter range used only when ``config`` is omitted.
    /// out_of_range : OutOfRangeMode | str, default=OutOfRangeMode.ERROR
    ///     Out-of-range policy used only when ``config`` is omitted.
    /// parametrization : Parametrization | str, default=Parametrization.UNIFORM
    ///     Waypoint parameter assignment used only when ``config`` is omitted.
    /// start_state, end_state : ArrayLike | None
    ///     Boundary derivative matrices used only when ``config`` is omitted.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout for both input waypoints and returned derivative
    ///     arrays. Strings ``"sample_major"`` and ``"dim_major"`` are
    ///     accepted for convenience.
    ///
    /// Returns
    /// -------
    /// Path
    ///     A Python-owned wrapper around the Rust path object.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If array layout, dtype, wrapper-level options, or mixed
    ///     ``config``/keyword options are invalid.
    /// CoppError
    ///     If the Rust COPP core rejects the path data or spline options.
    #[staticmethod]
    #[pyo3(
        signature = (waypoints, config = None, *, order = 5, s_min = 0.0, s_max = 1.0, out_of_range = OutOfRangeArg(PyOutOfRangeMode::Error), parametrization = ParametrizationArg(PyParametrization::Uniform), start_state = None, end_state = None, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(waypoints, config=None, *, order=5, s_min=0.0, s_max=1.0, out_of_range='error', parametrization='uniform', start_state=None, end_state=None, layout='sample_major')"
    )]
    fn from_waypoints<'py>(
        waypoints: &Bound<'py, PyAny>,
        config: Option<PyRef<'py, PySplineConfig>>,
        order: usize,
        s_min: f64,
        s_max: f64,
        out_of_range: OutOfRangeArg,
        parametrization: ParametrizationArg,
        start_state: Option<&Bound<'py, PyAny>>,
        end_state: Option<&Bound<'py, PyAny>>,
        layout: MatrixLayoutArg,
    ) -> PyResult<Self> {
        let layout = layout.0;
        let waypoints = waypoints_to_dmatrix("waypoints", waypoints, layout)?;
        let direct_config = PySplineConfig {
            order,
            parametrization: parametrization.0,
            s_min,
            s_max,
            out_of_range: out_of_range.0,
            start_state: optional_boundary_matrix("start_state", start_state)?,
            end_state: optional_boundary_matrix("end_state", end_state)?,
        };
        let config = match config {
            Some(config) => {
                ensure_default_direct_config(&direct_config)?;
                config.to_rust()
            }
            None => direct_config.to_rust(),
        };
        let inner = RustPath::from_waypoints(&waypoints, config)
            .map_err(|error| to_py_err(error.into()))?;
        Ok(Self {
            inner,
            layout,
            callback_state: None,
        })
    }

    /// Build a path from a Python evaluator object with derivatives up to second order.
    ///
    /// Parameters
    /// ----------
    /// evaluator : object
    ///     Python object implementing the evaluator protocol. It must provide
    ///     ``dim`` as an integer attribute or zero-argument method, and
    ///     ``evaluate_up_to_2nd(s) -> (q, dq, ddq)``. ``evaluate_q(s) -> q``
    ///     is optional and is used when available.
    /// s_min, s_max : float
    ///     Valid path-parameter range. Evaluator-backed paths currently match
    ///     the Rust API and reject out-of-range queries.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout expected from callback return arrays and used for
    ///     returned derivative arrays.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If the evaluator protocol or callback return arrays are invalid.
    /// CoppError
    ///     If the Rust COPP core rejects the path range or evaluator dimension.
    /// Exception
    ///     Any exception raised by the Python evaluator callback is propagated
    ///     unchanged.
    #[staticmethod]
    #[pyo3(
        signature = (evaluator, s_min, s_max, *, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(evaluator, s_min, s_max, *, layout='sample_major')"
    )]
    fn from_evaluator_2nd(
        py: Python<'_>,
        evaluator: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Self> {
        let (dim, has_evaluate_q) = {
            let evaluator_bound = evaluator.bind(py);
            let dim = evaluator_dim(evaluator_bound)?;
            ensure_evaluator_method(evaluator_bound, "evaluate_up_to_2nd", "from_evaluator_2nd")?;
            (
                dim,
                has_callable_evaluator_method(evaluator_bound, "evaluate_q")?,
            )
        };
        let state = Arc::new(PyCallbackState::new(
            evaluator,
            dim,
            layout.0,
            has_evaluate_q,
            true,
        ));
        let inner = RustPath::from_evaluator_2nd(
            PyCallbackPathEvaluator2nd {
                state: Arc::clone(&state),
            },
            s_min,
            s_max,
        )
        .map_err(|error| to_py_err(error.into()))?;

        Ok(Self {
            inner,
            layout: layout.0,
            callback_state: Some(state),
        })
    }

    /// Build a path from a Python evaluator object with derivatives up to third order.
    ///
    /// Parameters
    /// ----------
    /// evaluator : object
    ///     Python object implementing the evaluator protocol. It must provide
    ///     ``dim`` as an integer attribute or zero-argument method, and
    ///     ``evaluate_up_to_3rd(s) -> (q, dq, ddq, dddq)``. ``evaluate_q`` and
    ///     ``evaluate_up_to_2nd`` are optional. If ``evaluate_up_to_2nd`` is
    ///     omitted, second-order evaluation calls ``evaluate_up_to_3rd`` and
    ///     discards ``dddq``; this is supported for convenience but not
    ///     recommended for performance-sensitive code.
    /// s_min, s_max : float
    ///     Valid path-parameter range. Evaluator-backed paths currently match
    ///     the Rust API and reject out-of-range queries.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout expected from callback return arrays and used for
    ///     returned derivative arrays.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If the evaluator protocol or callback return arrays are invalid.
    /// CoppError
    ///     If the Rust COPP core rejects the path range or evaluator dimension.
    /// Exception
    ///     Any exception raised by the Python evaluator callback is propagated
    ///     unchanged.
    #[staticmethod]
    #[pyo3(
        signature = (evaluator, s_min, s_max, *, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(evaluator, s_min, s_max, *, layout='sample_major')"
    )]
    fn from_evaluator_3rd(
        py: Python<'_>,
        evaluator: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Self> {
        let (dim, has_evaluate_q, has_evaluate_up_to_2nd) = {
            let evaluator_bound = evaluator.bind(py);
            let dim = evaluator_dim(evaluator_bound)?;
            ensure_evaluator_method(evaluator_bound, "evaluate_up_to_3rd", "from_evaluator_3rd")?;
            (
                dim,
                has_callable_evaluator_method(evaluator_bound, "evaluate_q")?,
                has_callable_evaluator_method(evaluator_bound, "evaluate_up_to_2nd")?,
            )
        };
        let state = Arc::new(PyCallbackState::new(
            evaluator,
            dim,
            layout.0,
            has_evaluate_q,
            has_evaluate_up_to_2nd,
        ));
        let inner = RustPath::from_evaluator_3rd(
            PyCallbackPathEvaluator3rd {
                state: Arc::clone(&state),
            },
            s_min,
            s_max,
        )
        .map_err(|error| to_py_err(error.into()))?;

        Ok(Self {
            inner,
            layout: layout.0,
            callback_state: Some(state),
        })
    }

    /// Compatibility alias for ``Path.from_evaluator_3rd``.
    ///
    /// New Python code should prefer ``from_evaluator_2nd`` or
    /// ``from_evaluator_3rd`` so the supported derivative order is explicit.
    #[staticmethod]
    #[pyo3(
        signature = (evaluator, s_min, s_max, *, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(evaluator, s_min, s_max, *, layout='sample_major')"
    )]
    fn from_evaluator(
        py: Python<'_>,
        evaluator: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Self> {
        Self::from_evaluator_3rd(py, evaluator, s_min, s_max, layout)
    }

    /// Build a path from a scalar-parametric Python callable using JAX.
    ///
    /// This convenience constructor lives in the Python facade layer. It lazily
    /// imports `copp_py._parametric`, builds a JAX-backed Python evaluator
    /// object, and delegates to [`Self::from_evaluator_3rd`]. The Rust core
    /// still receives the same [`PathEvaluator3rd`] protocol as explicit
    /// evaluator-backed paths.
    ///
    /// Parameters
    /// ----------
    /// q_fn : callable
    ///     Scalar-parametric function `q_fn(s)` returning one path vector.
    ///     The function should use `jax.numpy` operations so JAX can trace it.
    /// s_min, s_max : float
    ///     Valid path-parameter range. Parametric paths currently match the
    ///     Rust evaluator API and reject out-of-range queries.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout used for returned derivative arrays.
    /// jit : bool, default=True
    ///     JIT-compile the JAX batched evaluator.
    /// require_x64 : bool, default=True
    ///     Require JAX 64-bit mode before constructing the path.
    ///
    /// Raises
    /// ------
    /// ImportError
    ///     If the selected optional dependency is not installed.
    /// ValueError
    ///     If the callback output or JAX configuration is invalid.
    #[staticmethod]
    #[pyo3(
        signature = (q_fn, s_min, s_max, *, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor), jit = true, require_x64 = true),
        text_signature = "(q_fn, s_min, s_max, *, layout='sample_major', jit=True, require_x64=True)"
    )]
    fn from_jax(
        py: Python<'_>,
        q_fn: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
        jit: bool,
        require_x64: bool,
    ) -> PyResult<Py<PyAny>> {
        let helper = py.import("copp_py._parametric")?.getattr("_from_jax")?;
        Ok(helper
            .call1((q_fn, s_min, s_max, layout_token(layout.0), jit, require_x64))?
            .unbind())
    }

    /// Build a path from a scalar-parametric Python callable using Autograd.
    ///
    /// This is the lightweight Python AD alternative to [`Self::from_jax`].
    /// The Autograd dependency is imported lazily only when this constructor is
    /// called.
    ///
    /// Parameters
    /// ----------
    /// q_fn : callable
    ///     Scalar-parametric function `q_fn(s)` returning one path vector.
    ///     The function should use `autograd.numpy` operations so Autograd can
    ///     trace it.
    /// s_min, s_max : float
    ///     Valid path-parameter range. Autograd-backed paths currently match
    ///     the Rust evaluator API and reject out-of-range queries.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout used for returned derivative arrays.
    ///
    /// Raises
    /// ------
    /// ImportError
    ///     If Autograd is not installed.
    /// ValueError
    ///     If the callback output is invalid.
    #[staticmethod]
    #[pyo3(
        signature = (q_fn, s_min, s_max, *, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(q_fn, s_min, s_max, *, layout='sample_major')"
    )]
    fn from_autograd(
        py: Python<'_>,
        q_fn: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Py<PyAny>> {
        let helper = py
            .import("copp_py._parametric")?
            .getattr("_from_autograd")?;
        Ok(helper
            .call1((q_fn, s_min, s_max, layout_token(layout.0)))?
            .unbind())
    }

    /// Build a path from a scalar-parameter CasADi expression.
    ///
    /// The expression is converted to a Python evaluator by
    /// `copp_py._parametric` and then delegated to [`Self::from_evaluator_3rd`].
    /// This keeps CasADi optional and outside the Rust dependency graph.
    ///
    /// Parameters
    /// ----------
    /// q_expr : casadi.SX | casadi.MX | sequence
    ///     Vector expression for the path position.
    /// symbol : casadi.SX | casadi.MX
    ///     Scalar path parameter used to differentiate `q_expr`.
    /// s_min, s_max : float, default=0.0, 1.0
    ///     Valid path-parameter range.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout used for returned derivative arrays.
    #[staticmethod]
    #[pyo3(
        signature = (q_expr, *, symbol, s_min = 0.0, s_max = 1.0, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(q_expr, *, symbol, s_min=0.0, s_max=1.0, layout='sample_major')"
    )]
    fn from_casadi(
        py: Python<'_>,
        q_expr: Py<PyAny>,
        symbol: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Py<PyAny>> {
        let helper = py.import("copp_py._parametric")?.getattr("_from_casadi")?;
        Ok(helper
            .call1((q_expr, symbol, s_min, s_max, layout_token(layout.0)))?
            .unbind())
    }

    /// Build a path from scalar-parameter SymPy expressions.
    ///
    /// The SymPy expressions are differentiated in Python and wrapped as a
    /// [`PathEvaluator3rd`] object before entering the Rust core.
    ///
    /// Parameters
    /// ----------
    /// q_exprs : sympy.Expr | sequence | sympy.Matrix
    ///     Position expression or vector of position expressions.
    /// symbol : sympy.Symbol
    ///     Scalar path parameter used to differentiate `q_exprs`.
    /// s_min, s_max : float, default=0.0, 1.0
    ///     Valid path-parameter range.
    /// layout : MatrixLayout | str, default=MatrixLayout.SAMPLE_MAJOR
    ///     Matrix layout used for returned derivative arrays.
    #[staticmethod]
    #[pyo3(
        signature = (q_exprs, *, symbol, s_min = 0.0, s_max = 1.0, layout = MatrixLayoutArg(PyMatrixLayout::SampleMajor)),
        text_signature = "(q_exprs, *, symbol, s_min=0.0, s_max=1.0, layout='sample_major')"
    )]
    fn from_sympy(
        py: Python<'_>,
        q_exprs: Py<PyAny>,
        symbol: Py<PyAny>,
        s_min: f64,
        s_max: f64,
        layout: MatrixLayoutArg,
    ) -> PyResult<Py<PyAny>> {
        let helper = py.import("copp_py._parametric")?.getattr("_from_sympy")?;
        Ok(helper
            .call1((q_exprs, symbol, s_min, s_max, layout_token(layout.0)))?
            .unbind())
    }

    /// Return the number of path dimensions.
    #[getter]
    fn dim(&self) -> usize {
        self.inner.dim()
    }

    /// Return the inclusive valid path parameter range.
    #[getter]
    fn s_range(&self) -> (f64, f64) {
        self.inner.s_range()
    }

    /// Evaluate position ``q`` only at the query path parameters.
    ///
    /// Returns a ``PathDerivatives`` object whose ``q`` field is populated and
    /// whose derivative fields are ``None``.
    fn evaluate_q<'py>(
        &self,
        py: Python<'py>,
        s: &Bound<'py, PyAny>,
    ) -> PyResult<PyPathDerivatives> {
        let s = array_like_to_vec_f64("s", s)?;
        self.clear_callback_error();
        let out = self.map_path_error(self.inner.evaluate_q(&s))?;
        path_derivatives_to_python(py, out, self.layout)
    }

    /// Evaluate position, first derivative, and second derivative.
    ///
    /// Returns a ``PathDerivatives`` object with ``q``, ``dq``, and ``ddq``
    /// populated. ``dddq`` is ``None``.
    fn evaluate_up_to_2nd<'py>(
        &self,
        py: Python<'py>,
        s: &Bound<'py, PyAny>,
    ) -> PyResult<PyPathDerivatives> {
        let s = array_like_to_vec_f64("s", s)?;
        self.clear_callback_error();
        let out = self.map_path_error(self.inner.evaluate_up_to_2nd(&s))?;
        path_derivatives_to_python(py, out, self.layout)
    }

    /// Evaluate position and derivatives up to third order.
    ///
    /// Returns a ``PathDerivatives`` object with ``q``, ``dq``, ``ddq``, and
    /// ``dddq`` populated.
    fn evaluate_up_to_3rd<'py>(
        &self,
        py: Python<'py>,
        s: &Bound<'py, PyAny>,
    ) -> PyResult<PyPathDerivatives> {
        let s = array_like_to_vec_f64("s", s)?;
        self.clear_callback_error();
        let out = self.map_path_error(self.inner.evaluate_up_to_3rd(&s))?;
        path_derivatives_to_python(py, out, self.layout)
    }
}

impl PyPath {
    /// Evaluate up to second order for sibling Python FFI modules.
    ///
    /// This preserves pending Python callback exceptions from evaluator-backed
    /// paths while returning the Rust-owned derivative matrices needed by
    /// robot/constraint wrappers.
    pub(crate) fn evaluate_up_to_2nd_rust(
        &self,
        s: &[f64],
    ) -> PyResult<crate::path::PathDerivatives> {
        self.clear_callback_error();
        self.map_path_error(self.inner.evaluate_up_to_2nd(s))
    }

    /// Evaluate up to third order for sibling Python FFI modules.
    ///
    /// See [`Self::evaluate_up_to_2nd_rust`] for the callback-error handling
    /// contract.
    pub(crate) fn evaluate_up_to_3rd_rust(
        &self,
        s: &[f64],
    ) -> PyResult<crate::path::PathDerivatives> {
        self.clear_callback_error();
        self.map_path_error(self.inner.evaluate_up_to_3rd(s))
    }

    /// Clear stale Python callback errors before a new Rust core evaluation.
    fn clear_callback_error(&self) {
        if let Some(state) = &self.callback_state {
            state.clear_pending_error();
        }
    }

    /// Prefer a stored Python callback exception over the sentinel [`PathError`].
    fn map_path_error<T>(&self, result: Result<T, PathError>) -> PyResult<T> {
        result.map_err(|error| {
            if let Some(state) = &self.callback_state
                && let Some(py_err) = state.take_pending_error()
            {
                return py_err;
            }

            to_py_err(error.into())
        })
    }
}

/// Shared state for Python object evaluators stored inside [`RustPath`].
struct PyCallbackState {
    /// Python evaluator object implementing the path callback protocol.
    evaluator: Py<PyAny>,
    /// Stable evaluator dimension captured at construction time.
    dim: usize,
    /// Matrix layout expected from Python callback return arrays.
    layout: PyMatrixLayout,
    /// Whether the object provides an optimized `evaluate_q` method.
    has_evaluate_q: bool,
    /// Whether the object provides a second-order callback.
    has_evaluate_up_to_2nd: bool,
    /// Pending Python exception raised from inside a trait callback.
    pending_error: Mutex<Option<PyErr>>,
}

impl PyCallbackState {
    /// Construct callback state after the Python protocol has been validated.
    fn new(
        evaluator: Py<PyAny>,
        dim: usize,
        layout: PyMatrixLayout,
        has_evaluate_q: bool,
        has_evaluate_up_to_2nd: bool,
    ) -> Self {
        Self {
            evaluator,
            dim,
            layout,
            has_evaluate_q,
            has_evaluate_up_to_2nd,
            pending_error: Mutex::new(None),
        }
    }

    /// Store a Python exception and return the sentinel [`PathError`] for the Rust trait.
    fn store_error(&self, error: PyErr) -> PathError {
        *self
            .pending_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(error);
        PathError::DimensionMismatch
    }

    /// Remove any pending Python exception from an earlier callback.
    fn clear_pending_error(&self) {
        self.pending_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take();
    }

    /// Take the Python exception raised by the most recent callback, if any.
    fn take_pending_error(&self) -> Option<PyErr> {
        self.pending_error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take()
    }

    /// Call a Python method returning only `q` and copy it into the Rust buffer.
    fn call_evaluate_q(
        &self,
        method_name: &str,
        s: &[f64],
        q: &mut [f64],
    ) -> Result<(), PathError> {
        Python::attach(|py| -> PyResult<()> {
            let s_array = PyArray1::from_slice(py, s);
            let result = self
                .evaluator
                .bind(py)
                .call_method1(method_name, (&s_array,))?;
            let q_array = callback_array(method_name, "q", &result)?;
            copy_callback_matrix_to_buffer(method_name, "q", q_array, self, s.len(), q)
        })
        .map_err(|error| self.store_error(error))
    }

    /// Call a Python method returning `q`, `dq`, and `ddq`.
    fn call_evaluate_up_to_2nd(
        &self,
        method_name: &str,
        s: &[f64],
        q: &mut [f64],
        dq: &mut [f64],
        ddq: &mut [f64],
    ) -> Result<(), PathError> {
        Python::attach(|py| -> PyResult<()> {
            let s_array = PyArray1::from_slice(py, s);
            let result = self
                .evaluator
                .bind(py)
                .call_method1(method_name, (&s_array,))?;
            let tuple = callback_tuple(method_name, &result, 3)?;

            let q_item = tuple.get_item(0)?;
            let q_array = callback_array(method_name, "q", &q_item)?;
            copy_callback_matrix_to_buffer(method_name, "q", q_array, self, s.len(), q)?;

            let dq_item = tuple.get_item(1)?;
            let dq_array = callback_array(method_name, "dq", &dq_item)?;
            copy_callback_matrix_to_buffer(method_name, "dq", dq_array, self, s.len(), dq)?;

            let ddq_item = tuple.get_item(2)?;
            let ddq_array = callback_array(method_name, "ddq", &ddq_item)?;
            copy_callback_matrix_to_buffer(method_name, "ddq", ddq_array, self, s.len(), ddq)
        })
        .map_err(|error| self.store_error(error))
    }

    /// Call a Python method returning `q`, `dq`, `ddq`, and `dddq`.
    fn call_evaluate_up_to_3rd(
        &self,
        method_name: &str,
        s: &[f64],
        q: &mut [f64],
        dq: &mut [f64],
        ddq: &mut [f64],
        dddq: &mut [f64],
    ) -> Result<(), PathError> {
        Python::attach(|py| -> PyResult<()> {
            let s_array = PyArray1::from_slice(py, s);
            let result = self
                .evaluator
                .bind(py)
                .call_method1(method_name, (&s_array,))?;
            let tuple = callback_tuple(method_name, &result, 4)?;

            let q_item = tuple.get_item(0)?;
            let q_array = callback_array(method_name, "q", &q_item)?;
            copy_callback_matrix_to_buffer(method_name, "q", q_array, self, s.len(), q)?;

            let dq_item = tuple.get_item(1)?;
            let dq_array = callback_array(method_name, "dq", &dq_item)?;
            copy_callback_matrix_to_buffer(method_name, "dq", dq_array, self, s.len(), dq)?;

            let ddq_item = tuple.get_item(2)?;
            let ddq_array = callback_array(method_name, "ddq", &ddq_item)?;
            copy_callback_matrix_to_buffer(method_name, "ddq", ddq_array, self, s.len(), ddq)?;

            let dddq_item = tuple.get_item(3)?;
            let dddq_array = callback_array(method_name, "dddq", &dddq_item)?;
            copy_callback_matrix_to_buffer(method_name, "dddq", dddq_array, self, s.len(), dddq)
        })
        .map_err(|error| self.store_error(error))
    }
}

/// Python evaluator that supports explicit derivatives up to second order.
struct PyCallbackPathEvaluator2nd {
    /// Shared callback state and pending-error slot.
    state: Arc<PyCallbackState>,
}

impl PyCallbackPathEvaluator2nd {
    /// Check that Rust core output buffers match the stored evaluator dimension.
    fn check_output_len(&self, s: &[f64], buffers: &[&[f64]]) -> Result<(), PathError> {
        let expected = self.state.dim * s.len();
        if buffers.iter().any(|buffer| buffer.len() != expected) {
            return Err(PathError::DimensionMismatch);
        }
        Ok(())
    }
}

impl PathEvaluator2nd for PyCallbackPathEvaluator2nd {
    /// Return the evaluator dimension captured during Python construction.
    fn dim(&self) -> usize {
        self.state.dim
    }

    /// Evaluate `q`, using the optional Python shortcut when present.
    fn evaluate_q(&self, s: &[f64], q: &mut [f64]) -> Result<(), PathError> {
        self.check_output_len(s, &[q])?;
        if self.state.has_evaluate_q {
            self.state.call_evaluate_q("evaluate_q", s, q)
        } else {
            let mut dq = vec![0.0; q.len()];
            let mut ddq = vec![0.0; q.len()];
            self.evaluate_up_to_2nd(s, q, &mut dq, &mut ddq)
        }
    }

    /// Evaluate `q`, `dq`, and `ddq` through the required Python callback.
    fn evaluate_up_to_2nd(
        &self,
        s: &[f64],
        q: &mut [f64],
        dq: &mut [f64],
        ddq: &mut [f64],
    ) -> Result<(), PathError> {
        self.check_output_len(s, &[q, dq, ddq])?;
        self.state
            .call_evaluate_up_to_2nd("evaluate_up_to_2nd", s, q, dq, ddq)
    }
}

/// Python evaluator that supports explicit derivatives up to third order.
struct PyCallbackPathEvaluator3rd {
    /// Shared callback state and pending-error slot.
    state: Arc<PyCallbackState>,
}

impl PyCallbackPathEvaluator3rd {
    /// Check that Rust core output buffers match the stored evaluator dimension.
    fn check_output_len(&self, s: &[f64], buffers: &[&[f64]]) -> Result<(), PathError> {
        let expected = self.state.dim * s.len();
        if buffers.iter().any(|buffer| buffer.len() != expected) {
            return Err(PathError::DimensionMismatch);
        }
        Ok(())
    }
}

impl PathEvaluator2nd for PyCallbackPathEvaluator3rd {
    /// Return the evaluator dimension captured during Python construction.
    fn dim(&self) -> usize {
        self.state.dim
    }

    /// Evaluate `q`, falling back from `evaluate_q` to higher-order callbacks.
    fn evaluate_q(&self, s: &[f64], q: &mut [f64]) -> Result<(), PathError> {
        self.check_output_len(s, &[q])?;
        if self.state.has_evaluate_q {
            self.state.call_evaluate_q("evaluate_q", s, q)
        } else if self.state.has_evaluate_up_to_2nd {
            let mut dq = vec![0.0; q.len()];
            let mut ddq = vec![0.0; q.len()];
            self.evaluate_up_to_2nd(s, q, &mut dq, &mut ddq)
        } else {
            let mut dq = vec![0.0; q.len()];
            let mut ddq = vec![0.0; q.len()];
            let mut dddq = vec![0.0; q.len()];
            self.evaluate_up_to_3rd(s, q, &mut dq, &mut ddq, &mut dddq)
        }
    }

    /// Evaluate up to second order, optionally falling back to the third-order callback.
    fn evaluate_up_to_2nd(
        &self,
        s: &[f64],
        q: &mut [f64],
        dq: &mut [f64],
        ddq: &mut [f64],
    ) -> Result<(), PathError> {
        self.check_output_len(s, &[q, dq, ddq])?;
        if self.state.has_evaluate_up_to_2nd {
            self.state
                .call_evaluate_up_to_2nd("evaluate_up_to_2nd", s, q, dq, ddq)
        } else {
            let mut dddq = vec![0.0; q.len()];
            self.evaluate_up_to_3rd(s, q, dq, ddq, &mut dddq)
        }
    }
}

impl PathEvaluator3rd for PyCallbackPathEvaluator3rd {
    /// Evaluate all derivative orders through the required Python callback.
    fn evaluate_up_to_3rd(
        &self,
        s: &[f64],
        q: &mut [f64],
        dq: &mut [f64],
        ddq: &mut [f64],
        dddq: &mut [f64],
    ) -> Result<(), PathError> {
        self.check_output_len(s, &[q, dq, ddq, dddq])?;
        self.state
            .call_evaluate_up_to_3rd("evaluate_up_to_3rd", s, q, dq, ddq, dddq)
    }
}

/// Extract an evaluator dimension from a `dim` attribute or zero-argument method.
fn evaluator_dim(evaluator: &Bound<'_, PyAny>) -> PyResult<usize> {
    let dim_obj = evaluator.getattr("dim").map_err(|error| {
        if error.is_instance_of::<PyAttributeError>(evaluator.py()) {
            PyValueError::new_err(
                "path evaluator must define `dim` as a positive integer attribute or method",
            )
        } else {
            error
        }
    })?;
    let dim = if dim_obj.is_callable() {
        dim_obj.call0()?.extract::<usize>()?
    } else {
        dim_obj.extract::<usize>()?
    };

    if dim == 0 {
        return Err(PyValueError::new_err(
            "path evaluator `dim` must be a positive integer",
        ));
    }

    Ok(dim)
}

/// Ensure that a Python evaluator provides a required method.
fn ensure_evaluator_method(
    evaluator: &Bound<'_, PyAny>,
    method_name: &str,
    constructor_name: &str,
) -> PyResult<()> {
    if has_callable_evaluator_method(evaluator, method_name)? {
        Ok(())
    } else {
        Err(PyValueError::new_err(format!(
            "`Path.{constructor_name}` evaluator must define `{method_name}(s)`"
        )))
    }
}

/// Check whether an evaluator attribute exists and is callable.
fn has_callable_evaluator_method(
    evaluator: &Bound<'_, PyAny>,
    method_name: &str,
) -> PyResult<bool> {
    if !evaluator.hasattr(method_name)? {
        return Ok(false);
    }

    Ok(evaluator.getattr(method_name)?.is_callable())
}

/// Cast a callback return object to a fixed-length [`PyTuple`].
fn callback_tuple<'py>(
    method_name: &str,
    result: &'py Bound<'py, PyAny>,
    expected_len: usize,
) -> PyResult<&'py Bound<'py, PyTuple>> {
    let tuple = result.cast::<PyTuple>().map_err(|_| {
        PyValueError::new_err(format!(
            "`{method_name}` must return a tuple of {expected_len} array-like values"
        ))
    })?;

    if tuple.len() != expected_len {
        return Err(PyValueError::new_err(format!(
            "`{method_name}` must return a tuple of {expected_len} array-like values; got {}",
            tuple.len()
        )));
    }

    Ok(tuple)
}

/// Extract one callback output field as a copied two-dimensional `float64` array.
fn callback_array(
    method_name: &str,
    field_name: &str,
    value: &Bound<'_, PyAny>,
) -> PyResult<(usize, usize, Vec<f64>)> {
    array_like_to_vec2_f64(
        &format!("`{method_name}` return field `{field_name}`"),
        value,
    )
}

/// Copy one Python callback matrix into a Rust column-major evaluator buffer.
fn copy_callback_matrix_to_buffer(
    method_name: &str,
    field_name: &str,
    array: (usize, usize, Vec<f64>),
    state: &PyCallbackState,
    n_samples: usize,
    output: &mut [f64],
) -> PyResult<()> {
    let (expected_rows, expected_cols) =
        callback_expected_shape(state.layout, state.dim, n_samples);
    let (rows, cols, data) = array;
    if (rows, cols) != (expected_rows, expected_cols) {
        return Err(PyValueError::new_err(format!(
            "`{method_name}` returned `{field_name}` with shape ({rows}, {cols}); expected shape ({expected_rows}, {expected_cols})"
        )));
    }

    match state.layout {
        PyMatrixLayout::SampleMajor => {
            for sample in 0..n_samples {
                for dim in 0..state.dim {
                    output[dim + sample * state.dim] = data[sample * state.dim + dim];
                }
            }
        }
        PyMatrixLayout::DimMajor => {
            for dim in 0..state.dim {
                for sample in 0..n_samples {
                    output[dim + sample * state.dim] = data[dim * n_samples + sample];
                }
            }
        }
    }

    Ok(())
}

/// Return the Python callback matrix shape for a given layout.
fn callback_expected_shape(layout: PyMatrixLayout, dim: usize, n_samples: usize) -> (usize, usize) {
    match layout {
        PyMatrixLayout::SampleMajor => (n_samples, dim),
        PyMatrixLayout::DimMajor => (dim, n_samples),
    }
}

/// Return the canonical Python token for a [`PyMatrixLayout`] value.
fn layout_token(layout: PyMatrixLayout) -> &'static str {
    match layout {
        PyMatrixLayout::SampleMajor => "sample_major",
        PyMatrixLayout::DimMajor => "dim_major",
    }
}

/// Parse a Python value accepted by the `out_of_range` property setter.
fn parse_out_of_range(value: &Bound<'_, PyAny>) -> PyResult<PyOutOfRangeMode> {
    if value.is_none() {
        return Ok(PyOutOfRangeMode::Error);
    }

    if let Ok(mode) = value.extract::<PyOutOfRangeMode>() {
        return Ok(mode);
    }

    if let Ok(text) = value.extract::<&str>() {
        return match normalize_token(text).as_str() {
            "error" => Ok(PyOutOfRangeMode::Error),
            "clamp" => Ok(PyOutOfRangeMode::Clamp),
            _ => Err(PyValueError::new_err(
                "`out_of_range` must be OutOfRangeMode.ERROR, OutOfRangeMode.CLAMP, \"error\", or \"clamp\"",
            )),
        };
    }

    Err(PyValueError::new_err(
        "`out_of_range` must be an OutOfRangeMode value or a string",
    ))
}

/// Parse a Python value accepted by the `parametrization` property setter.
fn parse_parametrization(value: &Bound<'_, PyAny>) -> PyResult<PyParametrization> {
    if value.is_none() {
        return Ok(PyParametrization::Uniform);
    }

    if let Ok(parametrization) = value.extract::<PyParametrization>() {
        return Ok(parametrization);
    }

    if let Ok(text) = value.extract::<&str>() {
        return match normalize_token(text).as_str() {
            "uniform" => Ok(PyParametrization::Uniform),
            _ => Err(PyValueError::new_err(
                "`parametrization` must be Parametrization.UNIFORM or \"uniform\"",
            )),
        };
    }

    Err(PyValueError::new_err(
        "`parametrization` must be a Parametrization value or a string",
    ))
}

/// Normalize user-facing option strings for lenient matching.
///
/// The parser accepts case differences and hyphen/underscore spelling
/// differences while still keeping the documented spelling canonical.
fn normalize_token(text: &str) -> String {
    text.trim().to_ascii_lowercase().replace('-', "_")
}

/// Reject ambiguous calls that pass both `config` and direct spline keywords.
fn ensure_default_direct_config(config: &PySplineConfig) -> PyResult<()> {
    let has_non_default = config.order != 5
        || config.s_min != 0.0
        || config.s_max != 1.0
        || config.out_of_range != PyOutOfRangeMode::Error
        || config.parametrization != PyParametrization::Uniform
        || config.start_state.is_some()
        || config.end_state.is_some();

    if has_non_default {
        return Err(PyValueError::new_err(
            "pass either a `SplineConfig` object or direct spline keyword options, not both",
        ));
    }

    Ok(())
}

/// Convert an optional Python boundary-state array into an optional [`DMatrix`].
fn optional_boundary_matrix(
    name: &str,
    array: Option<&Bound<'_, PyAny>>,
) -> PyResult<Option<DMatrix<f64>>> {
    array
        .map(|array| c_contiguous_matrix_to_dmatrix(name, array))
        .transpose()
}

/// Parse a boundary-state property assignment from Python.
///
/// `None` clears the stored matrix; otherwise the value must be convertible to
/// a two-dimensional `float64` array.
fn parse_optional_boundary_value(
    name: &str,
    value: &Bound<'_, PyAny>,
) -> PyResult<Option<DMatrix<f64>>> {
    if value.is_none() {
        return Ok(None);
    }

    optional_boundary_matrix(name, Some(value))
}

/// Convert an ArrayLike two-dimensional value into [`DMatrix`].
///
/// The shape is preserved exactly. This is appropriate for boundary derivative
/// matrices, whose Python and Rust layouts are both documented as `(dim, m)`.
fn c_contiguous_matrix_to_dmatrix(name: &str, value: &Bound<'_, PyAny>) -> PyResult<DMatrix<f64>> {
    let (rows, cols, data) = array_like_to_vec2_f64(name, value)?;
    Ok(DMatrix::from_row_slice(rows, cols, &data))
}

/// Convert Python waypoint arrays into the Rust core `(dim, n_points)` layout.
///
/// With `SampleMajor`, the input is interpreted as `(n_points, dim)` and
/// transposed into a [`DMatrix`]. With `DimMajor`, the input shape is already the
/// Rust-facing `(dim, n_points)` contract.
fn waypoints_to_dmatrix(
    name: &str,
    value: &Bound<'_, PyAny>,
    layout: PyMatrixLayout,
) -> PyResult<DMatrix<f64>> {
    let (rows, cols, data) = array_like_to_vec2_f64(name, value)?;

    match layout {
        PyMatrixLayout::SampleMajor => {
            let n_points = rows;
            let dim = cols;
            let mut matrix = DMatrix::<f64>::zeros(dim, n_points);
            for point in 0..n_points {
                for d in 0..dim {
                    matrix[(d, point)] = data[point * dim + d];
                }
            }
            Ok(matrix)
        }
        PyMatrixLayout::DimMajor => Ok(DMatrix::from_row_slice(rows, cols, &data)),
    }
}

/// Convert Rust [`crate::path::PathDerivatives`] into [`PyPathDerivatives`].
fn path_derivatives_to_python(
    py: Python<'_>,
    out: crate::path::PathDerivatives,
    layout: PyMatrixLayout,
) -> PyResult<PyPathDerivatives> {
    let q = matrix_to_pyarray2(py, &out.q, layout)?.unbind();
    let dq = optional_matrix_to_pyarray2(py, out.dq.as_ref(), layout)?.map(Bound::unbind);
    let ddq = optional_matrix_to_pyarray2(py, out.ddq.as_ref(), layout)?.map(Bound::unbind);
    let dddq = optional_matrix_to_pyarray2(py, out.dddq.as_ref(), layout)?.map(Bound::unbind);

    Ok(PyPathDerivatives { q, dq, ddq, dddq })
}

/// Convert an optional boundary [`DMatrix`] to a Python [`PyArray2`].
///
/// Boundary matrices are always exposed in `(dim, m)` layout
/// because they are configuration data rather than sampled trajectory output.
fn optional_boundary_matrix_to_pyarray2<'py>(
    py: Python<'py>,
    matrix: Option<&DMatrix<f64>>,
) -> PyResult<Option<Bound<'py, PyArray2<f64>>>> {
    matrix
        .map(|matrix| matrix_to_pyarray2(py, matrix, PyMatrixLayout::DimMajor))
        .transpose()
}

/// Convert an optional derivative [`DMatrix`] to a Python [`PyArray2`].
fn optional_matrix_to_pyarray2<'py>(
    py: Python<'py>,
    matrix: Option<&DMatrix<f64>>,
    layout: PyMatrixLayout,
) -> PyResult<Option<Bound<'py, PyArray2<f64>>>> {
    matrix
        .map(|matrix| matrix_to_pyarray2(py, matrix, layout))
        .transpose()
}

/// Convert a Rust [`DMatrix`] into a C-contiguous [`PyArray2`].
///
/// Rust matrices arrive as `(dim, n_samples)`. `SampleMajor` produces
/// `(n_samples, dim)` for Python users; `DimMajor` preserves `(dim, n_samples)`.
fn matrix_to_pyarray2<'py>(
    py: Python<'py>,
    matrix: &DMatrix<f64>,
    layout: PyMatrixLayout,
) -> PyResult<Bound<'py, PyArray2<f64>>> {
    let rows = matrix.nrows();
    let cols = matrix.ncols();
    let (out_rows, out_cols) = match layout {
        PyMatrixLayout::SampleMajor => (cols, rows),
        PyMatrixLayout::DimMajor => (rows, cols),
    };
    let array = PyArray2::<f64>::zeros(py, [out_rows, out_cols], false);

    {
        let mut writable = array.readwrite();
        let data = writable.as_slice_mut().map_err(|_| {
            PyValueError::new_err("failed to create a contiguous NumPy output array")
        })?;

        match layout {
            PyMatrixLayout::SampleMajor => {
                for sample in 0..cols {
                    for dim in 0..rows {
                        data[sample * out_cols + dim] = matrix[(dim, sample)];
                    }
                }
            }
            PyMatrixLayout::DimMajor => {
                for dim in 0..rows {
                    for sample in 0..cols {
                        data[dim * out_cols + sample] = matrix[(dim, sample)];
                    }
                }
            }
        }
    }

    Ok(array)
}