@Override
 public Vertex<V> opposite(Vertex<V> v, Edge<E, V> e) {
   Vertex<V> vt;
   if (e.getSource().equals(v)) vt = (Vertex<V>) e.getDestination();
   else if (e.getDestination().equals(v)) vt = (Vertex<V>) e.getSource();
   else vt = null;
   return vt;
 }
Exemplo n.º 2
0
 public Node whatNodeIGetTo(Node from, Transition with) {
   for (Edge e : myGraph.edgeSet()) {
     if (e.getSource().equals(from) && e.getTransition().equals(with)) {
       return e.getDest();
     }
   }
   return null;
 }
Exemplo n.º 3
0
 private Graph buildGraph(List<Edge> edges) {
   Graph toReturn = new Graph();
   for (Edge e : edges) {
     toReturn.addNode(e.getSource());
     toReturn.addNode(e.getDest());
     toReturn.addEdge(e);
   }
   return toReturn;
 }
Exemplo n.º 4
0
  public double weight() {
    double result = 0.0;

    for (Edge e : mst) {
      result += e.weight();
    }

    return result;
  }
 @Override
 public Edge<E, V> insertEdge(Vertex<V> v, Vertex<V> w, E ele) throws Exception {
   @SuppressWarnings("unchecked")
   Position<PositionAwareType<E>> pos =
       edges.addPos(ele, (Class<? extends PositionAwareType<E>>) Edge.class);
   @SuppressWarnings("unchecked")
   Edge<E, V> eg = (Edge<E, V>) pos.element();
   eg.setSource(v);
   eg.setDestination(w);
   return eg;
 }
 /**
  * Test whether vertex b is adjacent to vertex a (i.e. a -> b) in a directed graph. Assumes that
  * we do not have negative cost edges in the graph.
  *
  * @param a one vertex
  * @param b another vertex
  * @return cost of edge if there is a directed edge from a to b in the graph, return -1 otherwise.
  * @throws IllegalArgumentException if a or b do not exist.
  */
 @Override
 public int edgeCost(Vertex a, Vertex b) {
   if (a == null || b == null || !totalVertices.contains(a) || !totalVertices.contains(b)) {
     throw new IllegalArgumentException();
   }
   for (Edge edge : adj.get(a)) {
     if (edge.getDestination().equals(b)) {
       return edge.getWeight();
     }
   }
   return -1;
 }
 @SuppressWarnings("unchecked")
 public String printEdges() {
   String s = "";
   Edge<E, V> eg = (Edge<E, V>) edges.getHeader();
   while (eg != null) {
     s += eg.toString() + " ";
     try {
       eg = (Edge<E, V>) edges.next((Pointer<E>) eg.getPosition()).element();
     } catch (Exception exc) {
       eg = null;
     }
   }
   return s;
 }
 @SuppressWarnings("unchecked")
 @Override
 public List<Edge<E, V>> list_edges() {
   List<Edge<E, V>> coll = new ArrayList<Edge<E, V>>();
   Edge<E, V> head_edg = (Edge<E, V>) edges.getHeader();
   while (head_edg != null) {
     coll.add(head_edg);
     try {
       head_edg = (Edge<E, V>) edges.next((Pointer<E>) head_edg.getPosition()).element();
     } catch (Exception exc) {
       head_edg = null;
     }
   }
   return coll;
 }
  /**
   * Return a collection of vertices adjacent to a given vertex v. i.e., the set of all vertices w
   * where edges v -> w exist in the graph. Return an empty collection if there are no adjacent
   * vertices.
   *
   * @param v one of the vertices in the graph
   * @return an iterable collection of vertices adjacent to v in the graph
   * @throws IllegalArgumentException if v does not exist.
   */
  @Override
  public Collection<Vertex> adjacentVertices(Vertex v) {
    if (v == null || !totalVertices.contains(v)) {
      throw new IllegalArgumentException();
    }
    List<Vertex> destiVertex = new ArrayList<Vertex>();

    // Returns the edge to which the specified key is mapped, or null if
    // this map contains no mapping for the key.Then add the edge to the
    // ArrayList
    for (Edge e : adj.get(v)) {
      destiVertex.add(e.getDestination());
    }
    return destiVertex;
  }
Exemplo n.º 10
0
 @SuppressWarnings("unchecked")
 @Override
 public Iterator<Edge<E, V>> edges(String type) {
   List<Edge<E, V>> coll = new ArrayList<Edge<E, V>>();
   Edge<E, V> head_edg = (Edge<E, V>) edges.getHeader();
   while (head_edg != null) {
     if (head_edg.getType().equals(type)) coll.add(head_edg);
     try {
       head_edg = (Edge<E, V>) edges.next((Pointer<E>) head_edg.getPosition()).element();
     } catch (Exception exc) {
       head_edg = null;
     }
   }
   return coll.iterator();
 }
