grid1d 0.6.0

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
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
#![deny(rustdoc::broken_intra_doc_links)]

//! Zero-copy windowed view over a contiguous slice of intervals in a partition.
//!
//! This module provides [`Grid1DWindow`], a lightweight borrowed view that
//! restricts an existing [`crate::Grid1DTrait`] to a contiguous sub-range
//! `[first_interval_id, first_interval_id + num_intervals_in_window)`. All point-location
//! queries are filtered to that sub-range: points outside the window return `None`.
//!
//! ## Motivation
//!
//! Domain-decomposition algorithms and overlapping Schwarz methods frequently operate on
//! a strict sub-domain of the global grid. `Grid1DWindow` avoids copying
//! coordinates or constructing a new grid object — it borrows the underlying partition
//! and delegates the heavy lifting (coordinate arrays, interval construction, point-location)
//! to it.
//!
//! ## Window domain semantics
//!
//! The [`Grid1DWindow::window_domain`] method returns the covering interval of
//! the window, with boundary semantics derived from the underlying partition domain:
//!
//! | Partition domain | Interior window | End window |
//! |-----------------|-----------------|------------|
//! | `[a, b]` | `[pₖ, pₖ₊ₘ)` | `[pₖ, pₙ]` |
//! | `(a, b)` | `(pₖ, pₖ₊ₘ]` | `(pₖ, pₙ)` |
//! | `[a, b)` | `[pₖ, pₖ₊ₘ)` | `[pₖ, pₙ)` |
//! | `(a, b]` | `(pₖ, pₖ₊ₘ]` | `(pₖ, pₙ]` |
//!
//! ## Construction and errors
//!
//! Use [`Grid1DWindow::try_new`]. The only possible error is
//! [`ErrorsGrid1DWindow::WindowExceedsPartitionBounds`], returned when
//! `first_interval_id + num_intervals_in_window` exceeds the total interval count.
//!
//! ```rust
//! use grid1d::{Grid1DUniform, Grid1DWindow, FindIntervalIdOfPoint, intervals::*};
//! use grid1d::scalars::{NumIntervals, IntervalId};
//! use try_create::TryNew;
//!
//! let grid = Grid1DUniform::new(
//!     IntervalClosed::new(0.0_f64, 3.0),
//!     NumIntervals::try_new(3).unwrap(),
//! );
//!
//! // Window over intervals 1 and 2 ([1.0, 3.0])
//! let window = Grid1DWindow::try_new(
//!     &grid,
//!     IntervalId::new(1),
//!     NumIntervals::try_new(2).unwrap(),
//! ).unwrap();
//!
//! assert!(window.find_interval_id_of_point(&1.5).is_some()); // inside window
//! assert!(window.find_interval_id_of_point(&0.5).is_none()); // outside window
//! ```

use crate::{
    Grid1D, Grid1DNonUniform, Grid1DUniform, IntervalClosed, IntervalFinitePositiveLength,
    IntervalId, IntervalLowerClosedUpperOpen, IntervalLowerOpenUpperClosed, IntervalOpen,
    NumIntervals,
    grids::{
        FindIntervalIdOfPoint, Grid1DIntervalBuilder, Grid1DTrait, HasCoords1D, HasDomain1D,
        HasIntervalIdRange, HasIntervals,
    },
    intervals::{Contains, GetLowerBoundValue, GetUpperBoundValue, bounded::IntervalFromBounds},
};
use std::backtrace::Backtrace;
use thiserror::Error;

