anise 0.9.6

Core of the ANISE library
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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
/*
 * ANISE Toolkit
 * Copyright (C) 2021-onward Christopher Rabotin <christopher.rabotin@gmail.com> et al. (cf. AUTHORS.md)
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 *
 * Documentation: https://nyxspace.com/
 */
use hifitime::{Duration, Epoch, TimeSeries};
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
use pyo3::types::PyType;
use std::collections::HashMap;

use crate::prelude::{Aberration, Almanac, Frame, Orbit};
use crate::NaifId;

pub use crate::analysis::elements::OrbitalElement;
use crate::analysis::specs::{OrthogonalFrame, Plane};
use crate::math::rotation::DCM;

use super::event::{Event, EventArc, EventDetails, VisibilityArc};
use super::prelude::{ScalarExpr, VectorExpr};
use super::report::PyReportScalars;
use super::specs::{DcmExpr, FrameSpec, StateSpec, StateSpecTrait};
use super::AnalysisError;

#[pymethods]
impl Almanac {
    /// Report a set of scalar expressions, optionally with aliases, at a fixed time step defined in the TimeSeries.
    ///
    /// :type report: ReportScalars
    /// :type time_series: TimeSeries
    /// :rtype: dict
    #[pyo3(name = "report_scalars")]
    pub fn py_report_scalars(
        &self,
        py: Python,
        report: &PyReportScalars,
        time_series: TimeSeries,
    ) -> Result<HashMap<String, HashMap<String, f64>>, AnalysisError> {
        let data = py.detach(|| self.report_scalars(&report.inner, time_series));
        // Modify the values to set errors to NaN
        let mut rslt = HashMap::new();
        for (k, v) in data {
            let mut data_epoch_ok = HashMap::new();
            for (col, value) in v? {
                data_epoch_ok.insert(col, value.unwrap_or(f64::NAN));
            }
            rslt.insert(k.to_isoformat(), data_epoch_ok);
        }

        Ok(rslt)
    }

    /// Report all of the states when the provided event happens.
    /// This method may only be used for equality events, minimum, and maximum events. For spanned events (e.g. Less Than/Greater Than), use report_event_arcs.
    ///
    /// # Method
    /// The report event function starts by lineraly scanning the whole state spec from the start to the end epoch.
    /// This uses an adaptive step scan modeled on the Runge Kutta adaptive step integrator, but the objective is to ensure that the scalar expression
    /// of the event is evaluated at steps where it is linearly changing (to within 10% of linearity). This allows finding coarse brackets where
    /// the expression changes signs exactly once.
    /// Then, each bracket it sent in parallel to a Brent's method root finder to find the exact time of the event.
    ///
    /// # Limitation
    /// While this approach is both very robust and very fast, if you think the finder may be missing some events, you should _reduce_ the epoch precision
    /// of the event as a multiplicative factor of that precision is used to scan the trajectory linearly. Alternatively, you may export the scalars at
    /// a fixed interval using the report_scalars or report_scalars_flat function and manually analyze the results of the scalar expression.
    ///
    /// :type state_spec: StateSpec
    /// :type event: Event
    /// :type start_epoch: Epoch
    /// :type end_epoch: Epoch
    /// :rtype: list
    #[pyo3(name = "report_events", signature=(state_spec, event, start_epoch, end_epoch))]
    #[allow(clippy::identity_op)]
    fn py_report_events(
        &self,
        py: Python,
        state_spec: PyStateSpec,
        event: &Event,
        start_epoch: Epoch,
        end_epoch: Epoch,
    ) -> Result<Vec<EventDetails>, AnalysisError> {
        py.detach(|| {
            self.report_events(&StateSpec::from(state_spec), event, start_epoch, end_epoch)
        })
    }

    /// Report the rising and falling edges/states where the event arc happens.
    ///
    /// For example, for a scalar expression less than X, this will report all of the times when the expression falls below X and rises above X.
    /// This method uses the report_events function under the hood.
    ///
    /// :type state_spec: StateSpec
    /// :type event: Event
    /// :type start_epoch: Epoch
    /// :type end_epoch: Epoch
    /// :rtype: list
    #[pyo3(name = "report_event_arcs")]
    fn py_report_event_arcs(
        &self,
        py: Python,
        state_spec: PyStateSpec,
        event: &Event,
        start_epoch: Epoch,
        end_epoch: Epoch,
    ) -> Result<Vec<EventArc>, AnalysisError> {
        py.detach(|| {
            self.report_event_arcs(&StateSpec::from(state_spec), event, start_epoch, end_epoch)
        })
    }

    /// Report the list of visibility arcs for the desired location ID.
    ///
    /// :type state_spec: StateSpec
    /// :type location_id: int
    /// :type start_epoch: Epoch
    /// :type end_epoch: Epoch
    /// :type sample_rate: Duration
    /// :type obstructing_body: Frame, optional
    /// :rtype: list
    #[pyo3(name = "report_visibility_arcs", signature=(state_spec, location_id, start_epoch, end_epoch, sample_rate, obstructing_body=None))]
    #[allow(clippy::too_many_arguments)]
    fn py_report_visibility_arcs(
        &self,
        py: Python,
        state_spec: PyStateSpec,
        location_id: i32,
        start_epoch: Epoch,
        end_epoch: Epoch,
        sample_rate: Duration,
        obstructing_body: Option<Frame>,
    ) -> Result<Vec<VisibilityArc>, AnalysisError> {
        py.detach(|| {
            self.report_visibility_arcs(
                &StateSpec::from(state_spec),
                location_id,
                start_epoch,
                end_epoch,
                sample_rate,
                obstructing_body,
            )
        })
    }
}

