graphity_core/mapping.rs
1//! Mappings between numberings of nodes and edges: the trait [`IndexMapping`] and the mappings
2//! [`NodeMapping`] and [`EdgeMapping`].
3
4use crate::array_limits::{MAX_ARRAY_LENGTH, is_negative_in_java};
5use crate::bits::next_clear_bit;
6use crate::dfs_frames;
7use crate::error::{index_out_of_bounds, invalid_argument};
8use crate::{Graph, GraphError, NONE, SortedIntView};
9
10pub(crate) mod sealed {
11 /// Restricts the mapping and partition traits to the types of this crate, as Java's sealed
12 /// class hierarchy does.
13 pub trait Sealed {}
14}
15
16/// A mapping from the indices `0..index_count()` to the indices of another numbering - Java's abstract
17/// class `IndexMapping`. It is the common base of the node and edge mappings and of the partitions.
18///
19/// The indices are node IDs or edge indices. [`get(i)`](Self::get) is the index that `i` maps to, or
20/// `None` if `i` is not mapped - Java's `-1`; a mapping with unmapped indices is partial. A
21/// [`NodeMapping`] maps the node IDs of one graph to those of another, and an [`EdgeMapping`] does the
22/// same for edge indices. Neither maps two indices to the same index, so both can be inverted. An
23/// [`IndexPartition`](crate::IndexPartition) maps indices to groups and lists the indices of each
24/// group. Several indices can map to the same group.
25///
26/// That a node or edge mapping maps no two indices to the same index is a contract, not a check:
27/// [`NodeMapping::of`] accepts an array that breaks it, and only `inverted` and
28/// [`graphs::remapped`](crate::graphs::remapped) reject such a mapping.
29///
30/// [`NodeMapping`], [`EdgeMapping`], [`NodePartition`](crate::NodePartition),
31/// [`EdgePartition`](crate::EdgePartition) and [`Sccs`](crate::Sccs) implement this trait. Each of
32/// them has the same methods as inherent methods too, so the trait is needed only for code that is
33/// generic over them. It is sealed, as Java's class hierarchy is. Instances are immutable and safe to
34/// share between threads (`Send` and `Sync`).
35///
36/// **Memory:** 4 x index_count bytes; a partition holds more.
37pub trait IndexMapping: sealed::Sealed {
38 /// Returns the index that `id` maps to, or `None` if `id` is not mapped - Java's `-1`.
39 ///
40 /// In a partition, it is the group of `id`.
41 ///
42 /// **Time:** O(1).
43 ///
44 /// # Panics
45 /// With an `index out of bounds` message if `id` is not in `0..index_count()`.
46 fn get(&self, id: u32) -> Option<u32>;
47
48 /// Returns whether `id` is mapped. Equivalent to `get(id).is_some()`.
49 ///
50 /// **Time:** O(1).
51 ///
52 /// # Panics
53 /// With an `index out of bounds` message if `id` is not in `0..index_count()`.
54 fn is_mapped(&self, id: u32) -> bool;
55
56 /// Returns whether some index is not mapped. Equivalent to `mapped_count() < index_count()`.
57 ///
58 /// **Time:** O(1).
59 fn is_partial(&self) -> bool;
60
61 /// Returns the number of indices that are mapped; in a partition, the number of indices that belong to
62 /// a group.
63 ///
64 /// **Time:** O(1).
65 fn mapped_count(&self) -> u32;
66
67 /// Returns the number of indices this mapping maps from, mapped or not.
68 ///
69 /// It is the length of the arrays that `gather` returns and that `reduce` takes.
70 ///
71 /// **Time:** O(1).
72 fn index_count(&self) -> u32;
73}
74
75/// Implements the inherent methods of [`IndexMapping`] and the trait itself for a type with the
76/// private methods `mapping_slice()` and `valid_count()`.
77macro_rules! index_mapping_impl {
78 ($ty:ty) => {
79 impl $ty {
80 /// Returns the index that `id` maps to, or `None` if `id` is not mapped - Java's `-1`.
81 ///
82 /// In a partition, it is the group of `id`.
83 ///
84 /// **Time:** O(1).
85 ///
86 /// # Panics
87 /// With an `index out of bounds` message if `id` is not in `0..index_count()`.
88 #[inline]
89 #[track_caller]
90 pub fn get(&self, id: u32) -> Option<u32> {
91 let mapping = self.mapping_slice();
92 $crate::error::check_index(id, mapping.len() as u32);
93 let target = mapping[id as usize];
94 (target != $crate::NONE).then_some(target)
95 }
96
97 /// Returns whether `id` is mapped. Equivalent to `get(id).is_some()`.
98 ///
99 /// **Time:** O(1).
100 ///
101 /// # Panics
102 /// With an `index out of bounds` message if `id` is not in `0..index_count()`.
103 #[inline]
104 #[track_caller]
105 pub fn is_mapped(&self, id: u32) -> bool {
106 self.get(id).is_some()
107 }
108
109 /// Returns whether some index is not mapped. Equivalent to `mapped_count() < index_count()`.
110 ///
111 /// **Time:** O(1).
112 #[inline]
113 pub fn is_partial(&self) -> bool {
114 (self.valid_count() as usize) < self.mapping_slice().len()
115 }
116
117 /// Returns the number of indices that are mapped; in a partition, the number of indices that belong to
118 /// a group.
119 ///
120 /// **Time:** O(1).
121 #[inline]
122 pub fn mapped_count(&self) -> u32 {
123 self.valid_count()
124 }
125
126 /// Returns the number of indices this mapping maps from, mapped or not.
127 ///
128 /// It is the length of the arrays that `gather` returns and that `reduce` takes.
129 ///
130 /// **Time:** O(1).
131 #[inline]
132 pub fn index_count(&self) -> u32 {
133 self.mapping_slice().len() as u32
134 }
135 }
136
137 impl $crate::mapping::sealed::Sealed for $ty {}
138
139 impl $crate::IndexMapping for $ty {
140 #[inline]
141 fn get(&self, id: u32) -> Option<u32> {
142 <$ty>::get(self, id)
143 }
144
145 #[inline]
146 fn is_mapped(&self, id: u32) -> bool {
147 <$ty>::is_mapped(self, id)
148 }
149
150 #[inline]
151 fn is_partial(&self) -> bool {
152 <$ty>::is_partial(self)
153 }
154
155 #[inline]
156 fn mapped_count(&self) -> u32 {
157 <$ty>::mapped_count(self)
158 }
159
160 #[inline]
161 fn index_count(&self) -> u32 {
162 <$ty>::index_count(self)
163 }
164 }
165 };
166}
167
168pub(crate) use index_mapping_impl;
169
170/// Number of mapped entries in `mapping`.
171pub(crate) fn count_valid(mapping: &[u32]) -> u32 {
172 mapping.iter().filter(|&&t| t != NONE).count() as u32
173}
174
175/// Inverts `mapping` into a target space of `target_count` indices.
176///
177/// # Panics
178/// With an `invalid argument` message if `target_count` is larger than the largest array, or
179/// several sources map to the same target; with an `index out of bounds` message if a target is
180/// `target_count` or more.
181#[track_caller]
182fn invert_array(mapping: &[u32], target_count: u32) -> Vec<u32> {
183 if target_count > MAX_ARRAY_LENGTH {
184 invalid_argument!("target_count out of range: {target_count}");
185 }
186 let mut inverse = vec![NONE; target_count as usize];
187 for (i, &value) in mapping.iter().enumerate() {
188 if value == NONE {
189 continue;
190 }
191 if value >= target_count {
192 index_out_of_bounds!("index {i} maps to {value}, but target_count is {target_count}");
193 }
194 let previous = inverse[value as usize];
195 if previous != NONE {
196 invalid_argument!(
197 "cannot invert mapping: indices {previous} and {i} both map to {value}"
198 );
199 }
200 inverse[value as usize] = i as u32;
201 }
202 inverse
203}
204
205/// Composes two mapping arrays: `result[i] = outer[inner[i]]`, unmapped entries propagate.
206#[track_caller]
207fn compose_arrays(outer: &[u32], inner: &[u32]) -> Vec<u32> {
208 inner
209 .iter()
210 .enumerate()
211 .map(|(i, &mid)| {
212 if mid == NONE {
213 NONE
214 } else if (mid as usize) < outer.len() {
215 outer[mid as usize]
216 } else {
217 index_out_of_bounds!(
218 "inner maps {i} to {mid}, outside the indices 0..{} of this mapping",
219 outer.len()
220 )
221 }
222 })
223 .collect()
224}
225
226/// `result[i] = values[mapping[i]]`, `T::default()` where unmapped.
227#[track_caller]
228fn gather_array<T: Copy + Default>(mapping: &[u32], values: &[T]) -> Vec<T> {
229 mapping
230 .iter()
231 .map(|&source| {
232 if source == NONE {
233 T::default()
234 } else {
235 values[source as usize]
236 }
237 })
238 .collect()
239}
240
241/// `new_values[i] = values[mapping[i]]`, untouched where unmapped.
242#[track_caller]
243fn gather_array_into<T: Clone>(mapping: &[u32], values: &[T], new_values: &mut [T]) {
244 check_length(new_values.len(), mapping.len(), "new_values");
245 for (slot, &source) in new_values.iter_mut().zip(mapping) {
246 if source != NONE {
247 *slot = values[source as usize].clone();
248 }
249 }
250}
251
252/// Rejects a slice longer than the largest array, an input Java cannot pass.
253fn check_array_length(length: usize, name: &str) -> Result<(), GraphError> {
254 if length > MAX_ARRAY_LENGTH as usize {
255 return Err(GraphError::invalid_argument(format!(
256 "{name} has {length} entries, more than the largest array of {MAX_ARRAY_LENGTH}"
257 )));
258 }
259 Ok(())
260}
261
262/// Rejects an array whose length is not the expected one.
263#[track_caller]
264pub(crate) fn check_length(length: usize, expected: usize, name: &str) {
265 if length != expected {
266 invalid_argument!("{name} has length {length}, expected {expected}");
267 }
268}
269
270/// A mapping from the node IDs of one graph to those of another, to extract a subgraph or to
271/// renumber the nodes of a graph.
272///
273/// [`get(node)`](Self::get) is the node ID that `node` maps to, or `None` if `node` is not mapped. The
274/// factories return mappings from a new graph to an old one. These map each new node to the node it
275/// comes from:
276///
277/// - [`for_subgraph`](Self::for_subgraph), [`for_subgraph_sorted`](Self::for_subgraph_sorted) and
278/// [`for_subgraph_mask`](Self::for_subgraph_mask) - the selected nodes, numbered in ascending
279/// order;
280/// - [`for_permutation`](Self::for_permutation) - every node, in an order of the caller's choice;
281/// - [`reindex`](Self::reindex) - every node, in depth-first preorder;
282/// - [`of`](Self::of) - any mapping, from an array.
283///
284/// [`graphs::remapped`](crate::graphs::remapped) builds the new graph from the old one, and
285/// [`gather`](Self::gather) carries data on the old nodes, such as their names, over to the new
286/// ones. Here, `calls` holds the calls between the methods of a program, and the methods that `load`
287/// reaches become a graph of their own, with their names from `names`:
288///
289/// <!-- example: mappings.rs#subgraph -->
290/// ```
291/// # use graphity_core::{NodeMapping, graphs};
292/// # let calls = graphity_core::Graph::of(
293/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
294/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
295/// # ).unwrap();
296/// # let names: &[&str] = &[
297/// # "main", "parseArgs", "run", "load", "save", "show", "parse", "format", "read", "write",
298/// # ];
299/// # let load = 3;
300/// let new_to_old =
301/// NodeMapping::for_subgraph_sorted(&graphs::reachable_from(&calls, load))?;
302/// let loading = graphs::remapped(&calls, &new_to_old);
303/// let loading_names = new_to_old.gather(names);
304/// // loading_names: ["load", "parse", "read"]
305/// // loading: load -> parse, load -> read, parse -> parse
306/// # assert_eq!(loading_names, ["load", "parse", "read"]);
307/// # assert_eq!(graphs::adjacency_list_of(&loading), "0 -> [1, 2]\n1 -> [1]\n2 -> []\n");
308/// # Ok::<(), graphity_core::GraphError>(())
309/// ```
310///
311/// [`graphs::edge_mapping`](crate::graphs::edge_mapping) derives the [`EdgeMapping`] that carries
312/// data on edges. [`inverted`](Self::inverted) returns the mapping from old to new, and
313/// [`compose`](Self::compose) chains two mappings.
314///
315/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
316///
317/// **Memory:** 4 x index_count bytes.
318#[derive(Debug, Clone, PartialEq, Eq, Hash)]
319pub struct NodeMapping {
320 mapping: Box<[u32]>,
321 valid: u32,
322}
323
324impl NodeMapping {
325 fn from_parts(mapping: Vec<u32>, valid: u32) -> Self {
326 Self {
327 mapping: mapping.into_boxed_slice(),
328 valid,
329 }
330 }
331
332 #[inline]
333 fn mapping_slice(&self) -> &[u32] {
334 &self.mapping
335 }
336
337 #[inline]
338 fn valid_count(&self) -> u32 {
339 self.valid
340 }
341
342 /// The array behind the mapping, for the algorithms of this crate.
343 #[inline]
344 pub(crate) fn as_array(&self) -> &[u32] {
345 &self.mapping
346 }
347
348 /// Returns the mapping that maps each node `i` to `mapping[i]`, and leaves it unmapped where that is
349 /// [`NONE`] - Java's `-1`.
350 ///
351 /// Use it for mappings that the other factories do not cover, from new to old or from old to new. The
352 /// slice is copied. Each value must be [`NONE`] or a node ID, and no two nodes may map to the same
353 /// node; without a graph, this function can only reject a value at or above `2^31`, which is negative
354 /// in Java's 32-bit IDs. [`graphs::remapped`](crate::graphs::remapped) rejects a value that is not a
355 /// node of its graph, and both it and [`inverted`](Self::inverted) reject two nodes that map to the
356 /// same node.
357 ///
358 /// **Time:** O(mapping.len()).
359 /// **Memory:** 4 x mapping.len() bytes for the copy, which the result keeps.
360 ///
361 /// # Errors
362 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if a value is neither [`NONE`]
363 /// nor below `2^31`; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if the slice is
364 /// longer than the largest array, `2^31 - 9`.
365 pub fn of(mapping: &[u32]) -> Result<NodeMapping, GraphError> {
366 check_array_length(mapping.len(), "mapping")?;
367 if let Some(node) = mapping
368 .iter()
369 .position(|&t| t != NONE && is_negative_in_java(t))
370 {
371 return Err(GraphError::index_out_of_bounds(format!(
372 "a mapping value must be NONE or a node ID, but node {node} maps to {}",
373 mapping[node]
374 )));
375 }
376 Ok(Self::from_parts(mapping.to_vec(), count_valid(mapping)))
377 }
378
379 /// Returns a mapping from the nodes of a subgraph to the selected nodes, given as a mask: node `v`
380 /// is selected if `selected[v]` is `true` - Java's overload `forSubgraph(BitSet)`.
381 ///
382 /// The selected nodes get the new node IDs `0..k`, where k is the number of selected nodes, in
383 /// ascending order of their node IDs. The selected node IDs are checked against a graph only when the
384 /// mapping is used: [`graphs::remapped`](crate::graphs::remapped) rejects one that is not a node of
385 /// its graph.
386 ///
387 /// **Time:** O(selected.len()).
388 /// **Memory:** 4 x k bytes for the result.
389 ///
390 /// # Errors
391 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if an entry at or above `2^31`
392 /// is selected: that ID is negative in Java's 32-bit IDs, which a `BitSet` cannot hold.
393 pub fn for_subgraph_mask(selected: &[bool]) -> Result<NodeMapping, GraphError> {
394 let java_ids = selected.len().min(1 << 31);
395 if let Some(i) = selected[java_ids..].iter().position(|&s| s) {
396 return Err(GraphError::index_out_of_bounds(format!(
397 "selected node ID must be below 2^31: {}",
398 java_ids + i
399 )));
400 }
401 // Counted first, as Java counts the set bits, so that the mapping has exactly its length.
402 let mut map = Vec::with_capacity(selected.iter().filter(|&&s| s).count());
403 map.extend((0..java_ids as u32).filter(|&v| selected[v as usize]));
404 let k = map.len() as u32;
405 Ok(Self::from_parts(map, k))
406 }
407
408 /// Returns a mapping from the nodes of a subgraph to the selected nodes, given as node IDs - Java's
409 /// overloads `forSubgraph(IntList)` and `forSubgraph(int...)`.
410 ///
411 /// The selected nodes get the new node IDs `0..selected.len()`, in ascending order of their node IDs,
412 /// whatever the order of the slice; the slice is sorted in a copy. For a [`SortedIntView`], as
413 /// [`graphs::reachable_from`](crate::graphs::reachable_from) and
414 /// [`NodePartition::nodes_of`](crate::NodePartition::nodes_of) return it,
415 /// [`for_subgraph_sorted`](Self::for_subgraph_sorted) skips the sort. As with
416 /// [`for_subgraph_mask`](Self::for_subgraph_mask), the node IDs are checked against a graph only when
417 /// the mapping is used.
418 ///
419 /// **Time:** O(k log k), where k is `selected.len()`.
420 /// **Memory:** 4 x selected.len() bytes for the result.
421 ///
422 /// # Errors
423 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if a node ID is at or above
424 /// `2^31`, negative in Java's 32-bit IDs; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument)
425 /// error if a node ID occurs more than once.
426 pub fn for_subgraph(selected: &[u32]) -> Result<NodeMapping, GraphError> {
427 let mut map = selected.to_vec();
428 map.sort_unstable();
429 check_selection(&map)?;
430 let k = map.len() as u32;
431 Ok(Self::from_parts(map, k))
432 }
433
434 /// Returns a mapping from the nodes of a subgraph to the selected nodes, given as a
435 /// [`SortedIntView`], which is taken as it is - the `SortedIntView` case of Java's
436 /// `forSubgraph(IntList)`.
437 ///
438 /// The selected nodes get the new node IDs `0..selected.len()`, in ascending order of their node IDs.
439 /// As with [`for_subgraph_mask`](Self::for_subgraph_mask), the node IDs are checked against a graph
440 /// only when the mapping is used.
441 ///
442 /// **Time:** O(k), where k is `selected.len()`.
443 /// **Memory:** 4 x selected.len() bytes for the result.
444 ///
445 /// # Errors
446 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if a node ID is at or above
447 /// `2^31`, negative in Java's 32-bit IDs.
448 pub fn for_subgraph_sorted(selected: &SortedIntView<'_>) -> Result<NodeMapping, GraphError> {
449 check_selection(selected)?;
450 Ok(Self::from_parts(selected.to_vec(), selected.len() as u32))
451 }
452
453 /// Returns a mapping that numbers the nodes in the given order, from new to old node IDs.
454 ///
455 /// `order[new_node]` is the node that gets the new node ID `new_node`. `order` holds every node ID in
456 /// `0..order.len()` once, so the mapping maps every node. For example,
457 /// `NodeMapping::for_permutation(&top_order::of(&dag)?)` numbers the nodes of a DAG (directed acyclic
458 /// graph) in topological order, so that every edge of the remapped graph goes from a lower to a higher
459 /// node ID.
460 ///
461 /// **Time:** O(order.len()).
462 /// **Memory:** 4 x order.len() bytes for the result; while it runs, 1 bit per node.
463 ///
464 /// # Errors
465 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if a node ID is not in
466 /// `0..order.len()`; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if a node ID
467 /// occurs more than once or the slice is longer than the largest array, `2^31 - 9`.
468 pub fn for_permutation(order: &[u32]) -> Result<NodeMapping, GraphError> {
469 check_array_length(order.len(), "order")?;
470 let n = order.len();
471 // One bit per node, as Java's BitSet.
472 let mut seen = vec![0u64; n.div_ceil(64)];
473 for (i, &old) in order.iter().enumerate() {
474 if old as usize >= n {
475 return Err(GraphError::index_out_of_bounds(format!(
476 "order value out of range 0..{n} at position {i}: {old}"
477 )));
478 }
479 let (word, bit) = (old as usize >> 6, 1u64 << (old & 63));
480 if seen[word] & bit != 0 {
481 return Err(GraphError::invalid_argument(format!(
482 "order contains {old} more than once"
483 )));
484 }
485 seen[word] |= bit;
486 }
487 Ok(Self::from_parts(order.to_vec(), n as u32))
488 }
489
490 /// Returns the inverse mapping, which maps `get(node)` back to `node`.
491 ///
492 /// The inverse maps the `target_count` nodes of the graph that this mapping maps to; a node that no
493 /// node maps to is not mapped, and the inverse is then partial. For a mapping from new to old node
494 /// IDs, as the factories return it, `target_count` is the node count of the old graph, and the
495 /// inverse gives the new node ID of an old node:
496 /// `new_to_old.inverted(old_graph.node_count()).get(old_node)`.
497 ///
498 /// **Time:** O(index_count + target_count).
499 /// **Memory:** 4 x target_count bytes for the result.
500 ///
501 /// # Panics
502 /// With an `invalid argument` message if `target_count` is larger than `2^31 - 9`, or two nodes map
503 /// to the same node; with an `index out of bounds` message if a node maps to `target_count` or more.
504 #[track_caller]
505 pub fn inverted(&self, target_count: u32) -> NodeMapping {
506 Self::from_parts(invert_array(&self.mapping, target_count), self.valid)
507 }
508
509 /// Returns the mapping that applies `inner` first and then this mapping.
510 ///
511 /// If `inner` maps the nodes of a graph A to those of B, and this mapping maps B to C, the result
512 /// maps A to C. A node is not mapped in the result if `inner` does not map it, or if this mapping
513 /// does not map the node that `inner` maps it to. For mappings from new to old node IDs,
514 /// `first_to_original.compose(&second_to_first)` maps the nodes of a graph remapped twice back to
515 /// those of the original one.
516 ///
517 /// **Time:** O(inner.index_count()).
518 /// **Memory:** 4 x inner.index_count() bytes for the result.
519 ///
520 /// # Panics
521 /// With an `index out of bounds` message if `inner` maps a node to a node ID outside
522 /// `0..index_count()`.
523 #[track_caller]
524 pub fn compose(&self, inner: &NodeMapping) -> NodeMapping {
525 let composed = compose_arrays(&self.mapping, &inner.mapping);
526 let valid = count_valid(&composed);
527 Self::from_parts(composed, valid)
528 }
529
530 /// Returns `values` renumbered by this mapping: the value at position `i` of the result is
531 /// `values[get(i)]`, or `T::default()` - Java's `0` - if `i` is not mapped.
532 ///
533 /// For a mapping from new to old node IDs, as the factories return it, this carries data on the nodes
534 /// of the old graph over to the new graph. This is one generic function for every `Copy` type; Java
535 /// has one per primitive type. [`gather_into`](Self::gather_into) does the same for other types, such
536 /// as `String`.
537 ///
538 /// **Time:** O(index_count).
539 /// **Memory:** `size_of::<T>()` x index_count bytes for the result.
540 ///
541 /// # Panics
542 /// With an `index out of bounds` message if a node maps to a node ID outside `values`.
543 #[track_caller]
544 pub fn gather<T: Copy + Default>(&self, values: &[T]) -> Vec<T> {
545 gather_array(&self.mapping, values)
546 }
547
548 /// Writes `values` renumbered by this mapping into `new_values`, for values that are not `Copy`,
549 /// such as names - Java's overload `gather(T[], T[])`.
550 ///
551 /// `new_values[i]` becomes a clone of `values[get(i)]`, and stays as it is if `i` is not mapped. If it
552 /// panics, `new_values` may be partly written. The borrow rules guarantee that the two slices are not
553 /// the same; Java checks this.
554 ///
555 /// **Time:** O(index_count).
556 ///
557 /// # Panics
558 /// With an `invalid argument` message if `new_values.len() != index_count()`; with an
559 /// `index out of bounds` message if a node maps to a node ID outside `values`.
560 #[track_caller]
561 pub fn gather_into<T: Clone>(&self, values: &[T], new_values: &mut [T]) {
562 gather_array_into(&self.mapping, values, new_values);
563 }
564
565 /// Returns a mapping that numbers the nodes of `graph` in depth-first preorder, from new to old node
566 /// IDs.
567 ///
568 /// The search starts at node 0, follows the out-nodes of each node in ascending order, and starts
569 /// again at the smallest node not yet visited until it has visited every node; each node gets the next
570 /// new node ID when the search reaches it. Nodes that the search visits one after another thus get
571 /// adjacent node IDs. Traversals of the remapped graph then read its arrays more in order, which can
572 /// make them faster on large graphs.
573 ///
574 /// **Time:** O(node_count + edge_count).
575 /// **Memory:** 4 x node_count bytes for the result; while it runs, 1 bit per node and up to
576 /// 8 x node_count bytes for the stack, which grows with the deepest path.
577 ///
578 /// # Panics
579 /// With an `invalid argument` message if a depth-first path is longer than `2^30 - 5` nodes.
580 pub fn reindex(graph: &Graph) -> NodeMapping {
581 let n = graph.node_count() as usize;
582 let out = graph.out_adjacency_start();
583 let adj = graph.out_adjacency();
584 // Visited bits, one per node, as raw words, so that the inner scan tests and sets a bit
585 // with one load and one store.
586 let mut visited = vec![0u64; (n >> 6) + 1];
587 let mut order = vec![0u32; n];
588 let mut pos = 0usize;
589 // Each frame is two interleaved entries, the node and its resume position in the
590 // adjacency array; the stack grows on demand.
591 let mut frames = dfs_frames::initial(n as u32);
592
593 let mut root = next_clear_bit(&visited, 0);
594 while root < n {
595 visited[root >> 6] |= 1 << (root & 63);
596 order[pos] = root as u32;
597 pos += 1;
598 frames[0] = root as u32;
599 frames[1] = out[root];
600 let mut top = 0usize;
601
602 'outer: loop {
603 let u = frames[2 * top] as usize;
604 let end = out[u + 1] as usize;
605 // Tight neighbor scan: the frame is touched only when the search descends.
606 let mut i = frames[2 * top + 1] as usize;
607 while i < end {
608 let v = adj[i] as usize;
609 i += 1;
610 let (w, mask) = (v >> 6, 1u64 << (v & 63));
611 let bits = visited[w];
612 if bits & mask == 0 {
613 visited[w] = bits | mask;
614 order[pos] = v as u32;
615 pos += 1;
616 frames[2 * top + 1] = i as u32;
617 top += 1;
618 if top == frames.len() >> 1 {
619 dfs_frames::grow(&mut frames, n as u32);
620 }
621 frames[2 * top] = v as u32;
622 frames[2 * top + 1] = out[v];
623 continue 'outer;
624 }
625 }
626 if top == 0 {
627 break;
628 }
629 top -= 1;
630 }
631 root = next_clear_bit(&visited, root + 1);
632 }
633 Self::from_parts(order, n as u32)
634 }
635}
636
637index_mapping_impl!(NodeMapping);
638
639/// Rejects a repeated ID in a sorted selection, then an ID that is negative in Java's 32-bit IDs;
640/// sorted as `u32`, those come last.
641fn check_selection(sorted: &[u32]) -> Result<(), GraphError> {
642 if let Some(w) = sorted.windows(2).find(|w| w[0] == w[1]) {
643 return Err(GraphError::invalid_argument(format!(
644 "selected contains node {} more than once",
645 w[0]
646 )));
647 }
648 if let Some(&last) = sorted.last().filter(|&&last| is_negative_in_java(last)) {
649 return Err(GraphError::index_out_of_bounds(format!(
650 "selected node ID must be below 2^31: {last}"
651 )));
652 }
653 Ok(())
654}
655
656/// A mapping from the edge indices of one graph to those of another, to carry data on edges over to
657/// a subgraph, a renumbered graph or the transposed graph.
658///
659/// [`get(e)`](Self::get) is the edge index that edge `e` maps to, or `None` if edge `e` is not mapped.
660/// The factories return mappings from a new graph to an old one. These map each new edge to the edge
661/// it comes from. [`graphs::edge_mapping`](crate::graphs::edge_mapping) derives one from the
662/// [`NodeMapping`] of a subgraph or a renumbering, and leaves a new edge without a counterpart in the
663/// old graph unmapped. [`graphs::transposed_edge_mapping`](crate::graphs::transposed_edge_mapping)
664/// maps each edge of the transposed graph to the edge it reverses.
665///
666/// [`gather`](Self::gather) carries data on the old edges over to the new ones. Here, `site_count`
667/// holds the number of call sites of each call by edge index of `calls`, and the subgraph `loading`
668/// from the example at [`NodeMapping`] takes these counts along:
669///
670/// <!-- example: mappings.rs#edgeMapping -->
671/// ```
672/// # use graphity_core::graphs;
673/// # let calls = graphity_core::Graph::of(
674/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
675/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
676/// # ).unwrap();
677/// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
678/// # let new_to_old = graphity_core::NodeMapping::for_subgraph(&[3, 6, 8]).unwrap();
679/// # let loading = graphity_core::graphs::remapped(&calls, &new_to_old);
680/// let loading_site_count =
681/// graphs::edge_mapping(&loading, &calls, &new_to_old).gather(&site_count);
682/// // 1 for load -> parse and for load -> read, 2 for parse -> parse
683/// # assert_eq!(loading_site_count, [1, 1, 2]);
684/// ```
685///
686/// [`inverted`](Self::inverted) returns the mapping from old to new, and [`compose`](Self::compose)
687/// chains two mappings.
688///
689/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
690///
691/// **Memory:** 4 x index_count bytes.
692#[derive(Debug, Clone, PartialEq, Eq, Hash)]
693pub struct EdgeMapping {
694 mapping: Box<[u32]>,
695 valid: u32,
696}
697
698impl EdgeMapping {
699 pub(crate) fn new(mapping: Vec<u32>, valid: u32) -> Self {
700 Self {
701 mapping: mapping.into_boxed_slice(),
702 valid,
703 }
704 }
705
706 /// The body of [`graphs::transposed_edge_mapping`](crate::graphs::transposed_edge_mapping),
707 /// here so that the algorithms that need it do not call the facade, as in Java.
708 pub(crate) fn for_transposed(graph: &Graph) -> EdgeMapping {
709 let n = graph.node_count() as usize;
710 let m = graph.edge_count() as usize;
711 let targets = graph.out_adjacency();
712 let start = graph.out_adjacency_start();
713
714 // Write pointer per target node: where that node's next in-edge slot goes. A bi-adjacent
715 // graph already has those offsets; otherwise count and prefix-sum them.
716 let mut write_pos = match graph.in_adjacency_start_if_present() {
717 Some(in_start) => in_start[..n].to_vec(),
718 None => {
719 let mut write_pos = vec![0u32; n];
720 for &target in targets {
721 write_pos[target as usize] += 1;
722 }
723 let mut next_start = 0u32;
724 for slot in &mut write_pos {
725 let in_degree = *slot;
726 *slot = next_start;
727 next_start += in_degree;
728 }
729 write_pos
730 }
731 };
732
733 // The counting sort of BiAdjacentGraph::of, with the edge index as payload instead of the
734 // source: the ascending node scan makes slot q of the transpose and entry q here one edge.
735 let mut mapping = vec![0u32; m];
736 for node in 0..n {
737 for edge_index in start[node]..start[node + 1] {
738 let slot = &mut write_pos[targets[edge_index as usize] as usize];
739 mapping[*slot as usize] = edge_index;
740 *slot += 1;
741 }
742 }
743 EdgeMapping::new(mapping, m as u32)
744 }
745
746 #[inline]
747 fn mapping_slice(&self) -> &[u32] {
748 &self.mapping
749 }
750
751 #[inline]
752 fn valid_count(&self) -> u32 {
753 self.valid
754 }
755
756 /// The array behind the mapping, handed over to an algorithm of this crate.
757 pub(crate) fn into_array(self) -> Box<[u32]> {
758 self.mapping
759 }
760
761 /// Returns the inverse mapping, which maps `get(e)` back to `e`.
762 ///
763 /// The inverse maps the `target_count` edges of the graph that this mapping maps to; an edge that no
764 /// edge maps to is not mapped, and the inverse is then partial. For a mapping from new to old edge
765 /// indices, as the factories return it, `target_count` is the edge count of the old graph, and the
766 /// inverse gives the new edge index of an old edge:
767 /// `new_to_old.inverted(old_graph.edge_count()).get(old_edge)`.
768 ///
769 /// **Time:** O(index_count + target_count).
770 /// **Memory:** 4 x target_count bytes for the result.
771 ///
772 /// # Panics
773 /// With an `invalid argument` message if `target_count` is larger than `2^31 - 9`, or two edges map
774 /// to the same edge; with an `index out of bounds` message if an edge maps to `target_count` or more.
775 #[track_caller]
776 pub fn inverted(&self, target_count: u32) -> EdgeMapping {
777 Self::new(invert_array(&self.mapping, target_count), self.valid)
778 }
779
780 /// Returns the mapping that applies `inner` first and then this mapping.
781 ///
782 /// If `inner` maps the edges of a graph A to those of B, and this mapping maps B to C, the result
783 /// maps A to C. An edge is not mapped in the result if `inner` does not map it, or if this mapping
784 /// does not map the edge that `inner` maps it to.
785 ///
786 /// **Time:** O(inner.index_count()).
787 /// **Memory:** 4 x inner.index_count() bytes for the result.
788 ///
789 /// # Panics
790 /// With an `index out of bounds` message if `inner` maps an edge to an edge index outside
791 /// `0..index_count()`.
792 #[track_caller]
793 pub fn compose(&self, inner: &EdgeMapping) -> EdgeMapping {
794 let composed = compose_arrays(&self.mapping, &inner.mapping);
795 let valid = count_valid(&composed);
796 Self::new(composed, valid)
797 }
798
799 /// Returns `values` renumbered by this mapping: the value at position `i` of the result is
800 /// `values[get(i)]`, or `T::default()` - Java's `0` - if edge `i` is not mapped.
801 ///
802 /// For a mapping from new to old edge indices, as the factories return it, this carries data on the
803 /// edges of the old graph over to the new graph. This is one generic function for every `Copy` type;
804 /// Java has one per primitive type. [`gather_into`](Self::gather_into) does the same for other types.
805 ///
806 /// **Time:** O(index_count).
807 /// **Memory:** `size_of::<T>()` x index_count bytes for the result.
808 ///
809 /// # Panics
810 /// With an `index out of bounds` message if an edge maps to an edge index outside `values`.
811 #[track_caller]
812 pub fn gather<T: Copy + Default>(&self, values: &[T]) -> Vec<T> {
813 gather_array(&self.mapping, values)
814 }
815
816 /// Writes `values` renumbered by this mapping into `new_values`, for values that are not `Copy` -
817 /// Java's overload `gather(T[], T[])`.
818 ///
819 /// `new_values[i]` becomes a clone of `values[get(i)]`, and stays as it is if edge `i` is not mapped.
820 /// If it panics, `new_values` may be partly written. The borrow rules guarantee that the two slices
821 /// are not the same; Java checks this.
822 ///
823 /// **Time:** O(index_count).
824 ///
825 /// # Panics
826 /// With an `invalid argument` message if `new_values.len() != index_count()`; with an
827 /// `index out of bounds` message if an edge maps to an edge index outside `values`.
828 #[track_caller]
829 pub fn gather_into<T: Clone>(&self, values: &[T], new_values: &mut [T]) {
830 gather_array_into(&self.mapping, values, new_values);
831 }
832}
833
834index_mapping_impl!(EdgeMapping);
835
836#[cfg(test)]
837mod tests {
838 use graphity_testutils::panic_message;
839
840 use super::*;
841 use crate::{GraphBuilder, graphs};
842
843 const N: u32 = NONE;
844
845 // EdgeMapping shares get, is_partial, inversion and composition with NodeMapping, which its
846 // own tests cover; here only what is EdgeMapping-specific, as in Java's EdgeMappingTest.
847
848 #[test]
849 fn inverse_returns_edge_mapping() {
850 let em = EdgeMapping::new(vec![2, 0, 1], 3);
851 let inv: EdgeMapping = em.inverted(3);
852 assert_eq!(inv.get(0), Some(1));
853 assert_eq!(inv.get(1), Some(2));
854 assert_eq!(inv.get(2), Some(0));
855 }
856
857 #[test]
858 fn compose_returns_edge_mapping() {
859 let outer = EdgeMapping::new(vec![10, 20, 30], 3);
860 let inner = EdgeMapping::new(vec![1, 0, 2], 3);
861 let composed: EdgeMapping = outer.compose(&inner);
862 assert_eq!(composed.get(0), Some(20));
863 assert_eq!(composed.get(1), Some(10));
864 assert_eq!(composed.get(2), Some(30));
865 }
866
867 #[test]
868 fn inverse_of_mapping_with_holes_is_partial() {
869 let em = EdgeMapping::new(vec![2, N, 0], 2);
870 let inv = em.inverted(3);
871 assert!(inv.is_partial());
872 assert_eq!(inv.get(1), None);
873 }
874
875 #[test]
876 fn inverse_covers_the_whole_target_space() {
877 // Path 0 -> 1 -> 2 -> 3 restricted to nodes {0, 1, 2}: the old edge 2 has no new edge.
878 let mut b = GraphBuilder::new();
879 b.add_nodes(4);
880 b.add_path(&[0, 1, 2, 3]);
881 let graph = b.build();
882 let keep = NodeMapping::for_subgraph(&[0, 1, 2]).unwrap();
883 let new_to_old = graphs::edge_mapping(&graphs::remapped(&graph, &keep), &graph, &keep);
884 let old_to_new = new_to_old.inverted(graph.edge_count());
885 assert!(old_to_new.is_partial());
886 assert_eq!(old_to_new.index_count(), 3);
887 assert_eq!(old_to_new.gather(&[0.5, 1.5]), [0.5, 1.5, 0.0]);
888 assert!(
889 panic_message(|| {
890 new_to_old.inverted(1);
891 })
892 .starts_with("index out of bounds")
893 );
894 }
895
896 #[test]
897 fn inverse_rejects_a_target_count_beyond_the_largest_array() {
898 let em = EdgeMapping::new(Vec::new(), 0);
899 let message = panic_message(|| {
900 em.inverted(i32::MAX as u32 - 7);
901 });
902 assert!(message.starts_with("invalid argument") && message.contains("target_count"));
903 }
904
905 #[test]
906 fn compose_with_holes_propagates_partiality() {
907 let outer = EdgeMapping::new(vec![10, 20, 30], 3);
908 let inner = EdgeMapping::new(vec![1, N, 2], 2);
909 let composed = outer.compose(&inner);
910 assert!(composed.is_partial());
911 assert_eq!(composed.get(1), None);
912 }
913
914 #[test]
915 fn gather_moves_edge_values_to_the_new_numbering() {
916 let em = EdgeMapping::new(vec![2, N, 1], 2);
917 assert_eq!(em.gather(&[5, 6, 7]), [7, 0, 6]);
918 assert_eq!(em.gather(&[5i64, 6, 7]), [7, 0, 6]);
919 assert_eq!(em.gather(&[0.5, 1.5, 2.5]), [2.5, 0.0, 1.5]);
920 assert!(
921 panic_message(|| {
922 em.gather(&[5, 6]);
923 })
924 .starts_with("index out of bounds")
925 );
926 assert!(
927 panic_message(|| em.gather_into(&[Some(1); 3], &mut [None; 2]))
928 .starts_with("invalid argument")
929 );
930 let mut new_values = [None; 3];
931 em.gather_into(&[Some(5), Some(6), Some(7)], &mut new_values);
932 assert_eq!(new_values, [Some(7), None, Some(6)]);
933 }
934}