photom 0.4.0

Rust library for loading, structuring and querying astronomical observation datasets — with trajectory grouping, multi-observer support, and efficient lookups.
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
#![cfg(feature = "parallel")]
//! Parallel iterators over [`ObsDataset`] and its internal index, powered by
//! [rayon](https://docs.rs/rayon).
//!
//! This module is controlled by the `parallel` feature flag.  It is compiled
//! only when `parallel` is enabled in your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! photom = { version = "0.1", features = ["parallel"] }
//! ```
//!
//! Every method in this module is the parallel counterpart of a sequential
//! iterator defined on [`ObsDataset`] in `observation_dataset/mod.rs`.  The
//! function names, arguments, and return types mirror those sequential
//! variants exactly, differing only in that they return a
//! [`rayon::iter::ParallelIterator`] instead of a standard
//! [`std::iter::Iterator`].
//!
//! ## Public methods
//!
//! | Method | Description |
//! |--------|-------------|
//! | [`ObsDataset::par_iter_night_id`] | Parallel iterator over all `NightId` keys in the night index |
//! | [`ObsDataset::par_iter_observations`] | Parallel iterator over all observations in insertion order |
//! | [`ObsDataset::par_iter_full_night`] | Parallel iterator over `(NightId, &Observation)` pairs for every indexed night |
//! | [`ObsDataset::par_iter_night_observations`] | Parallel iterator over observations for a single night |
//! | [`ObsDataset::par_iter_traj_id`] | Parallel iterator over all `TrajId` keys in the trajectory index |
//! | [`ObsDataset::materialize_night_par`] | Collect observations for a single night into a `Vec` using parallel iteration |
//! | [`ObsDataset::par_iter_trajectory_observations`] | Parallel iterator over observations for a single trajectory |
//! | [`ObsDataset::par_iter_full_trajectory`] | Parallel iterator over `(TrajId, &Observation)` pairs for every indexed trajectory |
//! | [`ObsDataset::materialize_trajectory_par`] | Collect observations for a single trajectory into a `Vec` using parallel iteration |
//! | [`ObsDataset::par_iter_observer`] | Parallel iterator over all observers in the dataset, including both custom geodetic observers and MPC-coded observers |
//!
//! ## Ordering guarantees
//!
//! - **Across nights / trajectories**: the order is unspecified because the
//!   underlying index is an `AHashMap` with non-deterministic key order.
//! - **Within a single night or trajectory**: observations appear in
//!   *insertion order* (the order of the source `DataFrame` rows).
//! - **Materialised `Vec`s**: the order of elements collected by
//!   [`ObsDataset::materialize_night_par`] and
//!   [`ObsDataset::materialize_trajectory_par`] is **not** guaranteed,
//!   because parallel collection does not preserve iterator order.
//!
//! [`ObsDataset`]: crate::observation_dataset::ObsDataset

use itertools::Either;
use rayon::iter::{
    IndexedParallelIterator, IntoParallelIterator, IntoParallelRefIterator, ParallelIterator,
};

use crate::{
    NightId, TrajId,
    observation_dataset::{
        ObsDataset, ObsDatasetError,
        index::{ObsDatasetIndex, ObsIndex, ObsMapIndex},
        iter::MemLayoutObservations,
        observation::Observation,
    },
    observer::{Observer, dataset::ObserverId},
};