/// ScalarExpr defines a scalar computation from a (set of) vector expression(s).
#[pyclass]
#[pyo3(module = "anise.analysis", name = "ScalarExpr", get_all, set_all)]
pub enum PyScalarExpr {
    Constant(f64),
    /// Mean radius of the provided body, must be loaded in the almanac
    MeanEquatorialRadius {
        celestial_object: i32,
    },
    SemiMajorEquatorialRadius {
        celestial_object: i32,
    },
    SemiMinorEquatorialRadius {
        celestial_object: i32,
    },
    PolarRadius {
        celestial_object: i32,
    },
    Flattening {
        celestial_object: i32,
    },
    GravParam {
        celestial_object: i32,
    },
    Abs(Py<PyScalarExpr>),
    Add {
        a: Py<PyScalarExpr>,
        b: Py<PyScalarExpr>,
    },
    Mul {
        a: Py<PyScalarExpr>,
        b: Py<PyScalarExpr>,
    },
    Negate(Py<PyScalarExpr>),
    Invert(Py<PyScalarExpr>),
    Sqrt(Py<PyScalarExpr>),
    Powi {
        scalar: Py<PyScalarExpr>,
        n: i32,
    },
    Powf {
        scalar: Py<PyScalarExpr>,
        n: f64,
    },
    Cos(Py<PyScalarExpr>),
    Sin(Py<PyScalarExpr>),
    Tan(Py<PyScalarExpr>),
    /// Compute the arccos, returned in degrees
    Acos(Py<PyScalarExpr>),
    /// Compute the arcsin, returned in degrees
    Asin(Py<PyScalarExpr>),
    /// Compute the arctan2 (i.e. arctan with quadrant check), returned in degrees
    Atan2 {
        y: Py<PyScalarExpr>,
        x: Py<PyScalarExpr>,
    },
    /// Computes v % m
    Modulo {
        v: Py<PyScalarExpr>,
        m: Py<PyScalarExpr>,
    },
    Norm(Py<PyVectorExpr>),
    NormSquared(Py<PyVectorExpr>),
    DotProduct {
        a: Py<PyVectorExpr>,
        b: Py<PyVectorExpr>,
    },
    /// Angle between two vectors, in degrees
    AngleBetween {
        a: Py<PyVectorExpr>,
        b: Py<PyVectorExpr>,
    },
    VectorX(Py<PyVectorExpr>),
    VectorY(Py<PyVectorExpr>),
    VectorZ(Py<PyVectorExpr>),
    Element(OrbitalElement),
    /// Computes the eclipsing percentage due to the eclipsing frame. Aberration correction is that of the state spec.
    SolarEclipsePercentage {
        eclipsing_frame: Frame,
    },
    /// Computes the occultation percentage of the back_frame due to the front_frame. Aberration correction is that of the state spec.
    OccultationPercentage {
        back_frame: Frame,
        front_frame: Frame,
    },
    /// Computes the beta angle, in degrees. Aberration correction is that of the state spec.
    BetaAngle(),
    /// Compute the local solar time, in hours
    LocalSolarTime(),
    /// Computes the local time of the ascending node, in hours
    LocalTimeAscNode(),
    /// Computes the local time of the descending node, in hours
    LocalTimeDescNode(),
    /// Computes the Sun angle where observer_id is the ID of the spacecraft for example.
    /// If the frame of the state spec is in an Earth frame, then this computes the Sun Probe Earth angle.
    /// Refer to the sun_angle_deg function for detailed documentation.
    SunAngle {
        observer_id: NaifId,
    },
    AzimuthFromLocation {
        location_id: i32,
        obstructing_body: Option<Frame>,
    },
    ElevationFromLocation {
        location_id: i32,
        obstructing_body: Option<Frame>,
    },
    RangeFromLocation {
        location_id: i32,
        obstructing_body: Option<Frame>,
    },
    RangeRateFromLocation {
        location_id: i32,
        obstructing_body: Option<Frame>,
    },
    RicDiff(PyStateSpec),
    /// FovMargin requires the spacecraft frame in sc_observer_frame and the StateSpec **must** be the target location on target obdy (e.g. IAU Moon).
    FovMargin {
        instrument_id: i32,
        sc_dcm_to_body: Py<PyDcmExpr>,
        target: PyStateSpec,
    },
    FovMarginToLocation {
        instrument_id: i32,
        sc_dcm_to_body: Py<PyDcmExpr>,
        location_id: i32,
    },
}