//------------------------------------------------------------------------------------------------
/// Errors that can arise when constructing a [`Grid1DWindow`].
#[derive(Error, Debug)]
pub enum ErrorsGrid1DWindow {
    /// Error indicating that the specified window of intervals exceeds the bounds of the partition.
    #[error("The requested window of intervals exceeds the bounds of the partition!")]
    WindowExceedsPartitionBounds {
        /// The first interval ID in the requested window.
        first_interval_id: IntervalId,
        /// The number of intervals requested in the window.
        num_intervals_in_window: NumIntervals,
        /// The total number of intervals in the partition.
        total_num_intervals: NumIntervals,
        /// Captured backtrace for debugging.
        backtrace: Backtrace,
    },
}
/// A contiguous sub-range of intervals within a borrowed [`Grid1DTrait`].
///
/// `Grid1DWindow` provides a lightweight, zero-copy view into a slice of
/// consecutive intervals `[first_interval_id, first_interval_id + num_intervals_in_window)`
/// of an existing partition.
///
/// It implements [`FindIntervalIdOfPoint`] for [`Grid1DUniform`], [`Grid1DNonUniform`], and
/// [`Grid1D`], restricting point-location queries to the window's extent: points outside
/// the window return `None`.
///
/// # Construction
///
/// Use [`Grid1DWindow::try_new`]; construction fails with
/// [`ErrorsGrid1DWindow::WindowExceedsPartitionBounds`] when the requested
/// range exceeds the partition's total interval count.
///
/// # Example
///
/// ```rust
/// use grid1d::{Grid1DUniform, Grid1DWindow, FindIntervalIdOfPoint};
/// use grid1d::scalars::{NumIntervals, IntervalId};
/// use grid1d::intervals::*;
/// use try_create::TryNew;
///
/// let grid = Grid1DUniform::new(IntervalClosed::new(0.0_f64, 1.0), NumIntervals::try_new(10).unwrap());
///
/// // Window covering intervals 2, 3, 4 (indices 2..5, i.e. [0.2, 0.5))
/// let window = Grid1DWindow::try_new(
///     &grid,
///     IntervalId::new(2),
///     NumIntervals::try_new(3).unwrap(),
/// ).unwrap();
///
/// assert!(window.find_interval_id_of_point(&0.25).is_some()); // inside window
/// assert!(window.find_interval_id_of_point(&0.05).is_none()); // outside window
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Grid1DWindow<'a, PartitionType: Grid1DTrait> {
    partition: &'a PartitionType,
    first_interval_id: IntervalId,
    num_intervals_in_window: NumIntervals,
}

impl<'a, PartitionType: Grid1DTrait> Grid1DWindow<'a, PartitionType> {
    /// Creates a new `Grid1DWindow` over a contiguous range of intervals.
    ///
    /// # Parameters
    ///
    /// - `partition`: shared reference to the underlying partition.
    /// - `first_interval_id`: global index of the first interval included in the window.
    /// - `num_intervals_in_window`: number of consecutive intervals the window covers.
    ///
    /// # Errors
    ///
    /// Returns [`ErrorsGrid1DWindow::WindowExceedsPartitionBounds`] when
    /// `first_interval_id + num_intervals_in_window` exceeds the partition's total
    /// interval count.
    pub fn try_new(
        partition: &'a PartitionType,
        first_interval_id: IntervalId,
        num_intervals_in_window: NumIntervals,
    ) -> Result<Self, ErrorsGrid1DWindow> {
        let total_num_intervals = partition.num_intervals();
        if first_interval_id.as_ref() + num_intervals_in_window.as_ref()
            > *total_num_intervals.as_ref()
        {
            Err(ErrorsGrid1DWindow::WindowExceedsPartitionBounds {
                first_interval_id,
                num_intervals_in_window,
                total_num_intervals,
                backtrace: Backtrace::capture(),
            })
        } else {
            Ok(Self {
                partition,
                first_interval_id,
                num_intervals_in_window,
            })
        }
    }

