From a8131a1930a3037d3d6edcc9fa58f5b4bb6739e5 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 18:29:31 -0500 Subject: [PATCH 1/8] feat(export): export edge weights on request export_graph takes a `weight` column name (Python keyword, `options.weight` in TypeScript) and returns `out_weights` / `in_weights` as float64 arrays aligned with `out_indices` / `in_indices`, the form icebug's `fromCSR`, scipy and igraph take. Only a weighted export pays for weights: it reads the extra column and sorts (key, weight) pairs, 16 bytes per edge instead of 8. Unweighted exports keep the existing u64-only path and allocate nothing for weights. Duplicate edges get the sum of their weights. In an undirected export, a -> b and b -> a combine the same way, and a self-loop's weight counts once. Null weights are an error for now. --- _typos.toml | 2 + crates/lance-csr-node/src/engine.rs | 15 +- crates/lance-csr-python/src/graph.rs | 24 +- crates/lance-csr/src/engine.rs | 20 +- crates/lance-csr/src/graph_export.rs | 282 +++++++++++++++++--- docs/graph-algorithms.md | 38 ++- docs/typescript.md | 2 +- nodejs/native.d.ts | 4 +- nodejs/src/cypher.ts | 17 +- nodejs/src/types.ts | 12 + nodejs/test/graph-export.test.ts | 24 ++ nodejs/typedoc/api.md | 10 +- python/python/lance_csr/_internal/graph.pyi | 11 +- python/python/lance_csr/cypher.py | 20 +- python/python/lance_csr/export.py | 21 +- python/python/tests/test_graph_export.py | 52 ++++ 16 files changed, 493 insertions(+), 61 deletions(-) diff --git a/_typos.toml b/_typos.toml index 27bdfa10..09795e26 100644 --- a/_typos.toml +++ b/_typos.toml @@ -5,3 +5,5 @@ extend-ignore-re = ["\\b[0-9a-f]{7,40}\\b"] [default.extend-words] # NetworKit, the graph library icebug is forked from. Networ = "Networ" +# The `outWeights` field of GraphExport, lowercased in TypeDoc anchors. +outweights = "outweights" diff --git a/crates/lance-csr-node/src/engine.rs b/crates/lance-csr-node/src/engine.rs index d12a29b1..d33d73f5 100644 --- a/crates/lance-csr-node/src/engine.rs +++ b/crates/lance-csr-node/src/engine.rs @@ -10,7 +10,7 @@ use lance_csr::engine::{ CypherEngine as RustCypherEngine, EngineOptions, PersistCsr, MAX_TARGET_PARTITIONS, }; use lance_csr::SqlEngine as RustSqlEngine; -use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer}; +use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer, Float64Array}; use napi_derive::napi; use tokio::sync::Mutex; @@ -71,6 +71,8 @@ pub struct GraphExport { pub out_indices: BigUint64Array, pub in_indptr: Option, pub in_indices: Option, + pub out_weights: Option, + pub in_weights: Option, pub dropped_edges: i64, } @@ -264,10 +266,15 @@ impl CypherEngine { &self, rel_types: Option>, directed: bool, + weight: Option, ) -> napi::Result { let inner = self.inner.clone(); - let g = blocking(async move { inner.export_graph(rel_types.as_deref(), directed).await }) - .await?; + let g = blocking(async move { + inner + .export_graph(rel_types.as_deref(), directed, weight.as_deref()) + .await + }) + .await?; Ok(GraphExport { num_nodes: g.num_nodes as i64, directed: g.directed, @@ -281,6 +288,8 @@ impl CypherEngine { out_indices: into_vec(g.out_indices).into(), in_indptr: g.in_indptr.map(|a| into_vec(a).into()), in_indices: g.in_indices.map(|a| into_vec(a).into()), + out_weights: g.out_weights.map(|a| into_vec(a).into()), + in_weights: g.in_weights.map(|a| into_vec(a).into()), dropped_edges: g.dropped_edges as i64, }) } diff --git a/crates/lance-csr-python/src/graph.rs b/crates/lance-csr-python/src/graph.rs index 0b9106de..e2190223 100644 --- a/crates/lance-csr-python/src/graph.rs +++ b/crates/lance-csr-python/src/graph.rs @@ -1078,6 +1078,24 @@ impl GraphExport { .transpose() } + #[getter] + fn out_weights<'py>(&self, py: Python<'py>) -> PyResult>> { + self.inner + .out_weights + .as_ref() + .map(|a| to_pyarrow_array(py, a)) + .transpose() + } + + #[getter] + fn in_weights<'py>(&self, py: Python<'py>) -> PyResult>> { + self.inner + .in_weights + .as_ref() + .map(|a| to_pyarrow_array(py, a)) + .transpose() + } + #[getter] fn dropped_edges(&self) -> u64 { self.inner.dropped_edges @@ -1313,17 +1331,19 @@ impl CypherEngine { Ok(stats.into_any().unbind()) } - #[pyo3(signature = (rel_types=None, *, directed=true))] + #[pyo3(signature = (rel_types=None, *, directed=true, weight=None))] fn export_graph( &self, py: Python, rel_types: Option>, directed: bool, + weight: Option, ) -> PyResult { let inner = RT .block_on( Some(py), - self.inner.export_graph(rel_types.as_deref(), directed), + self.inner + .export_graph(rel_types.as_deref(), directed, weight.as_deref()), )? .map_err(graph_error_to_pyerr)?; Ok(GraphExport { inner }) diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index 80740bad..e9a8be20 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -1608,21 +1608,33 @@ impl CypherEngine { /// `rel_types` `None` exports every relationship type whose dataset has integer /// endpoints. See [`crate::graph_export`] for how ids and rows are laid out. /// + /// `weight` names a numeric column of the relationship tables to export as `f64` + /// edge weights; duplicate edges get the sum of their weights. `None` exports no + /// weights and allocates nothing for them. + /// /// Sorting the edges is CPU-bound and runs on rayon's pool; as with the CSR /// build, call it from a blocking thread in an application with its own runtime. /// /// # Errors /// [`GraphError::ConfigError`] for an unknown relationship type or label, a missing - /// or non-integer key or endpoint column, or nothing to export; - /// [`GraphError::ExecutionError`] for a repeated node key or a failed scan. + /// or non-integer key or endpoint column, a missing or non-numeric weight column, or + /// nothing to export; [`GraphError::ExecutionError`] for a repeated node key, a null + /// weight or a failed scan. pub async fn export_graph( &self, rel_types: Option<&[String]>, directed: bool, + weight: Option<&str>, ) -> Result { let snapshot = self.snapshot(); - crate::graph_export::export_graph(&self.config, &snapshot.sources, rel_types, directed) - .await + crate::graph_export::export_graph( + &self.config, + &snapshot.sources, + rel_types, + directed, + weight, + ) + .await } /// Add `column` to the node tables of `export`, from `values` indexed by dense id, and pin the diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index 1686ce04..10b6ad7d 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -16,13 +16,16 @@ //! and deduplicated, which sorts every neighbour list too; `indptr` is then a count //! per row. Directed graphs also get the in-edge CSR (PageRank reads in-edges); //! undirected graphs get one CSR holding both directions, a self-loop once. +//! - weights, only when asked for: each packed key is paired with its weight (16 bytes +//! per edge instead of 8 while sorting), and duplicate edges are combined by summing +//! their weights. Unweighted exports never allocate the pairs. use std::collections::HashMap; use ahash::RandomState; -use arrow::array::{Array, ArrayRef, AsArray, Int64Array, UInt64Array}; +use arrow::array::{Array, ArrayRef, AsArray, Float64Array, Int64Array, UInt64Array}; use arrow::compute::cast; -use arrow::datatypes::{DataType, Int64Type}; +use arrow::datatypes::{DataType, Float64Type, Int64Type}; use futures::StreamExt; use rayon::prelude::*; @@ -52,6 +55,10 @@ pub struct GraphExport { pub in_indptr: Option, /// In-edge sources, sorted within each row; `None` for undirected graphs. pub in_indices: Option, + /// The weight of each entry in `out_indices`; `None` unless a weight column was asked for. + pub out_weights: Option, + /// The weight of each entry in `in_indices`; `None` for undirected or unweighted graphs. + pub in_weights: Option, /// Edges dropped because an endpoint key isn't in its node table. pub dropped_edges: u64, } @@ -62,6 +69,7 @@ struct RelSource<'a> { source: &'a EngineSource, src: String, dst: String, + weight: Option, src_label: usize, dst_label: usize, } @@ -69,12 +77,14 @@ struct RelSource<'a> { /// Build the export from `sources` (the engine's pinned snapshot). /// /// `rel_types` `None` takes every relationship type whose dataset is registered and -/// whose endpoints are integers. +/// whose endpoints are integers. `weight` names a numeric column every exported +/// relationship type must have. pub(crate) async fn export_graph( config: &GraphConfig, sources: &HashMap, rel_types: Option<&[String]>, directed: bool, + weight: Option<&str>, ) -> Result { let find_source = |name: &str| { sources @@ -164,11 +174,30 @@ pub(crate) async fn export_graph( } Ok(field.name().clone()) }; + let weight = weight + .map(|name| -> Result { + let field = schema + .fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(name)) + .ok_or_else(|| { + config_error(format!("Weight column '{name}' not found in '{rel}'")) + })?; + if !field.data_type().is_numeric() { + return Err(config_error(format!( + "Weight column '{name}' of '{rel}' is {}, not a numeric type", + field.data_type() + ))); + } + Ok(field.name().clone()) + }) + .transpose()?; rels.push(RelSource { name: rel.clone(), source, src: column(&m.source_id_field)?, dst: column(&m.target_id_field)?, + weight, src_label: labels.binary_search(src_label).expect("collected above"), dst_label: labels.binary_search(dst_label).expect("collected above"), }); @@ -223,49 +252,93 @@ pub(crate) async fn export_graph( for rel in &rels { rows += rel.source.num_rows(&rel.name).await?; } - let mut out: Vec = Vec::with_capacity(if directed { rows } else { 2 * rows }); - let mut inc: Vec = Vec::with_capacity(rows); + // Exactly one of the key and the (key, weight) vectors is used. + let weighted = weight.is_some(); + let (keys_cap, pairs_cap) = if weighted { (0, rows) } else { (rows, 0) }; + let mut out: Vec = Vec::with_capacity(if directed { keys_cap } else { 2 * keys_cap }); + let mut inc: Vec = Vec::with_capacity(keys_cap); + let mut out_w: Vec<(u64, f64)> = + Vec::with_capacity(if directed { pairs_cap } else { 2 * pairs_cap }); + let mut inc_w: Vec<(u64, f64)> = Vec::with_capacity(pairs_cap); let mut dropped = 0u64; for rel in &rels { let (src_map, dst_map) = (&maps[rel.src_label], &maps[rel.dst_label]); - let mut stream = rel - .source - .scan_columns(&[rel.src.as_str(), rel.dst.as_str()]) - .await?; + let mut columns = vec![rel.src.as_str(), rel.dst.as_str()]; + columns.extend(rel.weight.as_deref()); + let mut stream = rel.source.scan_columns(&columns).await?; while let Some(batch) = stream.next().await { let batch = batch?; let s = int64(batch.column(0), &rel.src, &rel.name)?; let d = int64(batch.column(1), &rel.dst, &rel.name)?; - let pairs: Vec> = (0..batch.num_rows()) + let w = match &rel.weight { + Some(name) => Some(float64(batch.column(2), name, &rel.name)?), + None => None, + }; + if w.as_ref().is_some_and(|w| w.null_count() > 0) { + return Err(exec_error(format!( + "Weight column '{}' of '{}' has null values", + rel.weight.as_deref().unwrap_or_default(), + rel.name + ))); + } + let pairs: Vec> = (0..batch.num_rows()) .into_par_iter() .with_min_len(4096) .filter(|&i| s.is_valid(i) && d.is_valid(i)) - .map(|i| Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?))) + .map(|i| Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?, i))) .collect(); for pair in pairs { - match pair { - Some((a, b)) => { + match (pair, &w) { + (Some((a, b, _)), None) => { out.push(a * n + b); // Undirected: the reverse goes into the same CSR. inc.push(b * n + a); } - None => dropped += 1, + (Some((a, b, i)), Some(w)) => { + let w = w.value(i); + out_w.push((a * n + b, w)); + // Undirected: a self-loop's reverse is itself; adding it would + // count its weight twice. + if directed || a != b { + inc_w.push((b * n + a, w)); + } + } + (None, _) => dropped += 1, } } } } - let (out, inc) = if directed { - (out, Some(inc)) + let ((out_indptr, out_indices, out_weights), inbound) = if weighted { + drop((out, inc)); + let inc_w = if directed { + Some(inc_w) + } else { + out_w.append(&mut inc_w); + None // `inc_w`'s allocation is freed here, before the sort + }; + let weighted = |pairs| { + let (p, i, w) = weighted_csr(n, pairs); + (p, i, Some(w)) + }; + (weighted(out_w), inc_w.map(weighted)) } else { - out.append(&mut inc); - drop(inc); // its allocation would otherwise stay alive through the sort - (out, None) + drop((out_w, inc_w)); + let inc = if directed { + Some(inc) + } else { + out.append(&mut inc); + None + }; + let unweighted = |keys| { + let (p, i) = csr(n, keys); + (p, i, None) + }; + (unweighted(out), inc.map(unweighted)) }; - let (out_indptr, out_indices) = csr(n, out); - let (in_indptr, in_indices) = match inc.map(|inc| csr(n, inc)) { - Some((p, i)) => (Some(p), Some(i)), - None => (None, None), + let (in_indptr, in_indices, in_weights) = match inbound { + Some((p, i, w)) => (Some(p), Some(i), w), + None => (None, None, None), }; Ok(GraphExport { num_nodes: n, @@ -276,6 +349,8 @@ pub(crate) async fn export_graph( out_indices, in_indptr, in_indices, + out_weights, + in_weights, dropped_edges: dropped, }) } @@ -298,6 +373,35 @@ fn csr(n: u64, mut packed: Vec) -> (UInt64Array, UInt64Array) { (UInt64Array::from(indptr), UInt64Array::from(packed)) } +/// [`csr`] for `(key, weight)` pairs: duplicate edges are combined by summing their weights. +fn weighted_csr(n: u64, mut pairs: Vec<(u64, f64)>) -> (UInt64Array, UInt64Array, Float64Array) { + pairs.par_sort_unstable_by_key(|p| p.0); + // `dedup_by` passes the later element first, the one kept second. + pairs.dedup_by(|later, kept| { + let same = later.0 == kept.0; + if same { + kept.1 += later.1; + } + same + }); + let mut indptr = vec![0u64; n as usize + 1]; + for &(key, _) in &pairs { + indptr[(key / n) as usize + 1] += 1; + } + for i in 1..indptr.len() { + indptr[i] += indptr[i - 1]; + } + let weights: Vec = pairs.par_iter().map(|p| p.1).collect(); + // Collected in place into the pairs' allocation, then shrunk to the final size. + let mut indices: Vec = pairs.into_iter().map(|p| p.0 % n).collect(); + indices.shrink_to_fit(); + ( + UInt64Array::from(indptr), + UInt64Array::from(indices), + Float64Array::from(weights), + ) +} + /// Add `column` to the node table of each label in `export`, from `values` indexed by dense id. /// /// Each label's slice of `values` is paired with its keys and merged into the label's Lance @@ -432,6 +536,15 @@ fn int64(array: &ArrayRef, column: &str, table: &str) -> Result { Ok(array.as_primitive::().clone()) } +fn float64(array: &ArrayRef, column: &str, table: &str) -> Result { + let array = cast(array, &DataType::Float64).map_err(|e| { + exec_error(format!( + "Column '{column}' of '{table}' is not numeric: {e}" + )) + })?; + Ok(array.as_primitive::().clone()) +} + fn config_error(message: String) -> GraphError { GraphError::ConfigError { message, @@ -532,7 +645,7 @@ mod tests { async fn directed_export_matches_hand_built_csr() { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; - let g = engine.export_graph(None, true).await.unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); // Dense ids follow row order: 60->0, 10->1, 50->2, 30->3, 20->4, 40->5. assert_eq!(g.node_keys.values().to_vec(), vec![60, 10, 50, 30, 20, 40]); assert_eq!(g.num_nodes, 6); @@ -555,7 +668,7 @@ mod tests { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let g = engine - .export_graph(Some(&["knows".to_string()]), false) + .export_graph(Some(&["knows".to_string()]), false, None) .await .unwrap(); assert!(!g.directed && g.in_indptr.is_none() && g.in_indices.is_none()); @@ -563,6 +676,99 @@ mod tests { assert_eq!(values(&g.out_indices), vec![2, 3, 4, 0, 1, 3, 4, 1, 3]); } + /// `people()` with an edge weight column `w`. + fn weighted_people(weights: Vec>) -> (RecordBatch, RecordBatch) { + let (nodes, edges) = people(); + let mut fields = edges.schema().fields().to_vec(); + fields.push(Arc::new(Field::new("w", DataType::Float64, true))); + let mut columns = edges.columns().to_vec(); + columns.push(Arc::new(arrow::array::Float64Array::from(weights))); + let edges = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap(); + (nodes, edges) + } + + fn powers_of_two() -> Vec> { + (0..9).map(|i| Some(f64::from(1 << i))).collect() + } + + fn weights(array: &Option) -> Vec { + array.as_ref().unwrap().values().to_vec() + } + + #[tokio::test] + async fn weights_follow_their_edges_and_duplicates_sum() { + let (nodes, edges) = weighted_people(powers_of_two()); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; + + // Unweighted: no weight arrays, same CSR as without the column. + let plain = engine.export_graph(None, true, None).await.unwrap(); + assert!(plain.out_weights.is_none() && plain.in_weights.is_none()); + + let g = engine.export_graph(None, true, Some("W")).await.unwrap(); + assert_eq!( + (&g.out_indptr, &g.out_indices), + (&plain.out_indptr, &plain.out_indices) + ); + assert_eq!( + (&g.in_indptr, &g.in_indices), + (&plain.in_indptr, &plain.in_indices) + ); + // 10->20 is listed twice, with weights 1 and 2. + assert_eq!( + weights(&g.out_weights), + vec![128.0, 3.0, 64.0, 8.0, 16.0, 4.0] + ); + assert_eq!( + weights(&g.in_weights), + vec![64.0, 8.0, 128.0, 16.0, 4.0, 3.0] + ); + assert_eq!(g.dropped_edges, 1); + + // Undirected: 50->60 and 60->50 become one edge, the self-loop's weight counts once. + let u = engine.export_graph(None, false, Some("w")).await.unwrap(); + let plain = engine.export_graph(None, false, None).await.unwrap(); + assert_eq!( + (&u.out_indptr, &u.out_indices), + (&plain.out_indptr, &plain.out_indices) + ); + assert_eq!( + weights(&u.out_weights), + vec![192.0, 8.0, 3.0, 192.0, 8.0, 16.0, 4.0, 3.0, 4.0] + ); + assert!(u.in_weights.is_none()); + } + + #[tokio::test] + async fn bad_weight_columns_are_errors() { + let (nodes, edges) = weighted_people(powers_of_two()); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; + let err = engine + .export_graph(None, true, Some("cost")) + .await + .unwrap_err(); + assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); + let names = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("src", DataType::Int64, true), + Field::new("dst", DataType::Int64, true), + Field::new("w", DataType::Utf8, true), + ])), + vec![ + Arc::new(Int64Array::from(vec![10])), + Arc::new(Int64Array::from(vec![20])), + Arc::new(StringArray::from(vec!["heavy"])), + ], + ) + .unwrap(); + let (nodes, _) = people(); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", names)]).await; + let err = engine + .export_graph(None, true, Some("w")) + .await + .unwrap_err(); + assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); + } + #[tokio::test] async fn labels_get_separate_ranges_for_colliding_keys() { let config = GraphConfig::builder() @@ -592,7 +798,7 @@ mod tests { ], ) .await; - let g = engine.export_graph(None, true).await.unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); // City 0..2, Person 2..4. assert_eq!( g.label_ranges, @@ -612,13 +818,13 @@ mod tests { vec![("Person", duplicate), ("KNOWS", edges.clone())], ) .await; - let err = engine.export_graph(None, true).await.unwrap_err(); + let err = engine.export_graph(None, true, None).await.unwrap_err(); assert!(matches!(err, GraphError::ExecutionError { .. }), "{err}"); let (nodes, _) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let err = engine - .export_graph(Some(&["LIKES".to_string()]), true) + .export_graph(Some(&["LIKES".to_string()]), true, None) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -641,7 +847,7 @@ mod tests { ], ) .await; - let err = engine.export_graph(None, true).await.unwrap_err(); + let err = engine.export_graph(None, true, None).await.unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); } @@ -684,8 +890,8 @@ mod tests { .unwrap(); let arrow = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let (a, b) = ( - lance.export_graph(None, true).await.unwrap(), - arrow.export_graph(None, true).await.unwrap(), + lance.export_graph(None, true, None).await.unwrap(), + arrow.export_graph(None, true, None).await.unwrap(), ); assert_eq!(a.node_keys, b.node_keys); assert_eq!( @@ -702,11 +908,17 @@ mod tests { ) .await; assert_eq!( - values(&lance.export_graph(None, true).await.unwrap().out_indptr)[6], + values( + &lance + .export_graph(None, true, None) + .await + .unwrap() + .out_indptr + )[6], 6 ); lance.checkout_latest().await.unwrap(); - let g = lance.export_graph(None, true).await.unwrap(); + let g = lance.export_graph(None, true, None).await.unwrap(); assert_eq!(values(&g.out_indptr), vec![0, 1, 2, 3, 5, 6, 7]); assert_eq!(values(&g.out_indices)[6], 0); } @@ -733,7 +945,7 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine.export_graph(None, true).await.unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); let degree = |g: &GraphExport| -> ArrayRef { let p = g.out_indptr.values(); Arc::new(Int64Array::from_iter_values( @@ -833,7 +1045,7 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine.export_graph(None, true).await.unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); let ones: ArrayRef = Arc::new(Int64Array::from(vec![1; g.num_nodes as usize])); engine .write_node_column(&g, "x", &ones, false) diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index 8868751f..ff3354b3 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -50,6 +50,7 @@ The returned [`GraphExport`][lance_csr.GraphExport] also holds: | `num_nodes`, `directed` | The number of nodes and whether the arrays are directed | | `in_indptr`, `in_indices` | The same arrays for incoming edges; `None` for an undirected export | | `label_ranges` | Each node label's dense ids, as `(start, end)` with `end` excluded | +| `out_weights`, `in_weights` | Edge weights, when asked for (see [Weighted graphs](#weighted-graphs)); otherwise `None` | | `dropped_edges` | Edges whose endpoint key isn't in its node table | The export follows the same rules as a query's join between relationship and node tables. An edge whose @@ -94,6 +95,34 @@ engine2 = CypherEngine(config2, {"Person": people, "City": cities, "LIVES_IN": l print(engine2.export_graph().label_ranges) # {'City': (0, 2), 'Person': (2, 6)} ``` +## Weighted graphs + +Some algorithms read a number on each edge as well as the edge itself: a distance for shortest paths, a +strength for weighted PageRank or community detection. In a relationship table that number is a column, such +as the messages sent along each `FOLLOWS` edge. Name it with `weight` and the export returns it as `float64` +arrays that line up with `out_indices` and `in_indices`: + +```python +messages = pa.table( + {"src": [10, 10, 20, 30, 10], "dst": [20, 30, 30, 10, 20], "messages": [3, 1, 5, 2, 4]} +) +weighted_engine = CypherEngine(config, {"Person": people, "FOLLOWS": messages}) +w = weighted_engine.export_graph(weight="messages") +print(w.out_indices.to_pylist()) # [1, 0, 2, 0] +print(w.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0] +``` + +The weight of `out_indices[i]` is `out_weights[i]`, and the same holds for the in-edges. Every included +relationship type must have the column, and it must be numeric. + +The export lists each edge once, so an edge that appears in several rows needs one weight. The export sums +them: 10 → 20 appears twice, with 3 and 4 messages, and gets 7. An undirected export does the same with an +edge stored in both directions, so `a → b` and `b → a` become one edge carrying both weights; a self-loop's +weight counts once. + +Weights cost memory only when you ask for them. Without `weight`, the export reads no extra column and +`out_weights` and `in_weights` are `None`. + ## Running an algorithm with icebug [icebug](https://github.com/Ladybug-Memory/icebug) is a fork of [NetworKit](https://networkit.github.io/) whose @@ -124,6 +153,10 @@ scores = pa.table({"id": g.node_keys, "pagerank": pagerank.run().scores()}) exactly `pyarrow==26.0.1`, imports only when `networkx` is installed, and on macOS needs OpenMP from Homebrew (`brew install libomp`). +For a weighted graph, pass the weights after the in-edge arrays: +`ib.Graph.fromCSR(w.num_nodes, w.directed, w.out_indices, w.out_indptr, w.in_indices, w.in_indptr, +w.out_weights, w.in_weights)`. Algorithms such as `ib.distance.Dijkstra` then use them. + Other libraries take the same arrays. For example, `scipy.sparse.csr_array((data, g.out_indices, g.out_indptr))` builds an adjacency matrix, after converting the arrays with `to_numpy()`, which doesn't copy them either. @@ -185,6 +218,7 @@ Some cases need care: - The export holds the whole graph in memory: eight bytes per edge in each direction for `indices`, plus the offsets and keys. A directed export of 10 million edges takes about 160 MB, and building it briefly needs - about as much again. + about as much again. Weights add eight bytes per edge in each direction, and while the export is built each + edge takes 16 bytes instead of eight. - Keys and endpoints must be integers up to `int64`; string and `uint64` keys aren't supported. -- Edge properties, such as weights, aren't exported. +- Only one edge property is exported, as a weight; other edge properties aren't. diff --git a/docs/typescript.md b/docs/typescript.md index 3033893d..bb8298ea 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -211,7 +211,7 @@ method, so your editor shows the details on hover. | `engine.checkout_latest()`, `optimize_csr()`, `delete_stored_csr()` | `await engine.checkoutLatest()`, `optimizeCsr()`, `deleteStoredCsr()` | | `engine.optimize_datasets(cleanup_older_than=timedelta(days=1))` | `await engine.optimizeDatasets({ cleanupOlderThanMs: 86_400_000 })` | | `engine.csr_stats()`, `node_index_stats()` (keys such as `delta_edges`, `build_ms`) | `engine.csrStats()`, `nodeIndexStats()` (keys such as `deltaEdges`, `buildMs`) | -| `engine.export_graph(rel_types, directed=False)`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false })`, a `GraphExport` of apache-arrow vectors | +| `engine.export_graph(rel_types, directed=False, weight="w")`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false, weight: "w" })`, a `GraphExport` of apache-arrow vectors | | `engine.dataset_versions()`, `engine.config()` | `engine.datasetVersions()`, `engine.config()` | | `engine.execute_with_vector_rerank(query, search)` | `await engine.executeWithVectorRerank(query, search)` | | `CypherQuery(text).with_config(config).with_parameter(key, value)` | `new CypherQuery(text).withConfig(config).withParameter(key, value)` | diff --git a/nodejs/native.d.ts b/nodejs/native.d.ts index 6ed8bbf4..f73fbdfb 100644 --- a/nodejs/native.d.ts +++ b/nodejs/native.d.ts @@ -20,7 +20,7 @@ export declare class CypherEngine { deleteStoredCsr(): Promise nodeIndexStats(): Record csrStats(): Record - exportGraph(relTypes: Array | undefined | null, directed: boolean): Promise + exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | undefined | null): Promise datasetVersions(): Record executeWithVectorRerank(query: string, search: VectorSearchSpec): Promise } @@ -123,6 +123,8 @@ export interface GraphExport { outIndices: BigUint64Array inIndptr?: BigUint64Array inIndices?: BigUint64Array + outWeights?: Float64Array + inWeights?: Float64Array droppedEdges: number } diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 8e437081..7f7ebf7f 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -430,16 +430,23 @@ export class CypherEngine { * end of the included types. * @param options.directed - `true` (the default) returns out-edge and in-edge arrays; `false` * returns one set of arrays listing every edge in both directions. + * @param options.weight - A numeric column of the relationship tables to export as float64 + * edge weights, in `outWeights` and `inWeights`; every included type must have it, + * case-insensitive. An edge listed more than once gets the sum of its weights. Left out, no + * weights are exported, and the export needs no memory for them. * @throws {@link LanceCsrError} `InvalidArgument` if a relationship type or label isn't in * the config, has no dataset, or a key or endpoint column is missing or isn't an integer - * type up to `int64`, or there's nothing to export; `Runtime` if a node key appears twice - * within a label, or a scan fails. + * type up to `int64`, the weight column is missing or isn't numeric, or there's nothing to + * export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan + * fails. */ async exportGraph( relTypes?: string[], - options: { directed?: boolean } = {}, + options: { directed?: boolean; weight?: string } = {}, ): Promise { - const g = await call(() => this.#inner.exportGraph(relTypes, options.directed ?? true)); + const g = await call(() => + this.#inner.exportGraph(relTypes, options.directed ?? true, options.weight), + ); return { numNodes: g.numNodes, directed: g.directed, @@ -451,6 +458,8 @@ export class CypherEngine { outIndices: makeVector(g.outIndices), inIndptr: g.inIndptr ? makeVector(g.inIndptr) : null, inIndices: g.inIndices ? makeVector(g.inIndices) : null, + outWeights: g.outWeights ? makeVector(g.outWeights) : null, + inWeights: g.inWeights ? makeVector(g.inWeights) : null, droppedEdges: g.droppedEdges, }; } diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 5c8971e7..718bb726 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -5,6 +5,7 @@ */ import { + type Float64, type Int64, RecordBatch, Table, @@ -129,6 +130,17 @@ export interface GraphExport { * Each node's in-neighbours, sorted, without duplicates; `null` for an undirected graph. */ inIndices: Vector | null; + /** + * The weight of each entry in `outIndices`; `null` unless `exportGraph` was given a `weight` + * column. An edge listed more than once gets the sum of its weights; in an undirected export, + * so do `a -> b` and `b -> a`. + */ + outWeights: Vector | null; + /** + * The weight of each entry in `inIndices`; `null` for an undirected export, or unless + * `exportGraph` was given a `weight` column. + */ + inWeights: Vector | null; /** * Edges left out because an endpoint key isn't in its node table. Edges with a null * endpoint are skipped and not counted. diff --git a/nodejs/test/graph-export.test.ts b/nodejs/test/graph-export.test.ts index 83238d58..3adf66c5 100644 --- a/nodejs/test/graph-export.test.ts +++ b/nodejs/test/graph-export.test.ts @@ -45,6 +45,30 @@ test("undirected export", async () => { assert.deepEqual(list(g.outIndices), [1, 2, 0, 2, 0, 1]); }); +test("edge weights only when asked for", async () => { + const weighted = { + ...datasets, + KNOWS: tableFromArrays({ + src: BigInt64Array.from([10n, 10n, 20n, 30n, 10n]), + dst: BigInt64Array.from([20n, 20n, 30n, 10n, 99n]), + w: Float64Array.from([1, 2, 4, 8, 16]), + }), + }; + const engine = await CypherEngine.create(config, weighted); + const plain = await engine.exportGraph(); + assert.equal(plain.outWeights, null); + assert.equal(plain.inWeights, null); + const g = await engine.exportGraph(undefined, { weight: "w" }); + // The duplicate 10->20 sums to 3. + assert.equal(g.outWeights!.type.typeId, Type.Float); + assert.deepEqual(Array.from(g.outWeights!.toArray()), [8, 3, 4]); + assert.deepEqual(Array.from(g.inWeights!.toArray()), [4, 8, 3]); + await assert.rejects( + engine.exportGraph(undefined, { weight: "cost" }), + (err) => err instanceof LanceCsrError && err.code === "InvalidArgument", + ); +}); + test("unknown relationship type", async () => { const engine = await CypherEngine.create(config, datasets); await assert.rejects( diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index 214ea4dd..ee745089 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -278,8 +278,9 @@ without `useCsr`. Lance datasets are scanned for just those columns. See | Parameter | Type | Description | | ------ | ------ | ------ | | `relTypes?` | `string`[] | Relationship types to include, case-insensitive. Left out, every type whose dataset has integer endpoint columns. The nodes are those of the labels at either end of the included types. | -| `options?` | \{ `directed?`: `boolean`; \} | - | +| `options?` | \{ `directed?`: `boolean`; `weight?`: `string`; \} | - | | `options.directed?` | `boolean` | `true` (the default) returns out-edge and in-edge arrays; `false` returns one set of arrays listing every edge in both directions. | +| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. An edge listed more than once gets the sum of its weights. Left out, no weights are exported, and the export needs no memory for them. | ###### Returns @@ -289,8 +290,9 @@ without `useCsr`. Lance datasets are scanned for just those columns. See [LanceCsrError](#lancecsrerror) `InvalidArgument` if a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer - type up to `int64`, or there's nothing to export; `Runtime` if a node key appears twice - within a label, or a scan fails. + type up to `int64`, the weight column is missing or isn't numeric, or there's nothing to + export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan + fails. @@ -1638,11 +1640,13 @@ id back to its node's key. The vectors wrap typed arrays built in Rust. See | `droppedEdges` | `number` | Edges left out because an endpoint key isn't in its node table. Edges with a null endpoint are skipped and not counted. | | `inIndices` | `Vector`\<`Uint64`\> \| `null` | Each node's in-neighbours, sorted, without duplicates; `null` for an undirected graph. | | `inIndptr` | `Vector`\<`Uint64`\> \| `null` | Offsets into `inIndices`; `null` for an undirected graph. | +| `inWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `inIndices`; `null` for an undirected export, or unless `exportGraph` was given a `weight` column. | | `labelRanges` | `Record`\<`string`, \[`number`, `number`\]\> | Each node label's dense ids, as `[start, end]` with `end` excluded. Labels get consecutive ranges in name order, so equal keys in two labels stay distinct. | | `nodeKeys` | `Vector`\<`Int64`\> | The key of each dense id. Each label's nodes are in the order its table is scanned; rows with a null key are left out. | | `numNodes` | `number` | Number of nodes. Dense ids run from 0 to `numNodes - 1`. | | `outIndices` | `Vector`\<`Uint64`\> | Each node's out-neighbours, sorted, without duplicates. An undirected graph lists every edge in both directions and a self-loop once. | | `outIndptr` | `Vector`\<`Uint64`\> | Offsets into `outIndices`, `numNodes + 1` entries. | +| `outWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `outIndices`; `null` unless `exportGraph` was given a `weight` column. An edge listed more than once gets the sum of its weights; in an undirected export, so do `a -> b` and `b -> a`. | *** diff --git a/python/python/lance_csr/_internal/graph.pyi b/python/python/lance_csr/_internal/graph.pyi index 519541a6..9d659ada 100644 --- a/python/python/lance_csr/_internal/graph.pyi +++ b/python/python/lance_csr/_internal/graph.pyi @@ -5,6 +5,7 @@ from typing import Any, ClassVar, Literal, Protocol, Self, TypedDict, TypeVar, f from lance import LanceDataset from pyarrow import ( Array, + DoubleArray, Int64Array, RecordBatch, RecordBatchReader, @@ -160,7 +161,11 @@ class CypherEngine: self, *, cleanup_older_than: timedelta | None = None ) -> dict[str, _DatasetOptimizeStats]: ... def export_graph( - self, rel_types: list[str] | None = None, *, directed: bool = True + self, + rel_types: list[str] | None = None, + *, + directed: bool = True, + weight: str | None = None, ) -> GraphExport: ... def write_node_column( self, @@ -241,6 +246,10 @@ class GraphExport: @property def in_indices(self) -> UInt64Array | None: ... @property + def out_weights(self) -> DoubleArray | None: ... + @property + def in_weights(self) -> DoubleArray | None: ... + @property def dropped_edges(self) -> int: ... @final diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index 64eafade..d9b959c8 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -465,7 +465,11 @@ def optimize_datasets( return result def export_graph( - self, rel_types: list[str] | None = None, *, directed: bool = True + self, + rel_types: list[str] | None = None, + *, + directed: bool = True, + weight: str | None = None, ) -> GraphExport: """The graph as dense CSR arrays, for graph-algorithm libraries. @@ -483,6 +487,12 @@ def export_graph( directed : bool Keyword-only. `True` returns out-edge and in-edge arrays; `False` returns one set of arrays listing every edge in both directions. + weight : str or None + Keyword-only. A numeric column of the relationship tables to export as + `float64` edge weights, in `out_weights` and `in_weights`; every included + type must have it, case-insensitive. An edge listed more than once gets the + sum of its weights. `None` (the default) exports no weights, and the export + then needs no memory for them. Returns ------- @@ -494,9 +504,11 @@ def export_graph( ValueError If a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer type up to `int64` - (`uint64` isn't supported), or there's nothing to export. + (`uint64` isn't supported), the weight column is missing or isn't numeric, + or there's nothing to export. RuntimeError - If a node key appears twice within a label, or a scan fails. + If a node key appears twice within a label, a weight is null, or a scan + fails. Examples -------- @@ -517,7 +529,7 @@ def export_graph( ([0, 1, 2, 2], [1, 2]) """ return GraphExport._from_inner( - self._inner.export_graph(rel_types, directed=directed) + self._inner.export_graph(rel_types, directed=directed, weight=weight) ) def write_node_column( diff --git a/python/python/lance_csr/export.py b/python/python/lance_csr/export.py index 5bdcf9bb..1e44a7b8 100644 --- a/python/python/lance_csr/export.py +++ b/python/python/lance_csr/export.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, Self, final if TYPE_CHECKING: - from pyarrow import Int64Array, UInt64Array + from pyarrow import DoubleArray, Int64Array, UInt64Array from ._internal import graph as _graph @@ -96,6 +96,25 @@ def in_indices(self) -> UInt64Array | None: """ return self._inner.in_indices + @property + def out_weights(self) -> DoubleArray | None: + """The weight of each entry in `out_indices`, as `float64`. + + `None` unless `export_graph` was given a `weight` column. An edge listed more + than once gets the sum of its weights; in an undirected export, so do `a -> b` + and `b -> a`. + """ + return self._inner.out_weights + + @property + def in_weights(self) -> DoubleArray | None: + """The weight of each entry in `in_indices`, as `float64`. + + `None` for an undirected export, or unless `export_graph` was given a `weight` + column. + """ + return self._inner.in_weights + @property def dropped_edges(self) -> int: """Edges left out because an endpoint key isn't in its node table. diff --git a/python/python/tests/test_graph_export.py b/python/python/tests/test_graph_export.py index 39600510..6c530db6 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -49,6 +49,34 @@ def test_undirected_export(): assert g.out_indices.to_pylist() == [2, 3, 4, 0, 1, 3, 4, 1, 3] +WEIGHTED = EDGES.append_column("w", pa.array([1, 2, 4, 8, 16, 32, 64, 128, 256])) + + +def test_weights(): + engine = CypherEngine(CONFIG, {"Person": NODES, "KNOWS": WEIGHTED}) + plain = engine.export_graph() + assert plain.out_weights is None and plain.in_weights is None + + g = engine.export_graph(weight="W") + assert g.out_indices.equals(plain.out_indices) + assert g.out_weights is not None and g.in_weights is not None + assert g.out_weights.type == pa.float64() + # The duplicate 10->20 (weights 1 and 2) sums to 3. + assert g.out_weights.to_pylist() == [128, 3, 64, 8, 16, 4] + assert g.in_weights.to_pylist() == [64, 8, 128, 16, 4, 3] + + # Undirected: 50->60 and 60->50 combine; the self-loop 30->30 counts once. + u = engine.export_graph(directed=False, weight="w") + assert u.in_weights is None and u.out_weights is not None + assert u.out_weights.to_pylist() == [192, 8, 3, 192, 8, 16, 4, 3, 4] + + with pytest.raises(ValueError, match="cost"): + engine.export_graph(weight="cost") + named = EDGES.append_column("w", pa.array(["x"] * 9)) + with pytest.raises(ValueError, match="not a numeric"): + CypherEngine(CONFIG, {"Person": NODES, "KNOWS": named}).export_graph(weight="w") + + def test_labels_with_colliding_keys(): config = ( GraphConfig.builder() @@ -126,6 +154,30 @@ def test_icebug_pagerank_and_components(): assert components.run().numberOfComponents() == 3 +def test_icebug_weighted_shortest_paths(): + ib = pytest.importorskip("icebug") + # 0->1 and 1->2 cost 1 each; the direct 0->2 costs 5. + nodes = pa.table({"id": [0, 1, 2]}) + edges = pa.table({"src": [0, 1, 0], "dst": [1, 2, 2], "cost": [1.0, 1.0, 5.0]}) + g = CypherEngine(CONFIG, {"Person": nodes, "KNOWS": edges}).export_graph( + weight="cost" + ) + graph = ib.Graph.fromCSR( + g.num_nodes, + g.directed, + g.out_indices, + g.out_indptr, + g.in_indices, + g.in_indptr, + g.out_weights, + g.in_weights, + ) + assert graph.isWeighted() + dijkstra = ib.distance.Dijkstra(graph, 0) + dijkstra.run() + assert dijkstra.getDistances() == [0.0, 1.0, 2.0] + + def test_write_node_column(tmp_path): config = ( GraphConfig.builder() From 1785ad99339a74a31fcb489bd939b94aae93c4a4 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 18:32:38 -0500 Subject: [PATCH 2/8] feat(export): choose how repeated edges combine their weights A weighted export lists each edge once, so an edge in several rows, or in an undirected export both a -> b and b -> a, needs one weight. `combine_edges` picks the rule: "sum" (the default; counts, amounts), "min" (distances, costs) or "max", after igraph's `combine_edges`. It is ignored without `weight`. An unknown rule is a ValueError in Python and an InvalidArgument error in TypeScript. Rust: `CombineEdges` enum, exported from the crate, passed to `CypherEngine::export_graph`. --- crates/lance-csr-node/src/engine.rs | 9 +- crates/lance-csr-python/src/graph.rs | 14 +- crates/lance-csr/src/engine.rs | 6 +- crates/lance-csr/src/graph_export.rs | 161 +++++++++++++++++--- crates/lance-csr/src/lib.rs | 2 +- docs/graph-algorithms.md | 16 +- docs/typescript.md | 2 +- nodejs/native.d.ts | 2 +- nodejs/src/cypher.ts | 21 ++- nodejs/src/types.ts | 4 +- nodejs/test/graph-export.test.ts | 6 + nodejs/typedoc/api.md | 11 +- python/python/lance_csr/_internal/graph.pyi | 1 + python/python/lance_csr/cypher.py | 21 ++- python/python/lance_csr/export.py | 4 +- python/python/tests/test_graph_export.py | 9 ++ 16 files changed, 231 insertions(+), 58 deletions(-) diff --git a/crates/lance-csr-node/src/engine.rs b/crates/lance-csr-node/src/engine.rs index d33d73f5..a2a51a02 100644 --- a/crates/lance-csr-node/src/engine.rs +++ b/crates/lance-csr-node/src/engine.rs @@ -267,11 +267,18 @@ impl CypherEngine { rel_types: Option>, directed: bool, weight: Option, + combine_edges: Option, ) -> napi::Result { + let combine = combine_edges + .as_deref() + .map(str::parse::) + .transpose() + .map_err(graph_error)? + .unwrap_or_default(); let inner = self.inner.clone(); let g = blocking(async move { inner - .export_graph(rel_types.as_deref(), directed, weight.as_deref()) + .export_graph(rel_types.as_deref(), directed, weight.as_deref(), combine) .await }) .await?; diff --git a/crates/lance-csr-python/src/graph.rs b/crates/lance-csr-python/src/graph.rs index e2190223..fda50372 100644 --- a/crates/lance-csr-python/src/graph.rs +++ b/crates/lance-csr-python/src/graph.rs @@ -1331,19 +1331,27 @@ impl CypherEngine { Ok(stats.into_any().unbind()) } - #[pyo3(signature = (rel_types=None, *, directed=true, weight=None))] + #[pyo3(signature = (rel_types=None, *, directed=true, weight=None, combine_edges="sum"))] fn export_graph( &self, py: Python, rel_types: Option>, directed: bool, weight: Option, + combine_edges: &str, ) -> PyResult { + let combine = combine_edges + .parse::() + .map_err(graph_error_to_pyerr)?; let inner = RT .block_on( Some(py), - self.inner - .export_graph(rel_types.as_deref(), directed, weight.as_deref()), + self.inner.export_graph( + rel_types.as_deref(), + directed, + weight.as_deref(), + combine, + ), )? .map_err(graph_error_to_pyerr)?; Ok(GraphExport { inner }) diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index e9a8be20..1a38c590 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -1609,8 +1609,8 @@ impl CypherEngine { /// endpoints. See [`crate::graph_export`] for how ids and rows are laid out. /// /// `weight` names a numeric column of the relationship tables to export as `f64` - /// edge weights; duplicate edges get the sum of their weights. `None` exports no - /// weights and allocates nothing for them. + /// edge weights, and `combine` sets how a repeated edge merges its weights (it's + /// ignored without `weight`). `None` exports no weights and allocates nothing for them. /// /// Sorting the edges is CPU-bound and runs on rayon's pool; as with the CSR /// build, call it from a blocking thread in an application with its own runtime. @@ -1625,6 +1625,7 @@ impl CypherEngine { rel_types: Option<&[String]>, directed: bool, weight: Option<&str>, + combine: crate::graph_export::CombineEdges, ) -> Result { let snapshot = self.snapshot(); crate::graph_export::export_graph( @@ -1633,6 +1634,7 @@ impl CypherEngine { rel_types, directed, weight, + combine, ) .await } diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index 10b6ad7d..e92bf31b 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -17,8 +17,8 @@ //! per row. Directed graphs also get the in-edge CSR (PageRank reads in-edges); //! undirected graphs get one CSR holding both directions, a self-loop once. //! - weights, only when asked for: each packed key is paired with its weight (16 bytes -//! per edge instead of 8 while sorting), and duplicate edges are combined by summing -//! their weights. Unweighted exports never allocate the pairs. +//! per edge instead of 8 while sorting), and duplicate edges are combined into one +//! weight by a [`CombineEdges`] rule. Unweighted exports never allocate the pairs. use std::collections::HashMap; @@ -63,6 +63,44 @@ pub struct GraphExport { pub dropped_edges: u64, } +/// How an edge listed more than once combines its weights into one. In an undirected +/// export, `a -> b` and `b -> a` are the same edge and combine too. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum CombineEdges { + /// Add the weights, as for message counts or transaction amounts. + #[default] + Sum, + /// Keep the smallest, as for distances or costs. + Min, + /// Keep the largest. + Max, +} + +impl CombineEdges { + fn apply(self, kept: f64, other: f64) -> f64 { + match self { + CombineEdges::Sum => kept + other, + CombineEdges::Min => kept.min(other), + CombineEdges::Max => kept.max(other), + } + } +} + +impl std::str::FromStr for CombineEdges { + type Err = GraphError; + + fn from_str(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "sum" => Ok(CombineEdges::Sum), + "min" => Ok(CombineEdges::Min), + "max" => Ok(CombineEdges::Max), + _ => Err(config_error(format!( + "Unknown combine_edges '{s}'; expected 'sum', 'min' or 'max'" + ))), + } + } +} + /// One relationship type to export: its dataset and the labels at both ends. struct RelSource<'a> { name: String, @@ -78,13 +116,14 @@ struct RelSource<'a> { /// /// `rel_types` `None` takes every relationship type whose dataset is registered and /// whose endpoints are integers. `weight` names a numeric column every exported -/// relationship type must have. +/// relationship type must have; `combine` merges the weights of a repeated edge. pub(crate) async fn export_graph( config: &GraphConfig, sources: &HashMap, rel_types: Option<&[String]>, directed: bool, weight: Option<&str>, + combine: CombineEdges, ) -> Result { let find_source = |name: &str| { sources @@ -318,7 +357,7 @@ pub(crate) async fn export_graph( None // `inc_w`'s allocation is freed here, before the sort }; let weighted = |pairs| { - let (p, i, w) = weighted_csr(n, pairs); + let (p, i, w) = weighted_csr(n, pairs, combine); (p, i, Some(w)) }; (weighted(out_w), inc_w.map(weighted)) @@ -373,14 +412,18 @@ fn csr(n: u64, mut packed: Vec) -> (UInt64Array, UInt64Array) { (UInt64Array::from(indptr), UInt64Array::from(packed)) } -/// [`csr`] for `(key, weight)` pairs: duplicate edges are combined by summing their weights. -fn weighted_csr(n: u64, mut pairs: Vec<(u64, f64)>) -> (UInt64Array, UInt64Array, Float64Array) { +/// [`csr`] for `(key, weight)` pairs: duplicate edges are combined by `combine`. +fn weighted_csr( + n: u64, + mut pairs: Vec<(u64, f64)>, + combine: CombineEdges, +) -> (UInt64Array, UInt64Array, Float64Array) { pairs.par_sort_unstable_by_key(|p| p.0); // `dedup_by` passes the later element first, the one kept second. pairs.dedup_by(|later, kept| { let same = later.0 == kept.0; if same { - kept.1 += later.1; + kept.1 = combine.apply(kept.1, later.1); } same }); @@ -645,7 +688,10 @@ mod tests { async fn directed_export_matches_hand_built_csr() { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; - let g = engine.export_graph(None, true, None).await.unwrap(); + let g = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); // Dense ids follow row order: 60->0, 10->1, 50->2, 30->3, 20->4, 40->5. assert_eq!(g.node_keys.values().to_vec(), vec![60, 10, 50, 30, 20, 40]); assert_eq!(g.num_nodes, 6); @@ -668,7 +714,7 @@ mod tests { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let g = engine - .export_graph(Some(&["knows".to_string()]), false, None) + .export_graph(Some(&["knows".to_string()]), false, None, CombineEdges::Sum) .await .unwrap(); assert!(!g.directed && g.in_indptr.is_none() && g.in_indices.is_none()); @@ -701,10 +747,16 @@ mod tests { let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; // Unweighted: no weight arrays, same CSR as without the column. - let plain = engine.export_graph(None, true, None).await.unwrap(); + let plain = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); assert!(plain.out_weights.is_none() && plain.in_weights.is_none()); - let g = engine.export_graph(None, true, Some("W")).await.unwrap(); + let g = engine + .export_graph(None, true, Some("W"), CombineEdges::Sum) + .await + .unwrap(); assert_eq!( (&g.out_indptr, &g.out_indices), (&plain.out_indptr, &plain.out_indices) @@ -725,8 +777,14 @@ mod tests { assert_eq!(g.dropped_edges, 1); // Undirected: 50->60 and 60->50 become one edge, the self-loop's weight counts once. - let u = engine.export_graph(None, false, Some("w")).await.unwrap(); - let plain = engine.export_graph(None, false, None).await.unwrap(); + let u = engine + .export_graph(None, false, Some("w"), CombineEdges::Sum) + .await + .unwrap(); + let plain = engine + .export_graph(None, false, None, CombineEdges::Sum) + .await + .unwrap(); assert_eq!( (&u.out_indptr, &u.out_indices), (&plain.out_indptr, &plain.out_indices) @@ -738,12 +796,41 @@ mod tests { assert!(u.in_weights.is_none()); } + #[tokio::test] + async fn combine_edges_picks_min_or_max() { + let (nodes, edges) = weighted_people(powers_of_two()); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; + // The duplicate 10->20 has weights 1 and 2; undirected 50-60 has 64 and 128. + for (combine, dup, pair) in [ + (CombineEdges::Min, 1.0, 64.0), + (CombineEdges::Max, 2.0, 128.0), + ] { + let g = engine + .export_graph(None, true, Some("w"), combine) + .await + .unwrap(); + assert_eq!(weights(&g.out_weights)[1], dup, "{combine:?}"); + assert_eq!(weights(&g.in_weights)[5], dup, "{combine:?}"); + let u = engine + .export_graph(None, false, Some("w"), combine) + .await + .unwrap(); + assert_eq!( + weights(&u.out_weights), + vec![pair, 8.0, dup, pair, 8.0, 16.0, 4.0, dup, 4.0], + "{combine:?}" + ); + } + assert_eq!("MAX".parse::().unwrap(), CombineEdges::Max); + assert!("mean".parse::().is_err()); + } + #[tokio::test] async fn bad_weight_columns_are_errors() { let (nodes, edges) = weighted_people(powers_of_two()); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let err = engine - .export_graph(None, true, Some("cost")) + .export_graph(None, true, Some("cost"), CombineEdges::Sum) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -763,7 +850,7 @@ mod tests { let (nodes, _) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", names)]).await; let err = engine - .export_graph(None, true, Some("w")) + .export_graph(None, true, Some("w"), CombineEdges::Sum) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -798,7 +885,10 @@ mod tests { ], ) .await; - let g = engine.export_graph(None, true, None).await.unwrap(); + let g = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); // City 0..2, Person 2..4. assert_eq!( g.label_ranges, @@ -818,13 +908,16 @@ mod tests { vec![("Person", duplicate), ("KNOWS", edges.clone())], ) .await; - let err = engine.export_graph(None, true, None).await.unwrap_err(); + let err = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap_err(); assert!(matches!(err, GraphError::ExecutionError { .. }), "{err}"); let (nodes, _) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let err = engine - .export_graph(Some(&["LIKES".to_string()]), true, None) + .export_graph(Some(&["LIKES".to_string()]), true, None, CombineEdges::Sum) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -847,7 +940,10 @@ mod tests { ], ) .await; - let err = engine.export_graph(None, true, None).await.unwrap_err(); + let err = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); } @@ -890,8 +986,14 @@ mod tests { .unwrap(); let arrow = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let (a, b) = ( - lance.export_graph(None, true, None).await.unwrap(), - arrow.export_graph(None, true, None).await.unwrap(), + lance + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(), + arrow + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(), ); assert_eq!(a.node_keys, b.node_keys); assert_eq!( @@ -910,7 +1012,7 @@ mod tests { assert_eq!( values( &lance - .export_graph(None, true, None) + .export_graph(None, true, None, CombineEdges::Sum) .await .unwrap() .out_indptr @@ -918,7 +1020,10 @@ mod tests { 6 ); lance.checkout_latest().await.unwrap(); - let g = lance.export_graph(None, true, None).await.unwrap(); + let g = lance + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); assert_eq!(values(&g.out_indptr), vec![0, 1, 2, 3, 5, 6, 7]); assert_eq!(values(&g.out_indices)[6], 0); } @@ -945,7 +1050,10 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine.export_graph(None, true, None).await.unwrap(); + let g = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); let degree = |g: &GraphExport| -> ArrayRef { let p = g.out_indptr.values(); Arc::new(Int64Array::from_iter_values( @@ -1045,7 +1153,10 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine.export_graph(None, true, None).await.unwrap(); + let g = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); let ones: ArrayRef = Arc::new(Int64Array::from(vec![1; g.num_nodes as usize])); engine .write_node_column(&g, "x", &ones, false) diff --git a/crates/lance-csr/src/lib.rs b/crates/lance-csr/src/lib.rs index e84bafd2..f9e57fcb 100644 --- a/crates/lance-csr/src/lib.rs +++ b/crates/lance-csr/src/lib.rs @@ -86,7 +86,7 @@ pub use engine::{ open_lance_dataset, CypherEngine, DatasetOptimizeStats, EngineSource, PersistCsr, SqlEngine, }; pub use error::{GraphError, Result}; -pub use graph_export::GraphExport; +pub use graph_export::{CombineEdges, GraphExport}; pub use lance_vector_search::VectorSearch; pub use mapping::{EdgeTableMapping, GraphMapping, GraphSnapshot, NodeTableMapping, PinnedTable}; pub use namespace::DirNamespace; diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index ff3354b3..c5597749 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -115,10 +115,18 @@ print(w.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0] The weight of `out_indices[i]` is `out_weights[i]`, and the same holds for the in-edges. Every included relationship type must have the column, and it must be numeric. -The export lists each edge once, so an edge that appears in several rows needs one weight. The export sums -them: 10 → 20 appears twice, with 3 and 4 messages, and gets 7. An undirected export does the same with an -edge stored in both directions, so `a → b` and `b → a` become one edge carrying both weights; a self-loop's -weight counts once. +The export lists each edge once, so an edge that appears in several rows needs one weight, and +`combine_edges` says how to get it. The default, `"sum"`, adds the weights, which suits counts and amounts: +10 → 20 appears twice, with 3 and 4 messages, and gets 7. When the weight is a distance or a cost, the +cheapest edge is usually the one that matters, and `"min"` keeps it; `"max"` keeps the largest: + +```python +cheapest = weighted_engine.export_graph(weight="messages", combine_edges="min") +print(cheapest.out_weights.to_pylist()) # [2.0, 1.0, 3.0, 5.0] +``` + +An undirected export applies the same rule to an edge stored in both directions, so `a → b` and `b → a` +become one edge with one combined weight. A self-loop's weight counts once. Weights cost memory only when you ask for them. Without `weight`, the export reads no extra column and `out_weights` and `in_weights` are `None`. diff --git a/docs/typescript.md b/docs/typescript.md index bb8298ea..616e6718 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -211,7 +211,7 @@ method, so your editor shows the details on hover. | `engine.checkout_latest()`, `optimize_csr()`, `delete_stored_csr()` | `await engine.checkoutLatest()`, `optimizeCsr()`, `deleteStoredCsr()` | | `engine.optimize_datasets(cleanup_older_than=timedelta(days=1))` | `await engine.optimizeDatasets({ cleanupOlderThanMs: 86_400_000 })` | | `engine.csr_stats()`, `node_index_stats()` (keys such as `delta_edges`, `build_ms`) | `engine.csrStats()`, `nodeIndexStats()` (keys such as `deltaEdges`, `buildMs`) | -| `engine.export_graph(rel_types, directed=False, weight="w")`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false, weight: "w" })`, a `GraphExport` of apache-arrow vectors | +| `engine.export_graph(rel_types, directed=False, weight="w", combine_edges="min")`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false, weight: "w", combineEdges: "min" })`, a `GraphExport` of apache-arrow vectors | | `engine.dataset_versions()`, `engine.config()` | `engine.datasetVersions()`, `engine.config()` | | `engine.execute_with_vector_rerank(query, search)` | `await engine.executeWithVectorRerank(query, search)` | | `CypherQuery(text).with_config(config).with_parameter(key, value)` | `new CypherQuery(text).withConfig(config).withParameter(key, value)` | diff --git a/nodejs/native.d.ts b/nodejs/native.d.ts index f73fbdfb..71bfe728 100644 --- a/nodejs/native.d.ts +++ b/nodejs/native.d.ts @@ -20,7 +20,7 @@ export declare class CypherEngine { deleteStoredCsr(): Promise nodeIndexStats(): Record csrStats(): Record - exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | undefined | null): Promise + exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | undefined | null, combineEdges?: string | undefined | null): Promise datasetVersions(): Record executeWithVectorRerank(query: string, search: VectorSearchSpec): Promise } diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 7f7ebf7f..5da6d328 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -432,20 +432,29 @@ export class CypherEngine { * returns one set of arrays listing every edge in both directions. * @param options.weight - A numeric column of the relationship tables to export as float64 * edge weights, in `outWeights` and `inWeights`; every included type must have it, - * case-insensitive. An edge listed more than once gets the sum of its weights. Left out, no - * weights are exported, and the export needs no memory for them. + * case-insensitive. Left out, no weights are exported, and the export needs no memory for + * them. + * @param options.combineEdges - How an edge listed more than once combines its weights: `"sum"` + * (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for + * distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge + * and combine the same way. Ignored without `weight`. * @throws {@link LanceCsrError} `InvalidArgument` if a relationship type or label isn't in * the config, has no dataset, or a key or endpoint column is missing or isn't an integer - * type up to `int64`, the weight column is missing or isn't numeric, or there's nothing to - * export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan + * type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't + * one of the three rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan * fails. */ async exportGraph( relTypes?: string[], - options: { directed?: boolean; weight?: string } = {}, + options: { directed?: boolean; weight?: string; combineEdges?: "sum" | "min" | "max" } = {}, ): Promise { const g = await call(() => - this.#inner.exportGraph(relTypes, options.directed ?? true, options.weight), + this.#inner.exportGraph( + relTypes, + options.directed ?? true, + options.weight, + options.combineEdges, + ), ); return { numNodes: g.numNodes, diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 718bb726..8ed4010a 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -132,8 +132,8 @@ export interface GraphExport { inIndices: Vector | null; /** * The weight of each entry in `outIndices`; `null` unless `exportGraph` was given a `weight` - * column. An edge listed more than once gets the sum of its weights; in an undirected export, - * so do `a -> b` and `b -> a`. + * column. An edge listed more than once, or in an undirected export both `a -> b` and + * `b -> a`, gets one weight, combined by the `combineEdges` rule (a sum by default). */ outWeights: Vector | null; /** diff --git a/nodejs/test/graph-export.test.ts b/nodejs/test/graph-export.test.ts index 3adf66c5..ac31fd20 100644 --- a/nodejs/test/graph-export.test.ts +++ b/nodejs/test/graph-export.test.ts @@ -63,6 +63,12 @@ test("edge weights only when asked for", async () => { assert.equal(g.outWeights!.type.typeId, Type.Float); assert.deepEqual(Array.from(g.outWeights!.toArray()), [8, 3, 4]); assert.deepEqual(Array.from(g.inWeights!.toArray()), [4, 8, 3]); + const min = await engine.exportGraph(undefined, { weight: "w", combineEdges: "min" }); + assert.deepEqual(Array.from(min.outWeights!.toArray()), [8, 1, 4]); + await assert.rejects( + engine.exportGraph(undefined, { weight: "w", combineEdges: "mean" as "sum" }), + (err) => err instanceof LanceCsrError && err.code === "InvalidArgument", + ); await assert.rejects( engine.exportGraph(undefined, { weight: "cost" }), (err) => err instanceof LanceCsrError && err.code === "InvalidArgument", diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index ee745089..6235fed6 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -278,9 +278,10 @@ without `useCsr`. Lance datasets are scanned for just those columns. See | Parameter | Type | Description | | ------ | ------ | ------ | | `relTypes?` | `string`[] | Relationship types to include, case-insensitive. Left out, every type whose dataset has integer endpoint columns. The nodes are those of the labels at either end of the included types. | -| `options?` | \{ `directed?`: `boolean`; `weight?`: `string`; \} | - | +| `options?` | \{ `combineEdges?`: `"sum"` \| `"min"` \| `"max"`; `directed?`: `boolean`; `weight?`: `string`; \} | - | +| `options.combineEdges?` | `"sum"` \| `"min"` \| `"max"` | How an edge listed more than once combines its weights: `"sum"` (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge and combine the same way. Ignored without `weight`. | | `options.directed?` | `boolean` | `true` (the default) returns out-edge and in-edge arrays; `false` returns one set of arrays listing every edge in both directions. | -| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. An edge listed more than once gets the sum of its weights. Left out, no weights are exported, and the export needs no memory for them. | +| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. Left out, no weights are exported, and the export needs no memory for them. | ###### Returns @@ -290,8 +291,8 @@ without `useCsr`. Lance datasets are scanned for just those columns. See [LanceCsrError](#lancecsrerror) `InvalidArgument` if a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer - type up to `int64`, the weight column is missing or isn't numeric, or there's nothing to - export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan + type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't + one of the three rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan fails. @@ -1646,7 +1647,7 @@ id back to its node's key. The vectors wrap typed arrays built in Rust. See | `numNodes` | `number` | Number of nodes. Dense ids run from 0 to `numNodes - 1`. | | `outIndices` | `Vector`\<`Uint64`\> | Each node's out-neighbours, sorted, without duplicates. An undirected graph lists every edge in both directions and a self-loop once. | | `outIndptr` | `Vector`\<`Uint64`\> | Offsets into `outIndices`, `numNodes + 1` entries. | -| `outWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `outIndices`; `null` unless `exportGraph` was given a `weight` column. An edge listed more than once gets the sum of its weights; in an undirected export, so do `a -> b` and `b -> a`. | +| `outWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `outIndices`; `null` unless `exportGraph` was given a `weight` column. An edge listed more than once, or in an undirected export both `a -> b` and `b -> a`, gets one weight, combined by the `combineEdges` rule (a sum by default). | *** diff --git a/python/python/lance_csr/_internal/graph.pyi b/python/python/lance_csr/_internal/graph.pyi index 9d659ada..c49e45d7 100644 --- a/python/python/lance_csr/_internal/graph.pyi +++ b/python/python/lance_csr/_internal/graph.pyi @@ -166,6 +166,7 @@ class CypherEngine: *, directed: bool = True, weight: str | None = None, + combine_edges: Literal["sum", "min", "max"] = "sum", ) -> GraphExport: ... def write_node_column( self, diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index d9b959c8..3d1a0466 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -470,6 +470,7 @@ def export_graph( *, directed: bool = True, weight: str | None = None, + combine_edges: Literal["sum", "min", "max"] = "sum", ) -> GraphExport: """The graph as dense CSR arrays, for graph-algorithm libraries. @@ -490,9 +491,14 @@ def export_graph( weight : str or None Keyword-only. A numeric column of the relationship tables to export as `float64` edge weights, in `out_weights` and `in_weights`; every included - type must have it, case-insensitive. An edge listed more than once gets the - sum of its weights. `None` (the default) exports no weights, and the export - then needs no memory for them. + type must have it, case-insensitive. `None` (the default) exports no + weights, and the export then needs no memory for them. + combine_edges : {"sum", "min", "max"} + Keyword-only. How an edge listed more than once combines its weights: + `"sum"` (the default) adds them, as for counts or amounts; `"min"` keeps the + smallest, as for distances; `"max"` the largest. In an undirected export, + `a -> b` and `b -> a` are one edge and combine the same way. Ignored without + `weight`. Returns ------- @@ -505,7 +511,7 @@ def export_graph( If a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer type up to `int64` (`uint64` isn't supported), the weight column is missing or isn't numeric, - or there's nothing to export. + `combine_edges` isn't one of the three rules, or there's nothing to export. RuntimeError If a node key appears twice within a label, a weight is null, or a scan fails. @@ -529,7 +535,12 @@ def export_graph( ([0, 1, 2, 2], [1, 2]) """ return GraphExport._from_inner( - self._inner.export_graph(rel_types, directed=directed, weight=weight) + self._inner.export_graph( + rel_types, + directed=directed, + weight=weight, + combine_edges=combine_edges, + ) ) def write_node_column( diff --git a/python/python/lance_csr/export.py b/python/python/lance_csr/export.py index 1e44a7b8..4b483ad9 100644 --- a/python/python/lance_csr/export.py +++ b/python/python/lance_csr/export.py @@ -101,8 +101,8 @@ def out_weights(self) -> DoubleArray | None: """The weight of each entry in `out_indices`, as `float64`. `None` unless `export_graph` was given a `weight` column. An edge listed more - than once gets the sum of its weights; in an undirected export, so do `a -> b` - and `b -> a`. + than once, or in an undirected export both `a -> b` and `b -> a`, gets one + weight, combined by `export_graph`'s `combine_edges` rule (a sum by default). """ return self._inner.out_weights diff --git a/python/python/tests/test_graph_export.py b/python/python/tests/test_graph_export.py index 6c530db6..c109fcf4 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -70,8 +70,17 @@ def test_weights(): assert u.in_weights is None and u.out_weights is not None assert u.out_weights.to_pylist() == [192, 8, 3, 192, 8, 16, 4, 3, 4] + # min/max instead: the duplicate 10->20 has 1 and 2, 50-60 has 64 and 128. + low = engine.export_graph(weight="w", combine_edges="min") + assert low.out_weights is not None and low.out_weights.to_pylist()[1] == 1 + high = engine.export_graph(directed=False, weight="w", combine_edges="max") + assert high.out_weights is not None + assert high.out_weights.to_pylist() == [128, 8, 2, 128, 8, 16, 4, 2, 4] + with pytest.raises(ValueError, match="cost"): engine.export_graph(weight="cost") + with pytest.raises(ValueError, match="combine_edges"): + engine.export_graph(weight="w", combine_edges="mean") # pyright: ignore[reportArgumentType] named = EDGES.append_column("w", pa.array(["x"] * 9)) with pytest.raises(ValueError, match="not a numeric"): CypherEngine(CONFIG, {"Person": NODES, "KNOWS": named}).export_graph(weight="w") From 1abc8a4efb4f2a809e20e9639f89bfa2e7278fda Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 18:34:22 -0500 Subject: [PATCH 3/8] feat(export): drop and count edges with a null weight A null weight is unknown, and no default stands in for it safely: 1.0 would make a costly edge look cheap to a shortest-path search. A weighted export now leaves such an edge out and counts it in `dropped_edges`, as it does an edge whose endpoint key is missing, instead of failing the whole export. Unweighted exports ignore the column and drop nothing extra. --- crates/lance-csr/src/engine.rs | 4 +- crates/lance-csr/src/graph_export.rs | 47 +++++++++++++++++++----- docs/graph-algorithms.md | 12 +++++- nodejs/src/cypher.ts | 8 ++-- nodejs/src/types.ts | 4 +- nodejs/typedoc/api.md | 8 ++-- python/python/lance_csr/cypher.py | 6 +-- python/python/lance_csr/export.py | 7 ++-- python/python/tests/test_graph_export.py | 8 ++++ 9 files changed, 75 insertions(+), 29 deletions(-) diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index 1a38c590..011e61e2 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -1618,8 +1618,8 @@ impl CypherEngine { /// # Errors /// [`GraphError::ConfigError`] for an unknown relationship type or label, a missing /// or non-integer key or endpoint column, a missing or non-numeric weight column, or - /// nothing to export; [`GraphError::ExecutionError`] for a repeated node key, a null - /// weight or a failed scan. + /// nothing to export; [`GraphError::ExecutionError`] for a repeated node key or a + /// failed scan. An edge with a null weight is dropped and counted in `dropped_edges`. pub async fn export_graph( &self, rel_types: Option<&[String]>, diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index e92bf31b..f216aa30 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -11,7 +11,8 @@ //! the node table's rows in scan order (rows with a null key are skipped), so keys //! that collide across labels stay distinct; //! - edges: endpoints are mapped to dense ids in parallel; an edge with a null -//! endpoint is skipped, one whose key isn't in its node table is dropped and counted; +//! endpoint is skipped, one whose key isn't in its node table, or whose weight is +//! null in a weighted export, is dropped and counted; //! - rows: each edge is packed as `row * n + column` into a `u64`, sorted in parallel //! and deduplicated, which sorts every neighbour list too; `indptr` is then a count //! per row. Directed graphs also get the in-edge CSR (PageRank reads in-edges); @@ -59,7 +60,8 @@ pub struct GraphExport { pub out_weights: Option, /// The weight of each entry in `in_indices`; `None` for undirected or unweighted graphs. pub in_weights: Option, - /// Edges dropped because an endpoint key isn't in its node table. + /// Edges dropped because an endpoint key isn't in its node table, or, in a weighted + /// export, because the weight is null. pub dropped_edges: u64, } @@ -313,18 +315,18 @@ pub(crate) async fn export_graph( Some(name) => Some(float64(batch.column(2), name, &rel.name)?), None => None, }; - if w.as_ref().is_some_and(|w| w.null_count() > 0) { - return Err(exec_error(format!( - "Weight column '{}' of '{}' has null values", - rel.weight.as_deref().unwrap_or_default(), - rel.name - ))); - } let pairs: Vec> = (0..batch.num_rows()) .into_par_iter() .with_min_len(4096) .filter(|&i| s.is_valid(i) && d.is_valid(i)) - .map(|i| Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?, i))) + .map(|i| { + // A null weight drops the edge, as a missing endpoint does: no weight + // is a safe stand-in for an unknown one. + if w.as_ref().is_some_and(|w| w.is_null(i)) { + return None; + } + Some((*src_map.get(&s.value(i))?, *dst_map.get(&d.value(i))?, i)) + }) .collect(); for pair in pairs { match (pair, &w) { @@ -825,6 +827,31 @@ mod tests { assert!("mean".parse::().is_err()); } + #[tokio::test] + async fn null_weights_drop_and_count_their_edges() { + // Null weights on one copy of the duplicate 10->20 and on 30->10. + let mut w = powers_of_two(); + w[1] = None; + w[3] = None; + let (nodes, edges) = weighted_people(w); + let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; + let g = engine + .export_graph(None, true, Some("w"), CombineEdges::Sum) + .await + .unwrap(); + // 10->99 and the two null weights; the null endpoint isn't counted. + assert_eq!(g.dropped_edges, 3); + assert_eq!(values(&g.out_indptr), vec![0, 1, 2, 3, 4, 5, 5]); + assert_eq!(values(&g.out_indices), vec![2, 4, 0, 3, 3]); + assert_eq!(weights(&g.out_weights), vec![128.0, 1.0, 64.0, 16.0, 4.0]); + // Without `weight`, the column is ignored and nothing extra is dropped. + let plain = engine + .export_graph(None, true, None, CombineEdges::Sum) + .await + .unwrap(); + assert_eq!(plain.dropped_edges, 1); + } + #[tokio::test] async fn bad_weight_columns_are_errors() { let (nodes, edges) = weighted_people(powers_of_two()); diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index c5597749..948421be 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -51,7 +51,7 @@ The returned [`GraphExport`][lance_csr.GraphExport] also holds: | `in_indptr`, `in_indices` | The same arrays for incoming edges; `None` for an undirected export | | `label_ranges` | Each node label's dense ids, as `(start, end)` with `end` excluded | | `out_weights`, `in_weights` | Edge weights, when asked for (see [Weighted graphs](#weighted-graphs)); otherwise `None` | -| `dropped_edges` | Edges whose endpoint key isn't in its node table | +| `dropped_edges` | Edges whose endpoint key isn't in its node table, or whose weight is null | The export follows the same rules as a query's join between relationship and node tables. An edge whose endpoint key isn't in its node table is left out (and counted in `dropped_edges`), an edge with a null endpoint is @@ -115,6 +115,16 @@ print(w.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0] The weight of `out_indices[i]` is `out_weights[i]`, and the same holds for the in-edges. Every included relationship type must have the column, and it must be numeric. +A null weight means the weight is unknown, and no number stands in for it safely: 1.0 would make a costly +edge look cheap to a shortest-path search. So the export leaves the edge out and counts it in `dropped_edges`, +as it does an edge whose endpoint is missing: + +```python +gaps = pa.table({"src": [10, 20], "dst": [20, 30], "messages": [3, None]}) +partial = CypherEngine(config, {"Person": people, "FOLLOWS": gaps}).export_graph(weight="messages") +print(partial.out_weights.to_pylist(), partial.dropped_edges) # [3.0] 1 +``` + The export lists each edge once, so an edge that appears in several rows needs one weight, and `combine_edges` says how to get it. The default, `"sum"`, adds the weights, which suits counts and amounts: 10 → 20 appears twice, with 3 and 4 messages, and gets 7. When the weight is a distance or a cost, the diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 5da6d328..0194f2a4 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -432,8 +432,8 @@ export class CypherEngine { * returns one set of arrays listing every edge in both directions. * @param options.weight - A numeric column of the relationship tables to export as float64 * edge weights, in `outWeights` and `inWeights`; every included type must have it, - * case-insensitive. Left out, no weights are exported, and the export needs no memory for - * them. + * case-insensitive. An edge whose weight is null is left out and counted in `droppedEdges`. + * Left out, no weights are exported, and the export needs no memory for them. * @param options.combineEdges - How an edge listed more than once combines its weights: `"sum"` * (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for * distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge @@ -441,8 +441,8 @@ export class CypherEngine { * @throws {@link LanceCsrError} `InvalidArgument` if a relationship type or label isn't in * the config, has no dataset, or a key or endpoint column is missing or isn't an integer * type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't - * one of the three rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan - * fails. + * one of the three rules, or there's nothing to export; `Runtime` if a node key appears + * twice within a label, or a scan fails. */ async exportGraph( relTypes?: string[], diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 8ed4010a..200cf8a0 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -142,8 +142,8 @@ export interface GraphExport { */ inWeights: Vector | null; /** - * Edges left out because an endpoint key isn't in its node table. Edges with a null - * endpoint are skipped and not counted. + * Edges left out because an endpoint key isn't in its node table, or, in a weighted export, + * because the weight is null. Edges with a null endpoint are skipped and not counted. */ droppedEdges: number; } diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index 6235fed6..bd9d3cd9 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -281,7 +281,7 @@ without `useCsr`. Lance datasets are scanned for just those columns. See | `options?` | \{ `combineEdges?`: `"sum"` \| `"min"` \| `"max"`; `directed?`: `boolean`; `weight?`: `string`; \} | - | | `options.combineEdges?` | `"sum"` \| `"min"` \| `"max"` | How an edge listed more than once combines its weights: `"sum"` (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge and combine the same way. Ignored without `weight`. | | `options.directed?` | `boolean` | `true` (the default) returns out-edge and in-edge arrays; `false` returns one set of arrays listing every edge in both directions. | -| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. Left out, no weights are exported, and the export needs no memory for them. | +| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. An edge whose weight is null is left out and counted in `droppedEdges`. Left out, no weights are exported, and the export needs no memory for them. | ###### Returns @@ -292,8 +292,8 @@ without `useCsr`. Lance datasets are scanned for just those columns. See [LanceCsrError](#lancecsrerror) `InvalidArgument` if a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't - one of the three rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, a weight is null, or a scan - fails. + one of the three rules, or there's nothing to export; `Runtime` if a node key appears + twice within a label, or a scan fails. @@ -1638,7 +1638,7 @@ id back to its node's key. The vectors wrap typed arrays built in Rust. See | Property | Type | Description | | ------ | ------ | ------ | | `directed` | `boolean` | Whether the arrays describe a directed graph. | -| `droppedEdges` | `number` | Edges left out because an endpoint key isn't in its node table. Edges with a null endpoint are skipped and not counted. | +| `droppedEdges` | `number` | Edges left out because an endpoint key isn't in its node table, or, in a weighted export, because the weight is null. Edges with a null endpoint are skipped and not counted. | | `inIndices` | `Vector`\<`Uint64`\> \| `null` | Each node's in-neighbours, sorted, without duplicates; `null` for an undirected graph. | | `inIndptr` | `Vector`\<`Uint64`\> \| `null` | Offsets into `inIndices`; `null` for an undirected graph. | | `inWeights` | `Vector`\<`Float64`\> \| `null` | The weight of each entry in `inIndices`; `null` for an undirected export, or unless `exportGraph` was given a `weight` column. | diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index 3d1a0466..9e5629ff 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -491,7 +491,8 @@ def export_graph( weight : str or None Keyword-only. A numeric column of the relationship tables to export as `float64` edge weights, in `out_weights` and `in_weights`; every included - type must have it, case-insensitive. `None` (the default) exports no + type must have it, case-insensitive. An edge whose weight is null is left + out and counted in `dropped_edges`. `None` (the default) exports no weights, and the export then needs no memory for them. combine_edges : {"sum", "min", "max"} Keyword-only. How an edge listed more than once combines its weights: @@ -513,8 +514,7 @@ def export_graph( (`uint64` isn't supported), the weight column is missing or isn't numeric, `combine_edges` isn't one of the three rules, or there's nothing to export. RuntimeError - If a node key appears twice within a label, a weight is null, or a scan - fails. + If a node key appears twice within a label, or a scan fails. Examples -------- diff --git a/python/python/lance_csr/export.py b/python/python/lance_csr/export.py index 4b483ad9..e37127e9 100644 --- a/python/python/lance_csr/export.py +++ b/python/python/lance_csr/export.py @@ -117,9 +117,10 @@ def in_weights(self) -> DoubleArray | None: @property def dropped_edges(self) -> int: - """Edges left out because an endpoint key isn't in its node table. + """Edges left out because an endpoint key isn't in its node table, or, in a + weighted export, because the weight is null. - A query's join between the relationship and node tables leaves them out too. - Edges with a null endpoint are skipped and not counted. + A query's join between the relationship and node tables leaves out the first + kind too. Edges with a null endpoint are skipped and not counted. """ return self._inner.dropped_edges diff --git a/python/python/tests/test_graph_export.py b/python/python/tests/test_graph_export.py index c109fcf4..212cb642 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -77,6 +77,14 @@ def test_weights(): assert high.out_weights is not None assert high.out_weights.to_pylist() == [128, 8, 2, 128, 8, 16, 4, 2, 4] + # A null weight drops its edge and counts it; unweighted exports ignore it. + gaps = EDGES.append_column("w", pa.array([1, None, 4, 8, 16, 32, 64, 128, 256])) + gappy = CypherEngine(CONFIG, {"Person": NODES, "KNOWS": gaps}) + dropped = gappy.export_graph(weight="w") + assert dropped.dropped_edges == 2 and dropped.out_weights is not None + assert dropped.out_weights.to_pylist() == [128, 1, 64, 8, 16, 4] + assert gappy.export_graph().dropped_edges == 1 + with pytest.raises(ValueError, match="cost"): engine.export_graph(weight="cost") with pytest.raises(ValueError, match="combine_edges"): From bc9f166cafee71c4afb107f9d33780d7d77de3c6 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 18:39:31 -0500 Subject: [PATCH 4/8] perf(export): keep undirected weighted edges in one vector Pushing each reverse edge straight into the out vector, instead of a second vector appended before the sort, avoids holding both at once: about 0.6 GB less peak memory for a 40M-edge undirected weighted export. --- crates/lance-csr/src/graph_export.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index f216aa30..d5c6ae10 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -300,7 +300,9 @@ pub(crate) async fn export_graph( let mut inc: Vec = Vec::with_capacity(keys_cap); let mut out_w: Vec<(u64, f64)> = Vec::with_capacity(if directed { pairs_cap } else { 2 * pairs_cap }); - let mut inc_w: Vec<(u64, f64)> = Vec::with_capacity(pairs_cap); + // Undirected weighted edges go straight into `out_w`: appending a second vector + // would hold both at once. + let mut inc_w: Vec<(u64, f64)> = Vec::with_capacity(if directed { pairs_cap } else { 0 }); let mut dropped = 0u64; for rel in &rels { let (src_map, dst_map) = (&maps[rel.src_label], &maps[rel.dst_label]); @@ -338,10 +340,12 @@ pub(crate) async fn export_graph( (Some((a, b, i)), Some(w)) => { let w = w.value(i); out_w.push((a * n + b, w)); - // Undirected: a self-loop's reverse is itself; adding it would - // count its weight twice. - if directed || a != b { + if directed { inc_w.push((b * n + a, w)); + } else if a != b { + // A self-loop's reverse is itself; adding it would count its + // weight twice. + out_w.push((b * n + a, w)); } } (None, _) => dropped += 1, @@ -352,12 +356,7 @@ pub(crate) async fn export_graph( let ((out_indptr, out_indices, out_weights), inbound) = if weighted { drop((out, inc)); - let inc_w = if directed { - Some(inc_w) - } else { - out_w.append(&mut inc_w); - None // `inc_w`'s allocation is freed here, before the sort - }; + let inc_w = directed.then_some(inc_w); let weighted = |pairs| { let (p, i, w) = weighted_csr(n, pairs, combine); (p, i, Some(w)) From 5851f767f79e10e7d2a6745e1fbc2b88f5dd0832 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 18:51:57 -0500 Subject: [PATCH 5/8] docs: state the memory a weighted export needs Measured on a 40M-edge graph: an unweighted export peaks at the same memory as before weights were added, and a weighted one at up to about three times that. --- docs/graph-algorithms.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index 948421be..5a1455d4 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -236,7 +236,8 @@ Some cases need care: - The export holds the whole graph in memory: eight bytes per edge in each direction for `indices`, plus the offsets and keys. A directed export of 10 million edges takes about 160 MB, and building it briefly needs - about as much again. Weights add eight bytes per edge in each direction, and while the export is built each - edge takes 16 bytes instead of eight. + about as much again. Weights add eight bytes per edge in each direction, and building a weighted export + briefly needs up to three times the memory of an unweighted one, because each edge is sorted together with its + weight. An unweighted export needs no memory for weights. - Keys and endpoints must be integers up to `int64`; string and `uint64` keys aren't supported. - Only one edge property is exported, as a weight; other edge properties aren't. From c3440db57dfabdfa0d70c202ec45a76ab674d8e4 Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 19:28:58 -0500 Subject: [PATCH 6/8] perf(export): build in-edges by transposing the out-edge CSR Directed exports sorted a second copy of the edges, reversed, to get the in-edge CSR. Both paths, weighted and unweighted, now sort only the out-edges and derive the in-edges in one counting-and-scatter pass, which keeps in-edge rows sorted and duplicate-free. Undirected unweighted exports also push reverse edges into the out vector instead of appending a second one, as the weighted path already did. The CSR offset count is shared by the three builders. Peak physical footprint at 40M edges (release, macOS, load 4 to 7), before -> after: directed unweighted 784 -> 784 MiB (about 5% slower: the scatter is sequential where the second sort was parallel); undirected unweighted 1090 -> 785 MiB; directed weighted 2185 -> 1897 MiB; undirected weighted unchanged. All four exports are byte-identical before and after. --- crates/lance-csr/src/graph_export.rs | 158 ++++++++++++++++++--------- 1 file changed, 108 insertions(+), 50 deletions(-) diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index d5c6ae10..723b69cd 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -15,8 +15,9 @@ //! null in a weighted export, is dropped and counted; //! - rows: each edge is packed as `row * n + column` into a `u64`, sorted in parallel //! and deduplicated, which sorts every neighbour list too; `indptr` is then a count -//! per row. Directed graphs also get the in-edge CSR (PageRank reads in-edges); -//! undirected graphs get one CSR holding both directions, a self-loop once. +//! per row. Directed graphs also get the in-edge CSR (PageRank reads in-edges), built +//! by transposing the finished out-edge CSR rather than sorting a second copy of the +//! edges; undirected graphs get one CSR holding both directions, a self-loop once. //! - weights, only when asked for: each packed key is paired with its weight (16 bytes //! per edge instead of 8 while sorting), and duplicate edges are combined into one //! weight by a [`CombineEdges`] rule. Unweighted exports never allocate the pairs. @@ -296,13 +297,11 @@ pub(crate) async fn export_graph( // Exactly one of the key and the (key, weight) vectors is used. let weighted = weight.is_some(); let (keys_cap, pairs_cap) = if weighted { (0, rows) } else { (rows, 0) }; + // Out-edges only: directed in-edges come from transposing the out CSR, and undirected + // reverse edges go into the same vector. let mut out: Vec = Vec::with_capacity(if directed { keys_cap } else { 2 * keys_cap }); - let mut inc: Vec = Vec::with_capacity(keys_cap); let mut out_w: Vec<(u64, f64)> = Vec::with_capacity(if directed { pairs_cap } else { 2 * pairs_cap }); - // Undirected weighted edges go straight into `out_w`: appending a second vector - // would hold both at once. - let mut inc_w: Vec<(u64, f64)> = Vec::with_capacity(if directed { pairs_cap } else { 0 }); let mut dropped = 0u64; for rel in &rels { let (src_map, dst_map) = (&maps[rel.src_label], &maps[rel.dst_label]); @@ -332,19 +331,17 @@ pub(crate) async fn export_graph( .collect(); for pair in pairs { match (pair, &w) { + // A self-loop's reverse is itself; adding it would count its weight twice. (Some((a, b, _)), None) => { out.push(a * n + b); - // Undirected: the reverse goes into the same CSR. - inc.push(b * n + a); + if !directed && a != b { + out.push(b * n + a); + } } (Some((a, b, i)), Some(w)) => { let w = w.value(i); out_w.push((a * n + b, w)); - if directed { - inc_w.push((b * n + a, w)); - } else if a != b { - // A self-loop's reverse is itself; adding it would count its - // weight twice. + if !directed && a != b { out_w.push((b * n + a, w)); } } @@ -354,31 +351,24 @@ pub(crate) async fn export_graph( } } - let ((out_indptr, out_indices, out_weights), inbound) = if weighted { - drop((out, inc)); - let inc_w = directed.then_some(inc_w); - let weighted = |pairs| { - let (p, i, w) = weighted_csr(n, pairs, combine); - (p, i, Some(w)) - }; - (weighted(out_w), inc_w.map(weighted)) + let (out_indptr, out_indices, out_weights) = if weighted { + drop(out); + let (p, i, w) = weighted_csr(n, out_w, combine); + (p, i, Some(w)) } else { - drop((out_w, inc_w)); - let inc = if directed { - Some(inc) - } else { - out.append(&mut inc); - None - }; - let unweighted = |keys| { - let (p, i) = csr(n, keys); - (p, i, None) - }; - (unweighted(out), inc.map(unweighted)) + drop(out_w); + let (p, i) = csr(n, out); + (p, i, None) }; - let (in_indptr, in_indices, in_weights) = match inbound { - Some((p, i, w)) => (Some(p), Some(i), w), - None => (None, None, None), + let (in_indptr, in_indices, in_weights) = if directed { + let (p, i, w) = transpose( + out_indptr.values(), + out_indices.values(), + out_weights.as_ref().map(|w| w.values().as_ref()), + ); + (Some(p), Some(i), w) + } else { + (None, None, None) }; Ok(GraphExport { num_nodes: n, @@ -395,17 +385,23 @@ pub(crate) async fn export_graph( }) } -/// Sort and deduplicate packed `row * n + column` keys into `(indptr, indices)`. -fn csr(n: u64, mut packed: Vec) -> (UInt64Array, UInt64Array) { - packed.par_sort_unstable(); - packed.dedup(); +/// CSR offsets, `n + 1` entries, from each entry's row in order. +fn offsets(n: u64, rows: impl Iterator) -> Vec { let mut indptr = vec![0u64; n as usize + 1]; - for &key in &packed { - indptr[(key / n) as usize + 1] += 1; + for row in rows { + indptr[row as usize + 1] += 1; } for i in 1..indptr.len() { indptr[i] += indptr[i - 1]; } + indptr +} + +/// Sort and deduplicate packed `row * n + column` keys into `(indptr, indices)`. +fn csr(n: u64, mut packed: Vec) -> (UInt64Array, UInt64Array) { + packed.par_sort_unstable(); + packed.dedup(); + let indptr = offsets(n, packed.iter().map(|key| key / n)); packed .par_iter_mut() .with_min_len(4096) @@ -428,15 +424,10 @@ fn weighted_csr( } same }); - let mut indptr = vec![0u64; n as usize + 1]; - for &(key, _) in &pairs { - indptr[(key / n) as usize + 1] += 1; - } - for i in 1..indptr.len() { - indptr[i] += indptr[i - 1]; - } + let indptr = offsets(n, pairs.iter().map(|(key, _)| key / n)); let weights: Vec = pairs.par_iter().map(|p| p.1).collect(); - // Collected in place into the pairs' allocation, then shrunk to the final size. + // Collected in place into the pairs' allocation, then shrunk to the final size (measured + // in place on macOS: a fresh vector instead raised the peak by 8 bytes per entry). let mut indices: Vec = pairs.into_iter().map(|p| p.0 % n).collect(); indices.shrink_to_fit(); ( @@ -446,6 +437,41 @@ fn weighted_csr( ) } +/// The in-edge CSR of a directed graph from its out-edge CSR, by counting and scattering. +/// +/// Sources are visited in order, so every in-edge row comes out sorted, and the out CSR has +/// no duplicates, so neither does the result. Each weight is the out-edge's combined weight. +fn transpose( + out_indptr: &[u64], + out_indices: &[u64], + out_weights: Option<&[f64]>, +) -> (UInt64Array, UInt64Array, Option) { + let n = out_indptr.len() - 1; + // `indptr[t]` is the next free slot of row `t` while scattering; afterwards it holds + // the end of row `t`, which the shift below turns back into the start of row `t + 1`. + let mut indptr = offsets(n as u64, out_indices.iter().copied()); + let mut indices = vec![0u64; out_indices.len()]; + let mut weights = out_weights.map(|_| vec![0f64; out_indices.len()]); + for source in 0..n { + for edge in out_indptr[source] as usize..out_indptr[source + 1] as usize { + let target = out_indices[edge] as usize; + let slot = indptr[target] as usize; + indptr[target] += 1; + indices[slot] = source as u64; + if let (Some(weights), Some(out)) = (weights.as_mut(), out_weights) { + weights[slot] = out[edge]; + } + } + } + indptr.copy_within(0..n, 1); + indptr[0] = 0; + ( + UInt64Array::from(indptr), + UInt64Array::from(indices), + weights.map(Float64Array::from), + ) +} + /// Add `column` to the node table of each label in `export`, from `values` indexed by dense id. /// /// Each label's slice of `values` is paired with its keys and merged into the label's Lance @@ -882,6 +908,38 @@ mod tests { assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); } + #[test] + fn transpose_matches_sorting_the_reversed_edges() { + // Random edges with duplicates and self-loops; weights tie each edge to its pair. + let n = 50u64; + let mut state = 7u64; + let mut next = || { + state = state + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (state >> 33) % n + }; + let edges: Vec<(u64, u64)> = (0..400).map(|_| (next(), next())).collect(); + let weight = |a: u64, b: u64| (a * 1000 + b) as f64; + let pairs = edges + .iter() + .map(|&(a, b)| (a * n + b, weight(a, b))) + .collect(); + let (p, i, w) = weighted_csr(n, pairs, CombineEdges::Max); + let (tp, ti, tw) = transpose(p.values(), i.values(), Some(w.values())); + let (rp, ri) = csr(n, edges.iter().map(|&(a, b)| b * n + a).collect()); + assert_eq!((&tp, &ti), (&rp, &ri)); + // In-row `t` lists sources `s` of edges s -> t. + let tw = tw.unwrap(); + for t in 0..n as usize { + for e in tp.value(t) as usize..tp.value(t + 1) as usize { + assert_eq!(tw.value(e), weight(ti.value(e), t as u64)); + } + } + let (_, _, none) = transpose(p.values(), i.values(), None); + assert!(none.is_none()); + } + #[tokio::test] async fn labels_get_separate_ranges_for_colliding_keys() { let config = GraphConfig::builder() From c0c88988ffb9cf6bffc3ee0d752fe27802216c9a Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 19:37:45 -0500 Subject: [PATCH 7/8] feat(export): weight columns per relationship type and a default weight An export over several relationship types needed one weight column name that every type had. `weight` now also takes a mapping from relationship type to column, so types can store weights under different names, and `default_weight` (`defaultWeight` in TypeScript) gives the weight of every edge of a type without a column: one the mapping leaves out, or one without the shared column. Without a default, a type with no weight column is still an error, so a guessed weight never changes an algorithm's answer silently. A column the mapping names must exist even with a default, a mapping entry for a type that isn't exported is an error, and so is a shared column that no type has. `default_weight` without `weight` is an error. Rust: `EdgeWeights` (column, per-type columns, default, combine rule) replaces the separate weight and combine arguments of `CypherEngine::export_graph`. --- crates/lance-csr-node/src/engine.rs | 27 +- crates/lance-csr-python/src/graph.rs | 47 ++- crates/lance-csr/src/engine.rs | 16 +- crates/lance-csr/src/graph_export.rs | 379 +++++++++++++++----- crates/lance-csr/src/lib.rs | 2 +- docs/graph-algorithms.md | 37 +- docs/typescript.md | 1 + nodejs/native.d.ts | 2 +- nodejs/src/cypher.ts | 28 +- nodejs/test/graph-export.test.ts | 31 ++ nodejs/typedoc/api.md | 11 +- python/python/lance_csr/_internal/graph.pyi | 3 +- python/python/lance_csr/cypher.py | 31 +- python/python/tests/test_graph_export.py | 45 +++ 14 files changed, 517 insertions(+), 143 deletions(-) diff --git a/crates/lance-csr-node/src/engine.rs b/crates/lance-csr-node/src/engine.rs index a2a51a02..50a78831 100644 --- a/crates/lance-csr-node/src/engine.rs +++ b/crates/lance-csr-node/src/engine.rs @@ -10,7 +10,7 @@ use lance_csr::engine::{ CypherEngine as RustCypherEngine, EngineOptions, PersistCsr, MAX_TARGET_PARTITIONS, }; use lance_csr::SqlEngine as RustSqlEngine; -use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer, Float64Array}; +use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer, Either, Float64Array}; use napi_derive::napi; use tokio::sync::Mutex; @@ -266,8 +266,9 @@ impl CypherEngine { &self, rel_types: Option>, directed: bool, - weight: Option, + weight: Option>>, combine_edges: Option, + default_weight: Option, ) -> napi::Result { let combine = combine_edges .as_deref() @@ -275,10 +276,30 @@ impl CypherEngine { .transpose() .map_err(graph_error)? .unwrap_or_default(); + let weights = match weight { + None if default_weight.is_some() => { + return Err(invalid( + "defaultWeight needs weight: name a weight column or a column per type", + )) + } + None => None, + Some(w) => { + let (column, per_type) = match w { + Either::A(name) => (Some(name), Vec::new()), + Either::B(map) => (None, map.into_iter().collect()), + }; + Some(lance_csr::EdgeWeights { + column, + per_type, + default: default_weight, + combine, + }) + } + }; let inner = self.inner.clone(); let g = blocking(async move { inner - .export_graph(rel_types.as_deref(), directed, weight.as_deref(), combine) + .export_graph(rel_types.as_deref(), directed, weights.as_ref()) .await }) .await?; diff --git a/crates/lance-csr-python/src/graph.rs b/crates/lance-csr-python/src/graph.rs index fda50372..d7a3434a 100644 --- a/crates/lance-csr-python/src/graph.rs +++ b/crates/lance-csr-python/src/graph.rs @@ -1331,27 +1331,58 @@ impl CypherEngine { Ok(stats.into_any().unbind()) } - #[pyo3(signature = (rel_types=None, *, directed=true, weight=None, combine_edges="sum"))] + #[pyo3(signature = ( + rel_types=None, *, directed=true, weight=None, combine_edges="sum", default_weight=None + ))] fn export_graph( &self, py: Python, rel_types: Option>, directed: bool, - weight: Option, + weight: Option>, combine_edges: &str, + default_weight: Option, ) -> PyResult { let combine = combine_edges .parse::() .map_err(graph_error_to_pyerr)?; + let weights = match weight { + None if default_weight.is_some() => { + return Err(PyValueError::new_err( + "default_weight needs weight: name a weight column or a column per type", + )) + } + None => None, + Some(w) => { + let (column, per_type) = if let Ok(name) = w.extract::() { + (Some(name), Vec::new()) + } else if let Ok(dict) = w.downcast::() { + let pairs = dict + .iter() + .map(|(k, v)| Ok((k.extract::()?, v.extract::()?))) + .collect::>>() + .map_err(|_| { + PyTypeError::new_err("weight dict must map type names to column names") + })?; + (None, pairs) + } else { + return Err(PyTypeError::new_err( + "weight must be a column name or a dict of type name -> column name", + )); + }; + Some(lance_csr::EdgeWeights { + column, + per_type, + default: default_weight, + combine, + }) + } + }; let inner = RT .block_on( Some(py), - self.inner.export_graph( - rel_types.as_deref(), - directed, - weight.as_deref(), - combine, - ), + self.inner + .export_graph(rel_types.as_deref(), directed, weights.as_ref()), )? .map_err(graph_error_to_pyerr)?; Ok(GraphExport { inner }) diff --git a/crates/lance-csr/src/engine.rs b/crates/lance-csr/src/engine.rs index 011e61e2..bc8b07de 100644 --- a/crates/lance-csr/src/engine.rs +++ b/crates/lance-csr/src/engine.rs @@ -1608,24 +1608,23 @@ impl CypherEngine { /// `rel_types` `None` exports every relationship type whose dataset has integer /// endpoints. See [`crate::graph_export`] for how ids and rows are laid out. /// - /// `weight` names a numeric column of the relationship tables to export as `f64` - /// edge weights, and `combine` sets how a repeated edge merges its weights (it's - /// ignored without `weight`). `None` exports no weights and allocates nothing for them. + /// `weights` says which numeric column of each relationship table to export as `f64` + /// edge weights, the weight of types without one, and how a repeated edge merges its + /// weights. `None` exports no weights and allocates nothing for them. /// /// Sorting the edges is CPU-bound and runs on rayon's pool; as with the CSR /// build, call it from a blocking thread in an application with its own runtime. /// /// # Errors /// [`GraphError::ConfigError`] for an unknown relationship type or label, a missing - /// or non-integer key or endpoint column, a missing or non-numeric weight column, or - /// nothing to export; [`GraphError::ExecutionError`] for a repeated node key or a + /// or non-integer key or endpoint column, a missing or non-numeric weight column, a type + /// with no weight column and no default, or nothing to export; [`GraphError::ExecutionError`] for a repeated node key or a /// failed scan. An edge with a null weight is dropped and counted in `dropped_edges`. pub async fn export_graph( &self, rel_types: Option<&[String]>, directed: bool, - weight: Option<&str>, - combine: crate::graph_export::CombineEdges, + weights: Option<&crate::graph_export::EdgeWeights>, ) -> Result { let snapshot = self.snapshot(); crate::graph_export::export_graph( @@ -1633,8 +1632,7 @@ impl CypherEngine { &snapshot.sources, rel_types, directed, - weight, - combine, + weights, ) .await } diff --git a/crates/lance-csr/src/graph_export.rs b/crates/lance-csr/src/graph_export.rs index 723b69cd..01619c37 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -21,6 +21,8 @@ //! - weights, only when asked for: each packed key is paired with its weight (16 bytes //! per edge instead of 8 while sorting), and duplicate edges are combined into one //! weight by a [`CombineEdges`] rule. Unweighted exports never allocate the pairs. +//! [`EdgeWeights`] names a column per relationship type, or one shared column, and a +//! default weight for types without one. use std::collections::HashMap; @@ -104,13 +106,44 @@ impl std::str::FromStr for CombineEdges { } } +/// Which column holds each relationship type's edge weights, and how repeated edges combine. +#[derive(Debug, Clone, Default)] +pub struct EdgeWeights { + /// The weight column of every type not in `per_type`, case-insensitive. With `default` + /// set, a type without this column gets the default instead, as long as some type has it. + pub column: Option, + /// Weight columns by relationship type, both case-insensitive; a named column must exist. + pub per_type: Vec<(String, String)>, + /// The weight of every edge of a type that has no weight column. `None` makes such a type + /// an error. + pub default: Option, + /// How an edge listed more than once combines its weights. + pub combine: CombineEdges, +} + +impl EdgeWeights { + /// One column for every exported relationship type. + pub fn column(name: impl Into) -> Self { + Self { + column: Some(name.into()), + ..Self::default() + } + } +} + +/// Where a relationship type's weights come from. +enum RelWeight { + Column(String), + Constant(f64), +} + /// One relationship type to export: its dataset and the labels at both ends. struct RelSource<'a> { name: String, source: &'a EngineSource, src: String, dst: String, - weight: Option, + weight: Option, src_label: usize, dst_label: usize, } @@ -118,15 +151,13 @@ struct RelSource<'a> { /// Build the export from `sources` (the engine's pinned snapshot). /// /// `rel_types` `None` takes every relationship type whose dataset is registered and -/// whose endpoints are integers. `weight` names a numeric column every exported -/// relationship type must have; `combine` merges the weights of a repeated edge. +/// whose endpoints are integers. `weights` says where each type's edge weights come from. pub(crate) async fn export_graph( config: &GraphConfig, sources: &HashMap, rel_types: Option<&[String]>, directed: bool, - weight: Option<&str>, - combine: CombineEdges, + weights: Option<&EdgeWeights>, ) -> Result { let find_source = |name: &str| { sources @@ -216,24 +247,7 @@ pub(crate) async fn export_graph( } Ok(field.name().clone()) }; - let weight = weight - .map(|name| -> Result { - let field = schema - .fields() - .iter() - .find(|f| f.name().eq_ignore_ascii_case(name)) - .ok_or_else(|| { - config_error(format!("Weight column '{name}' not found in '{rel}'")) - })?; - if !field.data_type().is_numeric() { - return Err(config_error(format!( - "Weight column '{name}' of '{rel}' is {}, not a numeric type", - field.data_type() - ))); - } - Ok(field.name().clone()) - }) - .transpose()?; + let weight = weights.map(|w| rel_weight(w, rel, &schema)).transpose()?; rels.push(RelSource { name: rel.clone(), source, @@ -245,6 +259,25 @@ pub(crate) async fn export_graph( }); } + if let Some(w) = weights { + for (rel_type, _) in &w.per_type { + if !rels.iter().any(|r| r.name.eq_ignore_ascii_case(rel_type)) { + return Err(config_error(format!( + "Weight column given for '{rel_type}', which isn't an exported relationship type" + ))); + } + } + // A shared column that no type has is a typo, not a reason to use the default. + let any_column = rels + .iter() + .any(|r| matches!(r.weight, Some(RelWeight::Column(_)))); + if let (Some(name), false) = (&w.column, any_column) { + return Err(config_error(format!( + "Weight column '{name}' not found in any exported relationship type" + ))); + } + } + // Node keys -> dense ids, one map per label. let mut node_keys: Vec = Vec::new(); let mut label_ranges = Vec::with_capacity(labels.len()); @@ -295,7 +328,7 @@ pub(crate) async fn export_graph( rows += rel.source.num_rows(&rel.name).await?; } // Exactly one of the key and the (key, weight) vectors is used. - let weighted = weight.is_some(); + let weighted = weights.is_some(); let (keys_cap, pairs_cap) = if weighted { (0, rows) } else { (rows, 0) }; // Out-edges only: directed in-edges come from transposing the out CSR, and undirected // reverse edges go into the same vector. @@ -306,13 +339,18 @@ pub(crate) async fn export_graph( for rel in &rels { let (src_map, dst_map) = (&maps[rel.src_label], &maps[rel.dst_label]); let mut columns = vec![rel.src.as_str(), rel.dst.as_str()]; - columns.extend(rel.weight.as_deref()); + let (weight_column, constant) = match &rel.weight { + Some(RelWeight::Column(name)) => (Some(name.as_str()), 0.0), + Some(RelWeight::Constant(value)) => (None, *value), + None => (None, 0.0), + }; + columns.extend(weight_column); let mut stream = rel.source.scan_columns(&columns).await?; while let Some(batch) = stream.next().await { let batch = batch?; let s = int64(batch.column(0), &rel.src, &rel.name)?; let d = int64(batch.column(1), &rel.dst, &rel.name)?; - let w = match &rel.weight { + let w = match weight_column { Some(name) => Some(float64(batch.column(2), name, &rel.name)?), None => None, }; @@ -330,22 +368,23 @@ pub(crate) async fn export_graph( }) .collect(); for pair in pairs { - match (pair, &w) { - // A self-loop's reverse is itself; adding it would count its weight twice. - (Some((a, b, _)), None) => { - out.push(a * n + b); - if !directed && a != b { - out.push(b * n + a); - } + let Some((a, b, i)) = pair else { + dropped += 1; + continue; + }; + // A self-loop's reverse is itself; adding it would count its weight twice. + let reverse = !directed && a != b; + if weighted { + let w = w.as_ref().map_or(constant, |w| w.value(i)); + out_w.push((a * n + b, w)); + if reverse { + out_w.push((b * n + a, w)); } - (Some((a, b, i)), Some(w)) => { - let w = w.value(i); - out_w.push((a * n + b, w)); - if !directed && a != b { - out_w.push((b * n + a, w)); - } + } else { + out.push(a * n + b); + if reverse { + out.push(b * n + a); } - (None, _) => dropped += 1, } } } @@ -353,6 +392,7 @@ pub(crate) async fn export_graph( let (out_indptr, out_indices, out_weights) = if weighted { drop(out); + let combine = weights.map(|w| w.combine).unwrap_or_default(); let (p, i, w) = weighted_csr(n, out_w, combine); (p, i, Some(w)) } else { @@ -589,6 +629,46 @@ pub(crate) async fn write_node_column( Ok(updated) } +/// Where `rel`'s weights come from: its column in `per_type`, else the shared column, else +/// the default. A column named for this type must exist and be numeric. +fn rel_weight( + weights: &EdgeWeights, + rel: &str, + schema: &arrow::datatypes::Schema, +) -> Result { + let named = weights + .per_type + .iter() + .find(|(t, _)| t.eq_ignore_ascii_case(rel)) + .map(|(_, column)| column); + let (name, required) = match (named, &weights.column) { + (Some(name), _) => (Some(name), true), + (None, Some(name)) => (Some(name), weights.default.is_none()), + (None, None) => (None, false), + }; + let field = name.and_then(|name| { + schema + .fields() + .iter() + .find(|f| f.name().eq_ignore_ascii_case(name)) + }); + match (field, name, weights.default) { + (Some(field), _, _) if !field.data_type().is_numeric() => Err(config_error(format!( + "Weight column '{}' of '{rel}' is {}, not a numeric type", + field.name(), + field.data_type() + ))), + (Some(field), _, _) => Ok(RelWeight::Column(field.name().clone())), + (None, Some(name), _) if required => Err(config_error(format!( + "Weight column '{name}' not found in '{rel}'" + ))), + (None, _, Some(value)) => Ok(RelWeight::Constant(value)), + (None, _, None) => Err(config_error(format!( + "No weight column for '{rel}'; name one for it or set a default weight" + ))), + } +} + fn field_type(schema: &arrow::datatypes::Schema, name: &str) -> Option { schema .fields() @@ -715,10 +795,7 @@ mod tests { async fn directed_export_matches_hand_built_csr() { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; - let g = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); // Dense ids follow row order: 60->0, 10->1, 50->2, 30->3, 20->4, 40->5. assert_eq!(g.node_keys.values().to_vec(), vec![60, 10, 50, 30, 20, 40]); assert_eq!(g.num_nodes, 6); @@ -741,7 +818,7 @@ mod tests { let (nodes, edges) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let g = engine - .export_graph(Some(&["knows".to_string()]), false, None, CombineEdges::Sum) + .export_graph(Some(&["knows".to_string()]), false, None) .await .unwrap(); assert!(!g.directed && g.in_indptr.is_none() && g.in_indices.is_none()); @@ -774,14 +851,11 @@ mod tests { let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; // Unweighted: no weight arrays, same CSR as without the column. - let plain = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let plain = engine.export_graph(None, true, None).await.unwrap(); assert!(plain.out_weights.is_none() && plain.in_weights.is_none()); let g = engine - .export_graph(None, true, Some("W"), CombineEdges::Sum) + .export_graph(None, true, Some(&EdgeWeights::column("W"))) .await .unwrap(); assert_eq!( @@ -805,13 +879,10 @@ mod tests { // Undirected: 50->60 and 60->50 become one edge, the self-loop's weight counts once. let u = engine - .export_graph(None, false, Some("w"), CombineEdges::Sum) - .await - .unwrap(); - let plain = engine - .export_graph(None, false, None, CombineEdges::Sum) + .export_graph(None, false, Some(&EdgeWeights::column("w"))) .await .unwrap(); + let plain = engine.export_graph(None, false, None).await.unwrap(); assert_eq!( (&u.out_indptr, &u.out_indices), (&plain.out_indptr, &plain.out_indices) @@ -833,13 +904,27 @@ mod tests { (CombineEdges::Max, 2.0, 128.0), ] { let g = engine - .export_graph(None, true, Some("w"), combine) + .export_graph( + None, + true, + Some(&EdgeWeights { + combine, + ..EdgeWeights::column("w") + }), + ) .await .unwrap(); assert_eq!(weights(&g.out_weights)[1], dup, "{combine:?}"); assert_eq!(weights(&g.in_weights)[5], dup, "{combine:?}"); let u = engine - .export_graph(None, false, Some("w"), combine) + .export_graph( + None, + false, + Some(&EdgeWeights { + combine, + ..EdgeWeights::column("w") + }), + ) .await .unwrap(); assert_eq!( @@ -861,7 +946,7 @@ mod tests { let (nodes, edges) = weighted_people(w); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let g = engine - .export_graph(None, true, Some("w"), CombineEdges::Sum) + .export_graph(None, true, Some(&EdgeWeights::column("w"))) .await .unwrap(); // 10->99 and the two null weights; the null endpoint isn't counted. @@ -870,19 +955,141 @@ mod tests { assert_eq!(values(&g.out_indices), vec![2, 4, 0, 3, 3]); assert_eq!(weights(&g.out_weights), vec![128.0, 1.0, 64.0, 16.0, 4.0]); // Without `weight`, the column is ignored and nothing extra is dropped. - let plain = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let plain = engine.export_graph(None, true, None).await.unwrap(); assert_eq!(plain.dropped_edges, 1); } + /// KNOWS has a weight column `w`; LIKES has none, only an unrelated `since`. + async fn mixed_engine() -> CypherEngine { + let config = GraphConfig::builder() + .node_table("Person", "id") + .rel_table("KNOWS", "Person", "Person", "src", "dst") + .rel_table("LIKES", "Person", "Person", "src", "dst") + .build() + .unwrap(); + let knows = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("src", DataType::Int64, true), + Field::new("dst", DataType::Int64, true), + Field::new("w", DataType::Float64, true), + ])), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(Int64Array::from(vec![2, 3])), + Arc::new(arrow::array::Float64Array::from(vec![5.0, 7.0])), + ], + ) + .unwrap(); + let likes = batch(&[ + ("src", vec![Some(1), Some(3)]), + ("dst", vec![Some(2), Some(1)]), + ("since", vec![Some(2020), Some(2021)]), + ]); + let nodes = batch(&[("id", vec![Some(1), Some(2), Some(3)])]); + arrow_engine( + config, + vec![("Person", nodes), ("KNOWS", knows), ("LIKES", likes)], + ) + .await + } + + #[tokio::test] + async fn weights_per_type_and_default() { + let engine = mixed_engine().await; + // Out-edges by dense id: 1->2 (KNOWS 5, and LIKES), 2->3 (KNOWS 7), 3->1 (LIKES). + let export = |w: EdgeWeights| { + let engine = &engine; + async move { engine.export_graph(None, true, Some(&w)).await } + }; + let per_type = |pairs: &[(&str, &str)]| -> Vec<(String, String)> { + pairs + .iter() + .map(|(t, c)| (t.to_string(), c.to_string())) + .collect() + }; + + // A shared column with a default: LIKES edges get the default. + let g = export(EdgeWeights { + default: Some(1.0), + ..EdgeWeights::column("w") + }) + .await + .unwrap(); + assert_eq!(values(&g.out_indices), vec![1, 2, 0]); + assert_eq!(weights(&g.out_weights), vec![6.0, 7.0, 1.0]); + + // A column per type, any name. + let g = export(EdgeWeights { + per_type: per_type(&[("knows", "w"), ("LIKES", "SINCE")]), + ..EdgeWeights::default() + }) + .await + .unwrap(); + assert_eq!(weights(&g.out_weights), vec![2025.0, 7.0, 2021.0]); + + // Some types named, a default for the rest. + let g = export(EdgeWeights { + per_type: per_type(&[("KNOWS", "w")]), + default: Some(2.0), + ..EdgeWeights::default() + }) + .await + .unwrap(); + assert_eq!(weights(&g.out_weights), vec![7.0, 7.0, 2.0]); + assert_eq!(weights(&g.in_weights), vec![2.0, 7.0, 7.0]); + + // Errors: a type without a weight and no default; a column named for a type that + // lacks it, even with a default; a type that isn't exported; a shared column no + // type has. + for w in [ + EdgeWeights::column("w"), + EdgeWeights { + per_type: per_type(&[("KNOWS", "w")]), + ..EdgeWeights::default() + }, + EdgeWeights { + per_type: per_type(&[("LIKES", "w")]), + default: Some(1.0), + ..EdgeWeights::default() + }, + EdgeWeights { + per_type: per_type(&[("FOLLOWS", "w")]), + default: Some(1.0), + ..EdgeWeights::default() + }, + EdgeWeights { + default: Some(1.0), + ..EdgeWeights::column("cost") + }, + ] { + let err = export(w.clone()).await.unwrap_err(); + assert!( + matches!(err, GraphError::ConfigError { .. }), + "{w:?}: {err}" + ); + } + + // Only LIKES: the default is every weight. + let g = engine + .export_graph( + Some(&["LIKES".to_string()]), + true, + Some(&EdgeWeights { + per_type: per_type(&[("KNOWS", "w")]), + default: Some(3.0), + ..EdgeWeights::default() + }), + ) + .await; + assert!(g.is_err(), "KNOWS isn't exported"); + } + #[tokio::test] async fn bad_weight_columns_are_errors() { let (nodes, edges) = weighted_people(powers_of_two()); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let err = engine - .export_graph(None, true, Some("cost"), CombineEdges::Sum) + .export_graph(None, true, Some(&EdgeWeights::column("cost"))) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -902,7 +1109,7 @@ mod tests { let (nodes, _) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", names)]).await; let err = engine - .export_graph(None, true, Some("w"), CombineEdges::Sum) + .export_graph(None, true, Some(&EdgeWeights::column("w"))) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -969,10 +1176,7 @@ mod tests { ], ) .await; - let g = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); // City 0..2, Person 2..4. assert_eq!( g.label_ranges, @@ -992,16 +1196,13 @@ mod tests { vec![("Person", duplicate), ("KNOWS", edges.clone())], ) .await; - let err = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap_err(); + let err = engine.export_graph(None, true, None).await.unwrap_err(); assert!(matches!(err, GraphError::ExecutionError { .. }), "{err}"); let (nodes, _) = people(); let engine = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let err = engine - .export_graph(Some(&["LIKES".to_string()]), true, None, CombineEdges::Sum) + .export_graph(Some(&["LIKES".to_string()]), true, None) .await .unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); @@ -1024,10 +1225,7 @@ mod tests { ], ) .await; - let err = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap_err(); + let err = engine.export_graph(None, true, None).await.unwrap_err(); assert!(matches!(err, GraphError::ConfigError { .. }), "{err}"); } @@ -1070,14 +1268,8 @@ mod tests { .unwrap(); let arrow = arrow_engine(person_config(), vec![("Person", nodes), ("KNOWS", edges)]).await; let (a, b) = ( - lance - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(), - arrow - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(), + lance.export_graph(None, true, None).await.unwrap(), + arrow.export_graph(None, true, None).await.unwrap(), ); assert_eq!(a.node_keys, b.node_keys); assert_eq!( @@ -1096,7 +1288,7 @@ mod tests { assert_eq!( values( &lance - .export_graph(None, true, None, CombineEdges::Sum) + .export_graph(None, true, None) .await .unwrap() .out_indptr @@ -1104,10 +1296,7 @@ mod tests { 6 ); lance.checkout_latest().await.unwrap(); - let g = lance - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let g = lance.export_graph(None, true, None).await.unwrap(); assert_eq!(values(&g.out_indptr), vec![0, 1, 2, 3, 5, 6, 7]); assert_eq!(values(&g.out_indices)[6], 0); } @@ -1134,10 +1323,7 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); let degree = |g: &GraphExport| -> ArrayRef { let p = g.out_indptr.values(); Arc::new(Int64Array::from_iter_values( @@ -1237,10 +1423,7 @@ mod tests { let engine = CypherEngine::new(person_config(), sources, true) .await .unwrap(); - let g = engine - .export_graph(None, true, None, CombineEdges::Sum) - .await - .unwrap(); + let g = engine.export_graph(None, true, None).await.unwrap(); let ones: ArrayRef = Arc::new(Int64Array::from(vec![1; g.num_nodes as usize])); engine .write_node_column(&g, "x", &ones, false) diff --git a/crates/lance-csr/src/lib.rs b/crates/lance-csr/src/lib.rs index f9e57fcb..b72d2113 100644 --- a/crates/lance-csr/src/lib.rs +++ b/crates/lance-csr/src/lib.rs @@ -86,7 +86,7 @@ pub use engine::{ open_lance_dataset, CypherEngine, DatasetOptimizeStats, EngineSource, PersistCsr, SqlEngine, }; pub use error::{GraphError, Result}; -pub use graph_export::{CombineEdges, GraphExport}; +pub use graph_export::{CombineEdges, EdgeWeights, GraphExport}; pub use lance_vector_search::VectorSearch; pub use mapping::{EdgeTableMapping, GraphMapping, GraphSnapshot, NodeTableMapping, PinnedTable}; pub use namespace::DirNamespace; diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index 5a1455d4..b94e53e3 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -112,8 +112,41 @@ print(w.out_indices.to_pylist()) # [1, 0, 2, 0] print(w.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0] ``` -The weight of `out_indices[i]` is `out_weights[i]`, and the same holds for the in-edges. Every included -relationship type must have the column, and it must be numeric. +The weight of `out_indices[i]` is `out_weights[i]`, and the same holds for the in-edges. The weight column +must be numeric. Only the endpoint and weight columns are read, so other properties of the relationship table +play no part. + +### Several relationship types + +When the export includes several relationship types, each needs a weight. They may store it under different +names, or one of them may have none. A `weight` dict names the column of each type, and `default_weight` gives +the weight of every edge of a type without a column: + +```python +config3 = ( + GraphConfig.builder() + .node_table("Person", "id") + .rel_table("FOLLOWS", "Person", "Person", "src", "dst") + .rel_table("MENTIONS", "Person", "Person", "src", "dst") + .build() +) +mentions = pa.table({"src": [20], "dst": [10], "times": [9]}) +mixed = CypherEngine(config3, {"Person": people, "FOLLOWS": messages, "MENTIONS": mentions}) + +both = mixed.export_graph(weight={"FOLLOWS": "messages", "MENTIONS": "times"}) +print(both.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0, 9.0] +some = mixed.export_graph(weight={"FOLLOWS": "messages"}, default_weight=1.0) +print(some.out_weights.to_pylist()) # [2.0, 1.0, 7.0, 5.0, 1.0] +``` + +A string `weight` with `default_weight` works the same way: types that have the column use it, and the others +get the default. Without `default_weight`, a type with no weight column is an error, since a guessed weight +can change an algorithm's answer without warning. A few mistakes are errors even with a default: a column the +dict names that doesn't exist, a dict entry for a type that isn't exported, and a string column that no type +has. To leave a type out of the export instead, list the others in `rel_types`. + +When the types' weights mean different things, such as messages and mentions, make sure adding them up, or +comparing them, makes sense for the algorithm. A null weight means the weight is unknown, and no number stands in for it safely: 1.0 would make a costly edge look cheap to a shortest-path search. So the export leaves the edge out and counts it in `dropped_edges`, diff --git a/docs/typescript.md b/docs/typescript.md index 616e6718..89ab4dab 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -212,6 +212,7 @@ method, so your editor shows the details on hover. | `engine.optimize_datasets(cleanup_older_than=timedelta(days=1))` | `await engine.optimizeDatasets({ cleanupOlderThanMs: 86_400_000 })` | | `engine.csr_stats()`, `node_index_stats()` (keys such as `delta_edges`, `build_ms`) | `engine.csrStats()`, `nodeIndexStats()` (keys such as `deltaEdges`, `buildMs`) | | `engine.export_graph(rel_types, directed=False, weight="w", combine_edges="min")`, a `GraphExport` of pyarrow arrays | `await engine.exportGraph(relTypes, { directed: false, weight: "w", combineEdges: "min" })`, a `GraphExport` of apache-arrow vectors | +| `engine.export_graph(weight={"ROAD": "km"}, default_weight=1.0)` | `await engine.exportGraph(undefined, { weight: { ROAD: "km" }, defaultWeight: 1 })` | | `engine.dataset_versions()`, `engine.config()` | `engine.datasetVersions()`, `engine.config()` | | `engine.execute_with_vector_rerank(query, search)` | `await engine.executeWithVectorRerank(query, search)` | | `CypherQuery(text).with_config(config).with_parameter(key, value)` | `new CypherQuery(text).withConfig(config).withParameter(key, value)` | diff --git a/nodejs/native.d.ts b/nodejs/native.d.ts index 71bfe728..f03f122f 100644 --- a/nodejs/native.d.ts +++ b/nodejs/native.d.ts @@ -20,7 +20,7 @@ export declare class CypherEngine { deleteStoredCsr(): Promise nodeIndexStats(): Record csrStats(): Record - exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | undefined | null, combineEdges?: string | undefined | null): Promise + exportGraph(relTypes: Array | undefined | null, directed: boolean, weight?: string | Record | undefined | null, combineEdges?: string | undefined | null, defaultWeight?: number | undefined | null): Promise datasetVersions(): Record executeWithVectorRerank(query: string, search: VectorSearchSpec): Promise } diff --git a/nodejs/src/cypher.ts b/nodejs/src/cypher.ts index 0194f2a4..571e7dbb 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -430,23 +430,36 @@ export class CypherEngine { * end of the included types. * @param options.directed - `true` (the default) returns out-edge and in-edge arrays; `false` * returns one set of arrays listing every edge in both directions. - * @param options.weight - A numeric column of the relationship tables to export as float64 - * edge weights, in `outWeights` and `inWeights`; every included type must have it, - * case-insensitive. An edge whose weight is null is left out and counted in `droppedEdges`. - * Left out, no weights are exported, and the export needs no memory for them. + * @param options.weight - The numeric column holding each edge's weight, exported as float64 in + * `outWeights` and `inWeights`. A string names one column for every included type; an object + * maps relationship types to their own columns, so types can store weights under different + * names. Names are case-insensitive. A type the object leaves out, or that lacks the shared + * column, needs `defaultWeight`. An edge whose weight is null is left out and counted in + * `droppedEdges`. Left out, no weights are exported, and the export needs no memory for them. * @param options.combineEdges - How an edge listed more than once combines its weights: `"sum"` * (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for * distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge * and combine the same way. Ignored without `weight`. + * @param options.defaultWeight - The weight of every edge of an included type that has no + * weight column: one the `weight` object leaves out, or one without the shared `weight` + * column (at least one type must have it). A column named in the object must exist even + * with a default. Needs `weight`. * @throws {@link LanceCsrError} `InvalidArgument` if a relationship type or label isn't in * the config, has no dataset, or a key or endpoint column is missing or isn't an integer - * type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't - * one of the three rules, or there's nothing to export; `Runtime` if a node key appears + * type up to `int64`, a weight column is missing or isn't numeric, an included type has no + * weight column and there's no `defaultWeight`, the `weight` object names a type that isn't + * included, `defaultWeight` is given without `weight`, `combineEdges` isn't one of the three + * rules, or there's nothing to export; `Runtime` if a node key appears * twice within a label, or a scan fails. */ async exportGraph( relTypes?: string[], - options: { directed?: boolean; weight?: string; combineEdges?: "sum" | "min" | "max" } = {}, + options: { + directed?: boolean; + weight?: string | Record; + combineEdges?: "sum" | "min" | "max"; + defaultWeight?: number; + } = {}, ): Promise { const g = await call(() => this.#inner.exportGraph( @@ -454,6 +467,7 @@ export class CypherEngine { options.directed ?? true, options.weight, options.combineEdges, + options.defaultWeight, ), ); return { diff --git a/nodejs/test/graph-export.test.ts b/nodejs/test/graph-export.test.ts index ac31fd20..f21c0750 100644 --- a/nodejs/test/graph-export.test.ts +++ b/nodejs/test/graph-export.test.ts @@ -75,6 +75,37 @@ test("edge weights only when asked for", async () => { ); }); +test("weight columns per type and a default weight", async () => { + const mixedConfig = GraphConfig.builder() + .nodeTable("Person", "id") + .relTable("KNOWS", "Person", "Person", "src", "dst") + .relTable("LIKES", "Person", "Person", "src", "dst") + .build(); + const engine = await CypherEngine.create(mixedConfig, { + Person: tableFromArrays({ id: BigInt64Array.from([1n, 2n, 3n]) }), + KNOWS: tableFromArrays({ + src: BigInt64Array.from([1n, 2n]), + dst: BigInt64Array.from([2n, 3n]), + w: Float64Array.from([5, 7]), + }), + LIKES: tableFromArrays({ + src: BigInt64Array.from([1n, 3n]), + dst: BigInt64Array.from([2n, 1n]), + since: Float64Array.from([2020, 2021]), + }), + }); + const g = await engine.exportGraph(undefined, { weight: { KNOWS: "w" }, defaultWeight: 2 }); + assert.deepEqual(Array.from(g.outWeights!.toArray()), [7, 7, 2]); + const both = await engine.exportGraph(undefined, { weight: { KNOWS: "w", LIKES: "since" } }); + assert.deepEqual(Array.from(both.outWeights!.toArray()), [2025, 7, 2021]); + for (const options of [{ weight: "w" }, { defaultWeight: 1 }]) { + await assert.rejects( + engine.exportGraph(undefined, options), + (err) => err instanceof LanceCsrError && err.code === "InvalidArgument", + ); + } +}); + test("unknown relationship type", async () => { const engine = await CypherEngine.create(config, datasets); await assert.rejects( diff --git a/nodejs/typedoc/api.md b/nodejs/typedoc/api.md index bd9d3cd9..c8fc99d4 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -278,10 +278,11 @@ without `useCsr`. Lance datasets are scanned for just those columns. See | Parameter | Type | Description | | ------ | ------ | ------ | | `relTypes?` | `string`[] | Relationship types to include, case-insensitive. Left out, every type whose dataset has integer endpoint columns. The nodes are those of the labels at either end of the included types. | -| `options?` | \{ `combineEdges?`: `"sum"` \| `"min"` \| `"max"`; `directed?`: `boolean`; `weight?`: `string`; \} | - | +| `options?` | \{ `combineEdges?`: `"sum"` \| `"min"` \| `"max"`; `defaultWeight?`: `number`; `directed?`: `boolean`; `weight?`: `string` \| `Record`\<`string`, `string`\>; \} | - | | `options.combineEdges?` | `"sum"` \| `"min"` \| `"max"` | How an edge listed more than once combines its weights: `"sum"` (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge and combine the same way. Ignored without `weight`. | +| `options.defaultWeight?` | `number` | The weight of every edge of an included type that has no weight column: one the `weight` object leaves out, or one without the shared `weight` column (at least one type must have it). A column named in the object must exist even with a default. Needs `weight`. | | `options.directed?` | `boolean` | `true` (the default) returns out-edge and in-edge arrays; `false` returns one set of arrays listing every edge in both directions. | -| `options.weight?` | `string` | A numeric column of the relationship tables to export as float64 edge weights, in `outWeights` and `inWeights`; every included type must have it, case-insensitive. An edge whose weight is null is left out and counted in `droppedEdges`. Left out, no weights are exported, and the export needs no memory for them. | +| `options.weight?` | `string` \| `Record`\<`string`, `string`\> | The numeric column holding each edge's weight, exported as float64 in `outWeights` and `inWeights`. A string names one column for every included type; an object maps relationship types to their own columns, so types can store weights under different names. Names are case-insensitive. A type the object leaves out, or that lacks the shared column, needs `defaultWeight`. An edge whose weight is null is left out and counted in `droppedEdges`. Left out, no weights are exported, and the export needs no memory for them. | ###### Returns @@ -291,8 +292,10 @@ without `useCsr`. Lance datasets are scanned for just those columns. See [LanceCsrError](#lancecsrerror) `InvalidArgument` if a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer - type up to `int64`, the weight column is missing or isn't numeric, `combineEdges` isn't - one of the three rules, or there's nothing to export; `Runtime` if a node key appears + type up to `int64`, a weight column is missing or isn't numeric, an included type has no + weight column and there's no `defaultWeight`, the `weight` object names a type that isn't + included, `defaultWeight` is given without `weight`, `combineEdges` isn't one of the three + rules, or there's nothing to export; `Runtime` if a node key appears twice within a label, or a scan fails. diff --git a/python/python/lance_csr/_internal/graph.pyi b/python/python/lance_csr/_internal/graph.pyi index c49e45d7..e5db1c0b 100644 --- a/python/python/lance_csr/_internal/graph.pyi +++ b/python/python/lance_csr/_internal/graph.pyi @@ -165,8 +165,9 @@ class CypherEngine: rel_types: list[str] | None = None, *, directed: bool = True, - weight: str | None = None, + weight: str | dict[str, str] | None = None, combine_edges: Literal["sum", "min", "max"] = "sum", + default_weight: float | None = None, ) -> GraphExport: ... def write_node_column( self, diff --git a/python/python/lance_csr/cypher.py b/python/python/lance_csr/cypher.py index 9e5629ff..39aec2cd 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -469,8 +469,9 @@ def export_graph( rel_types: list[str] | None = None, *, directed: bool = True, - weight: str | None = None, + weight: str | dict[str, str] | None = None, combine_edges: Literal["sum", "min", "max"] = "sum", + default_weight: float | None = None, ) -> GraphExport: """The graph as dense CSR arrays, for graph-algorithm libraries. @@ -488,18 +489,26 @@ def export_graph( directed : bool Keyword-only. `True` returns out-edge and in-edge arrays; `False` returns one set of arrays listing every edge in both directions. - weight : str or None - Keyword-only. A numeric column of the relationship tables to export as - `float64` edge weights, in `out_weights` and `in_weights`; every included - type must have it, case-insensitive. An edge whose weight is null is left - out and counted in `dropped_edges`. `None` (the default) exports no - weights, and the export then needs no memory for them. + weight : str, dict[str, str] or None + Keyword-only. The numeric column holding each edge's weight, exported as + `float64` in `out_weights` and `in_weights`. A string names one column for + every included type; a dict maps relationship types to their own columns, + so types can store weights under different names. Names are + case-insensitive. A type the dict leaves out, or that lacks the shared + column, needs `default_weight`. An edge whose weight is null is left out + and counted in `dropped_edges`. `None` (the default) exports no weights, + and the export then needs no memory for them. combine_edges : {"sum", "min", "max"} Keyword-only. How an edge listed more than once combines its weights: `"sum"` (the default) adds them, as for counts or amounts; `"min"` keeps the smallest, as for distances; `"max"` the largest. In an undirected export, `a -> b` and `b -> a` are one edge and combine the same way. Ignored without `weight`. + default_weight : float or None + Keyword-only. The weight of every edge of an included type that has no + weight column: one the `weight` dict leaves out, or one without the shared + `weight` column (at least one type must have it). A column named in the + dict must exist even with a default. Needs `weight`. Returns ------- @@ -511,8 +520,11 @@ def export_graph( ValueError If a relationship type or label isn't in the config, has no dataset, or a key or endpoint column is missing or isn't an integer type up to `int64` - (`uint64` isn't supported), the weight column is missing or isn't numeric, - `combine_edges` isn't one of the three rules, or there's nothing to export. + (`uint64` isn't supported), a weight column is missing or isn't numeric, an + included type has no weight column and there's no `default_weight`, the + `weight` dict names a type that isn't included, `default_weight` is given + without `weight`, `combine_edges` isn't one of the three rules, or there's + nothing to export. RuntimeError If a node key appears twice within a label, or a scan fails. @@ -540,6 +552,7 @@ def export_graph( directed=directed, weight=weight, combine_edges=combine_edges, + default_weight=default_weight, ) ) diff --git a/python/python/tests/test_graph_export.py b/python/python/tests/test_graph_export.py index 212cb642..fd33553b 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -94,6 +94,51 @@ def test_weights(): CypherEngine(CONFIG, {"Person": NODES, "KNOWS": named}).export_graph(weight="w") +def test_weights_per_type_and_default(): + config = ( + GraphConfig.builder() + .node_table("Person", "id") + .rel_table("KNOWS", "Person", "Person", "src", "dst") + .rel_table("LIKES", "Person", "Person", "src", "dst") + .build() + ) + # KNOWS has a weight column; LIKES has only an unrelated `since`. + engine = CypherEngine( + config, + { + "Person": pa.table({"id": [1, 2, 3]}), + "KNOWS": pa.table({"src": [1, 2], "dst": [2, 3], "w": [5.0, 7.0]}), + "LIKES": pa.table({"src": [1, 3], "dst": [2, 1], "since": [2020, 2021]}), + }, + ) + + def out_weights(**kwargs) -> list[float]: + g = engine.export_graph(**kwargs) + assert g.out_weights is not None + return g.out_weights.to_pylist() + + # Out-edges: 1->2 (KNOWS 5 and LIKES), 2->3 (KNOWS 7), 3->1 (LIKES). + assert out_weights(weight="w", default_weight=1.0) == [6, 7, 1] + assert out_weights(weight={"KNOWS": "w", "likes": "since"}) == [2025, 7, 2021] + assert out_weights(weight={"KNOWS": "w"}, default_weight=2.0) == [7, 7, 2] + assert engine.export_graph(["LIKES"], weight={"LIKES": "since"}).num_nodes == 3 + + with pytest.raises(ValueError, match="'LIKES'"): + engine.export_graph(weight="w") + with pytest.raises(ValueError, match="'LIKES'"): + engine.export_graph(weight={"KNOWS": "w"}) + with pytest.raises(ValueError, match="not found in 'LIKES'"): + engine.export_graph(weight={"LIKES": "w"}, default_weight=1.0) + with pytest.raises(ValueError, match="FOLLOWS"): + engine.export_graph(weight={"FOLLOWS": "w"}, default_weight=1.0) + with pytest.raises(ValueError, match="any exported"): + engine.export_graph(weight="cost", default_weight=1.0) + with pytest.raises(ValueError, match="default_weight needs weight"): + engine.export_graph(default_weight=1.0) + with pytest.raises(TypeError, match="weight"): + engine.export_graph(weight=3) # pyright: ignore[reportArgumentType] + + def test_labels_with_colliding_keys(): config = ( GraphConfig.builder() From b5a2504dfd74d6928e0f7bce80e6d73e07c94daa Mon Sep 17 00:00:00 2001 From: prrao87 Date: Tue, 24 Nov 2026 19:44:46 -0500 Subject: [PATCH 8/8] docs: list export_graph's parameters where the page introduces it The graph algorithms page explained each parameter in the section that uses it, so a reader had to know where to look. A table under the introduction now lists every parameter, its default and what it controls, linking to the section that explains it. Table cells broke inline code between any two letters, which split parameter names such as combine_edges across lines. Code in a table's first column now breaks only at spaces; no table on the site overflows at desktop width with the change. --- docs/graph-algorithms.md | 13 +++++++++++-- docs/stylesheets/extra.css | 6 ++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/graph-algorithms.md b/docs/graph-algorithms.md index b94e53e3..9875e3b1 100644 --- a/docs/graph-algorithms.md +++ b/docs/graph-algorithms.md @@ -7,8 +7,17 @@ whole graph and compute one value for every node, a score or a group. Libraries take the graph in the same form: compressed sparse rows (CSR) over dense node ids. [`CypherEngine.export_graph`][lance_csr.CypherEngine.export_graph] builds that form from your node and -relationship tables. It reads only the key and endpoint columns, from the same dataset versions your queries -see, and returns Arrow arrays that these libraries take without copying. +relationship tables. It reads only the key and endpoint columns, plus a weight column when you ask for one, +from the same dataset versions your queries see, and returns Arrow arrays that these libraries take without +copying. Every parameter is optional, and all but `rel_types` are keyword-only: + +| Parameter | Default | What it controls | +| --- | --- | --- | +| `rel_types` | `None` | The relationship types to include, or every type with integer endpoints; the nodes are those of the labels at either end. See [Directed and undirected graphs](#directed-and-undirected-graphs). | +| `directed` | `True` | `True` returns out-edge and in-edge arrays; `False` returns one set listing every edge both ways. See [Directed and undirected graphs](#directed-and-undirected-graphs). | +| `weight` | `None` | A column name, or a dict of relationship type to column, exported as `float64` edge weights; `None` exports none. See [Weighted graphs](#weighted-graphs). | +| `combine_edges` | `"sum"` | How an edge listed more than once combines its weights: `"sum"`, `"min"` or `"max"`. See [Weighted graphs](#weighted-graphs). | +| `default_weight` | `None` | The weight of every edge of a type with no weight column; `None` makes such a type an error. See [Several relationship types](#several-relationship-types). | ## What the export contains diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css index 8fe04bb1..2b2ee1a9 100644 --- a/docs/stylesheets/extra.css +++ b/docs/stylesheets/extra.css @@ -43,3 +43,9 @@ height: auto; margin: 0.5rem 0 1rem; } + +/* Names in a table's first column (parameters, fields) break only at spaces, not mid-word. */ +.md-typeset td:first-child code { + overflow-wrap: normal; + word-break: normal; +}