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.algorithms.Algorithm; 011 import graphlab.library.exceptions.InvalidVertexException; 012 013 import java.util.HashMap; 014 import java.util.HashSet; 015 import java.util.Iterator; 016 017 /** 018 * @author Mohammad Ali Rostami 019 * @email ma.rostami@yahoo.com 020 */ 021 022 public class GraphUnion 023 extends Algorithm { 024 public static <VertexType extends BaseVertex 025 , EdgeType extends BaseEdge<VertexType>> 026 BaseGraph<VertexType, EdgeType> union(BaseGraph<VertexType, EdgeType> g1, BaseGraph<VertexType, EdgeType> g2) { 027 BaseGraph<VertexType, EdgeType> g = g1.createEmptyGraph(); 028 HashMap<VertexType, VertexType> temp = new HashMap<VertexType, VertexType>(); 029 HashSet<EdgeType> E = new HashSet<EdgeType>(); 030 031 for (VertexType v : g1) { 032 VertexType vt = (VertexType) v.getCopy(); 033 temp.put(v, vt); 034 g.insertVertex(vt); 035 } 036 for (VertexType v : g2) { 037 VertexType vt = (VertexType) v.getCopy(); 038 temp.put(v, vt); 039 g.insertVertex(vt); 040 } 041 042 Iterator<EdgeType> iet = g1.lightEdgeIterator(); 043 while (iet.hasNext()) { 044 EdgeType e = iet.next(); 045 E.add((EdgeType) e.getCopy(temp.get(e.source), temp.get(e.target))); 046 //E.add(iet.next()); 047 } 048 049 iet = g2.lightEdgeIterator(); 050 while (iet.hasNext()) { 051 EdgeType e = iet.next(); 052 E.add((EdgeType) e.getCopy(temp.get(e.source), temp.get(e.target))); 053 } 054 055 for (EdgeType e : E) { 056 try { 057 g.insertEdge(e); 058 } catch (InvalidVertexException e1) { 059 e1.printStackTrace(); 060 } 061 } 062 return g; 063 } 064 }