polydat-nodes 0.12.0

Polydat node library: hashing, sampling, strings, encodings, noise, vectors, and more
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Element and set operations over the integer vector carriers,
//! element access over the float carriers, and elementwise equality
//! over every vector carrier.
//!
//! The float vector nodes ([`super::vector_math`]) compute over
//! embeddings; these read integer vectors as *lists*: how many
//! elements, what is at an index, does a value appear, where, and how
//! two lists compare as sets. A host holding a list of ordinals — the
//! records matching a label, the queries matching a predicate — asks
//! these the questions it would otherwise ask a counter.
//!
//! That is the point of them. A rank ("how many matching records come
//! before this one") and a cardinality ("how many match at all") look
//! like things a counter produces as records go by, but both are pure
//! functions of the list and the record: the rank is the position, the
//! cardinality is the length. Written that way the answer is owned by
//! its inputs, replays from its coordinates, and agrees on every engine
//! and every fiber, where a counter's answer depends on how many times
//! it was called ([Runtime Model](../../polydat/docs/design/runtime_model.md)
//! §9.1, "No state across pulls").
//!
//! Each operation exists for `vec_i32` and `vec_i64`, since the carrier
//! is part of the wire's type and polydat does not silently widen one
//! to the other. `vec_len` and `vec_at` exist for every carrier, as
//! `vec_eq` does: the integer elements come out as `i64` and the float
//! ones as `f64`, both exactly. An index or a value that is out of range answers
//! rather than panicking, because a miss is an ordinary result here:
//! `vec_position` returns the length when the value is absent, which is
//! "past the end" and the same convention `vec_len` bounds.

/// `vec_len_i32(v)` — how many elements the list holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_i32(v: &[i32]) -> u64 {
    v.len() as u64
}

/// `vec_len_i64(v)` — how many elements the list holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_i64(v: &[i64]) -> u64 {
    v.len() as u64
}

/// `vec_at_i32(v, i)` — the element at `i`, or `0` past the end.
///
/// Out of range answers rather than failing: a caller that cares
/// compares `i` with `vec_len_i32` first, and one that is walking a
/// list it already sized does not pay for a check it cannot fail.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_i32(v: &[i32], i: u64) -> i64 {
    v.get(i as usize).copied().unwrap_or(0) as i64
}

/// `vec_at_i64(v, i)` — the element at `i`, or `0` past the end.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_i64(v: &[i64], i: u64) -> i64 {
    v.get(i as usize).copied().unwrap_or(0)
}

/// `vec_len_f32(v)` — how many elements the vector holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_f32(v: &[f32]) -> u64 {
    v.len() as u64
}

/// `vec_len_f64(v)` — how many elements the vector holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_f64(v: &[f64]) -> u64 {
    v.len() as u64
}

/// `vec_at_f32(v, i)` — the element at `i`, widened to f64, or `0.0`
/// past the end.
///
/// A float vector read as a list rather than an embedding: a row of
/// stored distances, one per neighbor, where the question is what one
/// entry holds. Widening f32 to f64 is exact, so two elements that are
/// equal as stored compare equal through `f64_eq`. Out of range answers
/// `0.0` like the integer forms; a caller that cares compares `i` with
/// `vec_len_f32` first.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_f32(v: &[f32], i: u64) -> f64 {
    v.get(i as usize).copied().map_or(0.0, f64::from)
}

/// `vec_at_f64(v, i)` — the element at `i`, or `0.0` past the end.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_f64(v: &[f64], i: u64) -> f64 {
    v.get(i as usize).copied().unwrap_or(0.0)
}

/// `vec_len_f16(v)` — how many elements the vector holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_f16(v: &[polydat::half::f16]) -> u64 {
    v.len() as u64
}

/// `vec_at_f16(v, i)` — the element at `i`, widened to f64, or `0.0`
/// past the end. Widening f16 to f64 is exact, as it is from f32.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_f16(v: &[polydat::half::f16], i: u64) -> f64 {
    v.get(i as usize).copied().map_or(0.0, f64::from)
}