Exemplo n.º 11
0
 @SuppressWarnings("unchecked")
 public String printEdges(String type) {
   String s = "";
   Edge<E, V> eg = (Edge<E, V>) edges.getHeader();
   while (eg != null) {
     if (eg.getType().equals(type))
       s += eg.getSource().getInfo() + " -> " + eg.getDestination().getInfo() + "\n";
     try {
       eg = (Edge<E, V>) edges.next((Pointer<E>) eg.getPosition()).element();
     } catch (Exception exc) {
       eg = null;
     }
   }
   return s;
 }
Exemplo n.º 12
0
  /*
   * 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;
  }
Exemplo n.º 13
0
  @SuppressWarnings("unchecked")
  @Override
  public Iterator<Vertex<V>> adjacentVertices(Vertex<V> v) {
    List<Vertex<V>> coll = new ArrayList<Vertex<V>>();
    Edge<E, V> head_edg = (Edge<E, V>) edges.getHeader();
    while (head_edg != null) {
      if (head_edg.getSource().equals(v)) coll.add((Vertex<V>) head_edg.getDestination());
      try {
        head_edg = (Edge<E, V>) edges.next((Pointer<E>) head_edg.getPosition()).element();
      } catch (Exception exc) {
        head_edg = null;
      }
    }

    return coll.iterator();
  }
Exemplo n.º 14
0
 /**
  * Perform a traversal of G over all vertices reachable from V. ORDER determines the ordering in
  * which the successors to the set of traversed vertices are visited.
  */
 public void traverse(Graph<VLabel, ELabel> G, Vertex<VLabel> v, Comparator<VLabel> order) {
   _graph = G;
   if (_fringe.isEmpty()) {
     _fringe.add(v);
   }
   _order = order;
   while (!_fringe.isEmpty()) {
     Collections.sort(_fringe, new VertexComparator());
     Vertex<VLabel> vert = _fringe.get(0);
     if (!_markedVertices.contains(vert)) {
       _markedVertices.add(vert);
       try {
         _finalEdge = null;
         _finalVertex = vert;
         this.visit(vert);
       } catch (StopException e) {
         return;
       } catch (RejectException e) {
         continue;
       }
       Iterator<Edge<VLabel, ELabel>> iter = G.outEdges(vert);
       while (iter.hasNext()) {
         Edge<VLabel, ELabel> nextEdge = iter.next();
         if (!_markedEdges.contains(nextEdge)) {
           _markedEdges.add(nextEdge);
           try {
             _finalVertex = null;
             _finalEdge = nextEdge;
             this.preVisit(nextEdge, vert);
           } catch (StopException e) {
             return;
           } catch (RejectException e) {
             continue;
           }
           if (!_fringe.contains(nextEdge.getV1())) {
             _fringe.add(nextEdge.getV1());
           }
         }
       }
     }
     _fringe.remove(0);
   }
 }
Exemplo n.º 15
0
 public List<Graph> getAllNodeCoverage() {
   Node initial = getInitialState();
   Set<Node> toVisit = new HashSet<>(nodes);
   toVisit.remove(initial);
   Set<Node> left = new HashSet<>(nodes);
   left.remove(initial);
   List<Graph> toReturn = new ArrayList<>();
   for (Node visiting : toVisit) {
     if (left.contains(visiting)) {
       DijkstraShortestPath<Node, Edge> pathFinder =
           new DijkstraShortestPath<>(myGraph, initial, visiting);
       List<Edge> path = pathFinder.getPathEdgeList();
       for (Edge e : path) {
         left.remove(e.getDest());
       }
       toReturn.add(buildGraph(path));
     }
   }
   return toReturn;
 }