    /// Returns the interval (domain) covered by this window.
    ///
    /// The boundary semantics of the returned interval follow the same sub-interval
    /// construction rules defined by [`Grid1DIntervalBuilder`]:
    ///
    /// - **Lower bound**: always matches the partition domain's lower bound type.
    /// - **Upper bound**:
    ///   - Window ends at the partition's last interval → matches the domain's upper bound type.
    ///   - Interior window → opposite of the lower bound type (interior sub-intervals are
    ///     `[pₖ, pₖ₊₁)` for left-closed domains, `(pₖ, pₖ₊₁]` for left-open domains).
    ///
    /// | Domain  | Interior window    | Window ending at last interval |
    /// |---------|--------------------|--------------------------------|
    /// | `[a,b]` | `[pₖ, pₖ₊ₘ)`      | `[pₖ, pₙ]`                     |
    /// | `(a,b)` | `(pₖ, pₖ₊ₘ]`      | `(pₖ, pₙ)`                     |
    /// | `[a,b)` | `[pₖ, pₖ₊ₘ)`      | `[pₖ, pₙ)`                     |
    /// | `(a,b]` | `(pₖ, pₖ₊ₘ]`      | `(pₖ, pₙ]`                     |
    ///
    /// # Example
    ///
    /// ```rust
    /// use grid1d::{Grid1DUniform, Grid1DWindow, HasIntervalIdRange, intervals::*};
    /// use grid1d::scalars::{NumIntervals, IntervalId};
    /// use try_create::TryNew;
    ///
    /// let grid = Grid1DUniform::new(
    ///     IntervalClosed::new(0.0_f64, 1.0),
    ///     NumIntervals::try_new(10).unwrap(),
    /// );
    ///
    /// // Interior window — upper is open (interior sub-interval semantics)
    /// let w_int = Grid1DWindow::try_new(
    ///     &grid, IntervalId::new(2), NumIntervals::try_new(3).unwrap(),
    /// ).unwrap();
    /// assert!(matches!(
    ///     w_int.window_domain(),
    ///     IntervalFinitePositiveLength::LowerClosedUpperOpen(_)
    /// ));
    ///
    /// // Window ending at the last interval — upper is closed (matches domain)
    /// let w_end = Grid1DWindow::try_new(
    ///     &grid, IntervalId::new(7), NumIntervals::try_new(3).unwrap(),
    /// ).unwrap();
    /// assert!(matches!(w_end.window_domain(), IntervalFinitePositiveLength::Closed(_)));
    /// ```
    #[must_use]
    pub fn window_domain(
        &self,
    ) -> IntervalFinitePositiveLength<<PartitionType as HasCoords1D>::CoordType> {
        let coords = self.partition.coords().as_ref();
        let first = *self.first_interval_id.as_ref();
        let last = first + *self.num_intervals_in_window.as_ref();
        let lower = coords[first].clone();
        let upper = coords[last].clone();

        let domain = self.partition.domain();
        let is_lower_closed = domain.is_lower_bound_closed();
        let window_ends_at_partition_end = last == *self.partition.num_intervals().as_ref();
        let is_upper_closed = if window_ends_at_partition_end {
            domain.is_upper_bound_closed()
        } else {
            !is_lower_closed
        };

        match (is_lower_closed, is_upper_closed) {
            (true, true) => IntervalFinitePositiveLength::Closed(IntervalClosed::new(lower, upper)),
            (false, false) => IntervalFinitePositiveLength::Open(IntervalOpen::new(lower, upper)),
            (true, false) => IntervalFinitePositiveLength::LowerClosedUpperOpen(
                IntervalLowerClosedUpperOpen::new(lower, upper),
            ),
            (false, true) => IntervalFinitePositiveLength::LowerOpenUpperClosed(
                IntervalLowerOpenUpperClosed::new(lower, upper),
            ),
        }
    }
}

impl<PartitionType: Grid1DTrait> HasIntervalIdRange for Grid1DWindow<'_, PartitionType> {
    #[inline(always)]
    fn first_interval_id(&self) -> IntervalId {
        self.first_interval_id
    }

    #[inline(always)]
    fn last_interval_id(&self) -> IntervalId {
        IntervalId::new(
            *self.first_interval_id.as_ref() + *self.num_intervals_in_window.as_ref() - 1,
        )
    }
}

impl<PartitionType: Grid1DTrait> HasIntervals for Grid1DWindow<'_, PartitionType> {
    type IntervalType = <PartitionType as HasIntervals>::IntervalType;

    #[inline(always)]
    fn interval(&self, interval_id: &IntervalId) -> Self::IntervalType {
        self.partition.interval(interval_id)
    }
}