/// `vec_len_i8(v)` — how many elements the list holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_i8(v: &[i8]) -> u64 {
    v.len() as u64
}

/// `vec_at_i8(v, i)` — the element at `i`, or `0` past the end.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_i8(v: &[i8], i: u64) -> i64 {
    v.get(i as usize).copied().map_or(0, i64::from)
}

/// `vec_len_i16(v)` — how many elements the list holds.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_len_i16(v: &[i16]) -> u64 {
    v.len() as u64
}

/// `vec_at_i16(v, i)` — the element at `i`, or `0` past the end.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_at_i16(v: &[i16], i: u64) -> i64 {
    v.get(i as usize).copied().map_or(0, i64::from)
}

/// `vec_max_i32(v)` — the largest element, or `0` for an empty list.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_max_i32(v: &[i32]) -> i64 {
    v.iter().copied().max().unwrap_or(0) as i64
}

/// `vec_max_i64(v)` — the largest element, or `0` for an empty list.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_max_i64(v: &[i64]) -> i64 {
    v.iter().copied().max().unwrap_or(0)
}

/// `vec_min_i32(v)` — the smallest element, or `0` for an empty list.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_min_i32(v: &[i32]) -> i64 {
    v.iter().copied().min().unwrap_or(0) as i64
}

/// `vec_min_i64(v)` — the smallest element, or `0` for an empty list.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_min_i64(v: &[i64]) -> i64 {
    v.iter().copied().min().unwrap_or(0)
}

/// `vec_contains_i32(v, x)` — `1` when `x` appears in the list, else `0`.
#[polydat::polydat_node(category = Comparison)]
fn vec_contains_i32(v: &[i32], x: i64) -> u64 {
    u64::from(i32::try_from(x).is_ok_and(|x| v.contains(&x)))
}

/// `vec_contains_i64(v, x)` — `1` when `x` appears in the list, else `0`.
#[polydat::polydat_node(category = Comparison)]
fn vec_contains_i64(v: &[i64], x: i64) -> u64 {
    u64::from(v.contains(&x))
}

/// `vec_position_i32(v, x)` — the index of the first `x`, or the list's
/// length when it does not appear.
///
/// The length is "past the end", so a caller can branch on
/// `pos == vec_len_i32(v)` without a second sentinel, and a rank over a
/// sorted list of ordinals reads directly as the position.
#[polydat::polydat_node(category = Comparison)]
fn vec_position_i32(v: &[i32], x: i64) -> u64 {
    match i32::try_from(x) {
        Ok(x) => v.iter().position(|e| *e == x).unwrap_or(v.len()) as u64,
        Err(_) => v.len() as u64,
    }
}

/// `vec_position_i64(v, x)` — the index of the first `x`, or the list's
/// length when it does not appear.
#[polydat::polydat_node(category = Comparison)]
fn vec_position_i64(v: &[i64], x: i64) -> u64 {
    v.iter().position(|e| *e == x).unwrap_or(v.len()) as u64
}

/// `vec_count_below_i32(v, x)` — how many elements are less than `x`.
///
/// The rank of a record among the matching ones, without requiring the
/// list to be sorted or the record to be in it, which
/// `vec_position_i32` both do.
#[polydat::polydat_node(category = Comparison)]
fn vec_count_below_i32(v: &[i32], x: i64) -> u64 {
    v.iter().filter(|e| i64::from(**e) < x).count() as u64
}

/// `vec_count_below_i64(v, x)` — how many elements are less than `x`.
#[polydat::polydat_node(category = Comparison)]
fn vec_count_below_i64(v: &[i64], x: i64) -> u64 {
    v.iter().filter(|e| **e < x).count() as u64
}

/// `vec_intersect_count_i32(a, b)` — how many *distinct* values appear
/// in both lists.
///
/// Distinct, because this answers "how much do these two sets overlap",
/// which a repeated value would otherwise inflate. A caller wanting the
/// multiset count writes the fold it means.
#[polydat::polydat_node(category = Comparison)]
fn vec_intersect_count_i32(a: &[i32], b: &[i32]) -> u64 {
    let set: std::collections::BTreeSet<i32> = b.iter().copied().collect();
    let mine: std::collections::BTreeSet<i32> = a.iter().copied().collect();
    mine.intersection(&set).count() as u64
}