Exemplo n.º 16
0
  /**
   * 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);
  }
Exemplo n.º 17
0
  public KruskalMST(EdgeWeightedGraph g) {
    mst = new Queue<Edge>();

    MinPQ<Edge> pq = new MinPQ<Edge>();

    for (Edge e : g.edges()) {
      pq.insert(e);
    }

    UnionFind uf = new UnionFind(g.vertices());

    while (!pq.isEmpty() && mst.size() < g.vertices() - 1) {
      Edge e = pq.delMin();
      int v = e.either(), w = e.other(v);

      if (uf.connected(v, w)) continue; // -- would form a cycle

      uf.union(v, w);
      mst.enqueue(e);
    }
  }
  /**
   * Creates a MyGraph object with the given collection of vertices and the given collection of
   * edges.
   *
   * @param v a collection of the vertices in this graph
   * @param e a collection of the edges in this graph
   */
  public MyGraph(Collection<Vertex> v, Collection<Edge> e) {
    // collection passed in should not be null
    if (v == null || e == null) {
      throw new IllegalArgumentException();
    }

    adj = new HashMap<Vertex, ArrayList<Edge>>();
    totalEdges = new ArrayList<Edge>();
    totalVertices = new ArrayList<Vertex>();
    checkExcepction(v, e);

    // loop through a collection
    // for (iterable_type iterable_element : collection)
    // Add edges and vertex to the map
    for (Edge edge : e) {
      if (!totalEdges.contains(edge)) {
        totalEdges.add(edge);
      }
      // if this vertex is not in key groups of the HashMap, add it to the group
      if (!adj.containsKey(edge.getSource())) {
        adj.put(edge.getSource(), new ArrayList<Edge>());
      }
      // add edge to the ArrayList, which is the "value" in key-value pairs in HashMap, adj.
      adj.get(edge.getSource()).add(edge);
    }

    for (Vertex vertex : v) {
      if (!totalVertices.contains(vertex)) {
        totalVertices.add(vertex);
      }

      if (!adj.containsKey(
          vertex)) { // add this vertex as a key in adj even if there might not be edge extending
                     // from it,
        // namely even if we end up with empty ArrayList as value of this key
        adj.put(vertex, new ArrayList<Edge>());
      }
    }
  }
Exemplo n.º 19
0
 public List<Graph> getAllEdgeCoverage() {
   List<Edge> toVisit = new ArrayList<>(myGraph.edgeSet());
   List<Edge> left = new ArrayList<>(myGraph.edgeSet());
   List<Graph> toReturn = new ArrayList<>();
   for (Edge e : toVisit) {
     if (left.contains(e)) {
       if (getInitialState().equals(e.getSource())) {
         List<Edge> toAdd = new ArrayList<>();
         toAdd.add(e);
         toReturn.add(buildGraph(toAdd));
       } else {
         List<Edge> path =
             BellmanFordShortestPath.findPathBetween(myGraph, getInitialState(), e.getSource());
         path.add(e);
         left.remove(e);
         left.removeAll(path);
         toReturn.add(buildGraph(path));
       }
     }
   }
   return toReturn;
 }
Exemplo n.º 20
0
 public boolean isLegalMapping(Edge eQ, Edge eC) {
   if (!notMapped(eC)) {
     return false;
   }
   if (!eQ.getTail().getBpmnType().equals(eC.getTail().getBpmnType())
       && !eQ.getHead().getBpmnType().equals(eC.getHead().getBpmnType())) {
     return false;
   }
   if (!areMapped(eQ.getTail(), eC.getTail()) && !areMapped(eQ.getHead(), eC.getHead())) {
     // System.out.println("Not Mapped: ID-Query(tail): " + eQ.getTail().getId() + " ID-Case(tail):
     // " + eC.getTail().getId());
     // System.out.println("Not Mapped: ID-Query(head): " + eQ.getHead().getId() + " ID-Case(head):
     // " + eC.getHead().getId());
     return false;
   }
   return true;
 }
Exemplo n.º 21
0
 @SuppressWarnings("unchecked")
 @Override
 public void reverseDirection() {
   Edge<E, V> h = (Edge<E, V>) edges.getHeader();
   while (h != null) {
     Vertex<V> temp = h.getSource();
     h.setSource(h.getDestination());
     h.setDestination(temp);
     try {
       h = (Edge<E, V>) edges.next((Pointer<E>) h.getPosition()).element();
     } catch (Exception exc) {
       h = null;
     }
   }
 }
Exemplo n.º 22
0
 @SuppressWarnings("unchecked")
 @Override
 public boolean areAdjacent(Vertex<V> v, Vertex<V> w) {
   boolean b = false;
   Edge<E, V> eg = (Edge<E, V>) edges.getHeader();
   while (eg != null && !b) {
     if ((eg.getDestination().equals(v) || eg.getSource().equals(v))
         && (eg.getDestination().equals(w) || eg.getSource().equals(w))) b = true;
     try {
       eg = (Edge<E, V>) edges.next((Pointer<E>) eg.getPosition()).element();
     } catch (Exception exc) {
       eg = null;
     }
   }
   return b;
 }