impl Clone for PyScalarExpr {
    fn clone(&self) -> Self {
        Python::attach(|py| -> PyScalarExpr {
            match self {
                Self::Constant(c) => Self::Constant(*c),
                Self::MeanEquatorialRadius { celestial_object } => Self::MeanEquatorialRadius {
                    celestial_object: *celestial_object,
                },
                Self::SemiMajorEquatorialRadius { celestial_object } => {
                    Self::SemiMajorEquatorialRadius {
                        celestial_object: *celestial_object,
                    }
                }
                Self::SemiMinorEquatorialRadius { celestial_object } => {
                    Self::SemiMinorEquatorialRadius {
                        celestial_object: *celestial_object,
                    }
                }
                Self::PolarRadius { celestial_object } => Self::PolarRadius {
                    celestial_object: *celestial_object,
                },
                Self::Flattening { celestial_object } => Self::Flattening {
                    celestial_object: *celestial_object,
                },
                Self::GravParam { celestial_object } => Self::GravParam {
                    celestial_object: *celestial_object,
                },
                Self::Abs(v) => Self::Abs(v.clone_ref(py)),
                Self::Add { a, b } => Self::Add {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::Mul { a, b } => Self::Mul {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::Negate(s) => Self::Negate(s.clone_ref(py)),
                Self::Invert(s) => Self::Invert(s.clone_ref(py)),
                Self::Sqrt(s) => Self::Sqrt(s.clone_ref(py)),
                Self::Powi { scalar, n } => Self::Powi {
                    scalar: scalar.clone_ref(py),
                    n: *n,
                },
                Self::Powf { scalar, n } => Self::Powf {
                    scalar: scalar.clone_ref(py),
                    n: *n,
                },
                Self::Cos(s) => Self::Cos(s.clone_ref(py)),
                Self::Sin(s) => Self::Sin(s.clone_ref(py)),
                Self::Tan(s) => Self::Tan(s.clone_ref(py)),
                Self::Acos(s) => Self::Acos(s.clone_ref(py)),
                Self::Asin(s) => Self::Asin(s.clone_ref(py)),
                Self::Atan2 { y, x } => Self::Atan2 {
                    y: y.clone_ref(py),
                    x: x.clone_ref(py),
                },
                Self::Modulo { v, m } => Self::Modulo {
                    v: v.clone_ref(py),
                    m: m.clone_ref(py),
                },
                Self::Norm(v) => Self::Norm(v.clone_ref(py)),
                Self::NormSquared(v) => Self::NormSquared(v.clone_ref(py)),
                Self::DotProduct { a, b } => Self::DotProduct {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::AngleBetween { a, b } => Self::AngleBetween {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::VectorX(v) => Self::VectorX(v.clone_ref(py)),
                Self::VectorY(v) => Self::VectorY(v.clone_ref(py)),
                Self::VectorZ(v) => Self::VectorZ(v.clone_ref(py)),
                Self::Element(e) => Self::Element(*e),
                Self::SolarEclipsePercentage { eclipsing_frame } => Self::SolarEclipsePercentage {
                    eclipsing_frame: *eclipsing_frame,
                },
                Self::OccultationPercentage {
                    back_frame,
                    front_frame,
                } => Self::OccultationPercentage {
                    back_frame: *back_frame,
                    front_frame: *front_frame,
                },
                Self::BetaAngle() => Self::BetaAngle(),
                Self::LocalSolarTime() => Self::LocalSolarTime(),
                Self::LocalTimeAscNode() => Self::LocalTimeAscNode(),
                Self::LocalTimeDescNode() => Self::LocalTimeDescNode(),
                Self::SunAngle { observer_id } => Self::SunAngle {
                    observer_id: *observer_id,
                },
                Self::AzimuthFromLocation {
                    location_id,
                    obstructing_body,
                } => Self::AzimuthFromLocation {
                    location_id: *location_id,
                    obstructing_body: *obstructing_body,
                },
                Self::ElevationFromLocation {
                    location_id,
                    obstructing_body,
                } => Self::ElevationFromLocation {
                    location_id: *location_id,
                    obstructing_body: *obstructing_body,
                },
                Self::RangeFromLocation {
                    location_id,
                    obstructing_body,
                } => Self::RangeFromLocation {
                    location_id: *location_id,
                    obstructing_body: *obstructing_body,
                },
                Self::RangeRateFromLocation {
                    location_id,
                    obstructing_body,
                } => Self::RangeRateFromLocation {
                    location_id: *location_id,
                    obstructing_body: *obstructing_body,
                },
                Self::RicDiff(s) => Self::RicDiff(s.clone()),
                Self::FovMargin {
                    instrument_id,
                    sc_dcm_to_body,
                    target,
                } => Self::FovMargin {
                    instrument_id: *instrument_id,
                    sc_dcm_to_body: sc_dcm_to_body.clone_ref(py),
                    target: target.clone(),
                },
                Self::FovMarginToLocation {
                    instrument_id,
                    sc_dcm_to_body,
                    location_id,
                } => Self::FovMarginToLocation {
                    instrument_id: *instrument_id,
                    sc_dcm_to_body: sc_dcm_to_body.clone_ref(py),
                    location_id: *location_id,
                },
            }
        })
    }
}

#[pymethods]
impl PyScalarExpr {
    /// Compute this ScalarExpr for the provided Orbit
    ///
    /// :type orbit: Orbit
    /// :type almanac: Almanac
    /// :type ab_corr: Aberration, optional
    /// :rtype:float
    #[pyo3(signature=(orbit, almanac, ab_corr=None))]
    fn evaluate(
        &self,
        orbit: Orbit,
        almanac: &Almanac,
        ab_corr: Option<Aberration>,
    ) -> Result<f64, PyErr> {
        let py_scalar = self.clone();
        let scalar = ScalarExpr::from(py_scalar);

        scalar
            .evaluate(orbit, ab_corr, almanac)
            .map_err(|e| PyException::new_err(e.to_string()))
    }

    /// Convert the S-Expression to a ScalarExpr
    /// :type expr: str
    /// :rtype: ScalarExpr
    #[classmethod]
    fn from_s_expr(_cls: Bound<'_, PyType>, expr: &str) -> Result<Self, PyErr> {
        let scalar =
            ScalarExpr::from_s_expr(expr).map_err(|e| PyException::new_err(e.to_string()))?;

        scalar.try_into()
    }

    /// Converts this ScalarExpr to its S-Expression
    /// :rtype: str
    fn to_s_expr(&self) -> Result<String, PyErr> {
        let scalar = ScalarExpr::from(self.clone());

        scalar
            .to_s_expr()
            .map_err(|e| PyException::new_err(e.to_string()))
    }
}

#[pyclass]
#[pyo3(module = "anise.analysis", name = "VectorExpr", get_all, set_all)]
pub enum PyVectorExpr {
    // Vector with unspecified units, for arbitrary computations
    Fixed {
        x: f64,
        y: f64,
        z: f64,
    },
    /// Radius/position vector of this state specification
    Radius(Py<PyStateSpec>),
    /// Velocity vector of this state specification
    Velocity(Py<PyStateSpec>),
    /// Orbital moment (H) vector of this state specification
    OrbitalMomentum(Py<PyStateSpec>),
    /// Eccentricity vector of this state specification
    EccentricityVector(Py<PyStateSpec>),
    /// Cross product between two vector expression
    CrossProduct {
        a: Py<PyVectorExpr>,
        b: Py<PyVectorExpr>,
    },
    /// Unit vector of this vector expression, returns zero vector if norm less than 1e-12
    Unit(Py<PyVectorExpr>),
    Add {
        a: Py<PyVectorExpr>,
        b: Py<PyVectorExpr>,
    },
    /// Negate a vector.
    Negate(Py<PyVectorExpr>),
    /// Vector projection of a onto b
    VecProjection {
        a: Py<PyVectorExpr>,
        b: Py<PyVectorExpr>,
    },
    // This should be as simple as multiplying the input VectorExpr by the DCM.
    // I think it makes sense to have trivial rotations like VNC, RIC, RCN available in the frame spec.
    // The test should consist in checking that we can rebuild the VNC frame and project the Sun Earth vector onto
    // the VNC frame of that same Sun Earth orbit, returning the X, Y, or Z component.
    // Projection should allow XY, XZ, YZ which determines the components to account for.
    /// Multiplies the DCM of thr frame with this vector, thereby rotating it into the provided orthogonal frame, optionally projecting onto the plan, optionally projecting onto the plane
    Project {
        v: Py<PyVectorExpr>,
        frame: Py<PyOrthogonalFrame>,
        plane: Option<Plane>,
    },
    Rotate {
        v: Py<PyVectorExpr>,
        dcm: Py<PyDcmExpr>,
    },
}

impl Clone for PyVectorExpr {
    fn clone(&self) -> Self {
        // We must acquire the GIL to safely clone the Py<T> references.
        Python::attach(|py| -> PyVectorExpr {
            match self {
                Self::Fixed { x, y, z } => Self::Fixed {
                    x: *x,
                    y: *y,
                    z: *z,
                },
                Self::Radius(s) => Self::Radius(s.clone_ref(py)),
                Self::Velocity(s) => Self::Velocity(s.clone_ref(py)),
                Self::OrbitalMomentum(s) => Self::OrbitalMomentum(s.clone_ref(py)),
                Self::EccentricityVector(s) => Self::EccentricityVector(s.clone_ref(py)),
                Self::CrossProduct { a, b } => Self::CrossProduct {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::Unit(v) => Self::Unit(v.clone_ref(py)),
                Self::Add { a, b } => Self::Add {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::Negate(v) => Self::Negate(v.clone_ref(py)),
                Self::VecProjection { a, b } => Self::VecProjection {
                    a: a.clone_ref(py),
                    b: b.clone_ref(py),
                },
                Self::Project { v, frame, plane } => Self::Project {
                    v: v.clone_ref(py),
                    frame: frame.clone_ref(py),
                    plane: *plane,
                },
                Self::Rotate { v, dcm } => Self::Rotate {
                    v: v.clone_ref(py),
                    dcm: dcm.clone_ref(py),
                },
            }
        })
    }
}
/// StateSpec allows defining a state from the target to the observer
///
/// :type target_frame: FrameSpec
/// :type observer_frame: FrameSpec
/// :type ab_corr: Aberration, optional
/// :rtype: None
#[derive(Clone)]
#[pyclass]
#[pyo3(module = "anise.analysis", name = "StateSpec", get_all, set_all)]
pub struct PyStateSpec {
    /// :rtype: FrameSpec
    pub target_frame: PyFrameSpec,
    /// :rtype: FrameSpec
    pub observer_frame: PyFrameSpec,
    /// :rtype: Aberration
    pub ab_corr: Option<Aberration>,
}

#[pymethods]
impl PyStateSpec {
    #[new]
    #[pyo3(signature=(target_frame, observer_frame, ab_corr=None))]
    fn new(
        target_frame: PyFrameSpec,
        observer_frame: PyFrameSpec,
        ab_corr: Option<Aberration>,
    ) -> Self {
        Self {
            target_frame,
            observer_frame,
            ab_corr,
        }
    }

    /// Convert the S-Expression to a StateSpec
    /// :type expr: str
    /// :rtype: StateSpec
    #[classmethod]
    fn from_s_expr(_cls: Bound<'_, PyType>, expr: &str) -> Result<Self, PyErr> {
        let spec = StateSpec::from_s_expr(expr).map_err(|e| PyException::new_err(e.to_string()))?;

        spec.try_into()
    }

    /// Converts this StateSpec to its S-Expression
    /// :rtype: str
    fn to_s_expr(&self) -> Result<String, PyErr> {
        let spec = StateSpec::from(self.clone());

        spec.to_s_expr()
            .map_err(|e| PyException::new_err(e.to_string()))
    }
    /// Evaluate the orbital element enum variant for the provided orbit
    /// :type epoch: Epoch
    /// :type almanac: Almanac
    /// :rtype: Orbit
    #[pyo3(name = "evaluate", signature=(epoch, almanac))]
    fn py_evaluate(&self, epoch: Epoch, almanac: &Almanac) -> Result<Orbit, PyErr> {
        let spec = StateSpec::from(self.clone());
        spec.evaluate(epoch, almanac)
            .map_err(|e| PyException::new_err(e.to_string()))
    }
    fn __eq__(&self, other: &Self) -> bool {
        let me = StateSpec::from(self.clone());
        let other = StateSpec::from(other.clone());
        me == other
    }
    fn __ne__(&self, other: &Self) -> bool {
        let me = StateSpec::from(self.clone());
        let other = StateSpec::from(other.clone());
        me != other
    }
}

/// FrameSpec allows defining a frame that can be computed from another set of loaded frames, which include a center.
#[pyclass]
#[pyo3(module = "anise.analysis", name = "FrameSpec", get_all, set_all)]
pub enum PyFrameSpec {
    Loaded(Frame),
    Manual {
        name: String,
        defn: Py<PyOrthogonalFrame>,
    },
}

impl Clone for PyFrameSpec {
    fn clone(&self) -> Self {
        Python::attach(|py| -> PyFrameSpec {
            match self {
                PyFrameSpec::Loaded(frame) => PyFrameSpec::Loaded(*frame),

                // For the Manual variant, we clone each field individually.
                PyFrameSpec::Manual { name, defn } => {
                    PyFrameSpec::Manual {
                        name: name.clone(),
                        // The clone_ref() method on Py<T> requires the GIL token (`py`),
                        // which we have here. This is the correct way to clone a Py<T>.
                        defn: defn.clone_ref(py),
                    }
                }
            }
        })
    }
}

// Defines how to build an orthogonal frame from custom vector expressions
//
// WARNING: Building such a frame does NOT normalize the vectors, you must use the Unit vector expression
// to build an orthonormal frame.
#[pyclass]
#[pyo3(module = "anise.analysis", name = "OrthogonalFrame", get_all, set_all)]
pub enum PyOrthogonalFrame {
    XY {
        x: Py<PyVectorExpr>,
        y: Py<PyVectorExpr>,
    },
    XZ {
        x: Py<PyVectorExpr>,
        z: Py<PyVectorExpr>,
    },
    YZ {
        y: Py<PyVectorExpr>,
        z: Py<PyVectorExpr>,
    },
}

impl Clone for PyOrthogonalFrame {
    fn clone(&self) -> Self {
        Python::attach(|py| -> PyOrthogonalFrame {
            match self {
                Self::XY { x, y } => Self::XY {
                    x: x.clone_ref(py),
                    y: y.clone_ref(py),
                },
                Self::XZ { x, z } => Self::XZ {
                    x: x.clone_ref(py),
                    z: z.clone_ref(py),
                },
                Self::YZ { y, z } => Self::YZ {
                    z: z.clone_ref(py),
                    y: y.clone_ref(py),
                },
            }
        })
    }
}

#[pyclass]
#[pyo3(module = "anise.analysis", name = "DcmExpr", get_all, set_all)]
pub enum PyDcmExpr {
    Identity {
        from_id: i32,
        to_id: i32,
    },
    R1 {
        angle_rad: f64,
        from_id: i32,
        to_id: i32,
    },
    R2 {
        angle_rad: f64,
        from_id: i32,
        to_id: i32,
    },
    R3 {
        angle_rad: f64,
        from_id: i32,
        to_id: i32,
    },
    /// Builds a DCM from TRIAD/Align-Clock vectors
    Triad {
        primary_axis: Py<PyVectorExpr>,
        primary_vec: Py<PyVectorExpr>,
        secondary_axis: Py<PyVectorExpr>,
        secondary_vec: Py<PyVectorExpr>,
        from_id: i32,
        to_id: i32,
    },
    Quaternion {
        x: f64,
        y: f64,
        z: f64,
        w: f64,
        from_id: i32,
        to_id: i32,
    },
    RIC {
        state: Py<PyStateSpec>,
        from_id: i32,
        to_id: i32,
    },
    VNC {
        state: Py<PyStateSpec>,
        from_id: i32,
        to_id: i32,
    },
    RCN {
        state: Py<PyStateSpec>,
        from_id: i32,
        to_id: i32,
    },
    SEZ {
        state: Py<PyStateSpec>,
        from_id: i32,
        to_id: i32,
    },
}

impl Clone for PyDcmExpr {
    fn clone(&self) -> Self {
        // We must acquire the GIL to safely clone the Py<T> references.
        Python::attach(|py| -> PyDcmExpr {
            match self {
                Self::Identity {
                    from_id: from,
                    to_id: to,
                } => Self::Identity {
                    from_id: *from,
                    to_id: *to,
                },
                Self::R1 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                } => Self::R1 {
                    angle_rad: *angle_rad,
                    from_id: *from,
                    to_id: *to,
                },
                Self::R2 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                } => Self::R2 {
                    angle_rad: *angle_rad,
                    from_id: *from,
                    to_id: *to,
                },
                Self::R3 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                } => Self::R3 {
                    angle_rad: *angle_rad,
                    from_id: *from,
                    to_id: *to,
                },
                Self::Quaternion {
                    x,
                    y,
                    z,
                    w,
                    from_id: from,
                    to_id: to,
                } => Self::Quaternion {
                    x: *x,
                    y: *y,
                    z: *z,
                    w: *w,
                    from_id: *from,
                    to_id: *to,
                },
                Self::RIC {
                    state,
                    from_id: from,
                    to_id: to,
                } => Self::RIC {
                    state: state.clone_ref(py),
                    from_id: *from,
                    to_id: *to,
                },
                Self::RCN {
                    state,
                    from_id: from,
                    to_id: to,
                } => Self::RCN {
                    state: state.clone_ref(py),
                    from_id: *from,
                    to_id: *to,
                },
                Self::VNC {
                    state,
                    from_id: from,
                    to_id: to,
                } => Self::VNC {
                    state: state.clone_ref(py),
                    from_id: *from,
                    to_id: *to,
                },
                Self::SEZ {
                    state,
                    from_id: from,
                    to_id: to,
                } => Self::SEZ {
                    state: state.clone_ref(py),
                    from_id: *from,
                    to_id: *to,
                },
                Self::Triad {
                    primary_axis,
                    primary_vec,
                    secondary_axis,
                    secondary_vec,
                    from_id: from,
                    to_id: to,
                } => Self::Triad {
                    primary_axis: primary_axis.clone_ref(py),
                    primary_vec: primary_vec.clone_ref(py),
                    secondary_axis: secondary_axis.clone_ref(py),
                    secondary_vec: secondary_vec.clone_ref(py),
                    from_id: *from,
                    to_id: *to,
                },
            }
        })
    }
}

#[pymethods]
impl PyDcmExpr {
    /// Compute this ScalarExpr for the provided Orbit
    ///
    /// :type epoch: Epoch
    /// :type almanac: Almanac
    /// :type ab_corr: Aberration, optional
    /// :rtype: DCM
    #[pyo3(signature=(epoch, almanac))]
    fn evaluate(&self, epoch: Epoch, almanac: &Almanac) -> Result<DCM, PyErr> {
        let py_dcm = self.clone();
        let dcm_expr = DcmExpr::from(py_dcm);

        dcm_expr
            .evaluate(epoch, almanac)
            .map_err(|e| PyException::new_err(e.to_string()))
    }
}
// *** Implement the From<RustType> for PythonType to convert the LISP representation *** //

impl TryFrom<ScalarExpr> for PyScalarExpr {
    type Error = PyErr;

    fn try_from(value: ScalarExpr) -> Result<Self, Self::Error> {
        Python::attach(|py| -> Result<Self, PyErr> {
            match value {
                ScalarExpr::BetaAngle => Ok(Self::BetaAngle()),
                ScalarExpr::LocalSolarTime => Ok(Self::LocalSolarTime()),
                ScalarExpr::LocalTimeAscNode => Ok(Self::LocalTimeAscNode()),
                ScalarExpr::LocalTimeDescNode => Ok(Self::LocalTimeDescNode()),
                ScalarExpr::Constant(v) => Ok(Self::Constant(v)),
                ScalarExpr::SunAngle { observer_id } => Ok(Self::SunAngle { observer_id }),
                ScalarExpr::AzimuthFromLocation {
                    location_id,
                    obstructing_body,
                } => Ok(Self::AzimuthFromLocation {
                    location_id,
                    obstructing_body,
                }),
                ScalarExpr::ElevationFromLocation {
                    location_id,
                    obstructing_body,
                } => Ok(Self::ElevationFromLocation {
                    location_id,
                    obstructing_body,
                }),
                ScalarExpr::RangeFromLocation {
                    location_id,
                    obstructing_body,
                } => Ok(Self::RangeFromLocation {
                    location_id,
                    obstructing_body,
                }),
                ScalarExpr::RangeRateFromLocation {
                    location_id,
                    obstructing_body,
                } => Ok(Self::RangeRateFromLocation {
                    location_id,
                    obstructing_body,
                }),
                ScalarExpr::SolarEclipsePercentage { eclipsing_frame } => {
                    Ok(Self::SolarEclipsePercentage { eclipsing_frame })
                }
                ScalarExpr::OccultationPercentage {
                    back_frame,
                    front_frame,
                } => Ok(Self::OccultationPercentage {
                    back_frame,
                    front_frame,
                }),
                ScalarExpr::Element(e) => Ok(Self::Element(e)),
                ScalarExpr::MeanEquatorialRadius { celestial_object } => {
                    Ok(Self::MeanEquatorialRadius { celestial_object })
                }
                ScalarExpr::SemiMajorEquatorialRadius { celestial_object } => {
                    Ok(Self::SemiMajorEquatorialRadius { celestial_object })
                }
                ScalarExpr::SemiMinorEquatorialRadius { celestial_object } => {
                    Ok(Self::SemiMinorEquatorialRadius { celestial_object })
                }
                ScalarExpr::PolarRadius { celestial_object } => {
                    Ok(Self::PolarRadius { celestial_object })
                }
                ScalarExpr::Flattening { celestial_object } => {
                    Ok(Self::Flattening { celestial_object })
                }
                ScalarExpr::GravParam { celestial_object } => {
                    Ok(Self::GravParam { celestial_object })
                }
                ScalarExpr::Norm(v) => Ok(Self::Norm(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(v)?,
                )?)),
                ScalarExpr::NormSquared(v) => Ok(Self::NormSquared(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(v)?,
                )?)),
                ScalarExpr::VectorX(v) => Ok(Self::VectorX(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(v)?,
                )?)),
                ScalarExpr::VectorY(v) => Ok(Self::VectorY(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(v)?,
                )?)),
                ScalarExpr::VectorZ(v) => Ok(Self::VectorZ(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(v)?,
                )?)),
                ScalarExpr::DotProduct { a, b } => Ok(Self::DotProduct {
                    a: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(a)?)?,
                    b: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(b)?)?,
                }),
                ScalarExpr::AngleBetween { a, b } => Ok(Self::AngleBetween {
                    a: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(a)?)?,
                    b: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(b)?)?,
                }),
                ScalarExpr::Negate(v) => Ok(Self::Negate(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Invert(v) => Ok(Self::Invert(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Cos(v) => Ok(Self::Cos(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Sin(v) => Ok(Self::Sin(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Tan(v) => Ok(Self::Tan(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Acos(v) => Ok(Self::Acos(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Asin(v) => Ok(Self::Asin(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Sqrt(v) => Ok(Self::Sqrt(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Powi { scalar, n } => Ok(Self::Powi {
                    scalar: Py::new(
                        py,
                        <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*scalar)?,
                    )?,
                    n,
                }),
                ScalarExpr::Powf { scalar, n } => Ok(Self::Powf {
                    scalar: Py::new(
                        py,
                        <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*scalar)?,
                    )?,
                    n,
                }),
                ScalarExpr::Abs(v) => Ok(Self::Abs(Py::new(
                    py,
                    <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?,
                )?)),
                ScalarExpr::Add { a, b } => Ok(Self::Add {
                    a: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*a)?)?,
                    b: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*b)?)?,
                }),
                ScalarExpr::Mul { a, b } => Ok(Self::Mul {
                    a: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*a)?)?,
                    b: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*b)?)?,
                }),
                ScalarExpr::Atan2 { y, x } => Ok(Self::Atan2 {
                    y: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*y)?)?,
                    x: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*x)?)?,
                }),
                ScalarExpr::Modulo { v, m } => Ok(Self::Modulo {
                    v: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*v)?)?,
                    m: Py::new(py, <ScalarExpr as TryInto<PyScalarExpr>>::try_into(*m)?)?,
                }),
                ScalarExpr::RicDiff(s) => Ok(Self::RicDiff(
                    <StateSpec as TryInto<PyStateSpec>>::try_into(s.clone())?,
                )),
                ScalarExpr::FovMargin {
                    instrument_id,
                    sc_dcm_to_body,
                    target,
                } => Ok(Self::FovMargin {
                    instrument_id,
                    sc_dcm_to_body: Py::new(
                        py,
                        <DcmExpr as TryInto<PyDcmExpr>>::try_into(sc_dcm_to_body)?,
                    )?,
                    target: <StateSpec as TryInto<PyStateSpec>>::try_into(target)?,
                }),
                ScalarExpr::FovMarginToLocation {
                    instrument_id,
                    sc_dcm_to_body,
                    location_id,
                } => Ok(Self::FovMarginToLocation {
                    instrument_id,
                    sc_dcm_to_body: Py::new(
                        py,
                        <DcmExpr as TryInto<PyDcmExpr>>::try_into(sc_dcm_to_body)?,
                    )?,
                    location_id,
                }),
            }
        })
    }
}

