polydat_nodes/vector_set.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Element and set operations over the integer vector carriers, and
5//! elementwise equality over every vector carrier.
6//!
7//! The float vector nodes ([`super::vector_math`]) compute over
8//! embeddings; these read integer vectors as *lists*: how many
9//! elements, what is at an index, does a value appear, where, and how
10//! two lists compare as sets. A host holding a list of ordinals — the
11//! records matching a label, the queries matching a predicate — asks
12//! these the questions it would otherwise ask a counter.
13//!
14//! That is the point of them. A rank ("how many matching records come
15//! before this one") and a cardinality ("how many match at all") look
16//! like things a counter produces as records go by, but both are pure
17//! functions of the list and the record: the rank is the position, the
18//! cardinality is the length. Written that way the answer is owned by
19//! its inputs, replays from its coordinates, and agrees on every engine
20//! and every fiber, where a counter's answer depends on how many times
21//! it was called ([Runtime Model](../../polydat/docs/design/runtime_model.md)
22//! §9.1, "No state across pulls").
23//!
24//! Each operation exists for `vec_i32` and `vec_i64`, since the carrier
25//! is part of the wire's type and polydat does not silently widen one
26//! to the other. An index or a value that is out of range answers
27//! rather than panicking, because a miss is an ordinary result here:
28//! `vec_position` returns the length when the value is absent, which is
29//! "past the end" and the same convention `vec_len` bounds.
30
31/// `vec_len_i32(v)` — how many elements the list holds.
32#[polydat::polydat_node(category = Arithmetic)]
33fn vec_len_i32(v: &[i32]) -> u64 {
34 v.len() as u64
35}
36
37/// `vec_len_i64(v)` — how many elements the list holds.
38#[polydat::polydat_node(category = Arithmetic)]
39fn vec_len_i64(v: &[i64]) -> u64 {
40 v.len() as u64
41}
42
43/// `vec_at_i32(v, i)` — the element at `i`, or `0` past the end.
44///
45/// Out of range answers rather than failing: a caller that cares
46/// compares `i` with `vec_len_i32` first, and one that is walking a
47/// list it already sized does not pay for a check it cannot fail.
48#[polydat::polydat_node(category = Arithmetic)]
49fn vec_at_i32(v: &[i32], i: u64) -> i64 {
50 v.get(i as usize).copied().unwrap_or(0) as i64
51}
52
53/// `vec_at_i64(v, i)` — the element at `i`, or `0` past the end.
54#[polydat::polydat_node(category = Arithmetic)]
55fn vec_at_i64(v: &[i64], i: u64) -> i64 {
56 v.get(i as usize).copied().unwrap_or(0)
57}
58
59/// `vec_max_i32(v)` — the largest element, or `0` for an empty list.
60#[polydat::polydat_node(category = Arithmetic)]
61fn vec_max_i32(v: &[i32]) -> i64 {
62 v.iter().copied().max().unwrap_or(0) as i64
63}
64
65/// `vec_max_i64(v)` — the largest element, or `0` for an empty list.
66#[polydat::polydat_node(category = Arithmetic)]
67fn vec_max_i64(v: &[i64]) -> i64 {
68 v.iter().copied().max().unwrap_or(0)
69}
70
71/// `vec_min_i32(v)` — the smallest element, or `0` for an empty list.
72#[polydat::polydat_node(category = Arithmetic)]
73fn vec_min_i32(v: &[i32]) -> i64 {
74 v.iter().copied().min().unwrap_or(0) as i64
75}
76
77/// `vec_min_i64(v)` — the smallest element, or `0` for an empty list.
78#[polydat::polydat_node(category = Arithmetic)]
79fn vec_min_i64(v: &[i64]) -> i64 {
80 v.iter().copied().min().unwrap_or(0)
81}
82
83/// `vec_contains_i32(v, x)` — `1` when `x` appears in the list, else `0`.
84#[polydat::polydat_node(category = Comparison)]
85fn vec_contains_i32(v: &[i32], x: i64) -> u64 {
86 u64::from(i32::try_from(x).is_ok_and(|x| v.contains(&x)))
87}
88
89/// `vec_contains_i64(v, x)` — `1` when `x` appears in the list, else `0`.
90#[polydat::polydat_node(category = Comparison)]
91fn vec_contains_i64(v: &[i64], x: i64) -> u64 {
92 u64::from(v.contains(&x))
93}
94
95/// `vec_position_i32(v, x)` — the index of the first `x`, or the list's
96/// length when it does not appear.
97///
98/// The length is "past the end", so a caller can branch on
99/// `pos == vec_len_i32(v)` without a second sentinel, and a rank over a
100/// sorted list of ordinals reads directly as the position.
101#[polydat::polydat_node(category = Comparison)]
102fn vec_position_i32(v: &[i32], x: i64) -> u64 {
103 match i32::try_from(x) {
104 Ok(x) => v.iter().position(|e| *e == x).unwrap_or(v.len()) as u64,
105 Err(_) => v.len() as u64,
106 }
107}
108
109/// `vec_position_i64(v, x)` — the index of the first `x`, or the list's
110/// length when it does not appear.
111#[polydat::polydat_node(category = Comparison)]
112fn vec_position_i64(v: &[i64], x: i64) -> u64 {
113 v.iter().position(|e| *e == x).unwrap_or(v.len()) as u64
114}
115
116/// `vec_count_below_i32(v, x)` — how many elements are less than `x`.
117///
118/// The rank of a record among the matching ones, without requiring the
119/// list to be sorted or the record to be in it, which
120/// `vec_position_i32` both do.
121#[polydat::polydat_node(category = Comparison)]
122fn vec_count_below_i32(v: &[i32], x: i64) -> u64 {
123 v.iter().filter(|e| i64::from(**e) < x).count() as u64
124}
125
126/// `vec_count_below_i64(v, x)` — how many elements are less than `x`.
127#[polydat::polydat_node(category = Comparison)]
128fn vec_count_below_i64(v: &[i64], x: i64) -> u64 {
129 v.iter().filter(|e| **e < x).count() as u64
130}
131
132/// `vec_intersect_count_i32(a, b)` — how many *distinct* values appear
133/// in both lists.
134///
135/// Distinct, because this answers "how much do these two sets overlap",
136/// which a repeated value would otherwise inflate. A caller wanting the
137/// multiset count writes the fold it means.
138#[polydat::polydat_node(category = Comparison)]
139fn vec_intersect_count_i32(a: &[i32], b: &[i32]) -> u64 {
140 let set: std::collections::BTreeSet<i32> = b.iter().copied().collect();
141 let mine: std::collections::BTreeSet<i32> = a.iter().copied().collect();
142 mine.intersection(&set).count() as u64
143}
144
145/// `vec_intersect_count_i64(a, b)` — how many distinct values appear in
146/// both lists.
147#[polydat::polydat_node(category = Comparison)]
148fn vec_intersect_count_i64(a: &[i64], b: &[i64]) -> u64 {
149 let set: std::collections::BTreeSet<i64> = b.iter().copied().collect();
150 let mine: std::collections::BTreeSet<i64> = a.iter().copied().collect();
151 mine.intersection(&set).count() as u64
152}
153
154/// `vec_set_eq_i32(a, b)` — `1` when both lists hold the same set of
155/// values, whatever their order or repetition.
156#[polydat::polydat_node(category = Comparison)]
157fn vec_set_eq_i32(a: &[i32], b: &[i32]) -> u64 {
158 let x: std::collections::BTreeSet<i32> = a.iter().copied().collect();
159 let y: std::collections::BTreeSet<i32> = b.iter().copied().collect();
160 u64::from(x == y)
161}
162
163/// `vec_set_eq_i64(a, b)` — `1` when both lists hold the same set of
164/// values, whatever their order or repetition.
165#[polydat::polydat_node(category = Comparison)]
166fn vec_set_eq_i64(a: &[i64], b: &[i64]) -> u64 {
167 let x: std::collections::BTreeSet<i64> = a.iter().copied().collect();
168 let y: std::collections::BTreeSet<i64> = b.iter().copied().collect();
169 u64::from(x == y)
170}
171
172// ── Elementwise equality ────────────────────────────────────────────
173//
174// `vec_eq_<t>(a, b)` exists for every vector carrier. It answers
175// whether two vectors are the same value: the same length and every
176// element identical. A float element compares by its bits, so `-0.0`
177// and `0.0` differ and a NaN equals a NaN with the same bits; that is
178// the identity a host auditing a vector it wrote needs, where IEEE
179// equality would call a NaN unequal to itself. A length mismatch is
180// `false`, never a failure.
181
182/// Whether two slices have the same length and every element pair has
183/// the same key.
184fn same_by<T, K: PartialEq>(a: &[T], b: &[T], key: impl Fn(&T) -> K) -> bool {
185 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| key(x) == key(y))
186}
187
188/// `vec_eq_f16(a, b)` — `true` when both vectors have the same length
189/// and every element has the same bits.
190#[polydat::polydat_node(category = Comparison)]
191fn vec_eq_f16(a: &[polydat::half::f16], b: &[polydat::half::f16]) -> bool {
192 same_by(a, b, |x| x.to_bits())
193}
194
195/// `vec_eq_f32(a, b)` — `true` when both vectors have the same length
196/// and every element has the same bits.
197///
198/// `-0.0` and `0.0` differ, and a NaN equals a NaN with the same
199/// payload.
200#[polydat::polydat_node(category = Comparison)]
201fn vec_eq_f32(a: &[f32], b: &[f32]) -> bool {
202 same_by(a, b, |x| x.to_bits())
203}
204
205/// `vec_eq_f64(a, b)` — `true` when both vectors have the same length
206/// and every element has the same bits.
207#[polydat::polydat_node(category = Comparison)]
208fn vec_eq_f64(a: &[f64], b: &[f64]) -> bool {
209 same_by(a, b, |x| x.to_bits())
210}
211
212/// `vec_eq_i8(a, b)` — `true` when both vectors have the same length
213/// and equal elements.
214#[polydat::polydat_node(category = Comparison)]
215fn vec_eq_i8(a: &[i8], b: &[i8]) -> bool {
216 a == b
217}
218
219/// `vec_eq_i16(a, b)` — `true` when both vectors have the same length
220/// and equal elements.
221#[polydat::polydat_node(category = Comparison)]
222fn vec_eq_i16(a: &[i16], b: &[i16]) -> bool {
223 a == b
224}
225
226/// `vec_eq_i32(a, b)` — `true` when both vectors have the same length
227/// and equal elements, in order.
228///
229/// Order and repetition count, unlike `vec_set_eq_i32`.
230#[polydat::polydat_node(category = Comparison)]
231fn vec_eq_i32(a: &[i32], b: &[i32]) -> bool {
232 a == b
233}
234
235/// `vec_eq_i64(a, b)` — `true` when both vectors have the same length
236/// and equal elements, in order.
237#[polydat::polydat_node(category = Comparison)]
238fn vec_eq_i64(a: &[i64], b: &[i64]) -> bool {
239 a == b
240}
241
242// ── Reading a list from text ────────────────────────────────────────
243
244/// `str_to_vec_i32(s)` — a JSON array of integers as a `vec_i32` wire.
245///
246/// The public name for a parse the crate already performed internally
247/// at the boundary: a host holding a list as text — a column it
248/// selected, a facet it loaded, a literal in a workload — gets it onto
249/// a wire the list operations read. The `as` cast does not do this,
250/// because text to a typed vector can fail on its input and the
251/// adapter catalog only inserts conversions that cannot ([Type
252/// System](type_system.md) §3); naming it is the caller saying it
253/// accepts that.
254///
255/// Fails by name on anything that is not a JSON array of integers in
256/// range, rather than skipping the element: a list silently short one
257/// entry is a wrong count everywhere downstream.
258#[polydat::polydat_node(category = Conversions)]
259fn str_to_vec_i32(s: &str) -> Vec<i32> {
260 parse_int_array("str_to_vec_i32", s)
261 .into_iter()
262 .map(|n| {
263 i32::try_from(n).unwrap_or_else(|_| {
264 panic!(
265 "str_to_vec_i32: element {n} is outside i32 [{}, {}]",
266 i32::MIN,
267 i32::MAX
268 )
269 })
270 })
271 .collect()
272}
273
274/// `str_to_vec_i64(s)` — a JSON array of integers as a `vec_i64` wire.
275#[polydat::polydat_node(category = Conversions)]
276fn str_to_vec_i64(s: &str) -> Vec<i64> {
277 parse_int_array("str_to_vec_i64", s)
278}
279
280/// `str_to_vec_f64(s)` — a JSON array of numbers as a `vec_f64` wire,
281/// such as a window of samples for `is_stable`. Fails by name on
282/// anything that is not a JSON array of numbers.
283#[polydat::polydat_node(category = Conversions)]
284fn str_to_vec_f64(s: &str) -> Vec<f64> {
285 let raw = s.trim();
286 let parsed: serde_json::Value = serde_json::from_str(raw)
287 .unwrap_or_else(|e| panic!("str_to_vec_f64: cannot parse {raw:?} as a JSON array: {e}"));
288 let arr = parsed
289 .as_array()
290 .unwrap_or_else(|| panic!("str_to_vec_f64: parsed JSON is not an array: {raw:?}"));
291 arr.iter()
292 .map(|j| {
293 j.as_f64()
294 .unwrap_or_else(|| panic!("str_to_vec_f64: element {j} is not a number in {raw:?}"))
295 })
296 .collect()
297}
298
299/// The shared parse: a JSON array of integers, or a failure naming the
300/// node, the text, and what was wrong with it.
301fn parse_int_array(node: &str, s: &str) -> Vec<i64> {
302 let raw = s.trim();
303 let parsed: serde_json::Value = serde_json::from_str(raw)
304 .unwrap_or_else(|e| panic!("{node}: cannot parse {raw:?} as a JSON array: {e}"));
305 let arr = parsed
306 .as_array()
307 .unwrap_or_else(|| panic!("{node}: parsed JSON is not an array: {raw:?}"));
308 arr.iter()
309 .map(|j| {
310 j.as_i64()
311 .unwrap_or_else(|| panic!("{node}: element {j} is not an integer in {raw:?}"))
312 })
313 .collect()
314}