Skip to main content

ursa_engine/graph/view/
groups.rs

1//! `GROUP BY` (design §6, #499): a drawing aggregated by a column.
2//!
3//! `.graph karate GROUP BY club` draws a disc for each club and the ties
4//! between clubs, counted, in place of the members and their ties. What
5//! groups the nodes is resolved as `COLOR BY` is: a column of `NODES
6//! (query)`, a column of the result's own rows, a vertex column, or an
7//! algorithm (`louvain`, `connected_components`, `label_propagation`).
8//!
9//! [`grouped`] makes the result a front end draws:
10//!
11//! - **its nodes are the groups**, of the node label [`GROUP`], keyed `0`,
12//!   `1`, … from the largest (equal ones as first seen). A column named
13//!   as `GROUP BY` names what it groups by (`club`, `louvain`) says each
14//!   one's value, which its members share, as the shell prints it;
15//!   [`MEMBERS`] counts its members and [`INSIDE`] the edges among them. A drawing of more than [`MAX_GROUPS`] groups keeps the
16//!   largest, and the rest are one group at the end, `other (N groups)`;
17//! - **its edges are the pairs of groups with an edge between them**, one
18//!   each, from the lower group to the higher, in order; the edge column
19//!   [`COUNT`] says how many of the drawing's edges each stands for,
20//!   whichever way they point;
21//! - its encodings size the nodes by [`MEMBERS`] and group them by the
22//!   column of the groups' values.
23//!
24//! The edges inside a group are not in the result, and nor are the members:
25//! the [`Grouping`] beside it (`GraphView::groups`) knows which nodes each
26//! group has, for the explore session to open one (`.expand group:3`,
27//! [`super::session`]). An opened group's members are nodes of the same
28//! result, of the vertex tables' own labels, with their group's value in
29//! the same column and their place in the group's disc in [`X`] and [`Y`]
30//! ([`disc_layout`]).
31
32use 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
48/// The most groups drawn each as its own disc: the largest. The rest are
49/// one group, "other".
50pub const MAX_GROUPS: usize = 2_000;
51/// The label of the nodes that are groups. `.expand group:3` opens the
52/// group keyed 3.
53pub const GROUP: &str = "group";
54/// The node column that counts a group's members.
55pub const MEMBERS: &str = "members";
56/// The node column that counts the edges among a group's members.
57pub const INSIDE: &str = "edges inside";
58/// The edge column that counts the edges between two groups.
59pub const COUNT: &str = "count";
60/// The node columns that place a member of an opened group in its group's
61/// disc: a point of the unit disc, the group's centre at its origin.
62pub const X: &str = "group x";
63pub const Y: &str = "group y";
64/// The most members a group may have to be opened in place.
65pub const MAX_OPEN: usize = 100_000;
66/// The rule's name in a grouped result's provenance.
67pub const RULE: &str = "groups";
68/// What the nodes with no value are grouped as.
69const NO_VALUE: &str = "NULL";
70
71/// Which nodes of a drawing each group of a grouped result has: what
72/// `GROUP BY` leaves out of the result, kept for opening a group.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct Grouping {
75    /// What the nodes are grouped by, as typed.
76    by: String,
77    /// Each group's name: the values of the grouped result's group column,
78    /// in order.
79    names: Vec<String>,
80    /// Group `g`'s members are `order[starts[g]..starts[g + 1]]`: nodes of
81    /// the drawing, ascending.
82    starts: Vec<u32>,
83    order: Vec<u32>,
84    /// The drawing's nodes: each one's key, and its label in the grouped
85    /// result (empty when every one is of label 1, the only vertex table).
86    keys: Strings,
87    labels: Vec<u16>,
88}
89
90impl Grouping {
91    /// What the nodes are grouped by, as typed.
92    pub fn by(&self) -> &str {
93        &self.by
94    }
95
96    /// How many groups there are, "other" among them.
97    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    /// How many nodes are grouped.
106    pub fn n_nodes(&self) -> usize {
107        self.order.len()
108    }
109
110    /// Group `group`'s name.
111    pub fn name(&self, group: usize) -> &str {
112        &self.names[group]
113    }
114
115    /// Group `group`'s members: nodes of the drawing that was grouped,
116    /// ascending.
117    pub fn members(&self, group: usize) -> &[u32] {
118        &self.order[self.starts[group] as usize..self.starts[group + 1] as usize]
119    }
120
121    /// The key of node `node` of the drawing that was grouped.
122    pub fn key(&self, node: u32) -> &str {
123        self.keys.get(node as usize)
124    }
125
126    /// The label of node `node` in the grouped result: its vertex table.
127    pub fn label(&self, node: u32) -> u16 {
128        self.labels.get(node as usize).copied().unwrap_or(1)
129    }
130}
131
132/// The legend of a grouped result: `grouped by louvain: 12 groups`. `None`
133/// for a result that is not grouped.
134pub 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
147/// Whether node `node` of `result` is a group of a grouped result, not a
148/// node of a graph.
149pub 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
157/// How many of `result`'s node labels are not vertex tables: 1, the
158/// groups' own, if it is grouped.
159pub(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
173/// `edges` grouped by `values`, one per node in node order (`by` is what
174/// they are, as typed): see the [module](self).
175pub(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    // Each category: its name, its count, in the order first seen. The
199    // nodes with no value are one.
200    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    // A name no value has, for the nodes with none and for "other".
228    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    // The largest first; equal ones as first seen.
240    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    // Each group's members, ascending.
288    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    // The edges between groups, counted, and those inside each.
303    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    // The result: the groups as nodes of the label `group`, then the
320    // drawing's own labels, which an opened group's members are of.
321    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    // The column of the groups' values is named as GROUP BY names them,
342    // unless that is one of this module's own columns.
343    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        // In the result the drawing's labels come after `group`.
399        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
409/// How far from the middle of its disc the outermost member of a group is
410/// put, as a share of the disc's radius: the members are inside it, with
411/// room for their own discs.
412pub const DISC_FILL: f32 = 0.9;
413/// The work a group's layout may take on the group itself, in adjacency
414/// entries plus nodes per iteration, times iterations: a tenth of what a
415/// graph's own layout takes, for a picture a tenth as large.
416const DISC_WORK: f64 = 3.0e6;
417
418/// Where each of `n` nodes goes in the unit disc, by the edges
419/// `(src[i], dst[i])` among them: `x` and `y`, one per node.
420///
421/// The nodes are laid out as a graph is (`layout_fa2`'s coarse-to-fine
422/// ForceAtlas2, with its defaults), and then each is moved along its ray
423/// from the layout's middle so that the nodes fill the disc evenly: the
424/// `k`-th of them from the middle (ties by index) is put
425/// `DISC_FILL * sqrt((k + 0.5) / n)` from it. Neighbours stay beside each
426/// other, and no node is outside the disc whatever the layout's shape. One
427/// node is at the middle.
428///
429/// The same nodes and edges give the same bits, on any number of threads.
430pub 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    // The middle: of the box, which no node's place depends on the order
441    // of a sum for.
442    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        // A node at the middle, or nowhere, goes along the x axis.
469        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}