Skip to main content

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