Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions _typos.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
43 changes: 40 additions & 3 deletions crates/lance-csr-node/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -71,6 +71,8 @@ pub struct GraphExport {
pub out_indices: BigUint64Array,
pub in_indptr: Option<BigUint64Array>,
pub in_indices: Option<BigUint64Array>,
pub out_weights: Option<Float64Array>,
pub in_weights: Option<Float64Array>,
pub dropped_edges: i64,
}

Expand Down Expand Up @@ -264,10 +266,43 @@ impl CypherEngine {
&self,
rel_types: Option<Vec<String>>,
directed: bool,
weight: Option<Either<String, HashMap<String, String>>>,
combine_edges: Option<String>,
default_weight: Option<f64>,
) -> napi::Result<GraphExport> {
let combine = combine_edges
.as_deref()
.map(str::parse::<lance_csr::CombineEdges>)
.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,
Expand All @@ -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,
})
}
Expand Down
63 changes: 61 additions & 2 deletions crates/lance-csr-python/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,24 @@ impl GraphExport {
.transpose()
}

#[getter]
fn out_weights<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
self.inner
.out_weights
.as_ref()
.map(|a| to_pyarrow_array(py, a))
.transpose()
}

#[getter]
fn in_weights<'py>(&self, py: Python<'py>) -> PyResult<Option<Bound<'py, PyAny>>> {
self.inner
.in_weights
.as_ref()
.map(|a| to_pyarrow_array(py, a))
.transpose()
}

#[getter]
fn dropped_edges(&self) -> u64 {
self.inner.dropped_edges
Expand Down Expand Up @@ -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<Vec<String>>,
directed: bool,
weight: Option<Bound<'_, PyAny>>,
combine_edges: &str,
default_weight: Option<f64>,
) -> PyResult<GraphExport> {
let combine = combine_edges
.parse::<lance_csr::CombineEdges>()
.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::<String>() {
(Some(name), Vec::new())
} else if let Ok(dict) = w.downcast::<PyDict>() {
let pairs = dict
.iter()
.map(|(k, v)| Ok((k.extract::<String>()?, v.extract::<String>()?)))
.collect::<PyResult<Vec<_>>>()
.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 })
Expand Down
20 changes: 16 additions & 4 deletions crates/lance-csr/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<crate::graph_export::GraphExport> {
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
Expand Down
Loading
Loading