/** * TODO: Doesn't preserve edge elements. * * @param left * @param right * @param graph */ public BiGraph( Collection<Vertex<V>> left, Collection<Vertex<V>> right, IGraph<Vertex<V>, V, E> graph) { this(left.size(), Math.max(0, graph.numVertices() - left.size())); // add left and right vertices for (Vertex<V> v : graph.vertices()) { if (left.contains(v)) { insertLeft(v); } else { insertRight(v); } } // add edges going between left and right for (Vertex<V> v : left) { for (Vertex<V> v2 : graph.incidentVertices(v)) { if (right.contains(v2)) { int a = v.id(); int b = v2.id(); Vertex<V> va = this.vList.get(a); Vertex<V> vb = this.vList.get(b); insertEdge(va, vb, null); insertEdge(vb, va, null); } } } }
/** * This returns an enumeration of all Darts in Graph G in a canonical order starting with * firstDart. The order is canonical in the sense that it only depends on the oriented isomorphism * class of G (and firstDart). That is, if there is an oriented iso G <-> G' sending firstDart <-> * firstDart', then that bijection will send getDarts <-> getDarts'. * * <p>This enumeration is useful in finding explicit bijections of isomorphic graphs. */ public static Dart[] getDarts(Dart firstDart, Graph G) { /** * Description of algorithm: Return all the couples around V0=firstDart.V, then all couples * around V1, .... The order for couples around firstDart.V is counterclockwise starting with * firstDart.F. clockwise around V1,... So we need to order the vertices V0,V1,... and pick the * first face to use at each vertex and the rest is determined. Order on V0,... = first * encountered. Order on faces at vertex = first encountered. */ distinctFIFO vQueue = new distinctFIFO(); util.ConditionGetter fQueue = new util.ConditionGetter(); fQueue.add(firstDart.getF()); vQueue.put(firstDart.getV()); Collection coups = new ArrayList(); int coupsIndex = 0; Vertex V; while ((V = (Vertex) vQueue.remove()) != null) { Face F = (Face) fQueue.get(new incidence(V)); for (int i = 0; i < V.size(); i++) { Face Fx = V.next(F, i); coups.add(new Dart(V, Fx)); vQueue.put(Fx.next(V, 1)); fQueue.add(Fx); } } return (Dart[]) coups.toArray(new Dart[coups.size()]); }
/** * Convert graph to bigraph. Just uses methods in parent, but is not a real bigraph. Algorithms * will fail on this graph if BiGraph methods are used. The reason is that some algorithms take * bigraph as parameter but process as graph, so might as well have taken a graph. XXX: This is a * big hack. Doesn't work. Should modify the algorithms instead. * * @param graph */ public BiGraph(IGraph<Vertex<V>, V, E> graph) { this(graph.numVertices(), graph.numVertices()); // add left and right vertices for (Vertex<V> v : graph.vertices()) { Vertex<V> newVertexLeft = createVertex(v.element(), getNextID()); insertVertex(newVertexLeft); this.leftList.add(v); this.isLeft.add(true); this.rightList.add(v); // insertLeft(newVertexLeft); // insertRight(newVertexLeft); } // this.rightList = this.leftList; /*for (Vertex<V> v : graph.vertices()) { Vertex<V> newVertexRight = createVertex(v.element(), getNextID()); insertRight(newVertexRight); // maybe dup it? }*/ // add edges going between left and right for (Edge<Vertex<V>, V, E> e : graph.edges()) { int a = e.endVertices().get(0).id(); int b = e.endVertices().get(1).id(); // add right offset // b += graph.numVertices(); Vertex<V> va = this.vList.get(a); Vertex<V> vb = this.vList.get(b); insertEdge(va, vb, e.element()); } }
/* * Methode to performe the Breadth first search */ private static void performBreadthFirstSearch() { while (queue.size() != 0) { Vertex firstVertexInQueue = queue.get(0); LinkedList<Vertex> neighboursOfFirstVertexInQueue = (LinkedList<Vertex>) graph.getNeighbours(firstVertexInQueue.getId()); dequeue(); if (neighboursOfFirstVertexInQueue.size() != 0) { for (Vertex neighbour : neighboursOfFirstVertexInQueue) { int neighbourVertexID = neighbour.getId(); String colorOfNode = (String) verticesMap.get(neighbourVertexID).get(0); int weightOfEdge = calculateWeightOfWay(firstVertexInQueue, neighbour); if (colorOfNode.equals("white")) { verticesMap.put( neighbourVertexID, new ArrayList(Arrays.asList("gray", weightOfEdge, firstVertexInQueue))); enqueue(neighbour); } } } verticesMap.get(firstVertexInQueue.getId()).remove(0); verticesMap.get(firstVertexInQueue.getId()).add(0, "black"); } }
/** * Método recursivo para hacer un recorrido del grafo para obtener el valor de cada * vértice. * * @param v <code>Vertex<StructV></code> */ public boolean recurse(Vertex<StructV> v) { if (v == null) return false; if (v.getValue() == null) return false; if (!(v.getValue().getSprite() instanceof SpriteUnion)) precondition(v); ArrayList<Vertex<StructV>> neighbors = v.getNeighbors(); for (int i = 0; i < neighbors.size(); i++) { Vertex<StructV> tmp = neighbors.get(i); if (tmp == null) break; if (whileCase(tmp)) continue; if (forCase(tmp)) continue; if (ifCase(tmp)) continue; if (unionCase(tmp)) continue; recurse(tmp); } if (!(v.getValue().getSprite() instanceof SpriteIf)) postcondition(v); return false; }
/** * Método para realizar comparaciones entre vertices. * * @param v <code>Vertex<V></code> * @return <code>boolean</code> */ public boolean equals(Vertex<V> v) { if (v == null) return false; if (v.getValue() == null & value == null) return true; if (value == null) return false; StructV st = (StructV) value; return st.equalsTo((StructV) v.getValue()); }
/* * A methode to initialize the HashMap with default values before performing * the breadth first search. */ private static void fillThemHashmap() { ArrayList<Vertex> vertices = (ArrayList<Vertex>) graph.getVertices(); ArrayList initialPropertiers = new ArrayList(Arrays.asList("white", 0, "none")); for (Vertex v : vertices) { verticesMap.put(v.getId(), initialPropertiers); } }
public static ImmutableBinaryTree getCaterpillarIBTFromOrdering( ArrayList<Vertex<Integer>> vertexOrdering) { ImmutableBinaryTree ibt = new ImmutableBinaryTree(); ibt = ibt.addRoot(); SimpleNode last = ibt.getRoot(); for (Vertex<Integer> v : vertexOrdering) { ibt = ibt.addChild(last, v.id()); last = ibt.getReference(); } return ibt; }
protected Vertex getUnvisitedChildVertex(Vertex vertex, Vertex parent) { Iterator vertices = vertex.getNeighborIterator(); while (vertices.hasNext()) { Vertex child = (Vertex) vertices.next(); if (!child.isVisited()) { return child; } else { if (!child.equals(parent)) { hasCycle = true; } } } return null; }
@SuppressWarnings("unchecked") public String printVertices() { String s = "[ "; Vertex<V> head = (Vertex<V>) vertices.getHeader(); while (head != null) { s += head.toString() + " -- "; try { head = (Vertex<V>) vertices.next((Pointer<V>) head.getPosition()).element(); } catch (Exception e) { head = null; } } return s.substring(0, s.length() - 4) + " ]"; }
public int[][] getAdjacencyMatrix() { BiGraph<V, E> g = this; int[][] mat = new int[g.numLeftVertices()][g.numRightVertices()]; // use left/right iteration order as new matrix index int[] fromGraphToBiGraphNodeIndexLeft = new int[g.numVertices() + 1]; int[] fromGraphToBiGraphNodeIndexRight = new int[g.numVertices() + 1]; int leftid = 0; for (Vertex<V> v : g.leftVertices()) { fromGraphToBiGraphNodeIndexLeft[v.id()] = leftid; leftid++; } int rightid = 0; for (Vertex<V> v : g.rightVertices()) { fromGraphToBiGraphNodeIndexRight[v.id()] = rightid; rightid++; } for (Edge<Vertex<V>, V, E> edge : g.edges()) { Vertex<V> left = edge.left(); Vertex<V> right = edge.right(); // System.out.printf("e: %d %d\n", left.id(), right.id() - g.numLeftVertices()); leftid = fromGraphToBiGraphNodeIndexLeft[left.id()]; rightid = fromGraphToBiGraphNodeIndexRight[right.id()]; // System.out.printf("%b", this.isLeft.get(left.id()) != this.isLeft.get(right.id())); mat[leftid][rightid] = 1; } return mat; }
@SuppressWarnings("unchecked") @Override public List<Vertex<V>> list_vertices() { List<Vertex<V>> coll = new ArrayList<Vertex<V>>(); Vertex<V> head = (Vertex<V>) vertices.getHeader(); while (head != null) { coll.add(head); try { head = (Vertex<V>) vertices.next((Pointer<V>) head.getPosition()).element(); } catch (Exception e) { head = null; } } return coll; }
/** * Método para agregar un vecino. * * @param neighbor <code>Vertex<V></code> */ public boolean addNeighbor(Vertex<V> neighbor) { if (neighbor == null) return false; if (getNeighbor(neighbor.getValue()) == null) if (neighbors.add(neighbor)) return true; return false; }
/** * Método que lleva el control sobre el recorrido para el caso especial del If * * @param tmp Vertice Acual <code>Vertex<StructV></code> */ private boolean ifCase(Vertex<StructV> tmp) { if (tmp.getValue().getSprite() instanceof SpriteIf) { if (ifList.size() != 0) { Sprite currentIf = ifList.get(ifList.size() - 1).getValue().getSprite(); if (!currentIf.equals(tmp.getValue().getSprite())) { ifList.add(tmp); } } else { ifList.add(tmp); } } return false; }
/* * Methode to calculate a weight for a way to the start point , it can be * one edge or a couple of edges */ private static int calculateWeightOfWay(Vertex firstVertex, Vertex secondVertex) { int currentWeight = (Integer) verticesMap.get(firstVertex.getId()).get(1); ArrayList<Edge<Vertex>> edgesOfFirstVertex = (ArrayList<Edge<Vertex>>) graph.getIncidentEdges(firstVertex.getId()); for (Edge<Vertex> e : edgesOfFirstVertex) { if (e.getVertexB().getId() == secondVertex.getId()) { int edgeWeightBetweenFirstandSecond = e.getWeight(); return edgeWeightBetweenFirstandSecond + currentWeight; } } System.out.println("no edge weight found"); return 0; }
public boolean removeNeighbor(V value) { for (int i = 0; i < getNumNeighbors(); i++) { Vertex<V> v = this.neighbors.get(i); if (v == null) continue; if (v.getValue() == null & value == null) { this.neighbors.remove(i); return true; } if (this.neighbors.get(i).getValue().equals(value)) { this.neighbors.remove(i); return true; } } return false; }
@SuppressWarnings("unchecked") private Vertex<V> searchVertex(V v) { Vertex<V> head = (Vertex<V>) vertices.getHeader(); Vertex<V> found = null; while (head != null) { if (head.getInfo().equals(v)) { found = head; head = null; } try { head = (Vertex<V>) vertices.next((Pointer<V>) head.getPosition()).element(); } catch (Exception e) { head = null; } } return found; }
@SuppressWarnings("unchecked") @Override public void removeVertex(Vertex<V> v) throws Exception { Iterator<Edge<E, V>> it = incidentEdges(v); while (it.hasNext()) { removeEdge(it.next()); } vertices.removePos((Position<PositionAwareType<V>>) v.getPosition()); }
/** * Método que lleva el control sobre el recorrido para el caso especial del For * * @param tmp Vertice Acual <code>Vertex<StructV></code> */ private boolean forCase(Vertex<StructV> tmp) { if (tmp.getValue().getSprite() instanceof SpriteFor) { if (forList.size() != 0) { Sprite currentFor = forList.get(forList.size() - 1); if (!currentFor.equals(tmp.getValue().getSprite())) { forList.add(tmp.getValue().getSprite()); } else { forList.remove(forList.size() - 1); return true; } } else { forList.add(tmp.getValue().getSprite()); } } return false; }
/** * Método que lleva el control sobre el recorrido para el caso especial del While * * @param tmp Vertice Acual <code>Vertex<StructV></code> */ private boolean whileCase(Vertex<StructV> tmp) { if (tmp.getValue().getSprite() instanceof SpriteWhile) { if (whileList.size() != 0) { Sprite currentWhile = whileList.get(whileList.size() - 1); if (!currentWhile.equals(tmp.getValue().getSprite())) { whileList.add(tmp.getValue().getSprite()); } else { whileList.remove(whileList.size() - 1); return true; } } else { whileList.add(tmp.getValue().getSprite()); } } return false; }
@Override public V removeVertex(Vertex<V> v) { if (isLeft(v)) { this.leftList.remove(v); } if (isRight(v)) { this.rightList.remove(v); } super.removeVertex(v); if (this.isLeft.size() - 1 == v.id()) { this.isLeft.remove(v.id()); } else { this.isLeft.set(v.id(), this.isLeft.remove(this.isLeft.size() - 1)); } return v.element(); }
/** * Método que lleva el control sobre el recorrido para el caso especial de la Union * * @param tmp Vertice Acual <code>Vertex<StructV></code> */ private boolean unionCase(Vertex<StructV> tmp) { if (tmp.getValue().getSprite() instanceof SpriteUnion) { if (unionList.size() != 0) { unionList.remove(unionList.size() - 1); precondition(tmp); return false; } else { if (ifList.size() > 0) { Vertex<StructV> ifTemp = ifList.get(ifList.size() - 1); postcondition(ifTemp); ifList.remove(ifList.size() - 1); } unionList.add(tmp.getValue().getSprite()); return true; } } return false; }
/** * performs the Dijkstra algorithm * * @param graph a graph, in which the Dijkstra will be performed * @param queue a queue of vertices to help perform Dijkstra * @param startVertexID a start vertices id * @param destinationVertexID an end vertices id */ private static void performeDijkstra( Graph<Vertex, Edge<Vertex>> graph, ArrayList<Vertex> queue, int startVertexID, int destinationVertexID) { while (queue.size() != 0) { int lowest = 0; for (int i = 0; i < queue.size(); i++) { if (queue.get(i).getDistance() < queue.get(lowest).getDistance()) { lowest = i; } } Vertex lowestElementInQueue = queue.get(lowest); // stop the loop if the destination is reached if (lowestElementInQueue.getId() == destinationVertexID) break; queue.remove(lowestElementInQueue); Collection<Edge<Vertex>> edgesOfFirstVertex = graph.getIncidentEdges(lowestElementInQueue); if (edgesOfFirstVertex.size() != 0) { for (Edge<Vertex> edge : edgesOfFirstVertex) { Vertex neighbour = edge.getVertexB(); int weightOfEdge = edge.getWeight(); if (weightOfEdge < 0) { throw new IllegalArgumentException( "one edge of " + lowestElementInQueue.getId() + " is negative"); } relax(lowestElementInQueue, neighbour, weightOfEdge); } } } ResultsDisplay.printResults(graph); ResultsDisplay.printTheShortestWay(graph, startVertexID, destinationVertexID); }
/** * initializes the Dijkstra algorithm by setting the start vertex, setting a queue to help * performing Dijkstra * * @param graph the graph in which the Dijkstra algorithm should be performed * @param startVertexID the start vertex * @param destinationVertexID the end vertex */ public static void initializeDijkstra( Graph<Vertex, Edge<Vertex>> graph, int startVertexID, int destinationVertexID) { for (int i = 0; i < graph.getVertices().size(); i++) { graph.getVertex(i).setDistance(Integer.MAX_VALUE); graph.getVertex(i).setPredecessor(null); } Vertex startVertex = graph.getVertex(startVertexID); startVertex.setDistance(0); startVertex.setPredecessor(startVertex); startVertex.setState(EndStateOfPoint.STARTPOINT); ArrayList<Vertex> queue = new ArrayList<Vertex>(); for (int i = 0; i < graph.getVertices().size(); i++) { queue.add(graph.getVertex(i)); } performeDijkstra(graph, queue, startVertexID, destinationVertexID); }
/** * Método que genera las postcondiciones para el vertice actual * * @param v Vertice Acual <code>Vertex<StructV></code> */ public void postcondition(Vertex<StructV> v) { String name = (String) ((Hashtable) v.getValue().getValue()).get("name"); int line = search(name); if (line == -1) { code += "\r"; return; } if (!(template.get(line + 2).matches("[\\s]*"))) code += template.get(line + 2) + "\r"; }
/** * to performe the relaxation between two vertices * * @param firstVertex the first vertex * @param neighbour the neighbouring vertex of the first vertex * @param weightOfEdge the weight of the edge between the first vertex and the neighbouring vertex */ private static void relax(Vertex firstVertex, Vertex neighbour, int weightOfEdge) { if (neighbour.getDistance() > firstVertex.getDistance() + weightOfEdge) { neighbour.setDistance(firstVertex.getDistance() + weightOfEdge); neighbour.setPredecessor(firstVertex); neighbour.setState(EndStateOfPoint.REACHABLE); } }
public void testDart() { String S = Formatter.testString; // see formatterString.gif Graph G = Graph.getInstance(new Formatter(S)); Vertex V = null; int coupleCount = 0; for (Enumeration E = G.vertexEnumeration(); E.hasMoreElements(); /*--*/ ) { Vertex W = (Vertex) E.nextElement(); coupleCount += W.size(); if (W.size() == 3) V = W; } jassert(V.size() == 3); Face F = V.getAny(); while (F.size() != 5) F = V.next(F, 1); jassert(F.size() == 5); Dart C = new Dart(V, F); Dart[] list = Dart.getDarts(C, G); // compute the expected number of return values; jassert(list.length == coupleCount); jassert(list[0].getV() == C.getV()); jassert(list[0].getF() == C.getF()); // check integrity of each couple. for (int i = 0; i < list.length; i++) { V = list[i].getV(); F = list[i].getF(); jassert(V.next(F, 0) == F); jassert(F.next(V, 0) == V); } // check that all couples are distinct. Hashtable table = new Hashtable(); // { V-> set of F } for (Enumeration E = G.vertexEnumeration(); E.hasMoreElements(); /*--*/ ) { V = (Vertex) E.nextElement(); table.put(V, new HashSet()); } for (int i = 0; i < list.length; i++) { V = list[i].getV(); F = list[i].getF(); HashSet H = (HashSet) table.get(V); jassert(!H.contains(F)); H.add(F); } }
@Override protected void toGraphVizNodes(Formatter f) { f.format("subgraph cluster_0 {\n"); f.format("label = \"left\";\n"); f.format("color = red;\n"); for (Vertex<V> n : leftVertices()) { f.format("%s [ label = \"%d\" ];\n", n.id(), n.id()); } f.format("}\n"); f.format("subgraph cluster_1 {\n"); f.format("label = \"right\";\n"); f.format("color = blue;\n"); for (Vertex<V> n : rightVertices()) { f.format("%s [ label = \"%d\" ];\n", n.id(), n.id()); } f.format("}\n"); }
@Override public double getCost(Vertex<Integer> a, Vertex<Integer> b) { double cost = hoods.get(a.id()).symmetricDifference(hoods.get(b.id())).size(); return cost; }
@Override public void replace(Vertex<V> v, V ele) { v.setInfo(ele); }