impl ObsDatasetIndex {
    /// Return a parallel iterator over the vector positions of all observations on a given night.
    ///
    /// This is the parallel counterpart of [`ObsDatasetIndex::iter_night_obs_index`](crate::observation_dataset::index::ObsDatasetIndex).
    ///
    /// # Arguments
    ///
    /// - `night_id` — the night identifier whose observation positions are requested.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` yielding each `ObsIndex` in insertion order if the night index
    /// exists and the night is present; `None` otherwise.
    pub(crate) fn par_iter_night_obs_index(
        &self,
        night_id: &NightId,
    ) -> Option<impl IndexedParallelIterator<Item = ObsIndex> + '_> {
        self.get_by_night(night_id).map(|indices| match indices {
            ObsMapIndex::Contiguous { start, end } => Either::Left((*start..*end).into_par_iter()),
            ObsMapIndex::Split(vec) => Either::Right(vec.par_iter().copied()),
        })
    }

    /// Return a parallel iterator over all `NightId` keys present in the night index.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if a night index was built; `None` otherwise.
    /// The iteration order is unspecified (hash map key order).
    pub(crate) fn par_iter_night_id(
        &self,
    ) -> Option<impl IndexedParallelIterator<Item = &NightId>> {
        self.obs_index_by_night
            .as_ref()
            .map(|night_map| night_map.keys().collect::<Vec<_>>().into_par_iter())
    }

    /// Return a parallel iterator over `(NightId, ObsIndex)` pairs for every observation
    /// in the night index.
    ///
    /// Each pair associates a night identifier with the vector position of one of the
    /// observations recorded on that night.  The order between nights is unspecified
    /// (hash map key order).
    ///
    /// This is the parallel counterpart of [`ObsDatasetIndex::iter_full_night`](crate::observation_dataset::index::ObsDatasetIndex).
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if a night index was built; `None` otherwise.
    pub(crate) fn par_iter_full_night(
        &self,
    ) -> Option<impl ParallelIterator<Item = (NightId, ObsIndex)> + '_> {
        self.obs_index_by_night.as_ref().map(|night_map| {
            night_map
                .par_iter()
                .flat_map(|(night_id, indices)| match indices {
                    ObsMapIndex::Contiguous { start, end } => Either::Left(
                        (*start..*end)
                            .into_par_iter()
                            .map(move |idx| (*night_id, idx)),
                    ),
                    ObsMapIndex::Split(vec) => {
                        Either::Right(vec.par_iter().map(move |&idx| (*night_id, idx)))
                    }
                })
        })
    }

    /// Return a parallel iterator over the vector positions of all observations in a given
    /// trajectory.
    ///
    /// This is the parallel counterpart of [`ObsDatasetIndex::iter_traj_obs_index`](crate::observation_dataset::index::ObsDatasetIndex).
    ///
    /// # Arguments
    ///
    /// - `traj_id` — the trajectory identifier whose observation positions are requested.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` yielding each `ObsIndex` in insertion order if the trajectory index
    /// exists and the trajectory is present; `None` otherwise.
    pub(crate) fn par_iter_traj_obs_index(
        &self,
        traj_id: impl Into<TrajId>,
    ) -> Option<impl IndexedParallelIterator<Item = ObsIndex> + '_> {
        self.get_by_trajectory(traj_id)
            .map(|indices| match indices {
                ObsMapIndex::Contiguous { start, end } => {
                    Either::Left((*start..*end).into_par_iter())
                }
                ObsMapIndex::Split(vec) => Either::Right(vec.par_iter().copied()),
            })
    }

    /// Return a parallel iterator over `(TrajId, ObsIndex)` pairs for every observation in
    /// the trajectory index.
    ///
    /// Each pair associates a trajectory identifier with the vector position of one of the
    /// observations belonging to that trajectory.  The order between trajectories is
    /// unspecified (hash map key order).
    ///
    /// This is the parallel counterpart of [`ObsDatasetIndex::iter_full_trajectory`](crate::observation_dataset::index::ObsDatasetIndex).
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if a trajectory index was built; `None` otherwise.
    pub(crate) fn par_iter_full_trajectory(
        &self,
    ) -> Option<impl ParallelIterator<Item = (TrajId, ObsIndex)> + '_> {
        self.obs_index_by_trajectory.as_ref().map(|traj_map| {
            traj_map
                .par_iter()
                .flat_map(|(traj_id, indices)| match indices {
                    ObsMapIndex::Contiguous { start, end } => Either::Left(
                        (*start..*end)
                            .into_par_iter()
                            .map(move |idx| (traj_id.clone(), idx)),
                    ),
                    ObsMapIndex::Split(vec) => {
                        Either::Right(vec.par_iter().map(move |&idx| (traj_id.clone(), idx)))
                    }
                })
        })
    }

    /// Return a parallel iterator over all `TrajId` keys present in the trajectory index.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if a trajectory index was built; `None` otherwise.
    /// The iteration order is unspecified (hash map key order).
    pub(crate) fn par_iter_traj_id(&self) -> Option<impl IndexedParallelIterator<Item = &TrajId>> {
        self.obs_index_by_trajectory
            .as_ref()
            .map(|traj_map| traj_map.keys().collect::<Vec<_>>().into_par_iter())
    }
}

impl ObsDataset {
    /// Return a parallel iterator over all `NightId` keys present in the night index.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset was built with a night index; `None` otherwise.
    /// The iteration order is unspecified.
    pub fn par_iter_night_id(&self) -> Option<impl IndexedParallelIterator<Item = &NightId>> {
        self.index.par_iter_night_id()
    }

    /// Return a parallel iterator over all observations in insertion order.
    ///
    /// The iterator yields shared references and does not clone any data.
    /// The order matches the order of the source `DataFrame` rows.
    ///
    /// Unlike [`ObsDataset::get_observation`], this method takes `&self` and
    /// can therefore be called while other shared borrows of the dataset are live.
    ///
    /// This is the parallel counterpart of [`ObsDataset::iter_observations`].
    ///
    /// # Returns
    ///
    /// An iterator yielding `&Observation` for each observation in insertion order.
    pub fn par_iter_observations(&self) -> impl IndexedParallelIterator<Item = &Observation> {
        self.observations.par_iter()
    }

