Skip to content

Commit

Permalink
Add memoization when computing dag and tree cost
Browse files Browse the repository at this point in the history
Some of the tensat examples have a lot more paths than nodes, so this helps them
finish faster.
  • Loading branch information
ezrosent committed Jul 6, 2023
1 parent 39a329e commit 2d3adcc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
17 changes: 13 additions & 4 deletions src/extract/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::collections::HashMap;

pub use crate::*;

pub mod bottom_up;
Expand All @@ -19,34 +21,41 @@ pub trait Extractor: Sync {
#[derive(Clone)]
pub struct ExtractionResult {
pub choices: Vec<Id>,
tree_memo: HashMap<Id, Cost>,
}

impl ExtractionResult {
pub fn new(n_classes: usize) -> Self {
ExtractionResult {
choices: vec![0; n_classes],
tree_memo: HashMap::default(),
}
}

pub fn tree_cost(&self, egraph: &SimpleEGraph, root: Id) -> Cost {
pub fn tree_cost(&mut self, egraph: &SimpleEGraph, root: Id) -> Cost {
if let Some(&cost) = self.tree_memo.get(&root) {
return cost;
}
let node = &egraph[root].nodes[self.choices[root]];
let mut cost = node.cost;
for &child in &node.children {
cost += self.tree_cost(egraph, child);
}
self.tree_memo.insert(root, cost);
cost
}

// this will loop if there are cycles
pub fn dag_cost(&self, egraph: &SimpleEGraph, root: Id) -> Cost {
let mut costs = vec![INFINITY; egraph.classes.len()];
let mut todo = vec![root];
while !todo.is_empty() {
let i = todo.pop().unwrap();
while let Some(i) = todo.pop() {
let node = &egraph[i].nodes[self.choices[i]];
costs[i] = node.cost;
for &child in &node.children {
todo.push(child);
if costs[child] == INFINITY {
todo.push(child);
}
}
}
costs.iter().filter(|c| **c != INFINITY).sum()
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn main() {

for (ext_name, extractor) in &extractors {
let start_time = std::time::Instant::now();
let result = extractor.extract(&egraph, &egraph.roots);
let mut result = extractor.extract(&egraph, &egraph.roots);
let elapsed = start_time.elapsed();
for &root in &egraph.roots {
let msg = format!(
Expand Down

0 comments on commit 2d3adcc

Please sign in to comment.