2

Rust's Petgraph library has a bunch of filter 'adaptors', but I haven't been able to find any examples or tutorials for how to use them. Some (but not all) have constructors, such as EdgeFiltered.from_fn() which takes a graph and a function, but it's not clear how you'd then use it with the search methods like Dfs or astar as they don't have filter parameters.

So how do you use these filters? For example, if I had a graph with integer edge weights how would you:

  1. Perform a depth first search but excluding edges with a negative weight,
  2. Perform an astar search excluding edges with a negative weight?
curiousdannii
  • 1,658
  • 1
  • 25
  • 40

1 Answers1

2

The adapters implement GraphBase, you can just wrap your graph in them and pass the adapter struct to e.g. Dfs:

use petgraph::Graph;
use petgraph::visit::Dfs;
use petgraph::visit::EdgeFiltered;

fn main() {
    let mut graph = Graph::<(), i64>::new();
    let a = graph.add_node(());
    let b = graph.add_node(());
    let e = graph.add_edge(a, b, -1);
    let filtered = EdgeFiltered::from_fn(&graph, |edge_ref| *edge_ref.weight() > 0 );
    let dfs = Dfs::new(&filtered, a);
}

Playground Link

sebpuetz
  • 2,430
  • 1
  • 7
  • 15
  • What about things like https://docs.rs/petgraph/latest/petgraph/visit/struct.NodeFilteredEdges.html# that doesn't have a `from_fn`? – Mossa Jul 20 '22 at 09:18
  • I haven't used petgraph in a long time, but have you checked if https://docs.rs/petgraph/latest/petgraph/visit/struct.NodeFilteredEdges.html#impl-ElementIterator%3CN%2C%20E%3E `filter_elements()` provides what you need? – sebpuetz Jul 20 '22 at 10:28