graphity_core/partition.rs
1//! Partitions of index spaces into disjoint groups: the trait [`IndexPartition`] and its node and
2//! edge specializations [`NodePartition`] and [`EdgePartition`].
3
4use crate::array_limits::MAX_NODE_COUNT;
5use crate::mapping::check_length;
6use crate::{Graph, GraphError, IndexMapping, NONE, SortedIntView, growth, parent_forest};
7
8/// A partition of indices into groups: the common base of [`NodePartition`] and [`EdgePartition`] -
9/// Java's abstract class `IndexPartition`.
10///
11/// The indices are node IDs or edge indices. Each index is in at most one group, and the groups are
12/// numbered by group ID `0..group_count()`. [`get(i)`](IndexMapping::get) returns the group of index
13/// `i`, or `None` if it is in no group, and [`indices_of`](Self::indices_of) the indices of a group in
14/// ascending order. [`reduce`](Self::reduce) combines data on the indices into one value per group.
15/// The data is an array indexed by node ID or edge index.
16///
17/// A partition is a mapping from indices to groups that maps several indices to the same group, so
18/// unlike a [`NodeMapping`](crate::NodeMapping) or an [`EdgeMapping`](crate::EdgeMapping), it cannot
19/// be inverted.
20///
21/// [`NodePartition`], [`EdgePartition`] and [`Sccs`](crate::Sccs) implement this trait. Each of them
22/// has the same methods as inherent methods too, so the trait is needed only for code that is generic
23/// over them. It is sealed, as Java's class hierarchy is. Instances are immutable and safe to share
24/// between threads (`Send` and `Sync`).
25///
26/// **Memory:** 4 x (index_count + mapped_count + group_count) bytes, where mapped_count is the number
27/// of indices that belong to a group.
28pub trait IndexPartition: IndexMapping {
29 /// Returns the number of groups.
30 ///
31 /// **Time:** O(1).
32 fn group_count(&self) -> u32;
33
34 /// Returns the indices in group `group`, in ascending order.
35 ///
36 /// The result is a view of this partition's own array, not a copy.
37 ///
38 /// **Time:** O(1).
39 ///
40 /// # Panics
41 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
42 fn indices_of(&self, group: u32) -> SortedIntView<'_>;
43
44 /// Returns the number of indices in group `group`.
45 ///
46 /// **Time:** O(1).
47 ///
48 /// # Panics
49 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
50 fn size_of(&self, group: u32) -> u32;
51
52 /// Returns one value per group, combined from the values of its indices.
53 ///
54 /// For each group, starts from `identity` and combines the result so far with the value of each index
55 /// in the group, in ascending order of the indices. A group without indices gets `identity`, and the
56 /// values of indices in no group are left out. The result is indexed by group ID. `combine` is called
57 /// with the result so far and the value of the next index, and returns the two combined. This is one
58 /// generic function for every `Copy` type; Java has one per primitive type.
59 /// [`reduce_into`](Self::reduce_into) does the same for other types. Here, `by_package_call` groups
60 /// the calls between the methods of a program by the call between packages that each belongs to (see
61 /// [`EdgePartition`]), and the call sites in `site_count` are summed per call between packages:
62 ///
63 /// <!-- example: partitions.rs#reduce -->
64 /// ```
65 /// # use graphity_core::graphs;
66 /// # let calls = graphity_core::Graph::of(
67 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
68 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
69 /// # ).unwrap();
70 /// # let package_of = [0, 1, 0, 3, 3, 2, 4, 4, 5, 5];
71 /// # let by_package = graphity_core::NodePartition::of(&calls, &package_of, 8).unwrap();
72 /// # let by_package_call = graphs::edge_partition(&by_package.condense(), &by_package);
73 /// # let site_count = [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 2, 1];
74 /// let package_site_count =
75 /// by_package_call.reduce(&site_count, 0, |sum, count| sum + count);
76 /// // 2 for app -> ui, app -> service, service -> model and service -> storage,
77 /// // 1 for app -> cli and ui -> model
78 /// # assert_eq!(package_site_count, [1, 2, 2, 1, 2, 2]);
79 /// ```
80 ///
81 /// **Time:** O(index_count + group_count).
82 /// **Memory:** `size_of::<T>()` x group_count bytes for the result.
83 ///
84 /// # Panics
85 /// With an `invalid argument` message if `values.len() != index_count()`.
86 fn reduce<T: Copy>(&self, values: &[T], identity: T, combine: impl FnMut(T, T) -> T) -> Vec<T>;
87
88 /// Writes one value per group into `group_values`, combined from the values of the indices of that
89 /// group. This is the form of `reduce` for values that are not `Copy` - Java's overload
90 /// `reduce(T[], T[], BinaryOperator)`.
91 ///
92 /// For each group, starts from a clone of the value of its first index and combines the result so far
93 /// with the value of each further index, in ascending order of the indices. That takes one clone per
94 /// group; Java folds references. `combine` is called with the result so far and a reference to the
95 /// value of the next index, and returns the two combined. A group without indices keeps its entry in
96 /// `group_values`, and the values of indices in no group are left out. The borrow rules guarantee that
97 /// the two slices are not the same; Java checks this.
98 ///
99 /// **Time:** O(index_count + group_count).
100 ///
101 /// # Panics
102 /// With an `invalid argument` message if `values.len() != index_count()` or
103 /// `group_values.len() != group_count()`.
104 fn reduce_into<T: Clone>(
105 &self,
106 values: &[T],
107 group_values: &mut [T],
108 combine: impl FnMut(T, &T) -> T,
109 );
110}
111
112/// The arrays of a partition: forward mapping and the members of each group as CSR.
113#[derive(Debug, Clone, PartialEq, Eq, Hash)]
114pub(crate) struct PartitionArrays {
115 /// Index to group, [`NONE`] for an index in no group.
116 pub(crate) mapping: Box<[u32]>,
117 /// The indices of all groups, grouped by group ID, ascending within each group.
118 pub(crate) members: Box<[u32]>,
119 /// Group `g`'s members are `members[member_start[g]..member_start[g + 1]]`.
120 pub(crate) member_start: Box<[u32]>,
121}
122
123impl PartitionArrays {
124 pub(crate) fn new(mapping: Vec<u32>, members: Vec<u32>, member_start: Vec<u32>) -> Self {
125 Self {
126 mapping: mapping.into_boxed_slice(),
127 members: members.into_boxed_slice(),
128 member_start: member_start.into_boxed_slice(),
129 }
130 }
131
132 #[inline]
133 pub(crate) fn group_count(&self) -> u32 {
134 (self.member_start.len() - 1) as u32
135 }
136
137 #[inline]
138 #[track_caller]
139 pub(crate) fn indices_of(&self, group: u32) -> SortedIntView<'_> {
140 crate::error::check_index(group, self.group_count());
141 let g = group as usize;
142 SortedIntView::new(
143 &self.members[self.member_start[g] as usize..self.member_start[g + 1] as usize],
144 )
145 }
146
147 #[inline]
148 #[track_caller]
149 pub(crate) fn size_of(&self, group: u32) -> u32 {
150 crate::error::check_index(group, self.group_count());
151 let g = group as usize;
152 self.member_start[g + 1] - self.member_start[g]
153 }
154
155 #[track_caller]
156 pub(crate) fn reduce<T: Copy>(
157 &self,
158 values: &[T],
159 identity: T,
160 mut combine: impl FnMut(T, T) -> T,
161 ) -> Vec<T> {
162 check_length(values.len(), self.mapping.len(), "values");
163 self.member_start
164 .windows(2)
165 .map(|w| {
166 self.members[w[0] as usize..w[1] as usize]
167 .iter()
168 .fold(identity, |acc, &m| combine(acc, values[m as usize]))
169 })
170 .collect()
171 }
172
173 #[track_caller]
174 pub(crate) fn reduce_into<T: Clone>(
175 &self,
176 values: &[T],
177 group_values: &mut [T],
178 mut combine: impl FnMut(T, &T) -> T,
179 ) {
180 check_length(values.len(), self.mapping.len(), "values");
181 check_length(
182 group_values.len(),
183 self.group_count() as usize,
184 "group_values",
185 );
186 for (slot, w) in group_values.iter_mut().zip(self.member_start.windows(2)) {
187 let members = &self.members[w[0] as usize..w[1] as usize];
188 if let Some((&first, rest)) = members.split_first() {
189 *slot = rest.iter().fold(values[first as usize].clone(), |acc, &m| {
190 combine(acc, &values[m as usize])
191 });
192 }
193 }
194 }
195}
196
197/// Implements the inherent methods of [`IndexPartition`] and the trait itself for a type with the
198/// private method `arrays()`.
199macro_rules! index_partition_impl {
200 ($ty:ty) => {
201 impl $ty {
202 #[inline]
203 fn mapping_slice(&self) -> &[u32] {
204 &self.arrays().mapping
205 }
206
207 #[inline]
208 fn valid_count(&self) -> u32 {
209 self.arrays().members.len() as u32
210 }
211
212 /// Returns the number of groups.
213 ///
214 /// **Time:** O(1).
215 #[inline]
216 pub fn group_count(&self) -> u32 {
217 self.arrays().group_count()
218 }
219
220 /// Returns the indices in group `group`, in ascending order.
221 ///
222 /// The result is a view of this partition's own array, not a copy.
223 ///
224 /// **Time:** O(1).
225 ///
226 /// # Panics
227 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
228 #[inline]
229 #[track_caller]
230 pub fn indices_of(&self, group: u32) -> $crate::SortedIntView<'_> {
231 self.arrays().indices_of(group)
232 }
233
234 /// Returns the number of indices in group `group`.
235 ///
236 /// **Time:** O(1).
237 ///
238 /// # Panics
239 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
240 #[inline]
241 #[track_caller]
242 pub fn size_of(&self, group: u32) -> u32 {
243 self.arrays().size_of(group)
244 }
245
246 /// Returns one value per group, combined from the values of its indices.
247 ///
248 /// For each group, starts from `identity` and combines the result so far with the value of each index
249 /// in the group, in ascending order of the indices. A group without indices gets `identity`, and the
250 /// values of indices in no group are left out. The result is indexed by group ID. `combine` is called
251 /// with the result so far and the value of the next index, and returns the two combined. This is one
252 /// generic function for every `Copy` type; Java has one per primitive type.
253 /// [`reduce_into`](Self::reduce_into) does the same for other types.
254 ///
255 /// **Time:** O(index_count + group_count).
256 /// **Memory:** `size_of::<T>()` x group_count bytes for the result.
257 ///
258 /// # Panics
259 /// With an `invalid argument` message if `values.len() != index_count()`.
260 #[track_caller]
261 pub fn reduce<T: Copy>(
262 &self,
263 values: &[T],
264 identity: T,
265 combine: impl FnMut(T, T) -> T,
266 ) -> Vec<T> {
267 self.arrays().reduce(values, identity, combine)
268 }
269
270 /// Writes one value per group into `group_values`, combined from the values of the indices of that
271 /// group. This is the form of `reduce` for values that are not `Copy` - Java's overload
272 /// `reduce(T[], T[], BinaryOperator)`.
273 ///
274 /// For each group, starts from a clone of the value of its first index and combines the result so far
275 /// with the value of each further index, in ascending order of the indices. That takes one clone per
276 /// group; Java folds references. `combine` is called with the result so far and a reference to the
277 /// value of the next index, and returns the two combined. A group without indices keeps its entry in
278 /// `group_values`, and the values of indices in no group are left out. The borrow rules guarantee that
279 /// the two slices are not the same; Java checks this.
280 ///
281 /// **Time:** O(index_count + group_count).
282 ///
283 /// # Panics
284 /// With an `invalid argument` message if `values.len() != index_count()` or
285 /// `group_values.len() != group_count()`.
286 #[track_caller]
287 pub fn reduce_into<T: Clone>(
288 &self,
289 values: &[T],
290 group_values: &mut [T],
291 combine: impl FnMut(T, &T) -> T,
292 ) {
293 self.arrays().reduce_into(values, group_values, combine)
294 }
295 }
296
297 $crate::mapping::index_mapping_impl!($ty);
298
299 impl $crate::IndexPartition for $ty {
300 #[inline]
301 fn group_count(&self) -> u32 {
302 <$ty>::group_count(self)
303 }
304
305 #[inline]
306 fn indices_of(&self, group: u32) -> $crate::SortedIntView<'_> {
307 <$ty>::indices_of(self, group)
308 }
309
310 #[inline]
311 fn size_of(&self, group: u32) -> u32 {
312 <$ty>::size_of(self, group)
313 }
314
315 fn reduce<T: Copy>(
316 &self,
317 values: &[T],
318 identity: T,
319 combine: impl FnMut(T, T) -> T,
320 ) -> Vec<T> {
321 <$ty>::reduce(self, values, identity, combine)
322 }
323
324 fn reduce_into<T: Clone>(
325 &self,
326 values: &[T],
327 group_values: &mut [T],
328 combine: impl FnMut(T, &T) -> T,
329 ) {
330 <$ty>::reduce_into(self, values, group_values, combine)
331 }
332 }
333 };
334}
335
336/// A partition of the nodes of a graph into groups, such as its components.
337///
338/// [`get(node)`](Self::get) returns the group of `node`, or `None` if it is in no group, and
339/// [`nodes_of`](Self::nodes_of) the nodes of a group in ascending order.
340/// [`components`](crate::components) returns partitions into components, in which every node is in
341/// exactly one group: an [`Sccs`](crate::Sccs) for the strongly connected components, a plain
342/// `NodePartition` for the weakly connected ones. [`NodePartition::of`] takes groups of the caller's
343/// choice, which may leave nodes out.
344///
345/// A partition holds the graph whose nodes it partitions. [`condense`](Self::condense) builds the
346/// condensed graph, with a node for each group and an edge between two groups wherever an edge of the
347/// graph runs between them. [`graphs::edge_partition`](crate::graphs::edge_partition) builds the
348/// [`EdgePartition`] that tells which edges of the graph are behind each edge of the condensed graph.
349/// The functions for groups of any kind, such as [`group_count`](Self::group_count),
350/// [`size_of`](Self::size_of) and [`reduce`](Self::reduce), come from [`IndexPartition`].
351///
352/// ```
353/// use graphity_core::{graphs, GraphBuilder, NodePartition, NONE};
354///
355/// let mut b = GraphBuilder::new();
356/// b.add_nodes(4);
357/// b.add_path(&[0, 1, 2, 3]);
358/// let graph = b.build();
359///
360/// let packages = NodePartition::of(&graph, &[0, 0, 1, NONE], 2).unwrap();
361/// assert_eq!(packages.nodes_of(0), [0, 1]);
362/// let condensed = packages.condense(); // node IDs are group IDs
363/// assert_eq!(condensed.out_nodes(0), [1]);
364/// let behind = graphs::edge_partition(&condensed, &packages);
365/// assert_eq!(behind.edges_of(0), [1]); // the edge 1 -> 2 behind 0 -> 1
366/// ```
367///
368/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
369///
370/// **Memory:** 4 x (node_count + mapped_count + group_count) bytes, where mapped_count is the number
371/// of nodes that belong to a group; the graph is shared, not copied.
372#[derive(Debug, Clone)]
373pub struct NodePartition {
374 graph: Graph,
375 arrays: PartitionArrays,
376}
377
378impl NodePartition {
379 pub(crate) fn from_parts(
380 graph: &Graph,
381 node_to_group: Vec<u32>,
382 members: Vec<u32>,
383 member_start: Vec<u32>,
384 ) -> Self {
385 Self {
386 graph: graph.clone(),
387 arrays: PartitionArrays::new(node_to_group, members, member_start),
388 }
389 }
390
391 #[inline]
392 fn arrays(&self) -> &PartitionArrays {
393 &self.arrays
394 }
395
396 /// The arrays, for [`Sccs`](crate::Sccs).
397 #[inline]
398 pub(crate) fn arrays_ref(&self) -> &PartitionArrays {
399 &self.arrays
400 }
401
402 /// The graph the partition was computed from.
403 #[inline]
404 pub(crate) fn graph(&self) -> &Graph {
405 &self.graph
406 }
407
408 /// The node-to-group array, for the algorithms of this crate.
409 #[inline]
410 pub(crate) fn group_array(&self) -> &[u32] {
411 &self.arrays.mapping
412 }
413
414 /// The members of all groups, for the algorithms of this crate.
415 #[inline]
416 pub(crate) fn member_arrays(&self) -> (&[u32], &[u32]) {
417 (&self.arrays.members, &self.arrays.member_start)
418 }
419
420 /// Returns a partition of the nodes of `graph` into groups of the caller's choice.
421 ///
422 /// `group_of[node]` is the group of each node, in `0..group_count`, or [`NONE`] for a node in no
423 /// group; the slice is copied. A group may have no nodes: it becomes a node without edges in
424 /// [`condense`](Self::condense), so that group IDs from a numbering of the caller stay valid. Here,
425 /// `package_of` holds the package of each method of `calls` as a node ID of the package graph
426 /// `dependencies`, and the condensed graph shows which packages call which:
427 ///
428 /// <!-- example: partitions.rs#of -->
429 /// ```
430 /// # use graphity_core::NodePartition;
431 /// # let calls = graphity_core::Graph::of(
432 /// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
433 /// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
434 /// # ).unwrap();
435 /// # let dependencies = graphity_core::Graph::of(
436 /// # &[0, 3, 4, 7, 9, 10, 13, 14, 14],
437 /// # &[1, 2, 3, 7, 3, 4, 7, 4, 5, 5, 4, 6, 7, 7],
438 /// # ).unwrap();
439 /// # let package_of = [0, 1, 0, 3, 3, 2, 4, 4, 5, 5];
440 /// let by_package = NodePartition::of(&calls, &package_of, dependencies.node_count())?;
441 /// let package_calls = by_package.condense();
442 /// // package_calls: app -> [cli, ui, service], ui -> [model],
443 /// // service -> [model, storage]
444 /// # assert_eq!(
445 /// # graphity_core::graphs::adjacency_list_of(&package_calls),
446 /// # "0 -> [1, 2, 3]\n1 -> []\n2 -> [4]\n3 -> [4, 5]\n4 -> []\n5 -> []\n6 -> []\n7 -> []\n"
447 /// # );
448 /// # Ok::<(), graphity_core::GraphError>(())
449 /// ```
450 ///
451 /// **Time:** O(node_count + group_count).
452 /// **Memory:** 4 x (node_count + mapped_count + group_count) bytes for the result.
453 ///
454 /// # Errors
455 /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if a group is neither [`NONE`]
456 /// nor in `0..group_count`; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if
457 /// `group_of.len() != graph.node_count()`, or `group_count` is larger than a graph can have nodes,
458 /// `2^31 - 10`.
459 pub fn of(
460 graph: &Graph,
461 group_of: &[u32],
462 group_count: u32,
463 ) -> Result<NodePartition, GraphError> {
464 let n = graph.node_count() as usize;
465 if group_of.len() != n {
466 return Err(GraphError::invalid_argument(format!(
467 "group_of has length {}, expected {n}",
468 group_of.len()
469 )));
470 }
471 if group_count > MAX_NODE_COUNT {
472 return Err(GraphError::invalid_argument(format!(
473 "group_count out of range: {group_count}"
474 )));
475 }
476 let node_to_group = group_of.to_vec();
477 // Counted here rather than in parent_forest::group_indices, so that the range check needs
478 // no pass of its own.
479 let mut member_start = vec![0u32; group_count as usize + 1];
480 for (node, &group) in node_to_group.iter().enumerate() {
481 if group == NONE {
482 continue;
483 }
484 if group >= group_count {
485 return Err(GraphError::index_out_of_bounds(format!(
486 "group of node {node} is {group}, outside 0..{group_count} and not NONE"
487 )));
488 }
489 member_start[group as usize] += 1;
490 }
491 let members = parent_forest::group_counted(&node_to_group, &mut member_start);
492 Ok(Self::from_parts(
493 graph,
494 node_to_group,
495 members,
496 member_start,
497 ))
498 }
499
500 /// Returns the number of nodes of the partitioned graph, in a group or not. Equivalent to
501 /// [`index_count`](Self::index_count).
502 ///
503 /// **Time:** O(1).
504 #[inline]
505 pub fn node_count(&self) -> u32 {
506 self.index_count()
507 }
508
509 /// Returns the nodes in group `group`, in ascending order. Equivalent to
510 /// [`indices_of(group)`](Self::indices_of).
511 ///
512 /// The result is a view of this partition's own array, not a copy.
513 ///
514 /// **Time:** O(1).
515 ///
516 /// # Panics
517 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
518 #[inline]
519 #[track_caller]
520 pub fn nodes_of(&self, group: u32) -> SortedIntView<'_> {
521 self.indices_of(group)
522 }
523
524 /// Returns the condensed graph, with a node for each group and an edge between two groups wherever
525 /// an edge of the partitioned graph runs between them.
526 ///
527 /// The node IDs of the condensed graph are the group IDs. It has the edge `g -> h` if a node in group
528 /// `g` has an out-node in group `h` and `g != h`. Edges within a group and edges from or to a node in
529 /// no group are left out. The edges from one group to another become a single edge.
530 /// [`graphs::edge_partition`](crate::graphs::edge_partition) tells which edges are behind each edge of
531 /// the condensed graph. For an [`Sccs`](crate::Sccs), the condensed graph is acyclic.
532 ///
533 /// The condensed graph is built anew on every call, not cached: keep the result to use it more than
534 /// once.
535 ///
536 /// **Time:** O(node_count + edge_count + group_count), plus O(d log d) for each group with d
537 /// out-nodes in the result.
538 /// **Memory:** 4 x (group_count + condensed_edge_count) bytes for the result, where
539 /// condensed_edge_count is its edge count; while it runs, 1 bit per group and up to
540 /// 6 x condensed_edge_count bytes more.
541 pub fn condense(&self) -> Graph {
542 let groups = self.group_count() as usize;
543 let node_to_group = &self.arrays.mapping;
544 let members = &self.arrays.members;
545 let member_start = &self.arrays.member_start;
546 let adjacency = self.graph.out_adjacency();
547 let adjacency_start = self.graph.out_adjacency_start();
548
549 let mut condensed_start = vec![0u32; groups + 1];
550 let mut condensed_targets: Vec<u32> = Vec::new();
551 // Raw bit words, so that the reset below costs one write per emitted edge.
552 let mut seen = vec![0u64; (groups >> 6) + 1];
553
554 for g in 0..groups {
555 let group_start = condensed_targets.len();
556 condensed_start[g] = group_start as u32;
557 for &u in &members[member_start[g] as usize..member_start[g + 1] as usize] {
558 let u = u as usize;
559 for &target in
560 &adjacency[adjacency_start[u] as usize..adjacency_start[u + 1] as usize]
561 {
562 let target_group = node_to_group[target as usize];
563 if target_group as usize != g && target_group != NONE {
564 let (word, bit) = (target_group as usize >> 6, 1u64 << (target_group & 63));
565 if seen[word] & bit == 0 {
566 seen[word] |= bit;
567 growth::push(&mut condensed_targets, target_group);
568 }
569 }
570 }
571 }
572 // The bits set above are exactly the group's emitted targets, so resetting them costs
573 // one write per emitted edge; zeroing the whole word is safe, every bit in it belongs
574 // to this group.
575 for &h in &condensed_targets[group_start..] {
576 seen[h as usize >> 6] = 0;
577 }
578 condensed_targets[group_start..].sort_unstable();
579 }
580 condensed_start[groups] = condensed_targets.len() as u32;
581 Graph::from_csr_unchecked(condensed_start, condensed_targets)
582 }
583}
584
585index_partition_impl!(NodePartition);
586
587/// A partition of the edges of a graph into groups: the edges behind each edge of a condensed graph,
588/// or the blocks of a graph.
589///
590/// [`get(e)`](Self::get) returns the group of edge `e`, or `None` if it is in no group, and
591/// [`edges_of`](Self::edges_of) the edge indices of a group in ascending order. The groups come from
592/// one of two functions:
593///
594/// - [`graphs::edge_partition`](crate::graphs::edge_partition) groups the edges of the graph of a
595/// [`NodePartition`] by the edge of its condensed graph that they condense to: the group IDs are
596/// the edge indices of the condensed graph. Edges within a group of nodes, and edges from or to a
597/// node in no group, condense to no edge and are in no group.
598/// - [`Biconnectivity::blocks`](crate::Biconnectivity::blocks) groups the edges by block (biconnected
599/// component); self-loops are in no block.
600///
601/// Here, `by_package` groups the methods of a program by package. Its condensed graph `package_calls`
602/// holds the calls between packages (see [`NodePartition::of`]). `by_package_call` tells which calls
603/// between methods are behind the call from `service` to `model`:
604///
605/// <!-- example: partitions.rs#edgesOf -->
606/// ```
607/// # use graphity_core::graphs;
608/// # let calls = graphity_core::Graph::of(
609/// # &[0, 2, 2, 5, 7, 9, 10, 11, 12, 12, 12],
610/// # &[1, 2, 3, 4, 5, 6, 8, 7, 9, 7, 6, 7],
611/// # ).unwrap();
612/// # let package_of = [0, 1, 0, 3, 3, 2, 4, 4, 5, 5];
613/// # let by_package = graphity_core::NodePartition::of(&calls, &package_of, 8).unwrap();
614/// # let package_calls = by_package.condense();
615/// # let (service, model) = (3, 4);
616/// let by_package_call = graphs::edge_partition(&package_calls, &by_package);
617/// let service_to_model = package_calls.edge_index_of(service, model).unwrap();
618/// let behind = by_package_call.edges_of(service_to_model);
619/// // behind: [5, 7] - the calls load -> parse and save -> format
620/// # assert_eq!(behind, [5, 7]);
621/// ```
622///
623/// [`reduce`](Self::reduce) combines data on the edges into one value per group, such as the number
624/// of call sites behind each call between packages.
625///
626/// Instances are immutable and safe to share between threads (`Send` and `Sync`).
627///
628/// **Memory:** 4 x (edge_count + mapped_count + group_count) bytes, where mapped_count is the number
629/// of edges that belong to a group.
630#[derive(Debug, Clone, PartialEq, Eq, Hash)]
631pub struct EdgePartition {
632 arrays: PartitionArrays,
633}
634
635impl EdgePartition {
636 pub(crate) fn new(mapping: Vec<u32>, members: Vec<u32>, member_start: Vec<u32>) -> Self {
637 Self {
638 arrays: PartitionArrays::new(mapping, members, member_start),
639 }
640 }
641
642 #[inline]
643 fn arrays(&self) -> &PartitionArrays {
644 &self.arrays
645 }
646
647 /// Returns the number of edges of the partitioned graph, in a group or not. Equivalent to
648 /// [`index_count`](Self::index_count).
649 ///
650 /// **Time:** O(1).
651 #[inline]
652 pub fn edge_count(&self) -> u32 {
653 self.index_count()
654 }
655
656 /// Returns the edge indices in group `group`, in ascending order. Equivalent to
657 /// [`indices_of(group)`](Self::indices_of).
658 ///
659 /// The result is a view of this partition's own array, not a copy.
660 ///
661 /// **Time:** O(1).
662 ///
663 /// # Panics
664 /// With an `index out of bounds` message if `group` is not in `0..group_count()`.
665 #[inline]
666 #[track_caller]
667 pub fn edges_of(&self, group: u32) -> SortedIntView<'_> {
668 self.indices_of(group)
669 }
670}
671
672index_partition_impl!(EdgePartition);
673
674#[cfg(test)]
675mod tests {
676 use graphity_testutils::panic_message;
677
678 use super::*;
679
680 const N: u32 = NONE;
681
682 /// 6 original edges in 3 condensed groups: 0, 1 -> 0; 2 unmapped; 3 -> 1; 4 unmapped; 5 -> 2.
683 fn sample_edge_partition() -> EdgePartition {
684 EdgePartition::new(vec![0, 0, N, 1, N, 2], vec![0, 1, 3, 5], vec![0, 2, 3, 4])
685 }
686
687 #[test]
688 fn group_count_reports_number_of_condensed_edges() {
689 assert_eq!(sample_edge_partition().group_count(), 3);
690 }
691
692 #[test]
693 fn index_count_reports_total_original_edges() {
694 let p = sample_edge_partition();
695 assert_eq!(p.index_count(), 6);
696 assert_eq!(p.edge_count(), 6);
697 }
698
699 #[test]
700 fn get_returns_condensed_edge_or_none() {
701 let p = sample_edge_partition();
702 let got: Vec<Option<u32>> = (0..6).map(|e| p.get(e)).collect();
703 assert_eq!(got, [Some(0), Some(0), None, Some(1), None, Some(2)]);
704 }
705
706 #[test]
707 fn get_out_of_range_panics() {
708 let p = sample_edge_partition();
709 for edge in [6, 100, u32::MAX] {
710 assert!(
711 panic_message(|| {
712 p.get(edge);
713 })
714 .starts_with("index out of bounds")
715 );
716 assert!(
717 panic_message(|| {
718 p.is_mapped(edge);
719 })
720 .starts_with("index out of bounds")
721 );
722 }
723 }
724
725 #[test]
726 fn is_partial_true_when_intra_group_edges_present() {
727 let p = sample_edge_partition();
728 assert!(p.is_partial());
729 assert_eq!(p.mapped_count(), 4);
730 }
731
732 #[test]
733 fn indices_of_and_edges_of_return_sorted_original_edges() {
734 let p = sample_edge_partition();
735 assert_eq!(p.indices_of(0), [0, 1]);
736 assert_eq!(p.indices_of(1), [3]);
737 assert_eq!(p.indices_of(2), [5]);
738 assert_eq!(p.edges_of(0), [0, 1]);
739 assert_eq!(p.edges_of(1), [3]);
740 assert_eq!(p.edges_of(2), [5]);
741 assert_eq!([p.size_of(0), p.size_of(1), p.size_of(2)], [2, 1, 1]);
742 }
743
744 #[test]
745 fn group_lookups_out_of_range_panic() {
746 let p = sample_edge_partition();
747 for group in [3, 100, u32::MAX] {
748 assert!(
749 panic_message(|| {
750 p.indices_of(group);
751 })
752 .starts_with("index out of bounds")
753 );
754 assert!(
755 panic_message(|| {
756 p.size_of(group);
757 })
758 .starts_with("index out of bounds")
759 );
760 }
761 }
762
763 #[test]
764 fn reduce_folds_the_members_of_each_group() {
765 let p = sample_edge_partition();
766 assert_eq!(
767 p.reduce(&[1, 2, 100, 4, 100, 8], 0, |a, b| a + b),
768 [3, 4, 8]
769 );
770 assert_eq!(
771 p.reduce(&[1i64, 2, 100, 4, 100, 8], 1, |a, b| a * b),
772 [2, 4, 8]
773 );
774 assert_eq!(
775 p.reduce(&[1.0, 2.0, 100.0, 4.0, 100.0, 8.0], 0.0, f64::max),
776 [2.0, 4.0, 8.0]
777 );
778 let mut group_values = vec![String::new(); 3];
779 let values: Vec<String> = ["a", "b", "x", "c", "y", "d"].map(String::from).to_vec();
780 p.reduce_into(&values, &mut group_values, |a, b| a + b);
781 assert_eq!(group_values, ["ab", "c", "d"]);
782 }
783
784 #[test]
785 fn reduce_rejects_arrays_of_the_wrong_length() {
786 let p = sample_edge_partition();
787 assert!(
788 panic_message(|| {
789 p.reduce(&[0; 5], 0, |a, b| a + b);
790 })
791 .starts_with("invalid argument")
792 );
793 assert!(
794 panic_message(|| {
795 p.reduce_into(&[0; 6], &mut [0; 2], |a, b| a + b);
796 })
797 .starts_with("invalid argument")
798 );
799 }
800
801 #[test]
802 fn the_traits_answer_like_the_inherent_methods() {
803 fn total<P: IndexPartition>(p: &P) -> u32 {
804 (0..p.group_count()).map(|g| p.size_of(g)).sum::<u32>() + u32::from(p.is_partial())
805 }
806 let p = sample_edge_partition();
807 assert_eq!(total(&p), 5);
808 assert_eq!(IndexMapping::get(&p, 3), Some(1));
809 }
810}