Skip to main content

subgraphsearch_core/
largest.rs

1//! The largest induced path, cycle, tree, clique or independent set a search finds, by searching
2//! one size after another.
3//!
4//! [`largest`] first doubles its steps upward from a starting size while searches succeed, then
5//! bisects between the last size that succeeded and the first that did not. A size counts as
6//! reachable if the search succeeds at it or at one of the next `lookahead` sizes: some sizes are
7//! impossible even below the largest, such as paths with an odd number of vertices between two
8//! hypercube vertices that differ in an odd number of bits, and a search that stopped at the first
9//! failure would stop there. Every search is kept, so the sizes just beyond the largest found give
10//! the closest near misses.
11
12use std::collections::BTreeMap;
13use std::collections::btree_map::Entry;
14
15use serde::{Deserialize, Serialize};
16
17use crate::Error;
18use crate::graph::Graph;
19use crate::search::{Regular, SearchParams, SearchResult, search};
20
21/// The kinds of induced subgraph [`largest`] can grow.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "lowercase")]
24pub enum Shape {
25    /// An induced path ([`SearchParams::path`]), between [`SearchParams::endpoints`] if given.
26    Path,
27    /// An induced cycle: connected and regular of degree 2.
28    Cycle,
29    /// An induced tree: connected, with one edge fewer than vertices.
30    Tree,
31    /// A clique: every pair of vertices joined.
32    Clique,
33    /// An independent set: no pair of vertices joined.
34    Independent,
35}
36
37impl Shape {
38    /// The shape's name: "path", "cycle", "tree", "clique" or "independent".
39    pub fn name(self) -> &'static str {
40        match self {
41            Shape::Path => "path",
42            Shape::Cycle => "cycle",
43            Shape::Tree => "tree",
44            Shape::Clique => "clique",
45            Shape::Independent => "independent",
46        }
47    }
48
49    /// The search for this shape on `size` vertices, with everything else from `base`.
50    pub fn params(self, base: &SearchParams, size: usize) -> SearchParams {
51        let mut p = base.clone();
52        p.size = size;
53        p.edges = 0;
54        p.path = false;
55        p.regular = None;
56        if self != Shape::Path {
57            p.endpoints = None;
58        }
59        match self {
60            Shape::Path => p.path = true,
61            Shape::Cycle => {
62                p.connected = true;
63                p.regular = Some(Regular {
64                    degree: 2,
65                    two_phase: false,
66                });
67            }
68            Shape::Tree => {
69                p.connected = true;
70                p.edges = size as i64 - 1;
71            }
72            Shape::Clique => p.edges = (size * (size - 1) / 2) as i64,
73            Shape::Independent => p.edges = 0,
74        }
75        p
76    }
77
78    /// The fewest vertices the shape has: 3 for a cycle, 2 otherwise.
79    fn smallest(self) -> usize {
80        if self == Shape::Cycle { 3 } else { 2 }
81    }
82}
83
84impl std::str::FromStr for Shape {
85    type Err = Error;
86
87    fn from_str(s: &str) -> Result<Self, Error> {
88        match s {
89            "path" => Ok(Shape::Path),
90            "cycle" => Ok(Shape::Cycle),
91            "tree" => Ok(Shape::Tree),
92            "clique" => Ok(Shape::Clique),
93            "independent" => Ok(Shape::Independent),
94            _ => Err(Error::Invalid(format!(
95                "unknown shape {s:?}: choose path, cycle, tree, clique or independent"
96            ))),
97        }
98    }
99}
100
101/// The outcome of [`largest`]: every search made, by size.
102#[derive(Clone, Debug, Serialize, Deserialize)]
103pub struct Largest {
104    pub shape: Shape,
105    /// The largest size at which a search succeeded, if any did.
106    pub size: Option<usize>,
107    /// Every search made, in increasing order of size.
108    pub results: Vec<SearchResult>,
109}
110
111/// Searches `graph` for the largest `shape` it can find, starting at `start` vertices (by
112/// default the fewest the shape and the fixed vertices allow) and trusting a failure only when the
113/// next `lookahead` sizes fail too; see the module documentation. Each search takes its settings
114/// from `base`, except the size and target, which the shape sets.
115pub fn largest(
116    graph: &Graph,
117    shape: Shape,
118    base: &SearchParams,
119    start: Option<usize>,
120    lookahead: usize,
121) -> Result<Largest, Error> {
122    if base.endpoints.is_some() && shape != Shape::Path {
123        return Err(Error::Invalid("endpoints need a path search".into()));
124    }
125    let mut required = base.fixed.clone();
126    for v in base.endpoints.into_iter().flatten() {
127        if !required.contains(&v) {
128            required.push(v);
129        }
130    }
131    let mut floor = shape.smallest().max(required.len() + 1);
132    // a path between two vertices has at least as many as the shortest one
133    if let Some([s, t]) = base.endpoints {
134        if s.max(t) >= graph.num_vertices() {
135            return Err(Error::VertexOutOfRange {
136                vertex: s.max(t) as i64,
137                n: graph.num_vertices(),
138            });
139        }
140        let Some(shortest) = shortest_path_vertices(graph, s, t) else {
141            return Err(Error::Invalid(format!("no path joins {s} and {t}")));
142        };
143        floor = floor.max(shortest);
144    }
145    let start = start.unwrap_or(floor);
146    // a search needs at least one vertex outside the subgraph
147    let most = graph.num_vertices().saturating_sub(1);
148    if start > most {
149        return Err(Error::InvalidSubgraphSize(start as i64));
150    }
151    // check the settings once, at the starting size, before any search runs
152    shape.params(base, start).validate(graph.num_vertices())?;
153
154    let mut results = BTreeMap::new();
155    let mut found = |k: usize| -> Result<bool, Error> {
156        reachable(graph, shape, base, k, lookahead, most, &mut results)
157    };
158    if found(start)? {
159        let (mut low, mut step) = (start, 1);
160        while found(low + step)? {
161            low += step;
162            step *= 2;
163        }
164        let mut high = low + step;
165        while high - low > 1 {
166            let mid = low + (high - low) / 2;
167            if found(mid)? {
168                low = mid;
169            } else {
170                high = mid;
171            }
172        }
173    }
174    let size = results
175        .iter()
176        .filter(|(_, r)| r.successes() > 0)
177        .map(|(&k, _)| k)
178        .max();
179    Ok(Largest {
180        shape,
181        size,
182        results: results.into_values().collect(),
183    })
184}
185
186/// The number of vertices on a shortest path from `s` to `t`, if there is one.
187fn shortest_path_vertices(graph: &Graph, s: usize, t: usize) -> Option<usize> {
188    let mut dist = vec![usize::MAX; graph.num_vertices()];
189    dist[s] = 1;
190    let mut queue = std::collections::VecDeque::from([s]);
191    while let Some(u) = queue.pop_front() {
192        if u == t {
193            return Some(dist[u]);
194        }
195        for &w in graph.neighbors(u) {
196            let w = w as usize;
197            if dist[w] == usize::MAX {
198                dist[w] = dist[u] + 1;
199                queue.push_back(w);
200            }
201        }
202    }
203    None
204}
205
206/// Whether a search succeeds at `k` vertices or at one of the next `lookahead` sizes, searching
207/// each size at most once.
208fn reachable(
209    graph: &Graph,
210    shape: Shape,
211    base: &SearchParams,
212    k: usize,
213    lookahead: usize,
214    most: usize,
215    results: &mut BTreeMap<usize, SearchResult>,
216) -> Result<bool, Error> {
217    for size in (k..=k + lookahead).take_while(|&size| size <= most) {
218        let result = match results.entry(size) {
219            Entry::Occupied(e) => e.into_mut(),
220            Entry::Vacant(e) => e.insert(search(graph, &shape.params(base, size))?),
221        };
222        if result.successes() > 0 {
223            return Ok(true);
224        }
225    }
226    Ok(false)
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    fn cube(n: usize) -> Graph {
234        Graph::from_edges(
235            1 << n,
236            (0..1usize << n)
237                .flat_map(|u| (0..n).map(move |b| (u, u ^ (1 << b))))
238                .filter(|&(u, w)| u < w),
239        )
240        .unwrap()
241    }
242
243    fn settings() -> SearchParams {
244        let mut p = SearchParams::new(2, 0);
245        p.experiments = 50;
246        p.max_moves = 2000;
247        p.div_freq = 300;
248        p.div_dur = 8;
249        p
250    }
251
252    #[test]
253    fn finds_the_5_cube_records() {
254        // the longest snake and coil in the 5-cube have 14 vertices each (13 and 14 edges), and
255        // the cube has no triangles; a path is a tree, so its largest induced trees are no smaller
256        let g = cube(5);
257        for (shape, at_least, at_most) in [
258            (Shape::Path, 14, 14),
259            (Shape::Cycle, 14, 14),
260            (Shape::Tree, 14, 31),
261            (Shape::Clique, 2, 2),
262            // the cube is bipartite with two parts of 16, and no independent set is larger
263            (Shape::Independent, 16, 16),
264        ] {
265            let r = largest(&g, shape, &settings(), None, 2).unwrap();
266            let size = r.size.unwrap();
267            assert!((at_least..=at_most).contains(&size), "{shape:?}: {size}");
268            assert!(
269                r.results
270                    .windows(2)
271                    .all(|w| w[0].params.size < w[1].params.size)
272            );
273            // nothing larger succeeded, and the search looked beyond the largest found
274            assert!(
275                r.results
276                    .iter()
277                    .all(|x| x.params.size <= size || x.successes() == 0)
278            );
279            assert!(r.results.iter().any(|x| x.params.size > size));
280            let best = r.results.iter().find(|x| x.params.size == size).unwrap();
281            assert!(best.successes() > 0);
282        }
283    }
284
285    #[test]
286    fn looks_past_impossible_sizes() {
287        // 0 and 31 differ in five bits, so paths between them have an even number of vertices:
288        // without looking ahead, the search would stop at the first odd size
289        let g = cube(5);
290        let mut p = settings();
291        p.endpoints = Some([0, 31]);
292        let ahead = largest(&g, Shape::Path, &p, Some(6), 2).unwrap();
293        let size = ahead.size.unwrap();
294        assert!(size >= 10 && size.is_multiple_of(2), "{size}");
295        assert_eq!(
296            largest(&g, Shape::Path, &p, Some(6), 0).unwrap().size,
297            Some(6)
298        );
299        // by default it starts at the shortest path between the endpoints, here 6 vertices
300        let from_shortest = largest(&g, Shape::Path, &p, None, 2).unwrap();
301        assert_eq!(from_shortest.results[0].params.size, 6);
302        assert!(from_shortest.size.unwrap() >= 10);
303    }
304
305    #[test]
306    fn rejects_bad_requests() {
307        let g = cube(4);
308        let mut p = settings();
309        p.endpoints = Some([0, 15]);
310        assert!(largest(&g, Shape::Cycle, &p, None, 2).is_err());
311        assert!(largest(&g, Shape::Path, &settings(), Some(16), 2).is_err());
312        let one_edge = Graph::from_edges(16, [(0, 1)]).unwrap();
313        let mut apart = settings();
314        apart.endpoints = Some([0, 5]);
315        assert!(largest(&one_edge, Shape::Path, &apart, None, 2).is_err());
316        assert!("star".parse::<Shape>().is_err());
317        assert_eq!("tree".parse::<Shape>().unwrap(), Shape::Tree);
318    }
319}