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..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}; +use napi::bindgen_prelude::{BigInt64Array, BigUint64Array, Buffer, Either, 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,43 @@ impl CypherEngine { &self, rel_types: Option>, directed: bool, + weight: Option>>, + combine_edges: Option, + default_weight: Option, ) -> napi::Result { + let combine = combine_edges + .as_deref() + .map(str::parse::) + .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).await }) - .await?; + let g = blocking(async move { + inner + .export_graph(rel_types.as_deref(), directed, weights.as_ref()) + .await + }) + .await?; Ok(GraphExport { num_nodes: g.num_nodes as i64, directed: g.directed, @@ -281,6 +316,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..d7a3434a 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,58 @@ impl CypherEngine { Ok(stats.into_any().unbind()) } - #[pyo3(signature = (rel_types=None, *, directed=true))] + #[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>, + 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), + 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 80740bad..bc8b07de 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. /// + /// `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, 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, 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, + weights: Option<&crate::graph_export::EdgeWeights>, ) -> 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, + weights, + ) + .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..01619c37 100644 --- a/crates/lance-csr/src/graph_export.rs +++ b/crates/lance-csr/src/graph_export.rs @@ -11,18 +11,25 @@ //! 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); -//! 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. +//! [`EdgeWeights`] names a column per relationship type, or one shared column, and a +//! default weight for types without one. 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,16 +59,91 @@ pub struct GraphExport { pub in_indptr: Option, /// In-edge sources, sorted within each row; `None` for undirected graphs. pub in_indices: Option, - /// Edges dropped because an endpoint key isn't in its node table. + /// 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, or, in a weighted + /// export, because the weight is null. 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'" + ))), + } + } +} + +/// 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, src_label: usize, dst_label: usize, } @@ -69,12 +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. +/// 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, + weights: Option<&EdgeWeights>, ) -> Result { let find_source = |name: &str| { sources @@ -164,16 +247,37 @@ pub(crate) async fn export_graph( } Ok(field.name().clone()) }; + let weight = weights.map(|w| rel_weight(w, rel, &schema)).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"), }); } + 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()); @@ -223,49 +327,88 @@ 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 = 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. + let mut out: Vec = Vec::with_capacity(if directed { keys_cap } else { 2 * keys_cap }); + let mut out_w: Vec<(u64, f64)> = + Vec::with_capacity(if directed { pairs_cap } else { 2 * 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()]; + 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 pairs: Vec> = (0..batch.num_rows()) + let w = match weight_column { + Some(name) => Some(float64(batch.column(2), name, &rel.name)?), + None => None, + }; + 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| { + // 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 { - Some((a, b)) => { - out.push(a * n + b); - // Undirected: the reverse goes into the same CSR. - inc.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)); + } + } else { + out.push(a * n + b); + if reverse { + out.push(b * n + a); } - None => dropped += 1, } } } } - let (out, inc) = if directed { - (out, Some(inc)) + 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 { - out.append(&mut inc); - drop(inc); // its allocation would otherwise stay alive through the sort - (out, None) + drop(out_w); + let (p, i) = csr(n, out); + (p, i, None) }; - 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) = 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, @@ -276,21 +419,29 @@ pub(crate) async fn export_graph( out_indices, in_indptr, in_indices, + out_weights, + in_weights, dropped_edges: dropped, }) } -/// 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) @@ -298,6 +449,69 @@ 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 `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 = combine.apply(kept.1, later.1); + } + same + }); + 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 (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(); + ( + UInt64Array::from(indptr), + UInt64Array::from(indices), + Float64Array::from(weights), + ) +} + +/// 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 @@ -415,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() @@ -432,6 +686,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 +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).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 +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) + .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 +826,327 @@ 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(&EdgeWeights::column("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(&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) + ); + 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 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(&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(&EdgeWeights { + combine, + ..EdgeWeights::column("w") + }), + ) + .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 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(&EdgeWeights::column("w"))) + .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).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(&EdgeWeights::column("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(&EdgeWeights::column("w"))) + .await + .unwrap_err(); + 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() @@ -592,7 +1176,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 +1196,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 +1225,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 +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).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 +1286,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 +1323,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 +1423,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/crates/lance-csr/src/lib.rs b/crates/lance-csr/src/lib.rs index e84bafd2..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::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 8868751f..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 @@ -50,7 +59,8 @@ 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 | -| `dropped_edges` | Edges whose endpoint key isn't in its node table | +| `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, 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 @@ -94,6 +104,85 @@ 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. 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`, +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 +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`. + ## Running an algorithm with icebug [icebug](https://github.com/Ladybug-Memory/icebug) is a fork of [NetworKit](https://networkit.github.io/) whose @@ -124,6 +213,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 +278,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. + 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. -- 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/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; +} diff --git a/docs/typescript.md b/docs/typescript.md index 3033893d..89ab4dab 100644 --- a/docs/typescript.md +++ b/docs/typescript.md @@ -211,7 +211,8 @@ 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", 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 6ed8bbf4..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): 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 } @@ -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..571e7dbb 100644 --- a/nodejs/src/cypher.ts +++ b/nodejs/src/cypher.ts @@ -430,16 +430,46 @@ 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 - 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`, or there's nothing to export; `Runtime` if a node key appears twice - * within a label, or a scan fails. + * 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 } = {}, + options: { + directed?: boolean; + weight?: string | Record; + combineEdges?: "sum" | "min" | "max"; + defaultWeight?: number; + } = {}, ): 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, + options.combineEdges, + options.defaultWeight, + ), + ); return { numNodes: g.numNodes, directed: g.directed, @@ -451,6 +481,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..200cf8a0 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -5,6 +5,7 @@ */ import { + type Float64, type Int64, RecordBatch, Table, @@ -130,8 +131,19 @@ export interface GraphExport { */ inIndices: 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. + * 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). + */ + 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, 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/test/graph-export.test.ts b/nodejs/test/graph-export.test.ts index 83238d58..f21c0750 100644 --- a/nodejs/test/graph-export.test.ts +++ b/nodejs/test/graph-export.test.ts @@ -45,6 +45,67 @@ 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]); + 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", + ); +}); + +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 214ea4dd..c8fc99d4 100644 --- a/nodejs/typedoc/api.md +++ b/nodejs/typedoc/api.md @@ -278,8 +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?` | \{ `directed?`: `boolean`; \} | - | +| `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` \| `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 @@ -289,8 +292,11 @@ 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`, 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. @@ -1635,14 +1641,16 @@ 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. | | `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, 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 519541a6..e5db1c0b 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,13 @@ 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 | dict[str, str] | None = None, + combine_edges: Literal["sum", "min", "max"] = "sum", + default_weight: float | None = None, ) -> GraphExport: ... def write_node_column( self, @@ -241,6 +248,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..39aec2cd 100644 --- a/python/python/lance_csr/cypher.py +++ b/python/python/lance_csr/cypher.py @@ -465,7 +465,13 @@ 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 | 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. @@ -483,6 +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, 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 ------- @@ -494,7 +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), 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. @@ -517,7 +547,13 @@ 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, + combine_edges=combine_edges, + default_weight=default_weight, + ) ) def write_node_column( diff --git a/python/python/lance_csr/export.py b/python/python/lance_csr/export.py index 5bdcf9bb..e37127e9 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,11 +96,31 @@ 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, 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 + + @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. + """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 39600510..fd33553b 100644 --- a/python/python/tests/test_graph_export.py +++ b/python/python/tests/test_graph_export.py @@ -49,6 +49,96 @@ 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] + + # 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] + + # 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"): + 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") + + +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() @@ -126,6 +216,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()