use super::Interrupt;
use crate::datatypes::values::Value;
use crate::graph::schema::{DirGraph, InternedKey};
use crate::graph::storage::GraphRead;
use petgraph::algo::kosaraju_scc;
use petgraph::graph::NodeIndex;
use std::collections::{HashMap, HashSet};
pub use super::centrality::*;
pub use super::community::*;
use super::community::{scoped_universe, DedupNeighborSource};
pub fn algorithm_timeout_err() -> String {
"CALL procedure timed out. Pass timeout_ms=N to cypher() to extend, \
or timeout_ms=0 to disable the deadline. Scope to a subgraph with \
{node_type: '...', where: '...'} to run on fewer nodes."
.to_string()
}
pub(crate) fn intern_connection_types(
connection_types: Option<&[String]>,
) -> Option<Vec<InternedKey>> {
connection_types.map(|types| types.iter().map(|t| InternedKey::from_str(t)).collect())
}
pub(crate) type NodeScope = std::collections::HashSet<NodeIndex>;
pub(crate) fn scoped_node_set(graph: &DirGraph, scope: Option<&NodeScope>) -> Vec<NodeIndex> {
let g = &graph.graph;
match scope {
Some(s) => g.node_indices().filter(|n| s.contains(n)).collect(),
None => g.node_indices().collect(),
}
}
#[inline]
pub(crate) fn edge_in_scope(scope: Option<&NodeScope>, src: NodeIndex, tgt: NodeIndex) -> bool {
match scope {
Some(s) => s.contains(&src) && s.contains(&tgt),
None => true,
}
}
fn filtered_neighbors_undirected(
graph: &DirGraph,
node: NodeIndex,
connection_types: Option<&[InternedKey]>,
) -> Vec<NodeIndex> {
use petgraph::Direction;
let g = &graph.graph;
let mut neighbors: Vec<NodeIndex> = match connection_types {
None => g.neighbors_undirected(node).collect(),
Some(types) => {
let mut n = Vec::new();
for edge in g.edges_directed(node, Direction::Outgoing) {
if types.iter().any(|t| *t == edge.connection_type()) {
n.push(edge.target());
}
}
for edge in g.edges_directed(node, Direction::Incoming) {
if types.iter().any(|t| *t == edge.connection_type()) {
n.push(edge.source());
}
}
n
}
};
if neighbors.len() > 1 {
neighbors.sort_unstable();
neighbors.dedup();
}
neighbors
}
fn filtered_neighbors_outgoing(
graph: &DirGraph,
node: NodeIndex,
connection_types: Option<&[InternedKey]>,
) -> Vec<NodeIndex> {
use petgraph::Direction;
let g = &graph.graph;
match connection_types {
None => g.neighbors_directed(node, Direction::Outgoing).collect(),
Some(types) => g
.edges_directed(node, Direction::Outgoing)
.filter(|e| types.iter().any(|t| *t == e.connection_type()))
.map(|e| e.target())
.collect(),
}
}
fn node_passes_via_filter(
graph: &DirGraph,
node: NodeIndex,
via_types: &Option<HashSet<&str>>,
) -> bool {
match via_types {
None => true,
Some(types) => {
if let Some(node_data) = graph.graph.node_weight(node) {
types.contains(node_data.node_type_str(&graph.interner))
} else {
false
}
}
}
}
#[derive(Debug, Clone)]
pub struct PathResult {
pub path: Vec<NodeIndex>,
pub cost: usize,
}
#[derive(Debug, Clone)]
pub struct PathNodeInfo {
pub node_type: String,
pub title: String,
pub id: Value,
}
pub fn shortest_path(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[String]>,
via_types: Option<&[String]>,
deadline: Interrupt,
) -> Option<PathResult> {
let _arena_guard = graph.graph.begin_query();
let via_set: Option<HashSet<&str>> =
via_types.map(|vt| vt.iter().map(|s| s.as_str()).collect());
let interned = intern_connection_types(connection_types);
let path = reconstruct_path_bfs(
graph,
source,
target,
interned.as_deref(),
&via_set,
deadline,
)?;
let cost = path.len().saturating_sub(1);
Some(PathResult { path, cost })
}
pub fn all_shortest_paths(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[String]>,
deadline: Interrupt,
max_paths: usize,
) -> Vec<PathResult> {
let _arena_guard = graph.graph.begin_query();
all_shortest_paths_impl(
graph,
source,
target,
connection_types,
deadline,
max_paths,
false,
)
}
pub fn all_shortest_paths_directed(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[String]>,
deadline: Interrupt,
max_paths: usize,
) -> Vec<PathResult> {
let _arena_guard = graph.graph.begin_query();
all_shortest_paths_impl(
graph,
source,
target,
connection_types,
deadline,
max_paths,
true,
)
}
fn all_shortest_paths_impl(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[String]>,
deadline: Interrupt,
max_paths: usize,
directed: bool,
) -> Vec<PathResult> {
use std::collections::HashMap;
if source == target {
return vec![PathResult {
path: vec![source],
cost: 0,
}];
}
let interned = intern_connection_types(connection_types);
let interned_ref = interned.as_deref();
let mut dist: HashMap<NodeIndex, usize> = HashMap::new();
let mut preds: HashMap<NodeIndex, Vec<NodeIndex>> = HashMap::new();
dist.insert(source, 0);
let mut frontier = vec![source];
let mut level = 0usize;
let mut found = false;
let mut visit_count = 0u32;
while !frontier.is_empty() && !found {
level += 1;
let mut next: Vec<NodeIndex> = Vec::new();
for &u in &frontier {
visit_count += 1;
if visit_count.is_multiple_of(1000) && deadline.exceeded() {
return Vec::new();
}
let neighbors = if directed {
filtered_neighbors_outgoing(graph, u, interned_ref)
} else {
filtered_neighbors_undirected(graph, u, interned_ref)
};
for v in neighbors {
match dist.get(&v).copied() {
None => {
dist.insert(v, level);
preds.entry(v).or_default().push(u);
if v == target {
found = true;
}
next.push(v);
}
Some(dv) if dv == level => {
preds.entry(v).or_default().push(u);
}
_ => {}
}
}
}
frontier = next;
}
let Some(&d) = dist.get(&target) else {
return Vec::new();
};
let mut results: Vec<PathResult> = Vec::new();
let mut stack: Vec<Vec<NodeIndex>> = vec![vec![target]];
while let Some(path_rev) = stack.pop() {
if results.len() >= max_paths {
break;
}
let head = *path_rev.last().expect("path_rev is never empty");
if head == source {
let mut p = path_rev.clone();
p.reverse();
results.push(PathResult { path: p, cost: d });
continue;
}
if let Some(ps) = preds.get(&head) {
for &pnode in ps {
let mut np = path_rev.clone();
np.push(pnode);
stack.push(np);
}
}
}
results
}
pub fn shortest_path_cost(graph: &DirGraph, source: NodeIndex, target: NodeIndex) -> Option<usize> {
let _arena_guard = graph.graph.begin_query();
if source == target {
return Some(0);
}
let node_bound = graph.graph.node_bound();
let mut visited: Vec<bool> = vec![false; node_bound];
let target_idx = target.index();
let mut current_level: Vec<usize> = vec![source.index()];
let mut next_level: Vec<usize> = Vec::new();
visited[source.index()] = true;
let mut depth: usize = 0;
while !current_level.is_empty() {
depth += 1;
next_level.clear();
for ¤t_idx in ¤t_level {
let current = NodeIndex::new(current_idx);
for neighbor in {
let g = &graph.graph;
g.neighbors_undirected(current)
} {
let neighbor_idx = neighbor.index();
if !visited[neighbor_idx] {
if neighbor_idx == target_idx {
return Some(depth);
}
visited[neighbor_idx] = true;
next_level.push(neighbor_idx);
}
}
}
std::mem::swap(&mut current_level, &mut next_level);
}
None
}
pub fn shortest_path_cost_batch(
graph: &DirGraph,
pairs: &[(NodeIndex, NodeIndex)],
) -> Vec<Option<usize>> {
let _arena_guard = graph.graph.begin_query();
let node_bound = graph.graph.node_bound();
let nodes: Vec<NodeIndex> = {
let g = &graph.graph;
g.node_indices().collect()
};
let n = nodes.len();
let mut node_to_idx = vec![usize::MAX; node_bound];
for (i, &node) in nodes.iter().enumerate() {
node_to_idx[node.index()] = i;
}
let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
for edge in {
let g = &graph.graph;
g.edge_references()
} {
let src_i = node_to_idx[edge.source().index()];
let tgt_i = node_to_idx[edge.target().index()];
if src_i != usize::MAX && tgt_i != usize::MAX {
adj[src_i].push(tgt_i);
adj[tgt_i].push(src_i);
}
}
for neighbors in &mut adj {
neighbors.sort_unstable();
neighbors.dedup();
}
let mut visited: Vec<bool> = vec![false; n];
let mut current_level: Vec<usize> = Vec::new();
let mut next_level: Vec<usize> = Vec::new();
let mut results = Vec::with_capacity(pairs.len());
for &(source, target) in pairs {
if source == target {
results.push(Some(0));
continue;
}
let src_i = node_to_idx[source.index()];
let tgt_i = node_to_idx[target.index()];
if src_i == usize::MAX || tgt_i == usize::MAX {
results.push(None);
continue;
}
let mut touched: Vec<usize> = Vec::new();
current_level.clear();
current_level.push(src_i);
visited[src_i] = true;
touched.push(src_i);
let mut depth: usize = 0;
let mut found = false;
'bfs: while !current_level.is_empty() {
depth += 1;
next_level.clear();
for ¤t_idx in ¤t_level {
for &neighbor_idx in &adj[current_idx] {
if !visited[neighbor_idx] {
if neighbor_idx == tgt_i {
found = true;
break 'bfs;
}
visited[neighbor_idx] = true;
touched.push(neighbor_idx);
next_level.push(neighbor_idx);
}
}
}
std::mem::swap(&mut current_level, &mut next_level);
}
results.push(if found { Some(depth) } else { None });
for &idx in &touched {
visited[idx] = false;
}
}
results
}
fn reconstruct_path_bfs(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[InternedKey]>,
via_types: &Option<HashSet<&str>>,
deadline: Interrupt,
) -> Option<Vec<NodeIndex>> {
use std::collections::{HashMap, VecDeque};
if source == target {
return Some(vec![source]);
}
let mut parent: HashMap<usize, u32> = HashMap::with_capacity(64);
let mut queue: VecDeque<usize> = VecDeque::with_capacity(64);
let source_idx = source.index();
let target_idx = target.index();
parent.insert(source_idx, source_idx as u32);
queue.push_back(source_idx);
let mut visit_count = 0u32;
while let Some(current_idx) = queue.pop_front() {
visit_count += 1;
if visit_count.is_multiple_of(1000) && deadline.exceeded() {
{
return None;
}
}
let current = NodeIndex::new(current_idx);
let neighbors = filtered_neighbors_undirected(graph, current, connection_types);
for neighbor in neighbors {
let neighbor_idx = neighbor.index();
if parent.contains_key(&neighbor_idx) {
continue;
}
if neighbor_idx != target_idx && !node_passes_via_filter(graph, neighbor, via_types) {
continue;
}
parent.insert(neighbor_idx, current_idx as u32);
if neighbor_idx == target_idx {
let mut path = Vec::with_capacity(16);
let mut node_idx = target_idx;
while node_idx != source_idx {
path.push(NodeIndex::new(node_idx));
node_idx = parent[&node_idx] as usize;
}
path.push(source);
path.reverse();
return Some(path);
}
queue.push_back(neighbor_idx);
}
}
None }
pub fn shortest_path_directed(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
connection_types: Option<&[String]>,
via_types: Option<&[String]>,
deadline: Interrupt,
) -> Option<PathResult> {
let _arena_guard = graph.graph.begin_query();
use std::collections::VecDeque;
if source == target {
return Some(PathResult {
path: vec![source],
cost: 0,
});
}
let via_set: Option<HashSet<&str>> =
via_types.map(|vt| vt.iter().map(|s| s.as_str()).collect());
let interned = intern_connection_types(connection_types);
let node_bound = graph.graph.node_bound();
let mut visited: Vec<bool> = vec![false; node_bound];
let mut parent: Vec<u32> = vec![u32::MAX; node_bound];
let mut queue = VecDeque::with_capacity(node_bound / 4);
let source_idx = source.index();
let target_idx = target.index();
queue.push_back(source_idx);
visited[source_idx] = true;
let mut visit_count = 0u32;
while let Some(current_idx) = queue.pop_front() {
visit_count += 1;
if visit_count.is_multiple_of(1000) && deadline.exceeded() {
{
return None;
}
}
let current = NodeIndex::new(current_idx);
let neighbors = filtered_neighbors_outgoing(graph, current, interned.as_deref());
for neighbor in neighbors {
let neighbor_idx = neighbor.index();
if !visited[neighbor_idx] {
if neighbor_idx != target_idx && !node_passes_via_filter(graph, neighbor, &via_set)
{
continue;
}
visited[neighbor_idx] = true;
parent[neighbor_idx] = current_idx as u32;
queue.push_back(neighbor_idx);
if neighbor_idx == target_idx {
let mut path = Vec::with_capacity(16);
let mut node_idx = target_idx;
while node_idx != source_idx {
path.push(NodeIndex::new(node_idx));
node_idx = parent[node_idx] as usize;
}
path.push(source);
path.reverse();
let cost = path.len().saturating_sub(1);
return Some(PathResult { path, cost });
}
}
}
}
None
}
#[allow(clippy::too_many_arguments)]
pub fn all_paths(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
max_hops: usize,
max_results: Option<usize>,
connection_types: Option<&[String]>,
via_types: Option<&[String]>,
deadline: Interrupt,
) -> Vec<Vec<NodeIndex>> {
let _arena_guard = graph.graph.begin_query();
let via_set: Option<HashSet<&str>> =
via_types.map(|vt| vt.iter().map(|s| s.as_str()).collect());
let interned = intern_connection_types(connection_types);
let mut results = Vec::new();
let mut current_path = vec![source];
let mut visited = HashSet::new();
visited.insert(source);
find_all_paths_recursive(
graph,
source,
target,
max_hops,
&mut current_path,
&mut visited,
&mut results,
max_results,
interned.as_deref(),
&via_set,
deadline,
);
results
}
#[allow(clippy::only_used_in_recursion, clippy::too_many_arguments)]
fn find_all_paths_recursive(
graph: &DirGraph,
current: NodeIndex,
target: NodeIndex,
remaining_hops: usize,
current_path: &mut Vec<NodeIndex>,
visited: &mut HashSet<NodeIndex>,
results: &mut Vec<Vec<NodeIndex>>,
max_results: Option<usize>,
connection_types: Option<&[InternedKey]>,
via_types: &Option<HashSet<&str>>,
deadline: Interrupt,
) {
if let Some(max) = max_results {
if results.len() >= max {
return;
}
}
if deadline.exceeded() {
{
return;
}
}
if current == target {
results.push(current_path.clone());
return;
}
if remaining_hops == 0 {
return;
}
let neighbors = filtered_neighbors_undirected(graph, current, connection_types);
for neighbor in neighbors {
if let Some(max) = max_results {
if results.len() >= max {
return;
}
}
if !visited.contains(&neighbor) {
if neighbor != target && !node_passes_via_filter(graph, neighbor, via_types) {
continue;
}
visited.insert(neighbor);
current_path.push(neighbor);
find_all_paths_recursive(
graph,
neighbor,
target,
remaining_hops - 1,
current_path,
visited,
results,
max_results,
connection_types,
via_types,
deadline,
);
current_path.pop();
visited.remove(&neighbor);
}
}
}
pub fn connected_components(graph: &DirGraph) -> Vec<Vec<NodeIndex>> {
let _arena_guard = graph.graph.begin_query();
if GraphRead::is_disk(&graph.graph) {
return weakly_connected_components(graph, Interrupt::default())
.expect("weakly_connected_components with deadline=None cannot time out");
}
kosaraju_scc(graph.graph.as_stable_digraph())
}
pub fn weakly_connected_components(
graph: &DirGraph,
deadline: Interrupt,
) -> Result<Vec<Vec<NodeIndex>>, String> {
let _arena_guard = graph.graph.begin_query();
weakly_connected_components_scoped(graph, None, None, deadline)
}
pub fn weakly_connected_components_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<Vec<Vec<NodeIndex>>, String> {
let _arena_guard = graph.graph.begin_query();
let edge_matches = |key: InternedKey| -> bool {
match rel_types {
Some(keys) => keys.contains(&key),
None => true,
}
};
let nodes: Vec<NodeIndex> = if let Some(types) = node_types {
let mut v = Vec::new();
for t in types {
if let Some(type_nodes) = graph.type_indices.get(t.as_str()) {
v.extend(type_nodes.iter());
}
}
v
} else if rel_types.is_some() {
let mut seen: HashSet<NodeIndex> = HashSet::new();
for edge in {
let g = &graph.graph;
g.edge_references()
} {
if edge_matches(edge.connection_type()) {
seen.insert(edge.source());
seen.insert(edge.target());
}
}
seen.into_iter().collect()
} else {
let g = &graph.graph;
g.node_indices().collect()
};
let n = nodes.len();
if n == 0 {
return Ok(Vec::new());
}
let bound = graph.graph.node_bound();
let mut node_to_idx = vec![usize::MAX; bound];
for (i, &node) in nodes.iter().enumerate() {
node_to_idx[node.index()] = i;
}
let mut parent: Vec<usize> = (0..n).collect();
let mut rank: Vec<u8> = vec![0; n];
#[inline]
fn find(parent: &mut [usize], mut x: usize) -> usize {
while parent[x] != x {
parent[x] = parent[parent[x]]; x = parent[x];
}
x
}
#[inline]
fn union(parent: &mut [usize], rank: &mut [u8], a: usize, b: usize) {
let ra = find(parent, a);
let rb = find(parent, b);
if ra == rb {
return;
}
if rank[ra] < rank[rb] {
parent[ra] = rb;
} else if rank[ra] > rank[rb] {
parent[rb] = ra;
} else {
parent[rb] = ra;
rank[ra] += 1;
}
}
let mut edge_counter: usize = 0;
for edge in {
let g = &graph.graph;
g.edge_references()
} {
edge_counter += 1;
if edge_counter & 0xFFFFF == 0 && deadline.exceeded() {
{
return Err(algorithm_timeout_err());
}
}
if !edge_matches(edge.connection_type()) {
continue;
}
let src_i = node_to_idx[edge.source().index()];
let tgt_i = node_to_idx[edge.target().index()];
if src_i == usize::MAX || tgt_i == usize::MAX {
continue;
}
union(&mut parent, &mut rank, src_i, tgt_i);
}
let mut component_map: HashMap<usize, Vec<NodeIndex>> = HashMap::new();
for (i, &node) in nodes.iter().enumerate() {
let root = find(&mut parent, i);
component_map.entry(root).or_default().push(node);
}
let mut components: Vec<Vec<NodeIndex>> = component_map.into_values().collect();
components.sort_by_key(|b| std::cmp::Reverse(b.len()));
Ok(components)
}
fn build_scoped_undirected_adjacency(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<(Vec<NodeIndex>, Vec<Vec<u32>>), String> {
let edge_matches = |key: InternedKey| -> bool {
match rel_types {
Some(keys) => keys.contains(&key),
None => true,
}
};
let nodes: Vec<NodeIndex> = scoped_universe(graph, node_types, rel_types);
let n = nodes.len();
let bound = graph.graph.node_bound();
let mut node_to_idx = vec![u32::MAX; bound];
for (i, &node) in nodes.iter().enumerate() {
node_to_idx[node.index()] = i as u32;
}
let mut adj: Vec<Vec<u32>> = vec![Vec::new(); n];
let mut counter = 0usize;
for edge in {
let g = &graph.graph;
g.edge_references()
} {
counter += 1;
if counter & 0xFFFFF == 0 && deadline.exceeded() {
{
return Err(algorithm_timeout_err());
}
}
if !edge_matches(edge.connection_type()) {
continue;
}
let s = node_to_idx[edge.source().index()];
let t = node_to_idx[edge.target().index()];
if s == u32::MAX || t == u32::MAX || s == t {
continue;
}
adj[s as usize].push(t);
adj[t as usize].push(s);
}
for list in adj.iter_mut() {
list.sort_unstable();
list.dedup();
}
Ok((nodes, adj))
}
pub fn coreness_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<Vec<(NodeIndex, i64)>, String> {
let _arena_guard = graph.graph.begin_query();
if graph.graph.is_disk() || graph.graph.is_mapped() {
return coreness_scoped_streaming(graph, node_types, rel_types, deadline);
}
let (nodes, adj) = build_scoped_undirected_adjacency(graph, node_types, rel_types, deadline)?;
let n = nodes.len();
if n == 0 {
return Ok(Vec::new());
}
let mut deg: Vec<u32> = adj.iter().map(|a| a.len() as u32).collect();
let max_deg = deg.iter().copied().max().unwrap_or(0) as usize;
let mut bin = vec![0usize; max_deg + 2];
for &d in ° {
bin[d as usize] += 1;
}
let mut start = 0usize;
for slot in bin.iter_mut().take(max_deg + 1) {
let count = *slot;
*slot = start;
start += count;
}
let mut vert = vec![0usize; n];
let mut pos = vec![0usize; n];
{
let mut binc = bin.clone();
for v in 0..n {
let d = deg[v] as usize;
pos[v] = binc[d];
vert[pos[v]] = v;
binc[d] += 1;
}
}
let mut core = vec![0i64; n];
for i in 0..n {
let v = vert[i];
core[v] = deg[v] as i64;
let dv = deg[v];
for &nbr in &adj[v] {
let u = nbr as usize;
if deg[u] > dv {
let du = deg[u] as usize;
let pu = pos[u];
let pw = bin[du];
let w = vert[pw];
if u != w {
vert[pu] = w;
vert[pw] = u;
pos[u] = pw;
pos[w] = pu;
}
bin[du] += 1;
deg[u] -= 1;
}
}
}
Ok(nodes.into_iter().zip(core).collect())
}
fn coreness_scoped_streaming(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<Vec<(NodeIndex, i64)>, String> {
let nodes = scoped_universe(graph, node_types, rel_types);
let src = DedupNeighborSource::new(graph, nodes, rel_types.map(|k| k.to_vec()));
let n = src.len();
if n == 0 {
return Ok(Vec::new());
}
let mut buf: Vec<u32> = Vec::new();
let mut deg: Vec<u32> = vec![0; n];
for (v, d) in deg.iter_mut().enumerate() {
if v & 0xFFFFF == 0 && deadline.exceeded() {
{
return Err(algorithm_timeout_err());
}
}
src.neighbors_deduped(v, &mut buf);
*d = buf.len() as u32;
}
let max_deg = deg.iter().copied().max().unwrap_or(0) as usize;
let mut bin = vec![0usize; max_deg + 2];
for &d in ° {
bin[d as usize] += 1;
}
let mut start = 0usize;
for slot in bin.iter_mut().take(max_deg + 1) {
let count = *slot;
*slot = start;
start += count;
}
let mut vert = vec![0usize; n];
let mut pos = vec![0usize; n];
{
let mut binc = bin.clone();
for v in 0..n {
let d = deg[v] as usize;
pos[v] = binc[d];
vert[pos[v]] = v;
binc[d] += 1;
}
}
let mut core = vec![0i64; n];
for i in 0..n {
if i & 0xFFFFF == 0 && deadline.exceeded() {
{
return Err(algorithm_timeout_err());
}
}
let v = vert[i];
core[v] = deg[v] as i64;
let dv = deg[v];
src.neighbors_deduped(v, &mut buf);
for &nbr in &buf {
let u = nbr as usize;
if deg[u] > dv {
let du = deg[u] as usize;
let pu = pos[u];
let pw = bin[du];
let w = vert[pw];
if u != w {
vert[pu] = w;
vert[pw] = u;
pos[u] = pw;
pos[w] = pu;
}
bin[du] += 1;
deg[u] -= 1;
}
}
}
Ok(src.nodes.into_iter().zip(core).collect())
}
pub fn ready_set_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
done: &HashSet<NodeIndex>,
deadline: Interrupt,
) -> Result<Vec<(NodeIndex, i64)>, String> {
let _arena_guard = graph.graph.begin_query();
let candidates: Vec<NodeIndex> = match node_types {
Some(types) => {
let mut v = Vec::new();
for t in types {
if let Some(idxs) = graph.type_indices.get(t.as_str()) {
v.extend(idxs.iter());
}
}
v
}
None => graph.graph.node_indices().collect(),
};
let mut ready = Vec::new();
for (i, node) in candidates.into_iter().enumerate() {
if i & 0xFFFF == 0 && deadline.exceeded() {
return Err("Query interrupted".to_string());
}
if done.contains(&node) {
continue;
}
let deps = filtered_neighbors_outgoing(graph, node, rel_types);
if deps.iter().all(|d| done.contains(d)) {
ready.push((node, deps.len() as i64));
}
}
Ok(ready)
}
pub fn clustering_coefficient_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<Vec<(NodeIndex, f64)>, String> {
let _arena_guard = graph.graph.begin_query();
let (nodes, adj) = build_scoped_undirected_adjacency(graph, node_types, rel_types, deadline)?;
let n = nodes.len();
let mut out = Vec::with_capacity(n);
for v in 0..n {
if v & 0xFFFF == 0 && deadline.exceeded() {
{
return Err(algorithm_timeout_err());
}
}
let nbrs = &adj[v];
let k = nbrs.len();
if k < 2 {
out.push((nodes[v], 0.0));
continue;
}
let mut links: u64 = 0;
for &a in nbrs {
links += intersection_count_gt(&adj[a as usize], nbrs, a);
}
let kf = k as f64;
out.push((nodes[v], (2.0 * links as f64) / (kf * (kf - 1.0))));
}
Ok(out)
}
pub fn triangle_count_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<(u64, f64), String> {
let _arena_guard = graph.graph.begin_query();
let (nodes, adj) = build_scoped_undirected_adjacency(graph, node_types, rel_types, deadline)?;
let n = nodes.len();
let mut link_sum: u64 = 0;
let mut triple_sum: u64 = 0;
for (v, nbrs) in adj.iter().enumerate().take(n) {
if v & 0xFFFF == 0 && deadline.exceeded() {
return Err(algorithm_timeout_err());
}
let k = nbrs.len() as u64;
if k < 2 {
continue;
}
triple_sum += k * (k - 1) / 2;
for &a in nbrs {
link_sum += intersection_count_gt(&adj[a as usize], nbrs, a);
}
}
let triangles = link_sum / 3;
let transitivity = if triple_sum > 0 {
link_sum as f64 / triple_sum as f64
} else {
0.0
};
Ok((triangles, transitivity))
}
const MAX_ECCENTRICITY_NODES: usize = 20_000;
pub fn eccentricity_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<Vec<(NodeIndex, i64)>, String> {
let _arena_guard = graph.graph.begin_query();
use std::collections::VecDeque;
let (nodes, adj) = build_scoped_undirected_adjacency(graph, node_types, rel_types, deadline)?;
let n = nodes.len();
if n > MAX_ECCENTRICITY_NODES {
return Err(format!(
"eccentricity/diameter is an all-pairs O(V·(V+E)) computation; the scoped \
subgraph has {n} nodes (cap {MAX_ECCENTRICITY_NODES}). Narrow it with \
{{node_type, relationship}} scoping, or compute on a smaller subgraph."
));
}
let mut out = Vec::with_capacity(n);
let mut seen = vec![0u32; n];
let mut dist = vec![0u32; n];
let mut queue: VecDeque<u32> = VecDeque::with_capacity(64);
let mut generation = 0u32;
for (s, &node) in nodes.iter().enumerate() {
if s & 0x3FF == 0 && deadline.exceeded() {
return Err(algorithm_timeout_err());
}
generation += 1;
seen[s] = generation;
dist[s] = 0;
queue.clear();
queue.push_back(s as u32);
let mut ecc = 0u32;
while let Some(u) = queue.pop_front() {
let du = dist[u as usize];
for &w in &adj[u as usize] {
if seen[w as usize] != generation {
seen[w as usize] = generation;
dist[w as usize] = du + 1;
ecc = ecc.max(du + 1);
queue.push_back(w);
}
}
}
out.push((node, ecc as i64));
}
Ok(out)
}
pub fn diameter_scoped(
graph: &DirGraph,
node_types: Option<&[String]>,
rel_types: Option<&[InternedKey]>,
deadline: Interrupt,
) -> Result<i64, String> {
let _arena_guard = graph.graph.begin_query();
let eccs = eccentricity_scoped(graph, node_types, rel_types, deadline)?;
Ok(eccs.iter().map(|(_, e)| *e).max().unwrap_or(0))
}
fn intersection_count_gt(a: &[u32], b: &[u32], gt: u32) -> u64 {
let (mut i, mut j) = (0usize, 0usize);
let mut count = 0u64;
while i < a.len() && j < b.len() {
match a[i].cmp(&b[j]) {
std::cmp::Ordering::Less => i += 1,
std::cmp::Ordering::Greater => j += 1,
std::cmp::Ordering::Equal => {
if a[i] > gt {
count += 1;
}
i += 1;
j += 1;
}
}
}
count
}
pub fn get_node_info(graph: &DirGraph, node_idx: NodeIndex) -> Option<PathNodeInfo> {
let _arena_guard = graph.graph.begin_query();
let node = graph.get_node(node_idx)?;
let node_title = node.title();
let title_str = match &*node_title {
Value::String(s) => s.clone(),
_ => format!("{:?}", *node_title),
};
Some(PathNodeInfo {
node_type: node.node_type_str(&graph.interner).to_string(),
title: title_str,
id: node.id().into_owned(),
})
}
pub fn get_path_connections(graph: &DirGraph, path: &[NodeIndex]) -> Vec<Option<String>> {
let _arena_guard = graph.graph.begin_query();
let mut connections = Vec::with_capacity(path.len().saturating_sub(1));
for window in path.windows(2) {
let from = window[0];
let to = window[1];
let conn_type = graph
.graph
.edges(from)
.find(|e| e.target() == to)
.map(|e| e.weight().connection_type_str(&graph.interner).to_string())
.or_else(|| {
graph
.graph
.edges(to)
.find(|e| e.target() == from)
.map(|e| e.weight().connection_type_str(&graph.interner).to_string())
});
connections.push(conn_type);
}
connections
}
pub fn are_connected(graph: &DirGraph, source: NodeIndex, target: NodeIndex) -> bool {
shortest_path(graph, source, target, None, None, Interrupt::default()).is_some()
}
pub fn node_degree(graph: &DirGraph, node: NodeIndex) -> usize {
let g = &graph.graph;
g.edges(node).count()
+ g.neighbors_directed(node, petgraph::Direction::Incoming)
.count()
}
pub(crate) fn edge_weight(
graph: &DirGraph,
edge_id: petgraph::graph::EdgeIndex,
weight_property: Option<&str>,
) -> f64 {
if let Some(prop) = weight_property {
let g = &graph.graph;
if let Some(edge_data) = g.edge_weight(edge_id) {
if let Some(val) = edge_data.get_property(prop) {
return crate::graph::core::value_operations::value_to_f64(val).unwrap_or(1.0);
}
}
}
1.0
}
#[derive(Debug, Clone)]
pub struct WeightedPathResult {
pub path: Vec<NodeIndex>,
pub weight: f64,
}
pub fn shortest_path_weighted(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
weight_property: &str,
connection_types: Option<&[String]>,
via_types: Option<&[String]>,
deadline: Interrupt,
) -> Option<WeightedPathResult> {
let _arena_guard = graph.graph.begin_query();
use std::cmp::Ordering;
use std::collections::BinaryHeap;
if source == target {
return Some(WeightedPathResult {
path: vec![source],
weight: 0.0,
});
}
let via_set: Option<HashSet<&str>> =
via_types.map(|vt| vt.iter().map(|s| s.as_str()).collect());
let interned = intern_connection_types(connection_types);
let conn_filter = interned.as_deref();
let node_bound = graph.graph.node_bound();
let mut dist: Vec<f64> = vec![f64::INFINITY; node_bound];
let mut parent: Vec<u32> = vec![u32::MAX; node_bound];
dist[source.index()] = 0.0;
#[derive(PartialEq)]
struct State(f64, usize);
impl Eq for State {}
impl Ord for State {
fn cmp(&self, other: &Self) -> Ordering {
other
.0
.partial_cmp(&self.0)
.unwrap_or(Ordering::Equal)
.then_with(|| self.1.cmp(&other.1))
}
}
impl PartialOrd for State {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
let mut heap: BinaryHeap<State> = BinaryHeap::new();
heap.push(State(0.0, source.index()));
let mut visit_count = 0u32;
while let Some(State(d, current_idx)) = heap.pop() {
if d > dist[current_idx] {
continue;
}
if current_idx == target.index() {
let mut path = Vec::with_capacity(16);
let mut idx = current_idx;
while idx != source.index() {
path.push(NodeIndex::new(idx));
idx = parent[idx] as usize;
}
path.push(source);
path.reverse();
return Some(WeightedPathResult { path, weight: d });
}
visit_count += 1;
if visit_count.is_multiple_of(1000) && deadline.exceeded() {
{
return None;
}
}
let current = NodeIndex::new(current_idx);
for edge in graph
.graph
.edges_directed(current, petgraph::Direction::Outgoing)
.chain(
graph
.graph
.edges_directed(current, petgraph::Direction::Incoming),
)
{
if let Some(types) = conn_filter {
if !types.iter().any(|t| *t == edge.connection_type()) {
continue;
}
}
let neighbor = if edge.source() == current {
edge.target()
} else {
edge.source()
};
let n_idx = neighbor.index();
if n_idx != target.index() && !node_passes_via_filter(graph, neighbor, &via_set) {
continue;
}
let w = edge_weight(graph, edge.id(), Some(weight_property));
if w < 0.0 {
return None;
}
let next = d + w;
if next < dist[n_idx] {
dist[n_idx] = next;
parent[n_idx] = current_idx as u32;
heap.push(State(next, n_idx));
}
}
}
None
}
pub fn shortest_path_cost_weighted(
graph: &DirGraph,
source: NodeIndex,
target: NodeIndex,
weight_property: &str,
connection_types: Option<&[String]>,
via_types: Option<&[String]>,
deadline: Interrupt,
) -> Option<f64> {
let _arena_guard = graph.graph.begin_query();
shortest_path_weighted(
graph,
source,
target,
weight_property,
connection_types,
via_types,
deadline,
)
.map(|r| r.weight)
}
pub(super) fn compute_modularity(
graph: &DirGraph,
community: &[usize],
node_exists: &[bool],
total_weight: f64,
weight_property: Option<&str>,
) -> f64 {
if total_weight == 0.0 {
return 0.0;
}
let two_m = 2.0 * total_weight;
let mut q = 0.0f64;
let g = &graph.graph;
let bound = g.node_bound();
let mut degrees: Vec<f64> = vec![0.0; bound];
for node_idx in g.node_indices() {
let i = node_idx.index();
if !node_exists[i] {
continue;
}
for edge in g.edges(node_idx) {
degrees[i] += edge_weight(graph, edge.id(), weight_property);
}
for edge in g.edges_directed(node_idx, petgraph::Direction::Incoming) {
degrees[i] += edge_weight(graph, edge.id(), weight_property);
}
}
for edge in {
let g = &graph.graph;
g.edge_references()
} {
let u = edge.source().index();
let v = edge.target().index();
let w = edge_weight(graph, edge.id(), weight_property);
if community[u] == community[v] {
q += w - degrees[u] * degrees[v] / two_m;
}
}
q / two_m
}
#[cfg(test)]
#[path = "graph_algorithms_tests.rs"]
mod tests;