1use std::collections::HashMap;
33
34use datafusion::arrow::array::{Array, ArrayRef};
35use datafusion::arrow::datatypes::DataType;
36use datafusion::arrow::util::display::{ArrayFormatter, FormatOptions};
37use datafusion::error::{DataFusionError, Result};
38use ursa_core::algo::{layout_fa2_multilevel, MultilevelParams};
39use ursa_core::topology::Topology;
40use ursa_viz::model::{
41 Column as ModelColumn, EdgeBatch, Encodings, GraphDelta, GraphResult, NodeBatch, NodeLabel, Op,
42 Provenance, Role, Strings, Target, Values,
43};
44
45use super::build::EdgeList;
46use super::{key_type_of, plan_err, thousands, GraphView};
47
48pub const MAX_GROUPS: usize = 2_000;
51pub const GROUP: &str = "group";
54pub const MEMBERS: &str = "members";
56pub const INSIDE: &str = "edges inside";
58pub const COUNT: &str = "count";
60pub const X: &str = "group x";
63pub const Y: &str = "group y";
64pub const MAX_OPEN: usize = 100_000;
66pub const RULE: &str = "groups";
68const NO_VALUE: &str = "NULL";
70
71#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Grouping {
75 by: String,
77 names: Vec<String>,
80 starts: Vec<u32>,
83 order: Vec<u32>,
84 keys: Strings,
87 labels: Vec<u16>,
88}
89
90impl Grouping {
91 pub fn by(&self) -> &str {
93 &self.by
94 }
95
96 pub fn len(&self) -> usize {
98 self.names.len()
99 }
100
101 pub fn is_empty(&self) -> bool {
102 self.names.is_empty()
103 }
104
105 pub fn n_nodes(&self) -> usize {
107 self.order.len()
108 }
109
110 pub fn name(&self, group: usize) -> &str {
112 &self.names[group]
113 }
114
115 pub fn members(&self, group: usize) -> &[u32] {
118 &self.order[self.starts[group] as usize..self.starts[group + 1] as usize]
119 }
120
121 pub fn key(&self, node: u32) -> &str {
123 self.keys.get(node as usize)
124 }
125
126 pub fn label(&self, node: u32) -> u16 {
128 self.labels.get(node as usize).copied().unwrap_or(1)
129 }
130}
131
132pub fn legend(result: &GraphResult, by: &str) -> Option<String> {
135 let name = result.encodings().group_by.as_deref()?;
136 let Values::Dict { values, .. } = &result.node_column(name)?.values else {
137 return None;
138 };
139 let groups = values.len();
140 Some(format!(
141 "grouped by {by}: {} group{}",
142 thousands(groups),
143 if groups == 1 { "" } else { "s" }
144 ))
145}
146
147pub fn is_group(result: &GraphResult, node: usize) -> bool {
150 result.encodings().group_by.is_some()
151 && result
152 .node_label()
153 .get(node)
154 .is_some_and(|&l| result.node_labels()[l as usize].name == GROUP)
155}
156
157pub(crate) fn own_labels(result: &GraphResult) -> usize {
160 usize::from(
161 result.encodings().group_by.is_some()
162 && result
163 .node_labels()
164 .first()
165 .is_some_and(|l| l.name == GROUP),
166 )
167}
168
169fn model(e: ursa_viz::model::ModelError) -> DataFusionError {
170 DataFusionError::Plan(format!("the groups cannot be drawn: {e}"))
171}
172
173pub(crate) fn grouped(
176 edges: EdgeList,
177 key_type: &DataType,
178 graph: Option<String>,
179 mut provenance: Provenance,
180 by: &str,
181 values: &ArrayRef,
182) -> Result<GraphView> {
183 let n = edges.n as usize;
184 if n == 0 {
185 return plan_err(format!("GROUP BY {by}: there are no nodes to group"));
186 }
187 if values.null_count() == values.len() {
188 return plan_err(format!(
189 "GROUP BY {by}: no node has a value (are the ids the graph's?)"
190 ));
191 }
192 if edges.labels.iter().any(|l| l == GROUP) {
193 return plan_err(format!(
194 "GROUP BY {by}: the drawing has a vertex table named '{GROUP}', which is what a \
195 grouped drawing calls its groups; draw it under another name"
196 ));
197 }
198 let options = FormatOptions::default();
201 let shown = ArrayFormatter::try_new(values.as_ref(), &options)?;
202 let mut seen: HashMap<String, u32> = HashMap::new();
203 let mut categories: Vec<(String, u32)> = Vec::new();
204 let mut none: Option<u32> = None;
205 let mut of: Vec<u32> = Vec::with_capacity(n);
206 for i in 0..n {
207 let c = if values.is_null(i) {
208 *none.get_or_insert_with(|| {
209 categories.push((String::new(), 0));
210 categories.len() as u32 - 1
211 })
212 } else {
213 let name = shown.value(i).to_string();
214 match seen.get(&name) {
215 Some(&c) => c,
216 None => {
217 let c = categories.len() as u32;
218 seen.insert(name.clone(), c);
219 categories.push((name, 0));
220 c
221 }
222 }
223 };
224 categories[c as usize].1 += 1;
225 of.push(c);
226 }
227 let unused = |seen: &HashMap<String, u32>, mut name: String| {
229 while seen.contains_key(&name) {
230 name.push('\'');
231 }
232 name
233 };
234 if let Some(c) = none {
235 let name = unused(&seen, NO_VALUE.to_string());
236 seen.insert(name.clone(), c);
237 categories[c as usize].0 = name;
238 }
239 let distinct = categories.len();
241 let mut order: Vec<u32> = (0..distinct as u32).collect();
242 order.sort_by(|&a, &b| {
243 categories[b as usize]
244 .1
245 .cmp(&categories[a as usize].1)
246 .then(a.cmp(&b))
247 });
248 let kept = distinct.min(MAX_GROUPS);
249 let mut rank = vec![kept as u32; distinct];
250 for (r, &c) in order.iter().take(kept).enumerate() {
251 rank[c as usize] = r as u32;
252 }
253 let mut names: Vec<String> = order[..kept]
254 .iter()
255 .map(|&c| categories[c as usize].0.clone())
256 .collect();
257 let mut members: Vec<u32> = order[..kept]
258 .iter()
259 .map(|&c| categories[c as usize].1)
260 .collect();
261 if distinct > kept {
262 let folded = distinct - kept;
263 names.push(unused(
264 &seen,
265 format!("other ({} groups)", thousands(folded)),
266 ));
267 members.push(
268 order[kept..]
269 .iter()
270 .map(|&c| categories[c as usize].1)
271 .sum(),
272 );
273 provenance.notes.push(format!(
274 "the {} largest of {} groups are drawn, and the other {} as one",
275 thousands(kept),
276 thousands(distinct),
277 thousands(folded)
278 ));
279 }
280 drop(seen);
281 drop(categories);
282 let groups = names.len();
283 for g in &mut of {
284 *g = rank[*g as usize];
285 }
286
287 let mut starts = vec![0u32; groups + 1];
289 for &g in &of {
290 starts[g as usize + 1] += 1;
291 }
292 for g in 0..groups {
293 starts[g + 1] += starts[g];
294 }
295 let mut next = starts.clone();
296 let mut by_group = vec![0u32; n];
297 for (i, &g) in of.iter().enumerate() {
298 by_group[next[g as usize] as usize] = i as u32;
299 next[g as usize] += 1;
300 }
301
302 let mut inside = vec![0u32; groups];
304 let mut between: HashMap<(u32, u32), u32> = HashMap::new();
305 for (&s, &d) in edges.src.iter().zip(&edges.dst) {
306 let (a, b) = (of[s as usize], of[d as usize]);
307 if a == b {
308 inside[a as usize] += 1;
309 } else {
310 *between.entry((a.min(b), a.max(b))).or_insert(0) += 1;
311 }
312 }
313 let mut pairs: Vec<((u32, u32), u32)> = between.into_iter().collect();
314 pairs.sort_unstable();
315 let (src, dst): (Vec<u32>, Vec<u32>) = pairs.iter().map(|&(pair, _)| pair).unzip();
316 let counts: Vec<u32> = pairs.iter().map(|&(_, count)| count).collect();
317 drop(pairs);
318
319 let key = key_type_of(key_type, &edges.ids);
322 let mut ops = vec![Op::AddNodeLabel(NodeLabel::new(
323 GROUP,
324 ursa_viz::model::KeyType::Int,
325 ))];
326 let labels = if edges.labels.is_empty() {
327 vec![String::new()]
328 } else {
329 edges.labels.clone()
330 };
331 ops.extend(
332 labels
333 .into_iter()
334 .map(|name| Op::AddNodeLabel(NodeLabel::new(name, key))),
335 );
336 ops.push(Op::AddEdgeLabel(String::new()));
337 ops.push(Op::AddNodes(NodeBatch::of_label(0, 0..groups as i64)));
338 ops.push(Op::AddEdges(EdgeBatch::of_label(0, src, dst)));
339 provenance.rule = Some(RULE.to_string());
340 let mut result = GraphResult::build(graph, provenance, &GraphDelta::new(ops)).map_err(model)?;
341 let column = if [MEMBERS, INSIDE, X, Y].contains(&by) {
344 format!("{by} (group)")
345 } else {
346 by.to_string()
347 };
348 let columns = [
349 (
350 Target::Nodes,
351 ModelColumn::new(
352 column.clone(),
353 Some(Role::Category),
354 Values::Dict {
355 values: names.iter().collect(),
356 codes: (0..groups as u32).collect(),
357 },
358 ),
359 ),
360 (
361 Target::Nodes,
362 ModelColumn::new(MEMBERS, Some(Role::Metric), Values::U32(members)),
363 ),
364 (
365 Target::Nodes,
366 ModelColumn::new(INSIDE, Some(Role::Metric), Values::U32(inside)),
367 ),
368 (
369 Target::Nodes,
370 ModelColumn::new(X, None, Values::F32(vec![f32::NAN; groups])),
371 ),
372 (
373 Target::Nodes,
374 ModelColumn::new(Y, None, Values::F32(vec![f32::NAN; groups])),
375 ),
376 (
377 Target::Edges,
378 ModelColumn::new(COUNT, Some(Role::Metric), Values::U32(counts)),
379 ),
380 ];
381 for (target, column) in columns {
382 let op = result.set_column_op(target, column);
383 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
384 }
385 let op = result.set_encodings_op(Encodings {
386 size_by: Some(MEMBERS.to_string()),
387 group_by: Some(column),
388 ..Encodings::default()
389 });
390 result.apply(&GraphDelta::new(vec![op])).map_err(model)?;
391
392 let groups = Grouping {
393 by: by.to_string(),
394 names,
395 starts,
396 order: by_group,
397 keys: edges.ids.iter().collect(),
398 labels: edges.node_label.iter().map(|&l| l + 1).collect(),
400 };
401 Ok(GraphView {
402 result,
403 skipped: edges.skipped,
404 positions: None,
405 groups: Some(groups),
406 })
407}
408
409pub const DISC_FILL: f32 = 0.9;
413const DISC_WORK: f64 = 3.0e6;
417
418pub fn disc_layout(n: usize, src: Vec<u32>, dst: Vec<u32>) -> (Vec<f32>, Vec<f32>) {
431 if n <= 1 {
432 return (vec![0.0; n], vec![0.0; n]);
433 }
434 let topology = Topology::build(n, src, dst);
435 let params = MultilevelParams {
436 finest_work: DISC_WORK,
437 ..MultilevelParams::default()
438 };
439 let (mut x, mut y) = layout_fa2_multilevel(&topology, None, params);
440 let (mut lo, mut hi) = (
443 (f32::INFINITY, f32::INFINITY),
444 (f32::NEG_INFINITY, f32::NEG_INFINITY),
445 );
446 for i in 0..n {
447 if x[i].is_finite() && y[i].is_finite() {
448 lo = (lo.0.min(x[i]), lo.1.min(y[i]));
449 hi = (hi.0.max(x[i]), hi.1.max(y[i]));
450 }
451 }
452 let (cx, cy) = if lo.0 <= hi.0 {
453 ((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0)
454 } else {
455 (0.0, 0.0)
456 };
457 let mut far: Vec<(f32, u32)> = (0..n)
458 .map(|i| {
459 let (dx, dy) = (x[i] - cx, y[i] - cy);
460 let d = (dx * dx + dy * dy).sqrt();
461 (if d.is_finite() { d } else { f32::INFINITY }, i as u32)
462 })
463 .collect();
464 far.sort_unstable_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
465 for (k, &(d, i)) in far.iter().enumerate() {
466 let i = i as usize;
467 let r = DISC_FILL * ((k as f32 + 0.5) / n as f32).sqrt();
468 let (ux, uy) = if d > 0.0 && d.is_finite() {
470 ((x[i] - cx) / d, (y[i] - cy) / d)
471 } else {
472 (1.0, 0.0)
473 };
474 x[i] = r * ux;
475 y[i] = r * uy;
476 }
477 (x, y)
478}