open_hypergraphs/array/
traits.rs

1//! The operations which an array type must support to implement open hypergraphs
2use core::fmt::Debug;
3use core::ops::{Add, Sub};
4use core::ops::{Bound, Range, RangeBounds};
5
6use num_traits::{One, Zero};
7
8/// Array *kinds*.
9/// For example, [`super::vec::VecKind`] is the set of types [`Vec<T>`] for all `T`.
10pub trait ArrayKind: Sized {
11    /// The type of arrays containing elements type T
12    type Type<T>;
13
14    /// The type of index *elements*. For [`super::vec::VecKind`], this is [`usize`].
15    type I: Clone
16        + PartialEq
17        + Ord
18        + Debug
19        + One
20        + Zero
21        + Add<Output = Self::I>
22        + Sub<Output = Self::I>
23        // NOTE: this last constraint that an index can add with rhs an Index array is a hack that
24        // lets us implement `tensor` for finite functions without unnecessary cloning.
25        + for<'a> Add<&'a Self::Index, Output = Self::Index>;
26
27    /// Arrays of indices (isomorphic to `Type<I>`) must implement NaturalArray
28    type Index: NaturalArray<Self>
29        + Into<Self::Type<Self::I>>
30        + From<Self::Type<Self::I>>
31        + AsRef<Self::Type<Self::I>>
32        + AsMut<Self::Type<Self::I>>
33        + PartialEq;
34
35    /// a `Slice` is a read-only view into another array's data.
36    /// For `VecKind` this is `&[T]`.
37    type Slice<'a, T: 'a>; // part of an array
38}
39
40/// Arrays of elements T for some [`ArrayKind`] `K`.
41///
42/// # Panics
43///
44/// Any operation using an index out of range for the given array will panic.
45pub trait Array<K: ArrayKind, T>: Clone {
46    /// The empty array
47    fn empty() -> Self;
48
49    /// Length of an array
50    fn len(&self) -> K::I;
51
52    /// Test if an array is empty
53    fn is_empty(&self) -> bool {
54        self.len() == K::I::zero()
55    }
56
57    fn from_slice(slice: K::Slice<'_, T>) -> Self;
58
59    /// Clamp any `R: RangeBounds<K::I>` into the range of valid indices for this array.
60    fn to_range<R: RangeBounds<K::I>>(&self, r: R) -> Range<K::I> {
61        let n = self.len();
62        let start = match r.start_bound().cloned() {
63            Bound::Included(i) => i,
64            Bound::Excluded(i) => i + K::I::one(),
65            Bound::Unbounded => K::I::zero(),
66        };
67
68        // NOTE: Range is *exclusive* of end, so for Included(i) we need to increment!.
69        let end = match r.end_bound().cloned() {
70            Bound::Included(i) => i + K::I::one(),
71            Bound::Excluded(i) => i,
72            Bound::Unbounded => n,
73        };
74
75        Range { start, end }
76    }
77
78    /// Concatenate two arrays
79    fn concatenate(&self, other: &Self) -> Self;
80
81    /// `fill(x, n)` returns the array length n containing repeated element x.
82    fn fill(x: T, n: K::I) -> Self;
83
84    /// Retrieve a single element by its index.
85    fn get(&self, i: K::I) -> T;
86
87    /// Get a contiguous range of the underlying array as a slice.
88    fn get_range<R: RangeBounds<K::I>>(&self, rb: R) -> K::Slice<'_, T>;
89
90    /// Write to a contiguous range of data in an array
91    fn set_range<R: RangeBounds<K::I>>(&mut self, rb: R, v: &K::Type<T>); // mutate self
92
93    /// Gather elements of this array according to the indices.
94    /// <https://en.wikipedia.org/wiki/Gather/scatter_(vector_addressing)#Gather>
95    /// ```text
96    /// x = self.gather(idx) // equivalent to x[i] = self[idx[i]]
97    /// ```
98    fn gather(&self, idx: K::Slice<'_, K::I>) -> Self;
99
100    /// Scatter elements of `self` into a new array at indices `idx`.
101    /// ```text
102    /// x = self.scatter(idx) // equivalent to x[idx[i]] = self[i]
103    /// ```
104    ///
105    /// # Panics
106    ///
107    /// If there is any `i ≥ n` in `idx`
108    fn scatter(&self, idx: K::Slice<'_, K::I>, n: K::I) -> Self;
109
110    fn scatter_assign(&mut self, ixs: &K::Index, values: Self);
111
112    /// Numpy `self[ixs] = arg`
113    fn scatter_assign_constant(&mut self, ixs: &K::Index, arg: T);
114}
115
116pub trait OrdArray<K: ArrayKind, T>: Clone + Array<K, T> {
117    /// Produce an array of indices which sorts `self`.
118    /// That is, `self.gather(self.argsort())` is monotonic.
119    fn argsort(&self) -> K::Index;
120
121    /// Sort this array by the given keys
122    ///
123    /// ```rust
124    /// use open_hypergraphs::array::{*, vec::*};
125    /// let values = VecArray(vec![10, 20, 30, 40]);
126    /// let keys = VecArray(vec![3, 1, 0, 2]);
127    /// let expected = VecArray(vec![30, 20, 40, 10]);
128    /// let actual = values.sort_by(&keys);
129    /// assert_eq!(expected, actual);
130    /// ```
131    fn sort_by(&self, key: &Self) -> Self {
132        self.gather(key.argsort().get_range(..))
133    }
134}
135
136/// Arrays of natural numbers.
137/// This is used for computing with *indexes* and *sizes*.
138pub trait NaturalArray<K: ArrayKind>:
139    OrdArray<K, K::I> + Sized + Sub<Self, Output = Self> + Add<Self, Output = Self> + AsRef<K::Index>
140{
141    fn max(&self) -> Option<K::I>;
142
143    /// An inclusive-and-exclusive cumulative sum
144    /// For an input of size `N`, returns an array `x` of size `N+1` where `x[0] = 0` and `x[-1] = sum(x)`
145    fn cumulative_sum(&self) -> Self;
146
147    // NOTE: we can potentially remove this if IndexedCoproduct moves to using pointers instead of
148    // segment sizes.
149    #[must_use]
150    fn sum(&self) -> K::I {
151        if self.len() == K::I::zero() {
152            K::I::zero()
153        } else {
154            self.cumulative_sum().get(self.len())
155        }
156    }
157
158    /// Indices from start to stop
159    ///
160    /// ```rust
161    /// use open_hypergraphs::array::{*, vec::*};
162    /// let x0 = VecArray::arange(&0, &3);
163    /// assert_eq!(x0, VecArray(vec![0, 1, 2]));
164    ///
165    /// let x1 = VecArray::arange(&0, &0);
166    /// assert_eq!(x1, VecArray(vec![]));
167    /// ```
168    fn arange(start: &K::I, stop: &K::I) -> Self;
169
170    /// Repeat each element of the given slice.
171    /// self and x must be equal lengths.
172    fn repeat(&self, x: K::Slice<'_, K::I>) -> Self;
173
174    /// Compute the arrays (self%denominator, self/denominator)
175    ///
176    /// # Panics
177    ///
178    /// When d == 0.
179    fn quot_rem(&self, d: K::I) -> (Self, Self);
180
181    /// Compute `self * c + x`, where `c` is a constant (scalar) and `x` is an array.
182    ///
183    /// # Panics
184    ///
185    /// When self.len() != x.len().
186    fn mul_constant_add(&self, c: K::I, x: &Self) -> Self;
187
188    /// Compute the connected components of a graph with `n` nodes.
189    /// Edges are stored as a pair of arrays of nodes `(sources, targets)`
190    /// meaning that for each `i` there is an edge `sources[i] → targets[i]`.
191    ///
192    /// Since `n` is the number of nodes in the graph, the values in `sources` and `targets` must
193    /// be less than `n`.
194    ///
195    /// # Returns
196    ///
197    /// Returns a pair `(cc_ix, k)`, where `cc_ix[i]` is the connected component for the `i`th
198    /// node, and `k` is the total number of components.
199    ///
200    /// # Panics
201    ///
202    /// * Inequal lengths: `sources.len() != targets.len()`
203    /// * Indexes are out of bounds: `sources[i] >= n` or `targets[i] >= n`.
204    fn connected_components(sources: &Self, targets: &Self, n: K::I) -> (Self, K::I);
205
206    /// Segmented sum of input.
207    /// For example, for `self = [1 2 0]`,
208    /// `self.segmented_sum([1 | 2 3]) = [1 5 0]`.
209    ///
210    /// # Panics
211    ///
212    /// When `self.sum() != x.len()`
213    fn segmented_sum(&self, x: &Self) -> Self {
214        let segment_sizes = self;
215
216        // cumulative sum of segments, including total size (last element)
217        // [ 2 4 ] → [ 0 2 6 ]
218        let ptr = segment_sizes.cumulative_sum();
219
220        // Cumulative sum of values
221        // [ 1 2 3 4 5 6 ] → [ 0 1 3 6 10 15 21 ]
222        let sum = x.cumulative_sum();
223
224        // total number of pointers (num segments + 1)
225        let n = ptr.len();
226
227        // NOTE: we do two allocations for both `gather`s here, but avoiding this
228        // would require complicating the API quite a bit!
229        sum.gather(ptr.get_range(K::I::one()..)) - sum.gather(ptr.get_range(..n - K::I::one()))
230    }
231
232    /// Given an array of *sizes* compute the concatenation of `arange` arrays of each size.
233    ///
234    /// ```rust
235    /// use open_hypergraphs::array::{*, vec::*};
236    /// let x = VecArray::<usize>(vec![2, 3, 0, 5]);
237    /// let y = VecArray::<usize>(vec![0, 1, 0, 1, 2, 0, 1, 2, 3, 4]);
238    /// assert_eq!(x.segmented_arange(), y)
239    /// ```
240    ///
241    /// Default implementation has time complexity:
242    ///
243    /// - Sequential: `O(n)`
244    /// - PRAM CREW: `O(log n)`
245    fn segmented_arange(&self) -> Self {
246        // How this works, by example:
247        //   input   = [ 2 3 0 5 ]
248        //   output  = [ 0 1 | 0 1 2 | | 0 1 2 3 4 ]
249        // compute ptrs
250        //   p       = [ 0 2 5 5 ]
251        //   r       = [ 0 0 | 2 2 2 | | 5 5 5 5 5 ]
252        //   i       = [ 0 1   2 3 4     5 6 7 8 9 ]
253        //   i - r   = [ 0 1 | 0 1 2 | | 0 1 2 3 4 ]
254        // Note: r is computed as repeat(p, n)
255        //
256        // Complexity
257        //   O(n)     sequential
258        //   O(log n) PRAM CREW (cumsum is log n)
259        let p = self.cumulative_sum();
260        let last_idx = p.len() - K::I::one();
261        let sum = p.get(last_idx.clone());
262
263        let r = self.repeat(p.get_range(..last_idx));
264        let i = Self::arange(&K::I::zero(), &sum);
265        i - r
266    }
267
268    /// Count occurrences of each value in the range [0, size)
269    fn bincount(&self, size: K::I) -> K::Index;
270
271    /// Compute index of unique values and their counts
272    fn sparse_bincount(&self) -> (K::Index, K::Index);
273
274    /// Return indices of elements which are zero
275    fn zero(&self) -> K::Index;
276
277    /// Compute `self[ixs] -= rhs`
278    fn scatter_sub_assign(&mut self, ixs: &K::Index, rhs: &K::Index);
279}