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