1 /*
2 * Created on May 19, 2008
3 *
4 * Copyright (c) 2008, The JUNG Authors
5 *
6 * All rights reserved.
7 *
8 * This software is open-source under the BSD license; see either
9 * "license.txt" or
10 * https://github.com/jrtom/jung/blob/master/LICENSE for a description.
11 */
12 package edu.uci.ics.jung.algorithms.filters;
13
14 import java.util.Collection;
15
16 import com.google.common.base.Predicate;
17
18 import edu.uci.ics.jung.graph.Graph;
19
20 /**
21 * Transforms the input graph into one which contains only those vertices
22 * that pass the specified <code>Predicate</code>. The filtered graph
23 * is a copy of the original graph (same type, uses the same vertex and
24 * edge objects). Only those edges whose entire incident vertex collection
25 * passes the predicate are copied into the new graph.
26 *
27 * @author Joshua O'Madadhain
28 */
29 public class VertexPredicateFilter<V,E> implements Filter<V,E>
30 {
31 protected Predicate<V> vertex_pred;
32
33 /**
34 * Creates an instance based on the specified vertex <code>Predicate</code>.
35 * @param vertex_pred the predicate that specifies which vertices to add to the filtered graph
36 */
37 public VertexPredicateFilter(Predicate<V> vertex_pred)
38 {
39 this.vertex_pred = vertex_pred;
40 }
41
42 @SuppressWarnings("unchecked")
43 public Graph<V,E> apply(Graph<V,E> g)
44 {
45 Graph<V, E> filtered;
46 try
47 {
48 filtered = g.getClass().newInstance();
49 }
50 catch (InstantiationException e)
51 {
52 throw new RuntimeException("Unable to create copy of existing graph: ", e);
53 }
54 catch (IllegalAccessException e)
55 {
56 throw new RuntimeException("Unable to create copy of existing graph: ", e);
57 }
58
59 for (V v : g.getVertices())
60 if (vertex_pred.apply(v))
61 filtered.addVertex(v);
62
63 Collection<V> filtered_vertices = filtered.getVertices();
64
65 for (E e : g.getEdges())
66 {
67 Collection<V> incident = g.getIncidentVertices(e);
68 if (filtered_vertices.containsAll(incident))
69 filtered.addEdge(e, incident);
70 }
71
72 return filtered;
73 }
74
75 }