    /// Return a parallel iterator over `(NightId, &Observation)` pairs for every observation
    /// in the night index.
    ///
    /// Each pair associates a night identifier with a shared reference to one of the
    /// observations recorded on that night.  The order between different nights is
    /// unspecified (hash map key order).
    ///
    /// This is the parallel counterpart of [`ObsDataset::iter_full_night`].
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset was built with a night index (`night_id` column
    /// present in the source data); `None` otherwise.
    pub fn par_iter_full_night(
        &self,
    ) -> Option<impl ParallelIterator<Item = (NightId, &Observation)>> {
        self.index
            .par_iter_full_night()
            .map(|night_iter| night_iter.map(|(night_id, idx)| (night_id, &self.observations[idx])))
    }

    /// Return a parallel iterator over all observations belonging to a given night, in
    /// insertion order.
    ///
    /// The order of the yielded observations matches the order of the source `DataFrame`
    /// rows.
    ///
    /// This is the parallel counterpart of [`ObsDataset::iter_night_observations`].
    ///
    /// # Arguments
    ///
    /// - `night_id` — the identifier of the night for which to return observations.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset has a night index and the given `night_id` is found,
    /// where `iterator` yields shared references to the observations belonging to that night
    /// in insertion order; `None` otherwise.
    pub fn par_iter_night_observations(
        &self,
        night_id: &NightId,
    ) -> Option<impl IndexedParallelIterator<Item = &Observation> + '_> {
        self.index
            .par_iter_night_obs_index(night_id)
            .map(|indices| indices.map(|idx| &self.observations[idx]))
    }