impl TryFrom<OrthogonalFrame> for PyOrthogonalFrame {
    type Error = PyErr;
    fn try_from(value: OrthogonalFrame) -> Result<Self, PyErr> {
        Python::attach(|py| -> Result<Self, PyErr> {
            match value {
                OrthogonalFrame::XY { x, y } => Ok(Self::XY {
                    x: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(x)?)?,
                    y: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(y)?)?,
                }),
                OrthogonalFrame::XZ { x, z } => Ok(Self::XZ {
                    x: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(x)?)?,
                    z: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(z)?)?,
                }),
                OrthogonalFrame::YZ { y, z } => Ok(Self::YZ {
                    y: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(y)?)?,
                    z: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(z)?)?,
                }),
            }
        })
    }
}

impl TryFrom<VectorExpr> for PyVectorExpr {
    type Error = PyErr;
    fn try_from(value: VectorExpr) -> Result<Self, PyErr> {
        Python::attach(|py| -> Result<Self, PyErr> {
            match value {
                VectorExpr::Fixed { x, y, z } => Ok(Self::Fixed { x, y, z }),
                VectorExpr::CrossProduct { a, b } => Ok(Self::CrossProduct {
                    a: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*a)?)?,
                    b: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*b)?)?,
                }),
                VectorExpr::VecProjection { a, b } => Ok(Self::VecProjection {
                    a: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*a)?)?,
                    b: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*b)?)?,
                }),
                VectorExpr::Unit(v) => Ok(Self::Unit(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(*v)?,
                )?)),
                VectorExpr::Add { a, b } => Ok(Self::Add {
                    a: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*a)?)?,
                    b: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*b)?)?,
                }),
                VectorExpr::Negate(v) => Ok(Self::Negate(Py::new(
                    py,
                    <VectorExpr as TryInto<PyVectorExpr>>::try_into(*v)?,
                )?)),
                VectorExpr::Project { v, frame, plane } => Ok(Self::Project {
                    v: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*v)?)?,
                    frame: Py::new(
                        py,
                        <OrthogonalFrame as TryInto<PyOrthogonalFrame>>::try_into(*frame)?,
                    )?,
                    plane,
                }),
                VectorExpr::Rotate { v, dcm } => Ok(Self::Rotate {
                    v: Py::new(py, <VectorExpr as TryInto<PyVectorExpr>>::try_into(*v)?)?,
                    dcm: Py::new(py, <DcmExpr as TryInto<PyDcmExpr>>::try_into(*dcm)?)?,
                }),
                VectorExpr::Radius(spec) => Ok(Self::Radius(Py::new(
                    py,
                    <StateSpec as TryInto<PyStateSpec>>::try_into(spec)?,
                )?)),
                VectorExpr::Velocity(spec) => Ok(Self::Velocity(Py::new(
                    py,
                    <StateSpec as TryInto<PyStateSpec>>::try_into(spec)?,
                )?)),
                VectorExpr::EccentricityVector(spec) => Ok(Self::EccentricityVector(Py::new(
                    py,
                    <StateSpec as TryInto<PyStateSpec>>::try_into(spec)?,
                )?)),
                VectorExpr::OrbitalMomentum(spec) => Ok(Self::OrbitalMomentum(Py::new(
                    py,
                    <StateSpec as TryInto<PyStateSpec>>::try_into(spec)?,
                )?)),
            }
        })
    }
}
impl TryFrom<StateSpec> for PyStateSpec {
    type Error = PyErr;
    fn try_from(value: StateSpec) -> Result<Self, PyErr> {
        Ok(PyStateSpec {
            target_frame: value.target_frame.try_into()?,
            observer_frame: value.observer_frame.try_into()?,
            ab_corr: value.ab_corr,
        })
    }
}
impl TryFrom<FrameSpec> for PyFrameSpec {
    type Error = PyErr;
    fn try_from(value: FrameSpec) -> Result<Self, PyErr> {
        Python::attach(|py| -> Result<Self, PyErr> {
            Ok(match value {
                FrameSpec::Loaded(f) => PyFrameSpec::Loaded(f),
                FrameSpec::Manual { name, defn } => PyFrameSpec::Manual {
                    name,
                    defn: Py::new(
                        py,
                        <OrthogonalFrame as TryInto<PyOrthogonalFrame>>::try_into(*defn)?,
                    )?,
                },
            })
        })
    }
}

