1
1
use crate :: computation:: { Computation , Operator } ;
2
+ use bitvec:: prelude:: * ;
2
3
use petgraph:: visit:: { depth_first_search, DfsEvent } ;
3
4
4
5
/// Prunes the computation from anything not relevant for the output
5
- pub fn prune_graph ( comp : Computation ) -> anyhow:: Result < Computation > {
6
+ pub fn prune_graph ( mut comp : Computation ) -> anyhow:: Result < Computation > {
6
7
// Need to reverse the graph, because we will be traversing it from the outputs
7
8
let mut graph = comp. as_graph ( ) ;
8
9
graph. reverse ( ) ;
9
10
// Operations to keep
10
- let mut keep = Vec :: with_capacity ( comp. operations . len ( ) ) ;
11
+ let mut keep: BitVec < u8 , Lsb0 > = BitVec :: repeat ( false , comp. operations . len ( ) ) ;
11
12
// Identify all the output nodes
12
13
let outputs = graph
13
14
. node_indices ( )
@@ -16,12 +17,15 @@ pub fn prune_graph(comp: Computation) -> anyhow::Result<Computation> {
16
17
// Perform a DFS
17
18
depth_first_search ( & graph, outputs, |event| {
18
19
if let DfsEvent :: Discover ( visited, _) = event {
19
- keep. push ( comp . operations [ graph[ visited] . index ] . clone ( ) ) ;
20
+ keep. set ( graph[ visited] . index , true ) ;
20
21
} ;
21
22
} ) ;
22
23
23
- // Construct a new computation. NB: we did not toposort it.
24
- Ok ( Computation { operations : keep } )
24
+ let mut iter = keep. iter ( ) ;
25
+ // only keep the operations that were visited by DFS
26
+ comp. operations . retain ( |_| * iter. next ( ) . unwrap ( ) ) ;
27
+
28
+ Ok ( comp)
25
29
}
26
30
27
31
#[ cfg( test) ]
0 commit comments