graphity_core/frontier_traverser.rs
1use crate::Graph;
2use crate::bits::next_clear_bit;
3use crate::error::check_index;
4
5/// The hooks of a search of your own that works off a queue of nodes, which a [`FrontierTraverser`]
6/// runs: a type of yours implements [`visit_node`](Self::visit_node) and, if needed,
7/// [`leave_level`](Self::leave_level).
8///
9/// Java's `FrontierTraverser` is an abstract class whose subclass overrides `visitNode` and
10/// `leaveLevel` and calls the protected `enqueueChildren`, `enqueue`, `isVisited`, `currentLevel` and
11/// `stop` and the protected field `visited`. In Rust, the state of the search stays in the
12/// [`FrontierTraverser`], the hooks are this trait, and the protected members are on the
13/// [`FrontierControl`] each hook receives.
14pub trait FrontierHooks {
15 /// Called for each node of the frontier, in the order in which the nodes entered it.
16 ///
17 /// The hook puts the nodes that come next into the frontier:
18 /// [`enqueue_children(node)`](FrontierControl::enqueue_children) for a breadth-first search,
19 /// [`enqueue`](FrontierControl::enqueue) for single nodes, or nothing to end the search at `node`.
20 /// They join the next level and are visited after the rest of the current one.
21 fn visit_node(&mut self, node: u32, control: &mut FrontierControl<'_>);
22
23 /// Called after the last node of a level has been visited, before the first node of the next level.
24 /// Does nothing unless implemented.
25 ///
26 /// Nodes enqueued here join the next level, which then follows even if the completed level enqueued
27 /// nothing. `level` is the level just completed.
28 fn leave_level(&mut self, level: u32, control: &mut FrontierControl<'_>) {
29 let _ = (level, control);
30 }
31}
32
33/// What a hook may ask or do during a run of a [`FrontierTraverser`]: put nodes into the frontier,
34/// ask whether a node is visited and which level is being visited, keep nodes out of the search, and
35/// stop the run - the protected members of Java's `FrontierTraverser`.
36pub struct FrontierControl<'a> {
37 graph: &'a Graph,
38 visited: &'a mut [u64],
39 frontier: &'a mut Vec<u32>,
40 level: u32,
41 stop_requested: &'a mut bool,
42}
43
44impl FrontierControl<'_> {
45 /// Returns the graph that the search runs on - Java's protected field `graph`.
46 ///
47 /// **Time:** O(1).
48 #[inline]
49 pub fn graph(&self) -> &Graph {
50 self.graph
51 }
52
53 /// Puts the out-nodes of `node` that are not visited yet into the frontier, in ascending order, and
54 /// marks them visited.
55 ///
56 /// Called from [`visit_node(node)`](FrontierHooks::visit_node), it makes the traversal a breadth-first
57 /// search. Outside a run, [`FrontierTraverser::enqueue_children`] adds the nodes to the next run, as
58 /// [`FrontierTraverser::enqueue`] does.
59 ///
60 /// **Time:** O(out_degree(node)).
61 ///
62 /// # Panics
63 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
64 #[track_caller]
65 pub fn enqueue_children(&mut self, node: u32) {
66 enqueue_children(self.graph, self.visited, self.frontier, node);
67 }
68
69 /// Puts `node` into the frontier and marks it visited, unless it is visited already. Returns `true` if
70 /// `node` was not visited and is now in the frontier.
71 ///
72 /// Called from a hook, it adds `node` to the next level. Outside a run, [`FrontierTraverser::enqueue`]
73 /// adds `node` to the next run: the nodes enqueued then come first in its level 0, ahead of its start
74 /// nodes, and [`FrontierTraverser::run`] visits them before it starts from a node of its own.
75 ///
76 /// **Time:** O(1).
77 ///
78 /// # Panics
79 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
80 #[track_caller]
81 pub fn enqueue(&mut self, node: u32) -> bool {
82 let node_count = self.graph.node_count();
83 check_index(node, node_count);
84 enqueue_unchecked(self.visited, self.frontier, node, node_count)
85 }
86
87 /// Returns whether `node` is visited: it has entered the frontier, or it was marked with
88 /// [`mark_visited`](Self::mark_visited).
89 ///
90 /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
91 /// with an `index out of bounds` message.
92 ///
93 /// **Time:** O(1).
94 #[inline]
95 pub fn is_visited(&self, node: u32) -> bool {
96 is_set(self.visited, node)
97 }
98
99 /// Marks `node` visited without putting it into the frontier, to keep it out of the search - what a
100 /// Java subclass does with the protected bit set `visited`.
101 ///
102 /// A marked node counts as visited and no longer enters the frontier, neither from a `run` method nor
103 /// from [`enqueue`](Self::enqueue) or [`enqueue_children`](Self::enqueue_children). A node already in
104 /// the frontier is visited all the same. Java's subclass must not clear a bit of `visited`; Rust
105 /// offers no way to.
106 ///
107 /// **Time:** O(1).
108 ///
109 /// # Panics
110 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
111 #[track_caller]
112 pub fn mark_visited(&mut self, node: u32) {
113 check_index(node, self.graph.node_count());
114 self.visited[node as usize >> 6] |= 1 << (node & 63);
115 }
116
117 /// Returns the level of the node being visited: 0 for the start nodes, `k + 1` for the nodes that
118 /// entered the frontier while level `k` was visited.
119 ///
120 /// In [`leave_level`](FrontierHooks::leave_level), it is the level just completed.
121 ///
122 /// **Time:** O(1).
123 #[inline]
124 pub fn current_level(&self) -> u32 {
125 self.level
126 }
127
128 /// Stops the run in progress: the run returns as soon as the hook that calls this method returns,
129 /// without calling another hook.
130 ///
131 /// The nodes still waiting in the frontier are dropped from it, but stay marked visited, so no later
132 /// run visits them. A later run skips every node visited so far. To cancel a run from another thread,
133 /// let a hook check a flag of your own and call this method.
134 ///
135 /// **Time:** O(1).
136 #[inline]
137 pub fn stop(&mut self) {
138 *self.stop_requested = true;
139 }
140}
141
142/// The body of both `enqueue_children` methods.
143#[track_caller]
144fn enqueue_children(graph: &Graph, visited: &mut [u64], frontier: &mut Vec<u32>, node: u32) {
145 let node_count = graph.node_count();
146 check_index(node, node_count);
147 let start = graph.out_adjacency_start();
148 let adjacency = graph.out_adjacency();
149 let v = node as usize;
150 for &child in &adjacency[start[v] as usize..start[v + 1] as usize] {
151 let (w, bit) = (child as usize >> 6, 1u64 << (child & 63));
152 if visited[w] & bit == 0 {
153 visited[w] |= bit;
154 push(frontier, child, node_count);
155 }
156 }
157}
158
159#[inline]
160fn is_set(bits: &[u64], node: u32) -> bool {
161 bits[node as usize >> 6] & (1 << (node & 63)) != 0
162}
163
164fn enqueue_unchecked(
165 visited: &mut [u64],
166 frontier: &mut Vec<u32>,
167 node: u32,
168 node_count: u32,
169) -> bool {
170 let (w, bit) = (node as usize >> 6, 1u64 << (node & 63));
171 if visited[w] & bit != 0 {
172 return false;
173 }
174 visited[w] |= bit;
175 push(frontier, node, node_count);
176 true
177}
178
179/// Appends `node` to the frontier, which grows by half its capacity, as Java's `IntArrayList`
180/// does, but never beyond `node_count`, the most nodes it can ever hold: 4 to 6 bytes per node
181/// that has entered it, where doubling would take up to 8.
182#[inline]
183fn push(frontier: &mut Vec<u32>, node: u32, node_count: u32) {
184 if frontier.len() == frontier.capacity() {
185 grow(frontier, node_count);
186 }
187 frontier.push(node);
188}
189
190#[cold]
191fn grow(frontier: &mut Vec<u32>, node_count: u32) {
192 let capacity = frontier.capacity();
193 let wanted = (capacity + (capacity >> 1))
194 .max(16)
195 .min(node_count as usize)
196 .max(capacity + 1);
197 frontier.reserve_exact(wanted - frontier.len());
198}
199
200/// The base of a breadth-first search of your own over a [`Graph`], or of any search that works off a
201/// queue of nodes and chooses which nodes enter it - Java's abstract class `FrontierTraverser`. A type
202/// of yours implements the hooks of [`FrontierHooks`], and a `run` method starts the search with them.
203///
204/// The queue is called the frontier and works first in first out. The traverser calls
205/// [`visit_node`](FrontierHooks::visit_node) for each node in the order in which it entered the
206/// frontier. The `run` methods put the start nodes into the frontier. The hook puts in the nodes that
207/// come next: the out-nodes of a node with [`FrontierControl::enqueue_children`], or a single node
208/// with [`FrontierControl::enqueue`]. A node counts as visited from the moment it enters the frontier,
209/// so it enters the frontier at most once. From a node for which the hook enqueues nothing, the search
210/// goes no further. With `enqueue_children(node)` in every `visit_node(node)`, the traversal is a
211/// [breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search).
212///
213/// The nodes come in levels: the start nodes form level 0, and the nodes that enter the frontier while
214/// level `k` is visited form level `k + 1`. In a breadth-first search, those are the nodes at distance
215/// `k + 1` from the nearest start node. [`FrontierControl::current_level`] returns the level of the
216/// node being visited, and [`leave_level`](FrontierHooks::leave_level) is called after the last node
217/// of each level. Here, `calls` are the calls between the methods of a program, and the search follows
218/// them from `main` for two levels:
219///
220/// <!-- example: traversals.rs#currentLevel -->
221/// ```
222/// # use graphity_core::{FrontierControl, FrontierHooks, FrontierTraverser};
223/// # let calls = graphity_core::Graph::of(
224/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
225/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
226/// # ).unwrap();
227/// # let main = 0;
228/// struct WithinTwoCalls {
229/// reached: Vec<u32>,
230/// }
231///
232/// impl FrontierHooks for WithinTwoCalls {
233/// fn visit_node(&mut self, method: u32, control: &mut FrontierControl<'_>) {
234/// self.reached.push(method);
235/// if control.current_level() < 2 {
236/// control.enqueue_children(method);
237/// }
238/// }
239/// }
240///
241/// let mut within_two_calls = WithinTwoCalls {
242/// reached: Vec::new(),
243/// };
244/// FrontierTraverser::new(&calls).run_from(main, &mut within_two_calls);
245/// // within_two_calls.reached: [0, 1, 2, 3, 4, 5] - main, parseArgs, run, load, save and
246/// // show
247/// # assert_eq!(within_two_calls.reached, [0, 1, 2, 3, 4, 5]);
248/// ```
249///
250/// When `visit_node` returns, the nodes it enqueued are still waiting in the frontier: unlike
251/// [`DfsTraverser`](crate::DfsTraverser), this traverser has no postorder. A hook can end the whole
252/// run with [`FrontierControl::stop`].
253///
254/// [`run`](Self::run) searches from every node in ascending order, [`run_from`](Self::run_from) from
255/// one node and [`run_from_nodes`](Self::run_from_nodes) from several, such as the root nodes that
256/// [`graphs::root_nodes`](crate::graphs::root_nodes) returns. The visited nodes add up over the runs
257/// of a traverser: a node is visited at most once in the lifetime of the traverser, and a later run
258/// skips it. Nodes [enqueued](Self::enqueue) outside a run come first in the next run.
259/// A type of yours can also keep nodes out of the search by marking them with
260/// [`mark_visited`](Self::mark_visited).
261///
262/// A hook cannot start another run of the same traverser. Java throws `IllegalStateException`; in
263/// Rust, the borrow checker rejects the call at compile time.
264///
265/// ```compile_fail,E0499
266/// use graphity_core::{FrontierControl, FrontierHooks, FrontierTraverser, GraphBuilder};
267///
268/// struct Nested<'t>(&'t mut FrontierTraverser);
269/// impl FrontierHooks for Nested<'_> {
270/// fn visit_node(&mut self, _: u32, _: &mut FrontierControl<'_>) {}
271/// }
272/// let graph = GraphBuilder::new().build();
273/// let mut traverser = FrontierTraverser::new(&graph);
274/// let mut hooks = Nested(&mut traverser);
275/// traverser.run(&mut hooks); // error: the traverser is already borrowed by the hooks
276/// ```
277///
278/// If a run ends with a panic from a hook or from the search, the state of the traverser is undefined:
279/// a later run may visit the rest of the frontier, for example. A new traverser is needed for further
280/// runs. [`BfsDistances`](crate::BfsDistances) and
281/// [`graphs::reachable_from_sources`](crate::graphs::reachable_from_sources) are ready-made
282/// breadth-first searches.
283///
284/// A traverser is mutable, and a run borrows it mutably, so the borrow rules keep two threads from
285/// running it at once - Java's instances are not safe to share between threads.
286///
287/// **Memory:** 1 bit per node for the visited nodes, and 4 to 6 bytes for every node that has entered
288/// the frontier, which keeps them all: up to 6 x node_count bytes; the graph's arrays are shared.
289#[derive(Debug, Clone)]
290pub struct FrontierTraverser {
291 graph: Graph,
292 /// Visited or enqueued nodes, one bit each.
293 visited: Vec<u64>,
294 /// Every node enqueued so far; `cursor` is the next to visit.
295 frontier: Vec<u32>,
296 cursor: usize,
297}
298
299impl FrontierTraverser {
300 /// Returns a traverser for `graph`, with no node visited - Java's constructor. The graph's arrays are
301 /// shared.
302 ///
303 /// **Time:** O(node_count).
304 pub fn new(graph: &Graph) -> Self {
305 Self {
306 graph: graph.clone(),
307 visited: vec![0; (graph.node_count() as usize >> 6) + 1],
308 frontier: Vec::new(),
309 cursor: 0,
310 }
311 }
312
313 /// Returns the graph that this traverser searches - Java's protected field `graph`.
314 ///
315 /// **Time:** O(1).
316 #[inline]
317 pub fn graph(&self) -> &Graph {
318 &self.graph
319 }
320
321 /// Returns whether `node` is visited: it has entered the frontier, or it was marked with
322 /// [`mark_visited`](Self::mark_visited) - [`FrontierControl::is_visited`] outside a run.
323 ///
324 /// `node` is a node ID in `0..node_count`; for any other value the method returns `false` or panics
325 /// with an `index out of bounds` message.
326 ///
327 /// **Time:** O(1).
328 #[inline]
329 pub fn is_visited(&self, node: u32) -> bool {
330 is_set(&self.visited, node)
331 }
332
333 /// Marks `node` visited without putting it into the frontier, to keep it out of the search, also
334 /// before the first run - what a Java subclass does with the protected bit set `visited`.
335 ///
336 /// A marked node counts as visited and no longer enters the frontier, neither from a `run` method nor
337 /// from [`enqueue`](Self::enqueue) or [`FrontierControl::enqueue_children`]. A node already in the
338 /// frontier is visited all the same.
339 ///
340 /// **Time:** O(1).
341 ///
342 /// # Panics
343 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
344 #[track_caller]
345 pub fn mark_visited(&mut self, node: u32) {
346 check_index(node, self.graph.node_count());
347 self.visited[node as usize >> 6] |= 1 << (node & 63);
348 }
349
350 /// Puts `node` into the frontier and marks it visited, unless it is visited already, outside a run -
351 /// Java's protected `enqueue` called outside a run. Returns `true` if `node` was not visited and is
352 /// now in the frontier.
353 ///
354 /// It adds `node` to the next run: the nodes enqueued now come first in its level 0, ahead of its
355 /// start nodes, and [`run`](Self::run) visits them before it starts from a node of its own.
356 ///
357 /// **Time:** O(1).
358 ///
359 /// # Panics
360 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
361 #[track_caller]
362 pub fn enqueue(&mut self, node: u32) -> bool {
363 let node_count = self.graph.node_count();
364 check_index(node, node_count);
365 enqueue_unchecked(&mut self.visited, &mut self.frontier, node, node_count)
366 }
367
368 /// Puts the out-nodes of `node` that are not visited yet into the frontier, in ascending order, and
369 /// marks them visited, outside a run - Java's protected `enqueueChildren` called outside a run.
370 ///
371 /// It adds the nodes to the next run, as [`enqueue`](Self::enqueue) does: the nodes enqueued now come
372 /// first in its level 0. During a run, a hook calls [`FrontierControl::enqueue_children`].
373 ///
374 /// **Time:** O(out_degree(node)).
375 ///
376 /// # Panics
377 /// With an `index out of bounds` message if `node` is not in `0..node_count`.
378 #[track_caller]
379 pub fn enqueue_children(&mut self, node: u32) {
380 enqueue_children(&self.graph, &mut self.visited, &mut self.frontier, node);
381 }
382
383 /// Searches from every node not visited yet, in ascending order, until every node is visited.
384 ///
385 /// Nodes enqueued before the call come first, as a level 0 of their own. Then each node that no
386 /// earlier search has reached when its turn comes starts a search of its own, with levels counted
387 /// from 0 again.
388 ///
389 /// **Time:** O(node_count), plus the hooks: O(node_count + edge_count) for a breadth-first search.
390 pub fn run<H: FrontierHooks + ?Sized>(&mut self, hooks: &mut H) {
391 let mut stop = false;
392 // Nodes enqueued outside a run first; an empty frontier calls no hook.
393 if !self.process_frontier(hooks, &mut stop) {
394 return;
395 }
396 let node_count = self.graph.node_count();
397 let n = node_count as usize;
398 let mut root = next_clear_bit(&self.visited, 0);
399 while root < n {
400 enqueue_unchecked(
401 &mut self.visited,
402 &mut self.frontier,
403 root as u32,
404 node_count,
405 );
406 if !self.process_frontier(hooks, &mut stop) {
407 return;
408 }
409 root = next_clear_bit(&self.visited, root + 1);
410 }
411 }
412
413 /// Searches from `start_node` and from the nodes enqueued before the call, visiting the nodes they
414 /// reach that are not visited yet - Java's overload `run(int)`.
415 ///
416 /// Level 0 holds the nodes enqueued before the call, then `start_node` unless it is visited already.
417 ///
418 /// **Time:** O(nodes visited), plus the hooks: O(reachable nodes + reachable edges) for a
419 /// breadth-first search.
420 ///
421 /// # Panics
422 /// With an `index out of bounds` message if `start_node` is not in `0..node_count`.
423 #[track_caller]
424 pub fn run_from<H: FrontierHooks + ?Sized>(&mut self, start_node: u32, hooks: &mut H) {
425 let node_count = self.graph.node_count();
426 check_index(start_node, node_count);
427 let mut stop = false;
428 enqueue_unchecked(
429 &mut self.visited,
430 &mut self.frontier,
431 start_node,
432 node_count,
433 );
434 self.process_frontier(hooks, &mut stop);
435 }
436
437 /// Searches from `start_nodes` and from the nodes enqueued before the call, visiting the nodes they
438 /// reach that are not visited yet - Java's overload `run(IntList)`.
439 ///
440 /// Level 0 holds the nodes enqueued before the call, then the start nodes in list order, skipping
441 /// those visited already. The list is checked first, so a start node out of range leaves the
442 /// traverser unchanged.
443 ///
444 /// **Time:** O(start_nodes.len() + nodes visited), plus the hooks:
445 /// O(start_nodes.len() + reachable nodes + reachable edges) for a breadth-first search.
446 ///
447 /// # Panics
448 /// With an `index out of bounds` message if a start node is not in `0..node_count`.
449 #[track_caller]
450 pub fn run_from_nodes<H: FrontierHooks + ?Sized>(
451 &mut self,
452 start_nodes: &[u32],
453 hooks: &mut H,
454 ) {
455 let node_count = self.graph.node_count();
456 crate::error::check_nodes(start_nodes, node_count);
457 let mut stop = false;
458 for &start in start_nodes {
459 enqueue_unchecked(&mut self.visited, &mut self.frontier, start, node_count);
460 }
461 self.process_frontier(hooks, &mut stop);
462 }
463
464 /// Visits the frontier, one level per round, with `leave_level` after each; nodes enqueued
465 /// there form the next level. Returns `false` if the traversal was stopped.
466 fn process_frontier<H: FrontierHooks + ?Sized>(
467 &mut self,
468 hooks: &mut H,
469 stop: &mut bool,
470 ) -> bool {
471 let Self {
472 graph,
473 visited,
474 frontier,
475 cursor,
476 } = self;
477 let graph = &*graph;
478 let mut level = 0u32;
479 while *cursor < frontier.len() {
480 let level_end = frontier.len();
481 while *cursor < level_end {
482 let node = frontier[*cursor];
483 *cursor += 1;
484 let mut control = FrontierControl {
485 graph,
486 visited: &mut visited[..],
487 frontier: &mut *frontier,
488 level,
489 stop_requested: &mut *stop,
490 };
491 hooks.visit_node(node, &mut control);
492 if *stop {
493 *cursor = frontier.len();
494 return false;
495 }
496 }
497 let mut control = FrontierControl {
498 graph,
499 visited: &mut visited[..],
500 frontier: &mut *frontier,
501 level,
502 stop_requested: &mut *stop,
503 };
504 hooks.leave_level(level, &mut control);
505 if *stop {
506 *cursor = frontier.len();
507 return false;
508 }
509 level += 1;
510 }
511 true
512 }
513}