    /// Collect all observations belonging to a given night into a `Vec` using parallel
    /// iteration.
    ///
    /// This is a convenience wrapper around [`ObsDataset::par_iter_night_observations`] that
    /// eagerly collects the parallel iterator into a `Vec`.  Because collection is parallel,
    /// the order of elements in the returned `Vec` is **not** guaranteed.
    ///
    /// This is the parallel counterpart of [`ObsDataset::materialize_night`].
    ///
    /// # Arguments
    ///
    /// - `night_id` — the identifier of the night to materialise.
    ///
    /// # Returns
    ///
    /// `Some(Vec<&Observation>)` if the night index exists and the given `night_id` is
    /// present; `None` otherwise.  The order of elements in the `Vec` is unspecified.
    pub fn materialize_night_par(&self, night_id: &NightId) -> Option<MemLayoutObservations<'_>> {
        let night_index = self.index.obs_index_by_night.as_ref()?.get(night_id)?;
        match night_index {
            ObsMapIndex::Split(indices) => Some(MemLayoutObservations::Split(
                indices
                    .par_iter()
                    .map(|idx| &self.observations[*idx])
                    .collect(),
            )),
            ObsMapIndex::Contiguous { start, end } => Some(MemLayoutObservations::Contiguous(
                &self.observations[*start..*end],
            )),
        }
    }

    /// Return a parallel iterator over all `TrajId` keys present in the trajectory index.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset was built with a trajectory index; `None` otherwise.
    /// The iteration order is unspecified.
    pub fn par_iter_traj_id(&self) -> Option<impl IndexedParallelIterator<Item = &TrajId>> {
        self.index.par_iter_traj_id()
    }

    /// Return a parallel iterator over all observations belonging to a given trajectory, in
    /// insertion order.
    ///
    /// The order of the yielded observations matches the order of the source `DataFrame`
    /// rows.
    ///
    /// This is the parallel counterpart of [`ObsDataset::iter_trajectory_observations`].
    ///
    /// # Arguments
    ///
    /// - `traj_id` — the identifier of the trajectory for which to return observations.
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset has a trajectory index and the given `traj_id` is
    /// found, where `iterator` yields shared references to the observations belonging to
    /// that trajectory in insertion order; `None` otherwise.
    pub fn par_iter_trajectory_observations(
        &self,
        traj_id: impl Into<TrajId>,
    ) -> Option<impl IndexedParallelIterator<Item = &Observation>> {
        self.index
            .par_iter_traj_obs_index(traj_id)
            .map(|indices| indices.map(|idx| &self.observations[idx]))
    }

    /// Return a parallel iterator over `(TrajId, &Observation)` pairs for every observation
    /// in the trajectory index.
    ///
    /// Each pair associates a trajectory identifier with a shared reference to one of the
    /// observations belonging to that trajectory.  The order between different trajectories
    /// is unspecified (hash map key order).
    ///
    /// This is the parallel counterpart of [`ObsDataset::iter_full_trajectory`].
    ///
    /// # Returns
    ///
    /// `Some(iterator)` if the dataset was built with a trajectory index (`traj_id` column
    /// present in the source data); `None` otherwise.
    pub fn par_iter_full_trajectory(
        &self,
    ) -> Option<impl ParallelIterator<Item = (TrajId, &Observation)>> {
        self.index.par_iter_full_trajectory().map(|traj_iter| {
            traj_iter.map(|(traj_id, idx)| (traj_id.clone(), &self.observations[idx]))
        })
    }

    /// Collect all observations belonging to a given trajectory into a `Vec` using parallel
    /// iteration.
    ///
    /// This is a convenience wrapper around [`ObsDataset::par_iter_trajectory_observations`]
    /// that eagerly collects the parallel iterator into a `Vec`.  Because collection is
    /// parallel, the order of elements in the returned `Vec` is **not** guaranteed.
    ///
    /// This is the parallel counterpart of [`ObsDataset::materialize_trajectory`].
    ///
    /// # Arguments
    ///
    /// - `traj_id` — the identifier of the trajectory to materialise.
    ///
    /// # Returns
    ///
    /// `Some(Vec<&Observation>)` if the trajectory index exists and the given `traj_id` is
    /// present; `None` otherwise.  The order of elements in the `Vec` is unspecified.
    pub fn materialize_trajectory_par(
        &self,
        traj_id: impl Into<TrajId>,
    ) -> Option<MemLayoutObservations<'_>> {
        let traj_id = traj_id.into();
        let traj_index = self.index.obs_index_by_trajectory.as_ref()?.get(&traj_id)?;
        match traj_index {
            ObsMapIndex::Split(indices) => Some(MemLayoutObservations::Split(
                indices
                    .par_iter()
                    .map(|idx| &self.observations[*idx])
                    .collect(),
            )),
            ObsMapIndex::Contiguous { start, end } => Some(MemLayoutObservations::Contiguous(
                &self.observations[*start..*end],
            )),
        }
    }

    /// Return a parallel iterator over all observers in the dataset, including both custom geodetic observers and MPC-coded observers.
    /// The order of the yielded observers is unspecified.
    ///
    /// # Returns
    ///
    /// `Ok(iterator)` where `iterator` yields `(ObserverId, &Observer)` pairs for each observer in the dataset, if the MPC observatory catalogue was successfully loaded;
    /// `Err(ObsDatasetError::MpcCatalogueLoadError)` if the MPC observatory catalogue could not be loaded, which prevents access to MPC-coded observers.
    pub fn par_iter_observer(
        &self,
    ) -> Result<impl IndexedParallelIterator<Item = (ObserverId, &Observer)>, ObsDatasetError> {
        // Collect MPC observers into a Vec to get a stable, indexed iterator.
        let mpc_vec: Vec<_> = self
            .observer_dataset
            .mpc_observers()?
            .iter()
            .map(|(code, obs)| (ObserverId::MpcCode(*code), obs))
            .collect();

        let mpc_iter = mpc_vec.into_par_iter();

        let custom_iter = self
            .observer_dataset
            .custom_observers
            .par_iter()
            .enumerate()
            .map(|(idx, obs)| (ObserverId::IntId(idx), obs));

        Ok(mpc_iter.chain(custom_iter))
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod obsdataset_parallel_tests {
    use super::*;
    use ahash::AHashMap;
    use rayon::iter::ParallelIterator;

    use crate::{
        NightId, TrajId,
        coordinates::equatorial::EquCoord,
        observation_dataset::{
            index::{NightIndexMap, TrajIndexMap},
            observation::ObservationInput,
        },
        observer::error_model::ObsErrorModel,
        photometry::{Filter, Photometry},
    };

    // -----------------------------------------------------------------------
    // Test data helpers
    // -----------------------------------------------------------------------

    /// Build a minimal [`Observation`] with a given id and its position in the Vec.
    ///
    /// No observer is attached; all coordinate/photometry values are fixed constants
    /// so tests remain purely structural and do not depend on astrometric values.
    fn make_obs(id: u64, _index: usize) -> ObservationInput {
        ObservationInput {
            id,
            equ_coord: EquCoord::new(0.5, 1e-5, 0.2, 1e-5),
            photometry: Photometry {
                magnitude: 15.0,
                error: 0.1,
                filter: Filter::String("G".to_string()),
            },
            mjd_tt: 60000.0 + id as f64,
            observer: None,
        }
    }

    /// Build a dataset with 4 observations, a night index (2 nights × 2 obs) and a
    /// trajectory index (2 trajectories × 2 obs).
    ///
    /// Layout:
    /// - Night 1  → obs at positions 0, 1  (ids 1, 2)
    /// - Night 2  → obs at positions 2, 3  (ids 3, 4)
    /// - Traj 10  → obs at positions 0, 2  (ids 1, 3)
    /// - Traj 20  → obs at positions 1, 3  (ids 2, 4)
    fn make_dataset_with_index() -> ObsDataset {
        let obs = vec![
            make_obs(1, 0),
            make_obs(2, 1),
            make_obs(3, 2),
            make_obs(4, 3),
        ];

        let mut night_map: NightIndexMap = AHashMap::new();
        night_map.insert(NightId(1), ObsMapIndex::Split(vec![0, 1]));
        night_map.insert(NightId(2), ObsMapIndex::Split(vec![2, 3]));

        let mut traj_map: TrajIndexMap = AHashMap::new();
        traj_map.insert(TrajId::Int(10), ObsMapIndex::Split(vec![0, 2]));
        traj_map.insert(TrajId::Int(20), ObsMapIndex::Split(vec![1, 3]));

        ObsDataset::new(
            obs,
            vec![],
            Some(ObsErrorModel::FCCT14),
            Some(night_map),
            Some(traj_map),
        )
    }

    /// Build a dataset with 2 observations and **no** night or trajectory index.
    fn make_dataset_no_index() -> ObsDataset {
        let obs = vec![make_obs(1, 0), make_obs(2, 1)];
        ObsDataset::new(obs, vec![], Some(ObsErrorModel::FCCT14), None, None)
    }

    // -----------------------------------------------------------------------
    // Helper: extract the inner u32 from TrajId::Int for sorting.
    // Panics on TrajId::Str — only used in tests that exclusively use Int ids.
    // -----------------------------------------------------------------------
    /// Extract the inner `u32` from a [`TrajId::Int`] for use as a sort key.
    ///
    /// # Panics
    ///
    /// Panics if `id` is `TrajId::Str` — this helper is only used in tests
    /// that exclusively build `Int` trajectory identifiers.
    fn traj_id_key(id: &TrajId) -> u32 {
        match id {
            TrajId::Int(n) => *n,
            TrajId::Str(_) => panic!("unexpected TrajId::Str in sort key"),
        }
    }

    // =======================================================================
    // mod parallel_obs_iter — par_iter_observations (tests 1–3)
    // =======================================================================

    mod parallel_obs_iter {
        use super::*;

        /// Test 1 — parallel observation iterator over a 4-element dataset yields 4 items.
        #[test]
        fn par_iter_observations_count() {
            let dataset = make_dataset_with_index();
            assert_eq!(dataset.par_iter_observations().count(), 4);
        }

        /// Test 2 — collect observation ids from the parallel iterator; sorted result
        /// must equal [1, 2, 3, 4] regardless of thread scheduling order.
        #[test]
        fn par_iter_observations_ids() {
            let dataset = make_dataset_with_index();
            let mut ids: Vec<u64> = dataset.par_iter_observations().map(|o| o.id).collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1u64, 2, 3, 4]);
        }

        /// Test 3 — parallel observation iterator works even when the dataset was built
        /// without a night or trajectory index (no index is required for this method).
        #[test]
        fn par_iter_observations_no_index_count() {
            let dataset = make_dataset_no_index();
            assert_eq!(dataset.par_iter_observations().count(), 2);
        }
    }

    // =======================================================================
    // mod parallel_night — night-related parallel methods (tests 4–16)
    // =======================================================================

    mod parallel_night {
        use super::*;

        // -------------------------------------------------------------------
        // par_iter_full_night on ObsDataset
        // -------------------------------------------------------------------

        /// Test 4 — par_iter_full_night returns Some when the dataset was built with a
        /// night index.
        #[test]
        fn par_iter_full_night_some_when_night_index_present() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.par_iter_full_night().is_some(),
                "Expected Some when night index is present"
            );
        }

        /// Test 5 — par_iter_full_night returns None when the dataset has no night index.
        #[test]
        fn par_iter_full_night_none_when_no_night_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset.par_iter_full_night().is_none(),
                "Expected None when no night index"
            );
        }

        /// Test 6 — the full-night parallel iterator yields exactly 4 (NightId, &Observation)
        /// pairs across 2 nights of 2 observations each.
        #[test]
        fn par_iter_full_night_total_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 4 confirmed Some
            let count = dataset.par_iter_full_night().unwrap().count();
            assert_eq!(count, 4);
        }

        /// Test 7 — collect the NightId components, sort and dedup; the unique night ids
        /// must be exactly [NightId(1), NightId(2)].
        #[test]
        fn par_iter_full_night_night_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 4 confirmed Some
            let mut night_ids: Vec<NightId> = dataset
                .par_iter_full_night()
                .unwrap()
                .map(|(nid, _)| nid)
                .collect();
            night_ids.sort_unstable();
            night_ids.dedup();
            assert_eq!(night_ids, vec![NightId(1), NightId(2)]);
        }

        // -------------------------------------------------------------------
        // par_iter_night_observations on ObsDataset
        // -------------------------------------------------------------------

        /// Test 8 — par_iter_night_observations returns Some for a night that exists in
        /// the index.
        #[test]
        fn par_iter_night_observations_some_for_existing_night() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.par_iter_night_observations(&NightId(1)).is_some(),
                "Expected Some for NightId(1) which is present in the index"
            );
        }

        /// Test 9 — par_iter_night_observations returns None for a night that is not in
        /// the index.
        #[test]
        fn par_iter_night_observations_none_for_missing_night() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.par_iter_night_observations(&NightId(99)).is_none(),
                "Expected None for NightId(99) which is absent from the index"
            );
        }

        /// Test 10 — par_iter_night_observations returns None when the dataset has no night
        /// index at all (None was passed for obs_index_by_night).
        #[test]
        fn par_iter_night_observations_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset.par_iter_night_observations(&NightId(1)).is_none(),
                "Expected None when the dataset has no night index"
            );
        }

        /// Test 11 — the per-night parallel iterator for NightId(1) yields exactly 2 items.
        #[test]
        fn par_iter_night_observations_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 8 confirmed Some
            let count = dataset
                .par_iter_night_observations(&NightId(1))
                .unwrap()
                .count();
            assert_eq!(count, 2);
        }

        /// Test 12 — collect ids from night 1's parallel iterator, sort, and assert they
        /// equal [1, 2] (the two observations assigned to that night).
        #[test]
        fn par_iter_night_observations_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 8 confirmed Some
            let mut ids: Vec<u64> = dataset
                .par_iter_night_observations(&NightId(1))
                .unwrap()
                .map(|o| o.id)
                .collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1u64, 2]);
        }

        // -------------------------------------------------------------------
        // materialize_night_par on ObsDataset
        // -------------------------------------------------------------------

        /// Test 13 — materialize_night_par returns Some(vec) for a night that exists in
        /// the index.
        #[test]
        fn materialize_night_par_some_for_existing_night() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.materialize_night_par(&NightId(1)).is_some(),
                "Expected Some(vec) for NightId(1)"
            );
        }

        /// Test 14 — materialize_night_par returns None for a night that is not in the index.
        #[test]
        fn materialize_night_par_none_for_missing_night() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.materialize_night_par(&NightId(99)).is_none(),
                "Expected None for NightId(99)"
            );
        }

        /// Test 15 — the materialised Vec for NightId(1) has exactly 2 elements.
        #[test]
        fn materialize_night_par_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 13 confirmed Some
            let vec = dataset.materialize_night_par(&NightId(1)).unwrap();
            assert_eq!(vec.len(), 2);
        }

        /// Test 16 — ids in the materialised Vec for NightId(1), sorted, equal [1, 2].
        #[test]
        fn materialize_night_par_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 13 confirmed Some
            let vec = dataset.materialize_night_par(&NightId(1)).unwrap();
            let mut ids: Vec<u64> = vec.iter().map(|o| o.id).collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1u64, 2]);
        }
    }

    // =======================================================================
    // mod parallel_trajectory — trajectory-related parallel methods (tests 17–29)
    // =======================================================================

    mod parallel_trajectory {
        use super::*;

        // -------------------------------------------------------------------
        // par_iter_trajectory_observations on ObsDataset
        // -------------------------------------------------------------------

        /// Test 17 — par_iter_trajectory_observations returns Some for a trajectory that
        /// exists in the index.
        #[test]
        fn par_iter_trajectory_observations_some_for_existing_traj() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .par_iter_trajectory_observations(&TrajId::Int(10))
                    .is_some(),
                "Expected Some for TrajId::Int(10) which is present in the index"
            );
        }

        /// Test 18 — par_iter_trajectory_observations returns None for a trajectory that is
        /// not in the index.
        #[test]
        fn par_iter_trajectory_observations_none_for_missing_traj() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .par_iter_trajectory_observations(&TrajId::Int(99))
                    .is_none(),
                "Expected None for TrajId::Int(99) which is absent from the index"
            );
        }

        /// Test 19 — par_iter_trajectory_observations returns None when the dataset has no
        /// trajectory index at all.
        #[test]
        fn par_iter_trajectory_observations_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset
                    .par_iter_trajectory_observations(&TrajId::Int(10))
                    .is_none(),
                "Expected None when the dataset has no trajectory index"
            );
        }

        /// Test 20 — the per-trajectory parallel iterator for TrajId::Int(10) yields exactly
        /// 2 items (positions 0 and 2 in the observations Vec).
        #[test]
        fn par_iter_trajectory_observations_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 17 confirmed Some
            let count = dataset
                .par_iter_trajectory_observations(&TrajId::Int(10))
                .unwrap()
                .count();
            assert_eq!(count, 2);
        }

        /// Test 21 — collect ids from TrajId::Int(10)'s parallel iterator, sort, and assert
        /// they equal [1, 3] (observations at positions 0 and 2).
        #[test]
        fn par_iter_trajectory_observations_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 17 confirmed Some
            let mut ids: Vec<u64> = dataset
                .par_iter_trajectory_observations(&TrajId::Int(10))
                .unwrap()
                .map(|o| o.id)
                .collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1u64, 3]);
        }

        // -------------------------------------------------------------------
        // par_iter_full_trajectory on ObsDataset
        // -------------------------------------------------------------------

        /// Test 22 — par_iter_full_trajectory returns Some when the dataset was built with a
        /// trajectory index.
        #[test]
        fn par_iter_full_trajectory_some_when_traj_index_present() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset.par_iter_full_trajectory().is_some(),
                "Expected Some when trajectory index is present"
            );
        }

        /// Test 23 — par_iter_full_trajectory returns None when the dataset has no trajectory
        /// index.
        #[test]
        fn par_iter_full_trajectory_none_when_no_traj_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset.par_iter_full_trajectory().is_none(),
                "Expected None when no trajectory index"
            );
        }

        /// Test 24 — the full-trajectory parallel iterator yields exactly 4 pairs across
        /// 2 trajectories of 2 observations each.
        #[test]
        fn par_iter_full_trajectory_total_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 22 confirmed Some
            let count = dataset.par_iter_full_trajectory().unwrap().count();
            assert_eq!(count, 4);
        }

        /// Test 25 — collect the TrajId components from the full-trajectory iterator, sort
        /// and dedup by inner u32 value; the unique ids must be exactly
        /// [TrajId::Int(10), TrajId::Int(20)].
        #[test]
        fn par_iter_full_trajectory_traj_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 22 confirmed Some
            let mut traj_ids: Vec<TrajId> = dataset
                .par_iter_full_trajectory()
                .unwrap()
                .map(|(tid, _)| tid)
                .collect();
            traj_ids.sort_unstable_by_key(traj_id_key);
            traj_ids.dedup_by_key(|id| traj_id_key(id));
            assert_eq!(traj_ids, vec![TrajId::Int(10), TrajId::Int(20)]);
        }

        // -------------------------------------------------------------------
        // materialize_trajectory_par on ObsDataset
        // -------------------------------------------------------------------

        /// Test 26 — materialize_trajectory_par returns Some(vec) for a trajectory that
        /// exists in the index.
        #[test]
        fn materialize_trajectory_par_some_for_existing_traj() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .materialize_trajectory_par(TrajId::Int(10))
                    .is_some(),
                "Expected Some(vec) for TrajId::Int(10)"
            );
        }

        /// Test 27 — materialize_trajectory_par returns None for a trajectory that is not in
        /// the index.
        #[test]
        fn materialize_trajectory_par_none_for_missing_traj() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .materialize_trajectory_par(TrajId::Int(99))
                    .is_none(),
                "Expected None for TrajId::Int(99)"
            );
        }

        /// Test 28 — the materialised Vec for TrajId::Int(10) has exactly 2 elements.
        #[test]
        fn materialize_trajectory_par_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 26 confirmed Some
            let vec = dataset.materialize_trajectory_par(TrajId::Int(10)).unwrap();
            assert_eq!(vec.len(), 2);
        }

        /// Test 29 — ids in the materialised Vec for TrajId::Int(10), sorted, equal [1, 3].
        #[test]
        fn materialize_trajectory_par_ids() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 26 confirmed Some
            let vec = dataset.materialize_trajectory_par(TrajId::Int(10)).unwrap();
            let mut ids: Vec<u64> = vec.iter().map(|o| o.id).collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![1u64, 3]);
        }
    }

    // =======================================================================
    // mod parallel_index — crate-private ObsDatasetIndex parallel methods (tests 30–39)
    // =======================================================================
    //
    // ObsDatasetIndex is crate-private; we access it through the `index` field
    // of ObsDataset (also pub(crate)), which is visible here because this test
    // module lives inside the same crate.

    mod parallel_index {
        use super::*;

        // -------------------------------------------------------------------
        // par_iter_night_obs_index (tests 30–32)
        // -------------------------------------------------------------------

        /// Test 30 — par_iter_night_obs_index returns None on an index that has no night map.
        #[test]
        fn index_par_iter_night_obs_index_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset
                    .index
                    .par_iter_night_obs_index(&NightId(1))
                    .is_none(),
                "Expected None when the dataset index has no night map"
            );
        }

        /// Test 31 — par_iter_night_obs_index returns Some for a night that is present in
        /// the night map.
        #[test]
        fn index_par_iter_night_obs_index_some_for_existing() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .index
                    .par_iter_night_obs_index(&NightId(1))
                    .is_some(),
                "Expected Some for NightId(1) which is in the night map"
            );
        }

        /// Test 32 — par_iter_night_obs_index for NightId(1) yields exactly 2 raw indices
        /// (positions 0 and 1 in the observations Vec).
        #[test]
        fn index_par_iter_night_obs_index_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 31 confirmed Some
            let count = dataset
                .index
                .par_iter_night_obs_index(&NightId(1))
                .unwrap()
                .count();
            assert_eq!(count, 2);
        }

        // -------------------------------------------------------------------
        // par_iter_full_night on ObsDatasetIndex (tests 33–34)
        // -------------------------------------------------------------------

        /// Test 33 — ObsDatasetIndex::par_iter_full_night returns None when no night map
        /// exists.
        #[test]
        fn index_par_iter_full_night_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset.index.par_iter_full_night().is_none(),
                "Expected None from index.par_iter_full_night() when no night map"
            );
        }

        /// Test 34 — ObsDatasetIndex::par_iter_full_night returns Some and yields exactly 4
        /// (NightId, ObsIndex) pairs (2 nights × 2 observations each).
        #[test]
        fn index_par_iter_full_night_some_and_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: the night map is present
            let count = dataset.index.par_iter_full_night().unwrap().count();
            assert_eq!(count, 4);
        }

        // -------------------------------------------------------------------
        // par_iter_traj_obs_index (tests 35–37)
        // -------------------------------------------------------------------

        /// Test 35 — par_iter_traj_obs_index returns None on an index that has no trajectory
        /// map.
        #[test]
        fn index_par_iter_traj_obs_index_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset
                    .index
                    .par_iter_traj_obs_index(TrajId::Int(10))
                    .is_none(),
                "Expected None when the dataset index has no trajectory map"
            );
        }

        /// Test 36 — par_iter_traj_obs_index returns Some for a trajectory that is present
        /// in the trajectory map.
        #[test]
        fn index_par_iter_traj_obs_index_some_for_existing() {
            let dataset = make_dataset_with_index();
            assert!(
                dataset
                    .index
                    .par_iter_traj_obs_index(TrajId::Int(10))
                    .is_some(),
                "Expected Some for TrajId::Int(10) which is in the trajectory map"
            );
        }

        /// Test 37 — par_iter_traj_obs_index for TrajId::Int(10) yields exactly 2 raw
        /// indices (positions 0 and 2 in the observations Vec).
        #[test]
        fn index_par_iter_traj_obs_index_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: test 36 confirmed Some
            let count = dataset
                .index
                .par_iter_traj_obs_index(TrajId::Int(10))
                .unwrap()
                .count();
            assert_eq!(count, 2);
        }

        // -------------------------------------------------------------------
        // par_iter_full_trajectory on ObsDatasetIndex (tests 38–39)
        // -------------------------------------------------------------------

        /// Test 38 — ObsDatasetIndex::par_iter_full_trajectory returns None when no
        /// trajectory map exists.
        #[test]
        fn index_par_iter_full_trajectory_none_without_index() {
            let dataset = make_dataset_no_index();
            assert!(
                dataset.index.par_iter_full_trajectory().is_none(),
                "Expected None from index.par_iter_full_trajectory() when no trajectory map"
            );
        }

        /// Test 39 — ObsDatasetIndex::par_iter_full_trajectory returns Some and yields
        /// exactly 4 (TrajId, ObsIndex) pairs (2 trajectories × 2 observations each).
        #[test]
        fn index_par_iter_full_trajectory_some_and_count() {
            let dataset = make_dataset_with_index();
            // unwrap is safe: the trajectory map is present
            let count = dataset.index.par_iter_full_trajectory().unwrap().count();
            assert_eq!(count, 4);
        }
    }

    // =======================================================================
    // mod parallel_traj_id_iter — par_iter_traj_id (tests 4–7)
    // =======================================================================

    mod parallel_traj_id_iter {
        use super::*;

        /// Test 4 — `par_iter_traj_id` returns `Some` when a trajectory index is present.
        #[test]
        fn returns_some_when_index_present() {
            let dataset = make_dataset_with_index();
            assert!(dataset.par_iter_traj_id().is_some());
        }

        /// Test 5 — `par_iter_traj_id` returns `None` when no trajectory index was built.
        #[test]
        fn returns_none_when_no_index() {
            let dataset = make_dataset_no_index();
            assert!(dataset.par_iter_traj_id().is_none());
        }

        /// Test 6 — the parallel iterator yields exactly as many keys as trajectories
        /// registered in the index (2 in the test fixture).
        #[test]
        fn yields_correct_count() {
            let dataset = make_dataset_with_index();
            let count = dataset
                .par_iter_traj_id()
                .expect("trajectory index must be present")
                .count();
            assert_eq!(count, 2);
        }

        /// Test 7 — the collected and sorted trajectory ids match the expected set,
        /// regardless of thread scheduling order.
        #[test]
        fn yields_correct_ids() {
            let dataset = make_dataset_with_index();
            let mut ids: Vec<u32> = dataset
                .par_iter_traj_id()
                .expect("trajectory index must be present")
                .map(traj_id_key)
                .collect();
            ids.sort_unstable();
            assert_eq!(ids, vec![10u32, 20]);
        }
    }
}