Exemplo n.º 23
0
 @SuppressWarnings("unchecked")
 @Override
 public void removeEdge(Edge<E, V> e) throws Exception {
   edges.removePos((Position<PositionAwareType<E>>) e.getPosition());
 }
  /**
   * Returns the shortest path from a to b in the graph, or null if there is no such path. Assumes
   * all edge weights are nonnegative. Uses Dijkstra's algorithm.
   *
   * @param a the starting vertex
   * @param b the destination vertex
   * @return a Path where the vertices indicate the path from a to b in order and contains a (first)
   *     and b (last) and the cost is the cost of the path. Returns null if b is not reachable from
   *     a.
   * @throws IllegalArgumentException if a or b does not exist.
   */
  public Path shortestPath(Vertex a, Vertex b) {

    List<Vertex> vertexList = new ArrayList<Vertex>();
    VertexComparator vcp = new VertexComparator();
    PriorityQueue<Vertex> vertexQueue =
        new PriorityQueue<Vertex>(10, vcp); // queue for unknow vertex

    // If the start and end vertex are equal
    // return a path containing one vertex and a cost of 0.
    if (a.equals(b)) {
      vertexList.add(a);
      return new Path(vertexList, 0);
    }

    // if the start and end vertex are not equal:

    // if there is no path starting from a, return null
    if (!adj.containsKey(a)) {
      return null;
    }

    // for (Vertex v : this.vertices() ) {
    //    System.out.println(v.known);
    // }

    // initialize before searching path
    for (Vertex v : adj.keySet()) {
      // variables in adj.keySet() are actually pointers pointing to different memory with those in
      // this.vertices()
      // what we need is actually to change those in memory pointed by this.vertices()
      // have no idea why this.vertices.get() method did not work
      // thus I have to implement as below
      Vertex vn = v; // actually this is a bad initialization
      for (Vertex vi : this.vertices()) {
        if (vi.equals(v)) {
          vn = vi;
        }
      }

      vn.known = false;
      // set all vertex distance to infinity
      vn.distance = Integer.MAX_VALUE;
      // vn.distance = 99999;
      vertexQueue.add(vn);
    }
    // System.exit(1);
    // Set source vertex distance to 0
    for (Vertex vn : this.vertices()) {
      if (vn.equals(a)) {
        vertexQueue.remove(vn);
        vn.distance = 0;
        vn.previous = vn;
        // update vn in vertexQueue
        vertexQueue.add(vn);
      }
    }
    // a.distance = 0;
    // a.previous = a;
    // vertexQueue.remove(a);
    // vertexList.add(a);

    Vertex end = b;
    for (Vertex vn : this.vertices()) {
      if (vn.equals(b)) {
        end = vn;
      }
    }
    // for (Vertex v : this.vertices() ) {
    //    System.out.println(v.distance);
    // }
    System.out.println("start searching...");
    // while ( (!vertexQueue.isEmpty()) && (end.known == false) ) { //while there are still unknow
    // vertex and vertex b is unknown
    while ((!vertexQueue
        .isEmpty())) { // while there are still unknow vertex and vertex b is unknown
      // System.out.println("elements in vertexQueue at beginning:");
      // for (Vertex v : vertexQueue ) {
      //    System.out.println(v.getLabel());
      //    System.out.println("distance: " + v.distance);
      // }
      Vertex nt = vertexQueue.poll(); // unknown node with smallest distance
      // System.out.println("marked " + nt + " as known.");
      // System.out.println("its current distance: " + nt.distance);
      nt.known = true;
      for (Edge e : adj.get(nt)) {
        // search for vertex with the same name as e.getDestination() in this.vertices()
        Vertex en = e.getDestination();
        for (Vertex vn : this.vertices()) {
          if (vn.equals(e.getDestination())) {
            en = vn;
          }
        }

        if (!en.known) {
          if ((nt.distance + e.getWeight()) < en.distance) {
            // update en in vertexQueue
            vertexQueue.remove(en);
            en.distance = nt.distance + e.getWeight();
            en.previous = nt;
            vertexQueue.add(en);
          }
        }
      }
    }
    System.out.println("finished computing shortest path.");
    // for (Vertex v : this.vertices() ) {
    //    System.out.println(v.distance);
    // }

    // traverse to get path from a to b
    Vertex tmp = end;
    while (!tmp.equals(a)) {
      vertexList.add(0, tmp); // may need a heap here?
      tmp = tmp.previous;
    }
    vertexList.add(0, a);
    return new Path(vertexList, end.distance);

    // TODO: after searching for all possible path, return null if there is no path from a to b

  }
  private void checkExcepction(Collection<Vertex> v, Collection<Edge> e) {
    for (Edge edge : e) {
      // No edge from or to vertex labeled A if there is no vertex with
      // label A
      if (!v.contains(edge.getSource()) || !v.contains(edge.getDestination())) {
        throw new IllegalArgumentException();
      }

      // Edge weights should not be negative
      if (edge.getWeight() < 0) {
        throw new IllegalArgumentException();
      }

      // Collection of edges should not has the same directed edge more
      // than once
      // with a different weight
      for (Edge checkEdges : e) {
        if (checkEdges.getSource().equals(edge.getSource())
            && checkEdges.getDestination().equals(edge.getDestination())
            && checkEdges.getWeight() != edge.getWeight()) {
          throw new IllegalArgumentException();
        }
      }
    }
  }
Exemplo n.º 26
0
 public void addEdge(Edge toAdd) {
   myGraph.addEdge(toAdd.getSource(), toAdd.getDest(), toAdd);
 }