use std::collections::HashMap;
use datafusion::arrow::array::{Array, ArrayRef};
use datafusion::arrow::datatypes::DataType;
use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
use datafusion::error::{DataFusionError, Result};
use ursa_core::algo::{layout_fa2_multilevel, MultilevelParams};
use ursa_core::topology::Topology;
use ursa_viz::model::{
Column as ModelColumn, EdgeBatch, Encodings, GraphDelta, GraphResult, NodeBatch, NodeLabel, Op,
Provenance, Role, Strings, Target, Values,
};
use super::build::EdgeList;
use super::{key_type_of, plan_err, thousands, GraphView};
pub const MAX_GROUPS: usize = 2_000;
pub const GROUP: &str = "group";
pub const MEMBERS: &str = "members";
pub const INSIDE: &str = "edges inside";
pub const COUNT: &str = "count";
pub const X: &str = "group x";
pub const Y: &str = "group y";
pub const MAX_OPEN: usize = 100_000;
pub const RULE: &str = "groups";
const NO_VALUE: &str = "NULL";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grouping {
by: String,
names: Vec<String>,
starts: Vec<u32>,
order: Vec<u32>,
keys: Strings,
labels: Vec<u16>,
}
impl Grouping {
pub fn by(&self) -> &str {
&self.by
}
pub fn len(&self) -> usize {
self.names.len()
}
pub fn is_empty(&self) -> bool {
self.names.is_empty()
}
pub fn n_nodes(&self) -> usize {
self.order.len()
}
pub fn name(&self, group: usize) -> &str {
&self.names[group]
}
pub fn members(&self, group: usize) -> &[u32] {
&self.order[self.starts[group] as usize..self.starts[group + 1] as usize]
}
pub fn key(&self, node: u32) -> &str {
self.keys.get(node as usize)
}
pub fn label(&self, node: u32) -> u16 {
self.labels.get(node as usize).copied().unwrap_or(1)
}
}
pub fn legend(result: &GraphResult, by: &str) -> Option<String> {
let name = result.encodings().group_by.as_deref()?;
let Values::Dict { values, .. } = &result.node_column(name)?.values else {
return None;
};
let groups = values.len();
Some(format!(
"grouped by {by}: {} group{}",
thousands(groups),
if groups == 1 { "" } else { "s" }
))
}
pub fn is_group(result: &GraphResult, node: usize) -> bool {
result.encodings().group_by.is_some()
&& result
.node_label()
.get(node)
.is_some_and(|&l| result.node_labels()[l as usize].name == GROUP)
}
pub(crate) fn own_labels(result: &GraphResult) -> usize {
usize::from(
result.encodings().group_by.is_some()
&& result
.node_labels()
.first()
.is_some_and(|l| l.name == GROUP),
)
}
fn model(e: ursa_viz::model::ModelError) -> DataFusionError {
DataFusionError::Plan(format!("the groups cannot be drawn: {e}"))
}
pub(crate) fn grouped(
edges: EdgeList,
key_type: &DataType,
graph: Option<String>,
mut provenance: Provenance,
by: &str,
values: &ArrayRef,
) -> Result<GraphView> {
let n = edges.n as usize;
if n == 0 {
return plan_err(format!("GROUP BY {by}: there are no nodes to group"));
}
if values.null_count() == values.len() {
return plan_err(format!(
"GROUP BY {by}: no node has a value (are the ids the graph's?)"
));
}
if edges.labels.iter().any(|l| l == GROUP) {
return plan_err(format!(
"GROUP BY {by}: the drawing has a vertex table named '{GROUP}', which is what a \
grouped drawing calls its groups; draw it under another name"
));
}
let options = FormatOptions::default();
let shown = ArrayFormatter::try_new(values.as_ref(), &options)?;
let mut seen: HashMap<String, u32> = HashMap::new();
let mut categories: Vec<(String, u32)> = Vec::new();
let mut none: Option<u32> = None;
let mut of: Vec<u32> = Vec::with_capacity(n);
for i in 0..n {
let c = if values.is_null(i) {
*none.get_or_insert_with(|| {
categories.push((String::new(), 0));
categories.len() as u32 - 1
})
} else {
let name = shown.value(i).to_string();
match seen.get(&name) {
Some(&c) => c,
None => {
let c = categories.len() as u32;
seen.insert(name.clone(), c);
categories.push((name, 0));
c
}
}
};
categories[c as usize].1 += 1;
of.push(c);
}
let unused = |seen: &HashMap<String, u32>, mut name: String| {
while seen.contains_key(&name) {
name.push('\'');
}
name
};
if let Some(c) = none {
let name = unused(&seen, NO_VALUE.to_string());
seen.insert(name.clone(), c);
categories[c as usize].0 = name;
}
let distinct = categories.len();
let mut order: Vec<u32> = (0..distinct as u32).collect();
order.sort_by(|&a, &b| {
categories[b as usize]
.1
.cmp(&categories[a as usize].1)
.then(a.cmp(&b))
});
let kept = distinct.min(MAX_GROUPS);
let mut rank = vec![kept as u32; distinct];
for (r, &c) in order.iter().take(kept).enumerate() {
rank[c as usize] = r as u32;
}
let mut names: Vec<String> = order[..kept]
.iter()
.map(|&c| categories[c as usize].0.clone())
.collect();
let mut members: Vec<u32> = order[..kept]
.iter()
.map(|&c| categories[c as usize].1)
.collect();
if distinct > kept {
let folded = distinct - kept;
names.push(unused(
&seen,
format!("other ({} groups)", thousands(folded)),
));
members.push(
order[kept..]
.iter()
.map(|&c| categories[c as usize].1)
.sum(),
);
provenance.notes.push(format!(
"the {} largest of {} groups are drawn, and the other {} as one",
thousands(kept),
thousands(distinct),
thousands(folded)
));
}
drop(seen);
drop(categories);
let groups = names.len();
for g in &mut of {
*g = rank[*g as usize];
}
let mut starts = vec![0u32; groups + 1];
for &g in &of {
starts[g as usize + 1] += 1;
}
for g in 0..groups {
starts[g + 1] += starts[g];
}
let mut next = starts.clone();
let mut by_group = vec![0u32; n];
for (i, &g) in of.iter().enumerate() {
by_group[next[g as usize] as usize] = i as u32;
next[g as usize] += 1;
}
let mut inside = vec![0u32; groups];
let mut between: HashMap<(u32, u32), u32> = HashMap::new();
for (&s, &d) in edges.src.iter().zip(&edges.dst) {
let (a, b) = (of[s as usize], of[d as usize]);
if a == b {
inside[a as usize] += 1;
} else {
*between.entry((a.min(b), a.max(b))).or_insert(0) += 1;
}
}
let mut pairs: Vec<((u32, u32), u32)> = between.into_iter().collect();
pairs.sort_unstable();
let (src, dst): (Vec<u32>, Vec<u32>) = pairs.iter().map(|&(pair, _)| pair).unzip();
let counts: Vec<u32> = pairs.iter().map(|&(_, count)| count).collect();
drop(pairs);
let key = key_type_of(key_type, &edges.ids);
let mut ops = vec![Op::AddNodeLabel(NodeLabel::new(
GROUP,
ursa_viz::model::KeyType::Int,
))];
let labels = if edges.labels.is_empty() {
vec![String::new()]
} else {
edges.labels.clone()
};
ops.extend(
labels
.into_iter()
.map(|name| Op::AddNodeLabel(NodeLabel::new(name, key))),
);
ops.push(Op::AddEdgeLabel(String::new()));
ops.push(Op::AddNodes(NodeBatch::of_label(0, 0..groups as i64)));
ops.push(Op::AddEdges(EdgeBatch::of_label(0, src, dst)));
provenance.rule = Some(RULE.to_string());
let mut result = GraphResult::build(graph, provenance, &GraphDelta::new(ops)).map_err(model)?;
let column = if [MEMBERS, INSIDE, X, Y].contains(&by) {
format!("{by} (group)")
} else {
by.to_string()
};
let columns = [
(
Target::Nodes,
ModelColumn::new(
column.clone(),
Some(Role::Category),
Values::Dict {
values: names.iter().collect(),
codes: (0..groups as u32).collect(),
},
),
),
(
Target::Nodes,
ModelColumn::new(MEMBERS, Some(Role::Metric), Values::U32(members)),
),
(
Target::Nodes,
ModelColumn::new(INSIDE, Some(Role::Metric), Values::U32(inside)),
),
(
Target::Nodes,
ModelColumn::new(X, None, Values::F32(vec![f32::NAN; groups])),
),
(
Target::Nodes,
ModelColumn::new(Y, None, Values::F32(vec![f32::NAN; groups])),
),
(
Target::Edges,
ModelColumn::new(COUNT, Some(Role::Metric), Values::U32(counts)),
),
];
for (target, column) in columns {
let op = result.set_column_op(target, column);
result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
}
let op = result.set_encodings_op(Encodings {
size_by: Some(MEMBERS.to_string()),
group_by: Some(column),
..Encodings::default()
});
result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
let groups = Grouping {
by: by.to_string(),
names,
starts,
order: by_group,
keys: edges.ids.iter().collect(),
labels: edges.node_label.iter().map(|&l| l + 1).collect(),
};
Ok(GraphView {
result,
skipped: edges.skipped,
positions: None,
groups: Some(groups),
})
}
pub const DISC_FILL: f32 = 0.9;
const DISC_WORK: f64 = 3.0e6;
pub fn disc_layout(n: usize, src: Vec<u32>, dst: Vec<u32>) -> (Vec<f32>, Vec<f32>) {
if n <= 1 {
return (vec![0.0; n], vec![0.0; n]);
}
let topology = Topology::build(n, src, dst);
let params = MultilevelParams {
finest_work: DISC_WORK,
..MultilevelParams::default()
};
let (mut x, mut y) = layout_fa2_multilevel(&topology, None, params);
let (mut lo, mut hi) = (
(f32::INFINITY, f32::INFINITY),
(f32::NEG_INFINITY, f32::NEG_INFINITY),
);
for i in 0..n {
if x[i].is_finite() && y[i].is_finite() {
lo = (lo.0.min(x[i]), lo.1.min(y[i]));
hi = (hi.0.max(x[i]), hi.1.max(y[i]));
}
}
let (cx, cy) = if lo.0 <= hi.0 {
((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0)
} else {
(0.0, 0.0)
};
let mut far: Vec<(f32, u32)> = (0..n)
.map(|i| {
let (dx, dy) = (x[i] - cx, y[i] - cy);
let d = (dx * dx + dy * dy).sqrt();
(if d.is_finite() { d } else { f32::INFINITY }, i as u32)
})
.collect();
far.sort_unstable_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
for (k, &(d, i)) in far.iter().enumerate() {
let i = i as usize;
let r = DISC_FILL * ((k as f32 + 0.5) / n as f32).sqrt();
let (ux, uy) = if d > 0.0 && d.is_finite() {
((x[i] - cx) / d, (y[i] - cy) / d)
} else {
(1.0, 0.0)
};
x[i] = r * ux;
y[i] = r * uy;
}
(x, y)
}