Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/src/order.rs

//! An order of a split's parts for one sweep: the strong components of the part graph
//! (which part's border leads to which), feeders before what they feed. A part outside a
//! circle runs once, after every part that feeds it; only the parts of a circle loop, and
//! only among themselves. A graph split by a real key (a code graph by crate, where Cargo
//! forbids circles; a road net by region) mostly has no circle.

use crate::graph::GraphError;
use crate::split::PartSummary;

/// The groups of parts in sweep order ([`PartOrder::new`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PartOrder {
    /// The strong components of the part graph, feeders first; each group's parts rising.
    groups: Vec<Vec<u32>>,
    /// Per group its level: 0 when nothing outside it feeds it, else one past the highest
    /// level of the groups that feed it.
    level: Vec<u32>,
    /// Per part its group.
    group_of: Vec<u32>,
}

impl PartOrder {
    /// The order of `parts` parts whose graph is `to[off[p]..off[p + 1]]` per part `p` (the
    /// central index's part graph).
    pub fn new(parts: usize, off: &[u64], to: &[u32]) -> crate::Result<Self> {
        if off.len() != parts + 1 || off.windows(2).any(|w| w[0] > w[1]) {
            return Err(GraphError::Split(format!(
                "a part graph of {} offsets for {parts} parts",
                off.len()
            )));
        }
        if off[parts] as usize != to.len() || to.iter().any(|&q| q as usize >= parts) {
            return Err(GraphError::Split(
                "a part graph that leads past its parts".into(),
            ));
        }
        let next = |p: usize| &to[off[p] as usize..off[p + 1] as usize];
        // Tarjan's strong components without recursion: a component is closed after every
        // component it leads to, so the closing order reversed puts feeders first.
        const NONE: u32 = u32::MAX;
        let mut index = vec![NONE; parts];
        let mut low = vec![0u32; parts];
        let mut on = vec![false; parts];
        let mut stack: Vec<u32> = Vec::new();
        let mut closed: Vec<Vec<u32>> = Vec::new();
        let mut count = 0u32;
        let mut call: Vec<(u32, usize)> = Vec::new();
        for root in 0..parts {
            if index[root] != NONE {
                continue;
            }
            call.push((root as u32, 0));
            while let Some(top) = call.last_mut() {
                let (p, at) = *top;
                let pu = p as usize;
                if at == 0 && index[pu] == NONE {
                    index[pu] = count;
                    low[pu] = count;
                    count += 1;
                    stack.push(p);
                    on[pu] = true;
                }
                if let Some(&q) = next(pu).get(at) {
                    top.1 += 1;
                    let qu = q as usize;
                    if index[qu] == NONE {
                        call.push((q, 0));
                    } else if on[qu] {
                        low[pu] = low[pu].min(index[qu]);
                    }
                    continue;
                }
                call.pop();
                if let Some(&(parent, _)) = call.last() {
                    low[parent as usize] = low[parent as usize].min(low[pu]);
                }
                if low[pu] == index[pu] {
                    let mut group = Vec::new();
                    while let Some(q) = stack.pop() {
                        on[q as usize] = false;
                        group.push(q);
                        if q == p {
                            break;
                        }
                    }
                    group.sort_unstable();
                    closed.push(group);
                }
            }
        }
        closed.reverse();
        let mut group_of = vec![0u32; parts];
        for (g, group) in closed.iter().enumerate() {
            for &p in group {
                group_of[p as usize] = g as u32;
            }
        }
        let mut level = vec![0u32; closed.len()];
        for (g, group) in closed.iter().enumerate() {
            for &p in group {
                for &q in next(p as usize) {
                    let h = group_of[q as usize] as usize;
                    if h != g {
                        level[h] = level[h].max(level[g] + 1);
                    }
                }
            }
        }
        Ok(PartOrder {
            groups: closed,
            level,
            group_of,
        })
    }

    /// The order of the parts whose summaries are `summaries` (in part order, as
    /// [`crate::Split::summaries`] gives them).
    pub fn from_summaries(summaries: &[PartSummary]) -> crate::Result<Self> {
        let mut off = vec![0u64];
        let mut to = Vec::new();
        for s in summaries {
            to.extend(s.border.iter().map(|&(q, _)| q));
            off.push(to.len() as u64);
        }
        Self::new(summaries.len(), &off, &to)
    }

    /// The groups, feeders first (each a strong component of the part graph).
    pub fn groups(&self) -> &[Vec<u32>] {
        &self.groups
    }

    /// Group `g`'s level: 0 when nothing outside it feeds it, else one past the highest
    /// level of its feeders. The groups of one level do not feed each other.
    pub fn level(&self, g: usize) -> u32 {
        self.level[g]
    }

    /// The number of levels (0 with no part).
    pub fn levels(&self) -> u32 {
        self.level.iter().max().map_or(0, |&l| l + 1)
    }

    /// Part `p`'s group.
    pub fn group_of(&self, p: u32) -> usize {
        self.group_of[p as usize] as usize
    }

    /// Whether group `g` is a circle (more than one part feeding each other), so it loops.
    pub fn circle(&self, g: usize) -> bool {
        self.groups[g].len() > 1
    }

    /// The number of circles.
    pub fn circles(&self) -> usize {
        (0..self.groups.len()).filter(|&g| self.circle(g)).count()
    }

    /// The parts of level `l`, rising.
    pub fn parts_at(&self, l: u32) -> Vec<u32> {
        let mut out: Vec<u32> = self
            .groups
            .iter()
            .enumerate()
            .filter(|&(g, _)| self.level[g] == l)
            .flat_map(|(_, group)| group.iter().copied())
            .collect();
        out.sort_unstable();
        out
    }
}