impl<Domain1D> FindIntervalIdOfPoint for Grid1DWindow<'_, Grid1DNonUniform<Domain1D>>
where
    Domain1D: Grid1DIntervalBuilder,
{
    type Point1DType = Domain1D::RealType;

    #[inline]
    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        let coords = self.partition.coords().as_ref();
        let window_start = *self.first_interval_id.as_ref();
        let num_window_intervals = *self.num_intervals_in_window.as_ref();
        let window_end = window_start + num_window_intervals;

        // The window uses coordinates coords[window_start..=window_end]
        // Deref Coords1D to &[T] first (Coords1D::Index only accepts CoordId)
        let window_coords: &[_] = &coords[window_start..=window_end];

        let is_lower_closed = self.partition.domain().is_lower_bound_closed();

        // Compute the upper bound closure of the window:
        //   - window ends at the partition boundary → inherits the domain's upper closure
        //   - interior window                       → opposite of the lower closure
        //     (e.g. [a,b] → sub-intervals are [pₖ,pₖ₊₁), so interior upper is open)
        let window_ends_at_partition_end = window_end == *self.partition.num_intervals().as_ref();
        let is_upper_closed = if window_ends_at_partition_end {
            self.partition.domain().is_upper_bound_closed()
        } else {
            !is_lower_closed
        };

        // O(1) early exit: reject points outside the window coordinate range.
        //   Closed lower [lower, ...): x < lower  → None
        //   Open   lower (lower, ...): x ≤ lower  → None
        //   Closed upper [..., upper]: x > upper  → None
        //   Open   upper [..., upper): x ≥ upper  → None
        let lower = &window_coords[0];
        let upper = &window_coords[num_window_intervals];
        if is_lower_closed {
            if x < lower {
                return None;
            }
        } else if x <= lower {
            return None;
        }
        if is_upper_closed {
            if x > upper {
                return None;
            }
        } else if x >= upper {
            return None;
        }

        // Mirror Grid1DNonUniform::find_interval_id_of_point:
        // the domain's lower bound closure determines whether sub-intervals are
        // left-closed or right-closed, which in turn determines how boundary
        // points are assigned to intervals.

        // find_insertion_index = partition_point(|c| c < x)
        let idx = window_coords.partition_point(|c| c < x);
        let candidate_id_in_window = if is_lower_closed {
            // Sub-intervals are left-closed [pₖ, pₖ₊₁): boundary point pₖ belongs
            // to interval k.
            // After the guard, x >= lower, so idx == 0 iff x == window_coords[0].
            if idx == 0 {
                0 // x is exactly the first window coordinate
            } else if idx < window_coords.len() && &window_coords[idx] == x {
                // Exact match at an interior coordinate: belongs to the right interval.
                idx.min(num_window_intervals - 1)
            } else {
                // x lies strictly inside an interval.
                // Safe: idx > 0 (handled above), so idx - 1 is valid.
                (idx - 1).min(num_window_intervals - 1)
            }
        } else {
            // Sub-intervals are right-closed (pₖ, pₖ₊₁]: boundary point pₖ belongs
            // to interval k-1.
            // After the guard, x > lower, so partition_point returns idx >= 1; no underflow.
            (idx - 1).min(num_window_intervals - 1)
        };

        // Convert to the partition's global interval ID and verify containment.
        // The containment check correctly handles boundary semantics (open/closed
        // window endpoints) without any additional logic.
        let interval_id = IntervalId::new(window_start + candidate_id_in_window);
        let interval = self.partition.interval(&interval_id);

        if interval.contains_point(x) {
            Some(interval_id)
        } else {
            None
        }
    }
}

impl<Domain1D> FindIntervalIdOfPoint for Grid1DWindow<'_, Grid1DUniform<Domain1D>>
where
    Domain1D: Grid1DIntervalBuilder,
{
    type Point1DType = Domain1D::RealType;

    #[inline(always)]
    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        // Uniform partition lookup is O(1). We still must restrict results to this
        // window, so we apply an O(1) membership filter on the computed global ID.
        self.partition
            .find_interval_id_of_point(x)
            .filter(|&id| self.range_contains_interval_id(&id))
    }
}

