Skip to main content

hypergraph_rs/layout/
orderings.rs

1//! Ordering providers for babylon's topology render lane (design canon S9):
2//! surfaces consume orderings, never force layouts. `paoh_ordering` mirrors
3//! `src/babylon/projection/topology/paoh.py`'s SHAPE (nodes, sorted edges) —
4//! with one declared deviation: node order here is insertion order (III.7
5//! determinism via `node_ids()`), not paoh.py's lexicographic `sorted(set)`;
6//! callers wanting the lexicographic view sort the returned vec. Edge
7//! sort-by-attr-with-missing-last matches paoh.py exactly. `levi_ego_tree` mirrors
8//! `levi.py`, modeled on this crate's own bipartite (agent/hyperedge)
9//! representation. Both are re-expressions of existing structure — no new
10//! mathematics.
11
12use std::collections::HashSet;
13
14use serde::{Deserialize, Serialize};
15
16use crate::core::hypergraph::Hypergraph;
17
18/// The kind of node represented by a [`LeviNode`] in the Levi (bipartite)
19/// ego-tree walk.
20#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
21pub enum LeviKind {
22    Agent,
23    Hyperedge,
24}
25
26/// A node in the Levi ego-tree: an agent or a hyperedge, with children in
27/// membership insertion order.
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29pub struct LeviNode {
30    pub id: String,
31    pub kind: LeviKind,
32    pub children: Vec<LeviNode>,
33}
34
35/// Build a breadth-limited bipartite ego-tree rooted at `root` (an agent id).
36/// `depth` counts hyperedge expansions: at `depth == 0` the root is returned
37/// with no children. Each agent/hyperedge is visited at most once (a
38/// `HashSet<String>` guard per kind — Power-of-10 rule 2: the walk is bounded
39/// by the hypergraph's finite node/edge count, so it always terminates).
40/// Returns `None` if `root` does not exist.
41pub fn levi_ego_tree<N, E, M>(
42    h: &Hypergraph<N, E, M>,
43    root: &str,
44    depth: usize,
45) -> Option<LeviNode> {
46    if !h.node_ids().iter().any(|n| n == root) {
47        return None;
48    }
49    let mut visited_agents: HashSet<String> = HashSet::new();
50    let mut visited_edges: HashSet<String> = HashSet::new();
51    visited_agents.insert(root.to_string());
52    Some(build_agent_node(
53        h,
54        root,
55        depth,
56        &mut visited_agents,
57        &mut visited_edges,
58    ))
59}
60
61fn build_agent_node<N, E, M>(
62    h: &Hypergraph<N, E, M>,
63    agent_id: &str,
64    remaining_depth: usize,
65    visited_agents: &mut HashSet<String>,
66    visited_edges: &mut HashSet<String>,
67) -> LeviNode {
68    let mut children = Vec::new();
69    if remaining_depth > 0 {
70        let memberships = h.memberships(agent_id).unwrap_or_default();
71        for edge_id in memberships {
72            if visited_edges.contains(&edge_id) {
73                continue;
74            }
75            visited_edges.insert(edge_id.clone());
76            children.push(build_edge_node(
77                h,
78                &edge_id,
79                remaining_depth,
80                visited_agents,
81                visited_edges,
82            ));
83        }
84    }
85    LeviNode {
86        id: agent_id.to_string(),
87        kind: LeviKind::Agent,
88        children,
89    }
90}
91
92fn build_edge_node<N, E, M>(
93    h: &Hypergraph<N, E, M>,
94    edge_id: &str,
95    remaining_depth: usize,
96    visited_agents: &mut HashSet<String>,
97    visited_edges: &mut HashSet<String>,
98) -> LeviNode {
99    let mut children = Vec::new();
100    let next_depth = remaining_depth - 1;
101    let members = h.members(edge_id).unwrap_or_default();
102    for member_id in members {
103        if visited_agents.contains(&member_id) {
104            continue;
105        }
106        visited_agents.insert(member_id.clone());
107        children.push(build_agent_node(
108            h,
109            &member_id,
110            next_depth,
111            visited_agents,
112            visited_edges,
113        ));
114    }
115    LeviNode {
116        id: edge_id.to_string(),
117        kind: LeviKind::Hyperedge,
118        children,
119    }
120}
121
122/// PAOH ordering (parallel aggregated ordered hypergraph): nodes in insertion
123/// order; edges in insertion order unless `sort_attr` names a numeric edge
124/// attribute, in which case edges are stable-sorted ascending by that attr's
125/// `as_f64()` value, with missing/non-numeric attrs sorted LAST (ties by
126/// insertion order) — matches babylon's `paoh.py` None-last rule.
127pub fn paoh_ordering(
128    h: &Hypergraph<serde_json::Value, serde_json::Value, serde_json::Value>,
129    sort_attr: Option<&str>,
130) -> (Vec<String>, Vec<String>) {
131    let nodes = h.node_ids();
132    let mut edges = h.edge_ids();
133    if let Some(attr) = sort_attr {
134        let key = |edge_id: &String| -> Option<f64> {
135            h.edge_attrs(edge_id)
136                .and_then(|v| v.get(attr))
137                .and_then(|v| v.as_f64())
138        };
139        edges.sort_by(|a, b| match (key(a), key(b)) {
140            (Some(x), Some(y)) => x.partial_cmp(&y).unwrap_or(std::cmp::Ordering::Equal),
141            (Some(_), None) => std::cmp::Ordering::Less,
142            (None, Some(_)) => std::cmp::Ordering::Greater,
143            (None, None) => std::cmp::Ordering::Equal,
144        });
145    }
146    (nodes, edges)
147}