/// `vec_intersect_count_i64(a, b)` — how many distinct values appear in
/// both lists.
#[polydat::polydat_node(category = Comparison)]
fn vec_intersect_count_i64(a: &[i64], b: &[i64]) -> u64 {
    let set: std::collections::BTreeSet<i64> = b.iter().copied().collect();
    let mine: std::collections::BTreeSet<i64> = a.iter().copied().collect();
    mine.intersection(&set).count() as u64
}

/// `vec_set_eq_i32(a, b)` — `1` when both lists hold the same set of
/// values, whatever their order or repetition.
#[polydat::polydat_node(category = Comparison)]
fn vec_set_eq_i32(a: &[i32], b: &[i32]) -> u64 {
    let x: std::collections::BTreeSet<i32> = a.iter().copied().collect();
    let y: std::collections::BTreeSet<i32> = b.iter().copied().collect();
    u64::from(x == y)
}

/// `vec_set_eq_i64(a, b)` — `1` when both lists hold the same set of
/// values, whatever their order or repetition.
#[polydat::polydat_node(category = Comparison)]
fn vec_set_eq_i64(a: &[i64], b: &[i64]) -> u64 {
    let x: std::collections::BTreeSet<i64> = a.iter().copied().collect();
    let y: std::collections::BTreeSet<i64> = b.iter().copied().collect();
    u64::from(x == y)
}

// ── Elementwise equality ────────────────────────────────────────────
//
// `vec_eq_<t>(a, b)` exists for every vector carrier. It answers
// whether two vectors are the same value: the same length and every
// element identical. A float element compares by its bits, so `-0.0`
// and `0.0` differ and a NaN equals a NaN with the same bits; that is
// the identity a host auditing a vector it wrote needs, where IEEE
// equality would call a NaN unequal to itself. A length mismatch is
// `false`, never a failure.

/// Whether two slices have the same length and every element pair has
/// the same key.
fn same_by<T, K: PartialEq>(a: &[T], b: &[T], key: impl Fn(&T) -> K) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| key(x) == key(y))
}

/// `vec_eq_f16(a, b)` — `true` when both vectors have the same length
/// and every element has the same bits.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_f16(a: &[polydat::half::f16], b: &[polydat::half::f16]) -> bool {
    same_by(a, b, |x| x.to_bits())
}

/// `vec_eq_f32(a, b)` — `true` when both vectors have the same length
/// and every element has the same bits.
///
/// `-0.0` and `0.0` differ, and a NaN equals a NaN with the same
/// payload.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_f32(a: &[f32], b: &[f32]) -> bool {
    same_by(a, b, |x| x.to_bits())
}

/// `vec_eq_f64(a, b)` — `true` when both vectors have the same length
/// and every element has the same bits.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_f64(a: &[f64], b: &[f64]) -> bool {
    same_by(a, b, |x| x.to_bits())
}

/// `vec_eq_i8(a, b)` — `true` when both vectors have the same length
/// and equal elements.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_i8(a: &[i8], b: &[i8]) -> bool {
    a == b
}

/// `vec_eq_i16(a, b)` — `true` when both vectors have the same length
/// and equal elements.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_i16(a: &[i16], b: &[i16]) -> bool {
    a == b
}

/// `vec_eq_i32(a, b)` — `true` when both vectors have the same length
/// and equal elements, in order.
///
/// Order and repetition count, unlike `vec_set_eq_i32`.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_i32(a: &[i32], b: &[i32]) -> bool {
    a == b
}

/// `vec_eq_i64(a, b)` — `true` when both vectors have the same length
/// and equal elements, in order.
#[polydat::polydat_node(category = Comparison)]
fn vec_eq_i64(a: &[i64], b: &[i64]) -> bool {
    a == b
}

// ── Reading a list from text ────────────────────────────────────────