impl<Domain1D> FindIntervalIdOfPoint for Grid1DWindow<'_, Grid1D<Domain1D>>
where
    Domain1D: Grid1DIntervalBuilder,
{
    type Point1DType = Domain1D::RealType;

    #[inline]
    fn find_interval_id_of_point(&self, x: &Self::Point1DType) -> Option<IntervalId> {
        match self.partition {
            Grid1D::Uniform(grid_uniform) => grid_uniform
                .find_interval_id_of_point(x)
                .filter(|&id| self.range_contains_interval_id(&id)),
            Grid1D::NonUniform(grid_non_uniform) => {
                // Convert the enum variant to a non-uniform window view and reuse
                // the existing boundary and window-aware point-location logic.
                let partition = Grid1DWindow {
                    partition: grid_non_uniform,
                    first_interval_id: self.first_interval_id,
                    num_intervals_in_window: self.num_intervals_in_window,
                };
                partition.find_interval_id_of_point(x)
            }
        }
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use crate::{coords::*, intervals::*};
    use num_valid::RealNative64StrictFinite;
    use sorted_vec::partial::SortedSet;
    use try_create::TryNew;

    use super::*;

    type Real = RealNative64StrictFinite;

    #[test]
    fn interval_partition_window_try_new_ok_and_membership() {
        let domain = IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
        let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());

        let window =
            Grid1DWindow::try_new(&grid, IntervalId::new(1), NumIntervals::try_new(2).unwrap())
                .unwrap();

        assert!(window.range_contains_interval_id(&IntervalId::new(1)));
        assert!(window.range_contains_interval_id(&IntervalId::new(2)));
        assert!(!window.range_contains_interval_id(&IntervalId::new(0)));
    }

    #[test]
    fn interval_partition_window_try_new_err_out_of_bounds() {
        let domain = IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
        let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());

        let err =
            Grid1DWindow::try_new(&grid, IntervalId::new(2), NumIntervals::try_new(2).unwrap())
                .unwrap_err();

        assert!(matches!(
            err,
            ErrorsGrid1DWindow::WindowExceedsPartitionBounds { .. }
        ));
    }

    #[test]
    fn interval_partition_window_find_non_uniform_left_closed() {
        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
            Real::try_new(0.0).unwrap(),
            Real::try_new(1.0).unwrap(),
            Real::try_new(2.0).unwrap(),
            Real::try_new(3.0).unwrap(),
        ]))
        .unwrap();

        let grid = Grid1DNonUniform::<IntervalClosed<Real>>::try_new_from_coords(coords).unwrap();

        let window =
            Grid1DWindow::try_new(&grid, IntervalId::new(1), NumIntervals::try_new(2).unwrap())
                .unwrap();

        // x equals the window left boundary (coord at global index 1)
        // and must map to interval 1 for left-closed semantics.
        assert_eq!(
            window
                .find_interval_id_of_point(&Real::try_new(1.0).unwrap())
                .unwrap(),
            IntervalId::new(1)
        );
    }

    #[test]
    fn interval_partition_window_find_non_uniform_right_closed() {
        let coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
            Real::try_new(0.0).unwrap(),
            Real::try_new(1.0).unwrap(),
            Real::try_new(2.0).unwrap(),
            Real::try_new(3.0).unwrap(),
        ]))
        .unwrap();

        let grid =
            Grid1DNonUniform::<IntervalLowerOpenUpperClosed<Real>>::try_new_from_coords(coords)
                .unwrap();

        let window =
            Grid1DWindow::try_new(&grid, IntervalId::new(1), NumIntervals::try_new(2).unwrap())
                .unwrap();

        // For right-closed semantics, interior boundary 2.0 belongs to interval 1.
        assert_eq!(
            window
                .find_interval_id_of_point(&Real::try_new(2.0).unwrap())
                .unwrap(),
            IntervalId::new(1)
        );
    }

    #[test]
    fn interval_partition_window_find_uniform_respects_window() {
        let domain = IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
        let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());

        let window =
            Grid1DWindow::try_new(&grid, IntervalId::new(1), NumIntervals::try_new(1).unwrap())
                .unwrap();

        assert_eq!(
            window
                .find_interval_id_of_point(&Real::try_new(1.5).unwrap())
                .unwrap(),
            IntervalId::new(1)
        );
        assert!(
            window
                .find_interval_id_of_point(&Real::try_new(0.5).unwrap())
                .is_none()
        );
    }

    #[test]
    fn interval_partition_window_find_grid1d_uniform_and_non_uniform() {
        let uniform_domain =
            IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
        let uniform_grid: Grid1D<IntervalClosed<Real>> =
            Grid1D::uniform(uniform_domain, NumIntervals::try_new(3).unwrap());
        let window_uniform = Grid1DWindow::try_new(
            &uniform_grid,
            IntervalId::new(1),
            NumIntervals::try_new(1).unwrap(),
        )
        .unwrap();

        assert_eq!(
            window_uniform
                .find_interval_id_of_point(&Real::try_new(1.5).unwrap())
                .unwrap(),
            IntervalId::new(1)
        );
        assert!(
            window_uniform
                .find_interval_id_of_point(&Real::try_new(0.5).unwrap())
                .is_none()
        );

        let non_uniform_coords = Coords1D::try_from(SortedSet::from_unsorted(vec![
            Real::try_new(0.0).unwrap(),
            Real::try_new(1.0).unwrap(),
            Real::try_new(2.0).unwrap(),
            Real::try_new(3.0).unwrap(),
        ]))
        .unwrap();
        let non_uniform_grid =
            Grid1D::<IntervalClosed<Real>>::try_from_coords(non_uniform_coords).unwrap();
        let window_non_uniform = Grid1DWindow::try_new(
            &non_uniform_grid,
            IntervalId::new(1),
            NumIntervals::try_new(2).unwrap(),
        )
        .unwrap();

        assert_eq!(
            window_non_uniform
                .find_interval_id_of_point(&Real::try_new(1.0).unwrap())
                .unwrap(),
            IntervalId::new(1)
        );
    }

    mod interval_partition_window_matrix {
        use super::*;

        fn assert_point_ids<W>(finder: &W, cases: &[(f64, Option<usize>)])
        where
            W: FindIntervalIdOfPoint<Point1DType = Real>,
        {
            for (x, expected_id) in cases {
                let x_real = Real::try_new(*x).unwrap();
                let actual = finder.find_interval_id_of_point(&x_real);
                let expected = expected_id.map(IntervalId::new);
                assert_eq!(actual, expected, "x = {x}");
            }
        }

        fn all_probe_points_closed() -> Vec<(f64, Option<usize>)> {
            vec![
                (0.0, Some(0)),
                (1.0, Some(1)),
                (2.0, Some(2)),
                (3.0, Some(2)),
                (0.5, Some(0)),
                (1.5, Some(1)),
                (2.5, Some(2)),
            ]
        }

        fn all_probe_points_open() -> Vec<(f64, Option<usize>)> {
            vec![
                (0.0, None),
                (1.0, Some(0)),
                (2.0, Some(1)),
                (3.0, None),
                (0.5, Some(0)),
                (1.5, Some(1)),
                (2.5, Some(2)),
            ]
        }

        fn all_probe_points_lc_uo() -> Vec<(f64, Option<usize>)> {
            vec![
                (0.0, Some(0)),
                (1.0, Some(1)),
                (2.0, Some(2)),
                (3.0, None),
                (0.5, Some(0)),
                (1.5, Some(1)),
                (2.5, Some(2)),
            ]
        }

        fn all_probe_points_lo_uc() -> Vec<(f64, Option<usize>)> {
            vec![
                (0.0, None),
                (1.0, Some(0)),
                (2.0, Some(1)),
                (3.0, Some(2)),
                (0.5, Some(0)),
                (1.5, Some(1)),
                (2.5, Some(2)),
            ]
        }

        fn make_window<'a, G: Grid1DTrait>(grid: &'a G) -> Grid1DWindow<'a, G> {
            Grid1DWindow::try_new(grid, IntervalId::new(0), NumIntervals::try_new(3).unwrap())
                .unwrap()
        }

        fn assert_point_ids_in_window<'a, G: Grid1DTrait>(
            grid: &'a G,
            cases: &[(f64, Option<usize>)],
        ) where
            Grid1DWindow<'a, G>: FindIntervalIdOfPoint<Point1DType = Real>,
        {
            let window = make_window(grid);

            assert_point_ids(&window, cases);
        }

        mod uniform {
            use super::*;

            #[test]
            fn interval_closed() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());
                assert_point_ids_in_window(&grid, &all_probe_points_closed());
            }

            #[test]
            fn interval_open() {
                let domain =
                    IntervalOpen::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());
                assert_point_ids_in_window(&grid, &all_probe_points_open());
            }

            #[test]
            fn interval_lower_closed_upper_open() {
                let domain = IntervalLowerClosedUpperOpen::new(
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                );
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());
                assert_point_ids_in_window(&grid, &all_probe_points_lc_uo());
            }

            #[test]
            fn interval_lower_open_upper_closed() {
                let domain = IntervalLowerOpenUpperClosed::new(
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                );
                let grid = Grid1DUniform::new(domain, NumIntervals::try_new(3).unwrap());
                assert_point_ids_in_window(&grid, &all_probe_points_lo_uc());
            }
        }

        mod non_uniform {
            use super::*;

            fn coords_0_1_2_3() -> Coords1D<Real> {
                Coords1D::try_from(SortedSet::from_unsorted(vec![
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(1.0).unwrap(),
                    Real::try_new(2.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                ]))
                .unwrap()
            }

            #[test]
            fn interval_closed() {
                let domain =
                    IntervalClosed::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
                let grid = Grid1DNonUniform::try_new(domain, coords_0_1_2_3()).unwrap();
                assert_point_ids_in_window(&grid, &all_probe_points_closed());
            }

            #[test]
            fn interval_open() {
                let domain =
                    IntervalOpen::new(Real::try_new(0.0).unwrap(), Real::try_new(3.0).unwrap());
                let grid = Grid1DNonUniform::try_new(domain, coords_0_1_2_3()).unwrap();
                assert_point_ids_in_window(&grid, &all_probe_points_open());
            }

            #[test]
            fn interval_lower_closed_upper_open() {
                let domain = IntervalLowerClosedUpperOpen::new(
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                );
                let grid = Grid1DNonUniform::try_new(domain, coords_0_1_2_3()).unwrap();
                assert_point_ids_in_window(&grid, &all_probe_points_lc_uo());
            }

            #[test]
            fn interval_lower_open_upper_closed() {
                let domain = IntervalLowerOpenUpperClosed::new(
                    Real::try_new(0.0).unwrap(),
                    Real::try_new(3.0).unwrap(),
                );
                let grid = Grid1DNonUniform::try_new(domain, coords_0_1_2_3()).unwrap();
                assert_point_ids_in_window(&grid, &all_probe_points_lo_uc());
            }
        }
    }

    mod window_domain {
        use super::*;

        fn r(v: f64) -> Real {
            Real::try_new(v).unwrap()
        }

        // Grid with 3 uniform intervals on [0, 3]: coords = [0, 1, 2, 3].
        // Interior window = first 2 intervals (coords[0]..coords[2]).
        // End window      = last 2 intervals  (coords[1]..coords[3]).

        mod uniform {
            use super::*;

            // [a, b] domain ─────────────────────────────────────────────
            // interior → [p, q),  end → [p, q]
            #[test]
            fn closed_interior_is_lower_closed_upper_open() {
                let grid = Grid1DUniform::new(
                    IntervalClosed::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::LowerClosedUpperOpen(_)),
                    "expected LowerClosedUpperOpen, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(0.0));
                assert_eq!(*d.upper_bound_value(), r(2.0));
            }

            #[test]
            fn closed_end_is_closed() {
                let grid = Grid1DUniform::new(
                    IntervalClosed::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::Closed(_)),
                    "expected Closed, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(1.0));
                assert_eq!(*d.upper_bound_value(), r(3.0));
            }

            // (a, b) domain ─────────────────────────────────────────────
            // interior → (p, q],  end → (p, q)
            #[test]
            fn open_interior_is_lower_open_upper_closed() {
                let grid = Grid1DUniform::new(
                    IntervalOpen::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::LowerOpenUpperClosed(_)),
                    "expected LowerOpenUpperClosed, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(0.0));
                assert_eq!(*d.upper_bound_value(), r(2.0));
            }

            #[test]
            fn open_end_is_open() {
                let grid = Grid1DUniform::new(
                    IntervalOpen::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::Open(_)),
                    "expected Open, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(1.0));
                assert_eq!(*d.upper_bound_value(), r(3.0));
            }

            // [a, b) domain ─────────────────────────────────────────────
            // always → [p, q)  (domain upper is already open)
            #[test]
            fn lower_closed_upper_open_interior_is_lower_closed_upper_open() {
                let grid = Grid1DUniform::new(
                    IntervalLowerClosedUpperOpen::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                assert!(matches!(
                    w.window_domain(),
                    IntervalFinitePositiveLength::LowerClosedUpperOpen(_)
                ));
            }

            #[test]
            fn lower_closed_upper_open_end_is_lower_closed_upper_open() {
                let grid = Grid1DUniform::new(
                    IntervalLowerClosedUpperOpen::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                assert!(matches!(
                    w.window_domain(),
                    IntervalFinitePositiveLength::LowerClosedUpperOpen(_)
                ));
            }

            // (a, b] domain ─────────────────────────────────────────────
            // always → (p, q]  (domain upper is already closed)
            #[test]
            fn lower_open_upper_closed_interior_is_lower_open_upper_closed() {
                let grid = Grid1DUniform::new(
                    IntervalLowerOpenUpperClosed::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                assert!(matches!(
                    w.window_domain(),
                    IntervalFinitePositiveLength::LowerOpenUpperClosed(_)
                ));
            }

            #[test]
            fn lower_open_upper_closed_end_is_lower_open_upper_closed() {
                let grid = Grid1DUniform::new(
                    IntervalLowerOpenUpperClosed::new(r(0.0), r(3.0)),
                    NumIntervals::try_new(3).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                assert!(matches!(
                    w.window_domain(),
                    IntervalFinitePositiveLength::LowerOpenUpperClosed(_)
                ));
            }

            // Window spanning the whole partition ────────────────────────
            #[test]
            fn full_partition_window_matches_domain() {
                let grid = Grid1DUniform::new(
                    IntervalClosed::new(r(0.0), r(4.0)),
                    NumIntervals::try_new(4).unwrap(),
                );
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(4).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(matches!(d, IntervalFinitePositiveLength::Closed(_)));
                assert_eq!(*d.lower_bound_value(), r(0.0));
                assert_eq!(*d.upper_bound_value(), r(4.0));
            }
        }

        mod non_uniform {
            use super::*;

            // Grid on [0, 6] with non-uniform coords [0, 1, 3, 6] (3 intervals).
            fn coords_0_1_3_6() -> Coords1D<Real> {
                Coords1D::try_from(SortedSet::from_unsorted(vec![
                    r(0.0),
                    r(1.0),
                    r(3.0),
                    r(6.0),
                ]))
                .unwrap()
            }

            // Interior window = intervals 0..1 (coords[0]=0 to coords[2]=3).
            // End window      = intervals 1..2 (coords[1]=1 to coords[3]=6).

            #[test]
            fn closed_interior_is_lower_closed_upper_open_with_correct_bounds() {
                let grid = Grid1DNonUniform::try_new(
                    IntervalClosed::new(r(0.0), r(6.0)),
                    coords_0_1_3_6(),
                )
                .unwrap();
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::LowerClosedUpperOpen(_)),
                    "expected LowerClosedUpperOpen, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(0.0));
                assert_eq!(*d.upper_bound_value(), r(3.0)); // coords[2]
            }

            #[test]
            fn closed_end_is_closed_with_correct_bounds() {
                let grid = Grid1DNonUniform::try_new(
                    IntervalClosed::new(r(0.0), r(6.0)),
                    coords_0_1_3_6(),
                )
                .unwrap();
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::Closed(_)),
                    "expected Closed, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(1.0)); // coords[1]
                assert_eq!(*d.upper_bound_value(), r(6.0)); // coords[3]
            }

            #[test]
            fn open_interior_is_lower_open_upper_closed_with_correct_bounds() {
                let grid =
                    Grid1DNonUniform::try_new(IntervalOpen::new(r(0.0), r(6.0)), coords_0_1_3_6())
                        .unwrap();
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(0),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::LowerOpenUpperClosed(_)),
                    "expected LowerOpenUpperClosed, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(0.0));
                assert_eq!(*d.upper_bound_value(), r(3.0)); // coords[2]
            }

            #[test]
            fn open_end_is_open_with_correct_bounds() {
                let grid =
                    Grid1DNonUniform::try_new(IntervalOpen::new(r(0.0), r(6.0)), coords_0_1_3_6())
                        .unwrap();
                let w = Grid1DWindow::try_new(
                    &grid,
                    IntervalId::new(1),
                    NumIntervals::try_new(2).unwrap(),
                )
                .unwrap();
                let d = w.window_domain();
                assert!(
                    matches!(d, IntervalFinitePositiveLength::Open(_)),
                    "expected Open, got {d:?}",
                );
                assert_eq!(*d.lower_bound_value(), r(1.0)); // coords[1]
                assert_eq!(*d.upper_bound_value(), r(6.0)); // coords[3]
            }
        }
    }
}
//------------------------------------------------------------------------------------------------