001 // GraphLab Project: http://graphlab.sharif.edu 002 // Copyright (C) 2008 Mathematical Science Department of Sharif University of Technology 003 // Distributed under the terms of the GNU Lesser General Public License (LGPL): http://www.gnu.org/licenses/ 004 005 package graphlab.library.algorithms.goperators; 006 007 import graphlab.library.BaseEdge; 008 import graphlab.library.BaseGraph; 009 import graphlab.library.BaseVertex; 010 import graphlab.library.exceptions.InvalidVertexException; 011 012 import java.util.Collection; 013 import java.util.HashMap; 014 import java.util.Iterator; 015 016 /** 017 * @author Mohammad Ali Rostami 018 * @email ma.rostami@yahoo.com 019 */ 020 021 public class VertexInduced { 022 public static <VertexType extends BaseVertex, EdgeType extends BaseEdge<VertexType>> 023 BaseGraph<VertexType, EdgeType> induced(BaseGraph<VertexType, EdgeType> g, Collection<VertexType> S) { 024 025 BaseGraph<VertexType, EdgeType> baseGraph = g.createEmptyGraph(); 026 HashMap<VertexType, VertexType> hm = new HashMap<VertexType, VertexType>(); 027 for (VertexType v : g) { 028 VertexType t = (VertexType) v.getCopy(); 029 hm.put(v, t); 030 baseGraph.insertVertex(t); 031 } 032 033 Iterator<EdgeType> i = g.edgeIterator(); 034 while (i.hasNext()) { 035 EdgeType e = i.next(); 036 baseGraph.insertEdge((EdgeType) e.getCopy(hm.get(e.source), hm.get(e.target))); 037 } 038 039 for (VertexType v : g) { 040 if (!S.contains(v)) { 041 try { 042 baseGraph.removeVertex(hm.get(v)); 043 } catch (InvalidVertexException e) { 044 e.printStackTrace(); 045 } 046 } 047 } 048 return baseGraph; 049 } 050 }