5e3be06d18cd77ef0a82f5d538c73cf7232162a8
[controller.git] / third-party / net.sf.jung2 / src / main / java / edu / uci / ics / jung / algorithms / filters / EdgePredicateFilter.java
1 /*
2  * Created on May 19, 2008
3  *
4  * Copyright (c) 2008, the JUNG Project and the Regents of the University 
5  * of California
6  * All rights reserved.
7  *
8  * This software is open-source under the BSD license; see either
9  * "license.txt" or
10  * http://jung.sourceforge.net/license.txt for a description.
11  */
12 package edu.uci.ics.jung.algorithms.filters;
13
14 import org.apache.commons.collections15.Predicate;
15
16 import edu.uci.ics.jung.graph.Graph;
17
18 /**
19  * Transforms the input graph into one which contains only those edges 
20  * that pass the specified <code>Predicate</code>.  The filtered graph
21  * is a copy of the original graph (same type, uses the same vertex and
22  * edge objects).  All vertices from the original graph
23  * are copied into the new graph (even if they are not incident to any
24  * edges in the new graph).
25  * 
26  * @author Joshua O'Madadhain
27  */
28 public class EdgePredicateFilter<V, E> implements Filter<V, E>
29 {
30     protected Predicate<E> edge_pred;
31
32     /**
33      * Creates an instance based on the specified edge <code>Predicate</code>.
34      * @param edge_pred   the predicate that specifies which edges to add to the filtered graph
35      */
36     public EdgePredicateFilter(Predicate<E> edge_pred)
37     {
38         this.edge_pred = edge_pred;
39     }
40     
41     @SuppressWarnings("unchecked")
42     public Graph<V,E> transform(Graph<V,E> g)
43     {
44         Graph<V, E> filtered;
45         try
46         {
47             filtered = g.getClass().newInstance();
48         }
49         catch (InstantiationException e)
50         {
51             throw new RuntimeException("Unable to create copy of existing graph: ", e);
52         }
53         catch (IllegalAccessException e)
54         {
55             throw new RuntimeException("Unable to create copy of existing graph: ", e);
56         }
57
58         for (V v : g.getVertices())
59             filtered.addVertex(v);
60         
61         for (E e : g.getEdges())
62         {
63             if (edge_pred.evaluate(e))
64                 filtered.addEdge(e, g.getIncidentVertices(e));
65         }
66         
67         return filtered;
68     }
69
70 }