use datafusion::arrow::array::{Array, ArrayRef, AsArray};
use datafusion::arrow::compute::cast;
use datafusion::arrow::datatypes::{DataType, Float32Type, SchemaRef};
use datafusion::error::Result;
use datafusion::prelude::SessionContext;
use ursa_core::algo::{fa2_grow, Fa2State, MultilevelParams, WarmParams};
use ursa_core::topology::UndirectedCsr;
use ursa_viz::model::Positions;
use super::build::{EdgeList, NodeIndex};
use super::{plan_err, thousands, RunSql};
const FORM: &str = "POSITIONS (SELECT id, x, y FROM …)";
const WARM_WORK: usize = 20_000_000;
pub(crate) struct Saved {
pub positions: Positions,
pub notes: Vec<String>,
}
fn column(schema: &SchemaRef, name: &str, or: usize) -> usize {
schema
.fields()
.iter()
.position(|f| f.name().eq_ignore_ascii_case(name))
.unwrap_or(or)
}
fn floats(column: &ArrayRef, name: &str, what: &str) -> Result<ArrayRef> {
let numeric = column.data_type().is_numeric();
match cast(column, &DataType::Float32) {
Ok(values) if numeric => Ok(values),
_ => plan_err(format!(
"POSITIONS (…): the column '{name}' is read as each node's {what}, and it is {}, not \
a number. Give the ids and then the positions: {FORM}",
column.data_type()
)),
}
}
pub(crate) async fn saved(
ctx: &SessionContext,
sql: &dyn RunSql,
query: &str,
edges: &EdgeList,
index: &NodeIndex,
) -> Result<Saved> {
let (schema, batches) = sql.run(ctx, query).await?;
let columns = schema.fields().len();
if columns < 3 {
return plan_err(format!(
"POSITIONS (…) needs three columns, each node's id and its x and y; got {columns}. \
Write {FORM}, or the rows layout_fa2 returns: POSITIONS (SELECT * FROM \
layout_fa2(g))"
));
}
let id = column(&schema, "id", 0);
let mut rest = (0..columns).filter(|&c| c != id);
let first = rest.next().expect("three columns");
let second = rest.next().expect("three columns");
let (x_at, y_at) = (column(&schema, "x", first), column(&schema, "y", second));
if x_at == id || y_at == id || x_at == y_at {
return plan_err(format!(
"POSITIONS (…) reads the column 'id' (or else the first) as the nodes' ids, 'x' and \
'y' (or else the next two) as their positions, and here two of them are one \
column. Name them: {FORM}"
));
}
let name = |c: usize| schema.field(c).name().as_str();
let n = edges.n as usize;
let mut x = vec![0.0f32; n];
let mut y = vec![0.0f32; n];
let mut placed = vec![false; n];
let (mut rows, mut strangers, mut unplaced_rows) = (0usize, 0usize, 0usize);
for batch in &batches {
let nodes = index.lookup(batch.column(id)).map_err(|e| {
datafusion::error::DataFusionError::Plan(format!(
"POSITIONS (…): the column '{}' is read as the nodes' ids, and {}",
name(id),
crate::user_message(&e)
))
})?;
let xs = floats(batch.column(x_at), name(x_at), "x")?;
let ys = floats(batch.column(y_at), name(y_at), "y")?;
let (xs, ys) = (
xs.as_primitive::<Float32Type>(),
ys.as_primitive::<Float32Type>(),
);
rows += batch.num_rows();
for (row, node) in nodes.into_iter().enumerate() {
let Some(node) = node else {
strangers += 1;
continue;
};
let node = node as usize;
let (px, py) = (xs.value(row), ys.value(row));
if xs.is_null(row) || ys.is_null(row) || !px.is_finite() || !py.is_finite() {
unplaced_rows += 1;
continue;
}
if !placed[node] {
placed[node] = true;
x[node] = px;
y[node] = py;
}
}
}
let known = placed.iter().filter(|&&p| p).count();
if known == 0 {
return plan_err(format!(
"POSITIONS (…) places none of the drawing's {} nodes: its {} rows have {}. The \
column '{}' is matched to the nodes' ids (the drawing's are like {}); positions \
saved from another graph, or from another id column, do not match",
thousands(n),
thousands(rows),
if unplaced_rows > 0 && strangers == 0 {
"no x and y that are numbers"
} else {
"no id that is a node of it"
},
name(id),
edges.ids.first().map_or("none", String::as_str),
));
}
let mut notes = Vec::new();
let missing = n - known;
if missing > 0 {
place_missing(edges, &placed, &mut x, &mut y);
notes.push(format!(
"{} of {} nodes had no saved position and {} placed beside {} neighbours",
thousands(missing),
thousands(n),
if missing == 1 { "was" } else { "were" },
if missing == 1 { "its" } else { "their" },
));
}
if strangers > 0 {
notes.push(format!(
"{} of POSITIONS's rows {} of no node drawn",
thousands(strangers),
if strangers == 1 { "is" } else { "are" },
));
}
Ok(Saved {
positions: Positions { x, y },
notes,
})
}
fn place_missing(edges: &EdgeList, placed: &[bool], x: &mut [f32], y: &mut [f32]) {
let n = placed.len();
let mut new = vec![0u32; n];
let mut old: Vec<u32> = Vec::with_capacity(n);
old.extend((0..n as u32).filter(|&i| placed[i as usize]));
let known = old.len();
old.extend((0..n as u32).filter(|&i| !placed[i as usize]));
for (j, &i) in old.iter().enumerate() {
new[i as usize] = j as u32;
}
let renumber = |ends: &[u32]| -> Vec<u32> { ends.iter().map(|&e| new[e as usize]).collect() };
let adjacency = UndirectedCsr::from_edges(n, &renumber(&edges.src), &renumber(&edges.dst));
drop(new);
let (kx, ky): (Vec<f32>, Vec<f32>) = old[..known]
.iter()
.map(|&i| (x[i as usize], y[i as usize]))
.unzip();
let params = MultilevelParams::default().fa2;
let mut state = Fa2State::from_positions(params, kx, ky, vec![1.0; known]);
let warm = WarmParams {
freeze_above: 0,
..WarmParams::default()
};
let schedule = fa2_grow(&mut state, &adjacency, None, &[], warm);
let iterations = schedule.min((WARM_WORK / n.max(1)).max(1) as u32);
state.step(&adjacency, iterations);
let (sx, sy) = state.positions();
for (j, &i) in old.iter().enumerate().skip(known) {
x[i as usize] = sx[j];
y[i as usize] = sy[j];
}
}