/// `str_to_vec_i32(s)` — a JSON array of integers as a `vec_i32` wire.
///
/// The public name for a parse the crate already performed internally
/// at the boundary: a host holding a list as text — a column it
/// selected, a facet it loaded, a literal in a workload — gets it onto
/// a wire the list operations read. The `as` cast does not do this,
/// because text to a typed vector can fail on its input and the
/// adapter catalog only inserts conversions that cannot ([Type
/// System](type_system.md) §3); naming it is the caller saying it
/// accepts that.
///
/// Fails by name on anything that is not a JSON array of integers in
/// range, rather than skipping the element: a list silently short one
/// entry is a wrong count everywhere downstream.
#[polydat::polydat_node(category = Conversions)]
fn str_to_vec_i32(s: &str) -> Vec<i32> {
    parse_int_array("str_to_vec_i32", s)
        .into_iter()
        .map(|n| {
            i32::try_from(n).unwrap_or_else(|_| {
                panic!(
                    "str_to_vec_i32: element {n} is outside i32 [{}, {}]",
                    i32::MIN,
                    i32::MAX
                )
            })
        })
        .collect()
}

/// `str_to_vec_i64(s)` — a JSON array of integers as a `vec_i64` wire.
#[polydat::polydat_node(category = Conversions)]
fn str_to_vec_i64(s: &str) -> Vec<i64> {
    parse_int_array("str_to_vec_i64", s)
}

/// `str_to_vec_f64(s)` — a JSON array of numbers as a `vec_f64` wire,
/// such as a window of samples for `is_stable`. Fails by name on
/// anything that is not a JSON array of numbers.
#[polydat::polydat_node(category = Conversions)]
fn str_to_vec_f64(s: &str) -> Vec<f64> {
    parse_float_array("str_to_vec_f64", s)
}

/// `str_to_vec_f32(s)` — a JSON array of numbers as a `vec_f32` wire,
/// the carrier of embeddings and of stored neighbor distances. Each
/// element is the f32 nearest the f64 its text parses as. Fails by
/// name on anything that is not a JSON array of numbers, and on a
/// number too large for an f32, rather than storing an infinity.
#[polydat::polydat_node(category = Conversions)]
fn str_to_vec_f32(s: &str) -> Vec<f32> {
    parse_float_array("str_to_vec_f32", s)
        .into_iter()
        .map(|x| {
            let narrowed = x as f32;
            if narrowed.is_infinite() {
                panic!("str_to_vec_f32: element {x:?} is outside the f32 range");
            }
            narrowed
        })
        .collect()
}

/// The shared parse of the float forms: a JSON array of numbers, or a
/// failure naming the node, the text, and what was wrong with it.
fn parse_float_array(node: &str, s: &str) -> Vec<f64> {
    let raw = s.trim();
    let parsed: serde_json::Value = serde_json::from_str(raw)
        .unwrap_or_else(|e| panic!("{node}: cannot parse {raw:?} as a JSON array: {e}"));
    let arr = parsed
        .as_array()
        .unwrap_or_else(|| panic!("{node}: parsed JSON is not an array: {raw:?}"));
    arr.iter()
        .map(|j| {
            j.as_f64()
                .unwrap_or_else(|| panic!("{node}: element {j} is not a number in {raw:?}"))
        })
        .collect()
}

/// The shared parse: a JSON array of integers, or a failure naming the
/// node, the text, and what was wrong with it.
fn parse_int_array(node: &str, s: &str) -> Vec<i64> {
    let raw = s.trim();
    let parsed: serde_json::Value = serde_json::from_str(raw)
        .unwrap_or_else(|e| panic!("{node}: cannot parse {raw:?} as a JSON array: {e}"));
    let arr = parsed
        .as_array()
        .unwrap_or_else(|| panic!("{node}: parsed JSON is not an array: {raw:?}"));
    arr.iter()
        .map(|j| {
            j.as_i64()
                .unwrap_or_else(|| panic!("{node}: element {j} is not an integer in {raw:?}"))
        })
        .collect()
}