impl TryFrom<DcmExpr> for PyDcmExpr {
    type Error = PyErr;
    fn try_from(value: DcmExpr) -> Result<Self, PyErr> {
        Python::attach(|py| -> Result<Self, PyErr> {
            match value {
                DcmExpr::Identity { from, to } => Ok(PyDcmExpr::Identity {
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::R1 {
                    angle_rad,
                    from,
                    to,
                } => Ok(PyDcmExpr::R1 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::R2 {
                    angle_rad,
                    from,
                    to,
                } => Ok(PyDcmExpr::R2 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::R3 {
                    angle_rad,
                    from,
                    to,
                } => Ok(PyDcmExpr::R3 {
                    angle_rad,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::Quaternion {
                    x,
                    y,
                    z,
                    w,
                    from,
                    to,
                } => Ok(PyDcmExpr::Quaternion {
                    x,
                    y,
                    z,
                    w,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::Triad {
                    primary_axis,
                    primary_vec,
                    secondary_axis,
                    secondary_vec,
                    from,
                    to,
                } => Ok(PyDcmExpr::Triad {
                    primary_axis: Py::new(
                        py,
                        <VectorExpr as TryInto<PyVectorExpr>>::try_into(*primary_axis)?,
                    )?,
                    primary_vec: Py::new(
                        py,
                        <VectorExpr as TryInto<PyVectorExpr>>::try_into(*primary_vec)?,
                    )?,
                    secondary_axis: Py::new(
                        py,
                        <VectorExpr as TryInto<PyVectorExpr>>::try_into(*secondary_axis)?,
                    )?,
                    secondary_vec: Py::new(
                        py,
                        <VectorExpr as TryInto<PyVectorExpr>>::try_into(*secondary_vec)?,
                    )?,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::RIC { state, from, to } => Ok(PyDcmExpr::RIC {
                    state: Py::new(py, <StateSpec as TryInto<PyStateSpec>>::try_into(*state)?)?,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::RCN { state, from, to } => Ok(PyDcmExpr::RCN {
                    state: Py::new(py, <StateSpec as TryInto<PyStateSpec>>::try_into(*state)?)?,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::VNC { state, from, to } => Ok(PyDcmExpr::VNC {
                    state: Py::new(py, <StateSpec as TryInto<PyStateSpec>>::try_into(*state)?)?,
                    from_id: from,
                    to_id: to,
                }),
                DcmExpr::SEZ { state, from, to } => Ok(PyDcmExpr::SEZ {
                    state: Py::new(py, <StateSpec as TryInto<PyStateSpec>>::try_into(*state)?)?,
                    from_id: from,
                    to_id: to,
                }),
            }
        })
    }
} // *** Converse *** //

impl From<PyScalarExpr> for ScalarExpr {
    fn from(value: PyScalarExpr) -> Self {
        Python::attach(|py| match value {
            // --- Direct Conversions (unaffected by the change but now run inside the GIL) ---
            PyScalarExpr::Constant(c) => ScalarExpr::Constant(c),
            PyScalarExpr::MeanEquatorialRadius { celestial_object } => {
                ScalarExpr::MeanEquatorialRadius { celestial_object }
            }
            PyScalarExpr::SemiMajorEquatorialRadius { celestial_object } => {
                ScalarExpr::SemiMajorEquatorialRadius { celestial_object }
            }
            PyScalarExpr::SemiMinorEquatorialRadius { celestial_object } => {
                ScalarExpr::SemiMinorEquatorialRadius { celestial_object }
            }
            PyScalarExpr::PolarRadius { celestial_object } => {
                ScalarExpr::PolarRadius { celestial_object }
            }
            PyScalarExpr::Flattening { celestial_object } => {
                ScalarExpr::Flattening { celestial_object }
            }
            PyScalarExpr::GravParam { celestial_object } => {
                ScalarExpr::GravParam { celestial_object }
            }
            PyScalarExpr::Element(e) => ScalarExpr::Element(e),
            PyScalarExpr::SolarEclipsePercentage { eclipsing_frame } => {
                ScalarExpr::SolarEclipsePercentage { eclipsing_frame }
            }
            PyScalarExpr::OccultationPercentage {
                back_frame,
                front_frame,
            } => ScalarExpr::OccultationPercentage {
                back_frame,
                front_frame,
            },
            PyScalarExpr::BetaAngle() => ScalarExpr::BetaAngle,
            PyScalarExpr::LocalSolarTime() => ScalarExpr::LocalSolarTime,
            PyScalarExpr::LocalTimeAscNode() => ScalarExpr::LocalTimeAscNode,
            PyScalarExpr::LocalTimeDescNode() => ScalarExpr::LocalTimeDescNode,
            PyScalarExpr::SunAngle { observer_id } => ScalarExpr::SunAngle { observer_id },
            PyScalarExpr::AzimuthFromLocation {
                location_id,
                obstructing_body,
            } => ScalarExpr::AzimuthFromLocation {
                location_id,
                obstructing_body,
            },
            PyScalarExpr::ElevationFromLocation {
                location_id,
                obstructing_body,
            } => ScalarExpr::ElevationFromLocation {
                location_id,
                obstructing_body,
            },
            PyScalarExpr::RangeFromLocation {
                location_id,
                obstructing_body,
            } => ScalarExpr::RangeFromLocation {
                location_id,
                obstructing_body,
            },
            PyScalarExpr::RangeRateFromLocation {
                location_id,
                obstructing_body,
            } => ScalarExpr::RangeRateFromLocation {
                location_id,
                obstructing_body,
            },

            // --- Recursive Conversions (now using the acquired `py` token) ---
            PyScalarExpr::Abs(v) => ScalarExpr::Abs(Box::new(v.borrow(py).clone().into())),
            PyScalarExpr::Add { a, b } => ScalarExpr::Add {
                a: Box::new(a.borrow(py).clone().into()),
                b: Box::new(b.borrow(py).clone().into()),
            },
            PyScalarExpr::Mul { a, b } => ScalarExpr::Mul {
                a: Box::new(a.borrow(py).clone().into()),
                b: Box::new(b.borrow(py).clone().into()),
            },
            PyScalarExpr::Negate(s) => ScalarExpr::Negate(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Invert(s) => ScalarExpr::Invert(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Sqrt(s) => ScalarExpr::Sqrt(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Powi { scalar, n } => ScalarExpr::Powi {
                scalar: Box::new(scalar.borrow(py).clone().into()),
                n,
            },
            PyScalarExpr::Powf { scalar, n } => ScalarExpr::Powf {
                scalar: Box::new(scalar.borrow(py).clone().into()),
                n,
            },
            PyScalarExpr::Cos(s) => ScalarExpr::Cos(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Sin(s) => ScalarExpr::Sin(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Tan(s) => ScalarExpr::Tan(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Acos(s) => ScalarExpr::Acos(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Asin(s) => ScalarExpr::Asin(Box::new(s.borrow(py).clone().into())),
            PyScalarExpr::Atan2 { y, x } => ScalarExpr::Atan2 {
                y: Box::new(y.borrow(py).clone().into()),
                x: Box::new(x.borrow(py).clone().into()),
            },
            PyScalarExpr::Modulo { v, m } => ScalarExpr::Modulo {
                v: Box::new(v.borrow(py).clone().into()),
                m: Box::new(m.borrow(py).clone().into()),
            },
            PyScalarExpr::Norm(v) => ScalarExpr::Norm(v.borrow(py).clone().into()),
            PyScalarExpr::NormSquared(v) => ScalarExpr::NormSquared(v.borrow(py).clone().into()),
            PyScalarExpr::DotProduct { a, b } => ScalarExpr::DotProduct {
                a: a.borrow(py).clone().into(),
                b: b.borrow(py).clone().into(),
            },
            PyScalarExpr::AngleBetween { a, b } => ScalarExpr::AngleBetween {
                a: a.borrow(py).clone().into(),
                b: b.borrow(py).clone().into(),
            },
            PyScalarExpr::VectorX(v) => ScalarExpr::VectorX(v.borrow(py).clone().into()),
            PyScalarExpr::VectorY(v) => ScalarExpr::VectorY(v.borrow(py).clone().into()),
            PyScalarExpr::VectorZ(v) => ScalarExpr::VectorZ(v.borrow(py).clone().into()),
            PyScalarExpr::RicDiff(s) => ScalarExpr::RicDiff(s.clone().into()),
            PyScalarExpr::FovMargin {
                instrument_id,
                sc_dcm_to_body,
                target,
            } => ScalarExpr::FovMargin {
                instrument_id,
                sc_dcm_to_body: sc_dcm_to_body.borrow(py).clone().into(),
                target: target.into(),
            },
            PyScalarExpr::FovMarginToLocation {
                instrument_id,
                sc_dcm_to_body,
                location_id,
            } => ScalarExpr::FovMarginToLocation {
                instrument_id,
                sc_dcm_to_body: sc_dcm_to_body.borrow(py).clone().into(),
                location_id,
            },
        })
    }
}
impl From<PyVectorExpr> for VectorExpr {
    fn from(value: PyVectorExpr) -> Self {
        Python::attach(|py| match value {
            PyVectorExpr::Fixed { x, y, z } => VectorExpr::Fixed { x, y, z },
            PyVectorExpr::Radius(spec) => VectorExpr::Radius(spec.borrow(py).clone().into()),
            PyVectorExpr::Velocity(spec) => VectorExpr::Velocity(spec.borrow(py).clone().into()),
            PyVectorExpr::OrbitalMomentum(spec) => {
                VectorExpr::OrbitalMomentum(spec.borrow(py).clone().into())
            }
            PyVectorExpr::EccentricityVector(spec) => {
                VectorExpr::EccentricityVector(spec.borrow(py).clone().into())
            }
            PyVectorExpr::CrossProduct { a, b } => VectorExpr::CrossProduct {
                a: Box::new(a.borrow(py).clone().into()),
                b: Box::new(b.borrow(py).clone().into()),
            },
            PyVectorExpr::VecProjection { a, b } => VectorExpr::VecProjection {
                a: Box::new(a.borrow(py).clone().into()),
                b: Box::new(b.borrow(py).clone().into()),
            },
            PyVectorExpr::Add { a, b } => VectorExpr::Add {
                a: Box::new(a.borrow(py).clone().into()),
                b: Box::new(b.borrow(py).clone().into()),
            },
            PyVectorExpr::Unit(v) => VectorExpr::Unit(Box::new(v.borrow(py).clone().into())),
            PyVectorExpr::Negate(v) => VectorExpr::Negate(Box::new(v.borrow(py).clone().into())),
            PyVectorExpr::Project { v, frame, plane } => VectorExpr::Project {
                v: Box::new(v.borrow(py).clone().into()),
                frame: Box::new(frame.borrow(py).clone().into()),
                plane,
            },
            PyVectorExpr::Rotate { v, dcm } => VectorExpr::Rotate {
                v: Box::new(v.borrow(py).clone().into()),
                dcm: Box::new(dcm.borrow(py).clone().into()),
            },
        })
    }
}

impl From<PyOrthogonalFrame> for OrthogonalFrame {
    fn from(value: PyOrthogonalFrame) -> Self {
        Python::attach(|py| match value {
            PyOrthogonalFrame::XY { x, y } => OrthogonalFrame::XY {
                x: x.borrow(py).clone().into(),
                y: y.borrow(py).clone().into(),
            },
            PyOrthogonalFrame::XZ { x, z } => OrthogonalFrame::XZ {
                x: x.borrow(py).clone().into(),
                z: z.borrow(py).clone().into(),
            },
            PyOrthogonalFrame::YZ { y, z } => OrthogonalFrame::YZ {
                y: y.borrow(py).clone().into(),
                z: z.borrow(py).clone().into(),
            },
        })
    }
}

impl From<PyStateSpec> for StateSpec {
    fn from(value: PyStateSpec) -> Self {
        StateSpec {
            target_frame: value.target_frame.into(),
            observer_frame: value.observer_frame.into(),
            ab_corr: value.ab_corr,
        }
    }
}

impl From<PyFrameSpec> for FrameSpec {
    fn from(value: PyFrameSpec) -> Self {
        match value {
            PyFrameSpec::Loaded(frame) => Self::Loaded(frame),
            PyFrameSpec::Manual { name, defn } => Python::attach(|py| {
                let py_ortho: PyOrthogonalFrame = defn.borrow(py).clone();

                Self::Manual {
                    name,
                    defn: Box::new(py_ortho.into()),
                }
            }),
        }
    }
}

impl From<PyDcmExpr> for DcmExpr {
    fn from(value: PyDcmExpr) -> Self {
        Python::attach(|py| match value {
            PyDcmExpr::Identity {
                from_id: from,
                to_id: to,
            } => DcmExpr::Identity { from, to },
            PyDcmExpr::R1 {
                angle_rad,
                from_id: from,
                to_id: to,
            } => DcmExpr::R1 {
                angle_rad,
                from,
                to,
            },
            PyDcmExpr::R2 {
                angle_rad,
                from_id: from,
                to_id: to,
            } => DcmExpr::R2 {
                angle_rad,
                from,
                to,
            },
            PyDcmExpr::R3 {
                angle_rad,
                from_id: from,
                to_id: to,
            } => DcmExpr::R3 {
                angle_rad,
                from,
                to,
            },
            PyDcmExpr::Quaternion {
                x,
                y,
                z,
                w,
                from_id: from,
                to_id: to,
            } => DcmExpr::Quaternion {
                x,
                y,
                z,
                w,
                from,
                to,
            },
            PyDcmExpr::RIC {
                state,
                from_id: from,
                to_id: to,
            } => DcmExpr::RIC {
                state: Box::new(state.borrow(py).clone().into()),
                from,
                to,
            },
            PyDcmExpr::RCN {
                state,
                from_id: from,
                to_id: to,
            } => DcmExpr::RCN {
                state: Box::new(state.borrow(py).clone().into()),
                from,
                to,
            },
            PyDcmExpr::VNC {
                state,
                from_id: from,
                to_id: to,
            } => DcmExpr::VNC {
                state: Box::new(state.borrow(py).clone().into()),
                from,
                to,
            },
            PyDcmExpr::SEZ {
                state,
                from_id: from,
                to_id: to,
            } => DcmExpr::SEZ {
                state: Box::new(state.borrow(py).clone().into()),
                from,
                to,
            },
            PyDcmExpr::Triad {
                primary_axis,
                primary_vec,
                secondary_axis,
                secondary_vec,
                from_id: from,
                to_id: to,
            } => DcmExpr::Triad {
                primary_axis: Box::new(primary_axis.borrow(py).clone().into()),
                primary_vec: Box::new(primary_vec.borrow(py).clone().into()),
                secondary_axis: Box::new(secondary_axis.borrow(py).clone().into()),
                secondary_vec: Box::new(secondary_vec.borrow(py).clone().into()),
                from,
                to,
            },
        })
    }
}