/**
   * 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;
  }
  private void saveMenuItemActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_saveMenuItemActionPerformed

    this.jTextStatus.setText("");
    if (this.pnGraph.listEdges.isEmpty() && this.pnGraph.listVertexs.isEmpty()) {
      this.jTextStatus.setText("Empty graph, not save");
      return;
    }
    if (this.jSaveFileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
      File file = this.jSaveFileChooser.getSelectedFile();
      try {
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        try {
          for (Vertex Vertex : this.pnGraph.listVertexs) {
            output.write(
                String.format(
                    "Vertex:%d:%d:%d", Vertex.getData(), Vertex.getX_cor(), Vertex.getY_cor()));
            output.newLine();
          }
          for (Edge edge : this.pnGraph.listEdges) {
            output.write(
                String.format(
                    "Edge:%d:%d:%d",
                    edge.getHead().getData(), edge.getTail().getData(), edge.getLength()));
            output.newLine();
          }
          this.jTextStatus.setText("Save graph successfully");
        } finally {
          output.close();
        }
      } catch (IOException e) {
      }
    }
  } // GEN-LAST:event_saveMenuItemActionPerformed
Esempio n. 3
0
 void computeIn(LinkedList<Vertex> worklist) {
   int i;
   BitSet old;
   BitSet ne;
   Vertex v;
   ListIterator<Vertex> iter;
   iter = succ.listIterator();
   while (iter.hasNext()) {
     v = iter.next();
     out.or(v.in);
   }
   old = in;
   in = new BitSet();
   in.or(out);
   in.andNot(def);
   in.or(use);
   if (!in.equals(old)) {
     iter = pred.listIterator();
     while (iter.hasNext()) {
       v = iter.next();
       if (!v.listed) {
         worklist.addLast(v);
         v.listed = true;
       }
     }
   }
 }
 private void computeMatchSet() {
   for (Vertex v : LV) {
     for (Vertex neighb : v.getNeighbors()) {
       if (neighb.getId() != SOURCE_ID && getFlow(v, neighb) > 0) {
         matches.add(v);
         matches.add(neighb);
       }
     }
   }
 }
Esempio n. 5
0
  public void run() {

    System.out.println("computing liveness...");
    System.out.println("Worklist size: " + worklist.size());
    while (!worklist.isEmpty()) {
      u = worklist.remove();
      u.listed = false;
      u.computeIn(worklist);
    }
  }
Esempio n. 6
0
 /**
  * Method to do the DFS traversal - Recursive call
  *
  * @param u: Vertex for which the DFS checks the adjacency list.
  * @param cno: Count variable to keep the number of connected components.
  */
 static void dfsVisit(Vertex u, int cno) {
   u.seen = true;
   u.cno = cno;
   for (Edge e : u.Adj) {
     Vertex v = e.otherEnd(u);
     if (!v.seen) {
       v.parent = u;
       dfsVisit(v, cno);
     }
   }
 }
Esempio n. 7
0
 /**
  * Method to find the DFS traversal for the Graph
  *
  * @param G : Input Graph G - undirected graph
  * @return : Returns the count for checking connected components
  */
 static int dfsUtil(Graph<Vertex> G) {
   for (Vertex u : G) {
     u.seen = false;
     u.parent = null;
   }
   int cno = 0; // Initializing count variable to check for connected components
   for (Vertex u : G) {
     if (!u.seen) dfsVisit(u, ++cno);
   }
   return cno;
 }
Esempio n. 8
0
 public void relaxEdges(FibonacciHeap<Vertex> unvisited) {
   Vertex[] vertices = Graph.this.vertices;
   for (Edge edge : edges) {
     Vertex to = vertices[edge.to];
     int newDistance = distance + edge.cost;
     if (newDistance < to.distance) {
       to.distance = newDistance;
       unvisited.decreaseKey(to.heapEntry, newDistance);
     }
   }
 }
  private void setupSinkSide(Set<Employee> emps) {
    for (Employee e : emps) {
      Vertex u = Vertex.vertexFromEmployee(e);
      RV.add(u);

      sink.addToNeighbors(u);
      u.addToNeighbors(sink);

      setCapacity(u, sink, 1);
      setFlow(u, sink, 0);
      V.add(u);
    }
  }
  private void konigDFS(Set<Vertex> konigSet, Vertex v, boolean edgesInMatch) {
    if (!konigSet.contains(v)) {
      konigSet.add(v);

      for (Vertex neighb : v.getNeighbors()) {
        if (neighb.getId() != SOURCE_ID && neighb.getId() != SINK_ID) {
          if (edgesInMatch == (getFlow(v, neighb) > 0 || getFlow(neighb, v) > 0)) {
            konigDFS(konigSet, neighb, !edgesInMatch);
          }
        }
      }
    }
  }
Esempio n. 11
0
 private void writeVerticies(Writer writer, List<Vertex> verticies, Map<Vertex, Integer> ids)
     throws IOException {
   int count = 1;
   for (Vertex v : verticies) {
     if (useId) {
       Integer id = Integer.valueOf(v.getId().toString());
       writeVertex(writer, v, id);
       ids.put(v, id);
     } else {
       writeVertex(writer, v, count);
       ids.put(v, count++);
     }
   }
 }
  // Uses Konig's theorem to compute min vertex cover
  // Compute in both directions as the friend, may or may not appear in a
  // particular vertex cover, depending on graph structure
  private void computeInvitees() {
    Set<Vertex> result;
    Set<Vertex> minVertexCovers1 = computeMinVertexCover(LV, RV);
    Set<Vertex> minVertexCovers2 = computeMinVertexCover(RV, LV);

    if (minVertexCovers1.contains(friend)) {
      result = minVertexCovers1;
    } else {
      result = minVertexCovers2;
    }

    for (Vertex v : result) {
      invitees.add(v.getId());
    }
  }
 private void relabelToFront() {
   assert (!V.isEmpty()) : "No vertices";
   ListIterator<Vertex> iter = V.listIterator();
   while (iter.hasNext()) {
     Vertex v = iter.next();
     // System.out.println("Considering vertex: " + v);
     int oldHeight = v.getHeight();
     discharge(v);
     if (v.getHeight() > oldHeight) {
       iter.remove();
       V.addFirst(v);
       iter = V.listIterator(1);
     }
   }
 }
  /**
   * M&eacute;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;
  }
  private void dijkstraAlgorithm() {
    this.jTextHeap.setText("");
    // check solved
    if (this.alState == StateAlgorithm.SOLVED) return;
    // first time run
    if (this.curVertex == null) {
      this.endVertex.state = State.UNLABELED;
      this.curVertex = this.pnHeap.heap.deleteMin();
      this.curVertex.state = State.SCANNED;
      this.curPos = 0;
    }
    int sz = this.curVertex.outgoingEdges.size();
    if (this.curPos < sz) {
      if (this.curEdge != null) this.curEdge.edgeState = State.UNLABELED;
      this.curEdge = this.curVertex.outgoingEdges.get(this.curPos);
      this.curEdge.edgeState = State.SCANNED;
      Vertex tailOfCurVertex = this.curEdge.getTail();

      if (tailOfCurVertex.state != State.SCANNED) {
        if (tailOfCurVertex.state == State.UNLABELED) {
          // insert a vertex with
          tailOfCurVertex.state = State.LABELED;
          tailOfCurVertex.setPred(this.curVertex);
          tailOfCurVertex.setKey(this.curVertex.getKey() + this.curEdge.getLength());
          this.pnHeap.heap.insertVertex(tailOfCurVertex);
          this.jTextHeap.setText("Insert vertex " + Integer.toString(tailOfCurVertex.getData()));
        } else if (tailOfCurVertex.getKey() > this.curVertex.getKey() + this.curEdge.getLength()) {
          // decrease the key of a vertex with finite key
          tailOfCurVertex.setPred(this.curVertex);
          this.jTextHeap.setText(
              "Decrease key of vertex "
                  + Integer.toString(tailOfCurVertex.getData())
                  + " from "
                  + Integer.toString(tailOfCurVertex.getKey())
                  + " to "
                  + Integer.toString(this.curVertex.getKey() + this.curEdge.getLength()));
          this.pnHeap.heap.decreaseKey(
              this.curVertex.getKey() + this.curEdge.getLength(), tailOfCurVertex);
        }
      }
      // check next outgoing edge
      this.curPos++;
    } else if (!this.pnHeap.heap.isEmpty()) {
      this.curEdge.edgeState = State.UNLABELED;
      this.curVertex = this.pnHeap.heap.deleteMin();
      this.jTextHeap.setText("Delete min vertex " + Integer.toString(this.curVertex.getData()));
      this.curVertex.state = State.SCANNED;
      this.curPos = 0;
    } else this.alState = StateAlgorithm.SOLVED;
    this.pnHeap.repaint();
    this.pnGraph.repaint();
  }
  private void discharge(Vertex u) {
    // System.out.println("Discharging " + u);
    while (u.getExcess() > 0) {
      if (u.getCurrNeighbor() >= u.getNumNeighbors()) {
        relabel(u);
        u.setCurrNeighbor(0);
      } else {
        Vertex v = u.getNeighbor(u.getCurrNeighbor());

        if (getResidualCapacity(u, v) > 0 && u.getHeight() == v.getHeight() + 1) {
          push(u, v);
        } else {
          u.incNextNeighbor();
        }
      }
    }
  }
  /**
   * M&eacute;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;
  }
  /**
   * M&eacute;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&eacute;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;
  }
  // Push-relabel methods
  // Push() pushes flow forwards, or decreases incoming flow
  private void push(Vertex u, Vertex v) {
    // System.out.println("Pushing from " + u + " to " + v);
    int excess = u.getExcess();
    int residualCapacity = getResidualCapacity(u, v);

    assert (excess > 0) : "Excess <= 0";
    assert (residualCapacity > 0) : "Resid capacity <= 0";
    assert (u.getHeight() == v.getHeight() + 1) : "Height of u != height of v + 1";

    int changeInFlow = excess < residualCapacity ? excess : residualCapacity;

    if (flowsForward(u, v)) {
      addToFlow(u, v, changeInFlow);
    } else {
      addToFlow(v, u, -changeInFlow);
    }

    u.addToExcess(-changeInFlow);
    v.addToExcess(changeInFlow);
  }
Esempio n. 21
0
  public int getDistance(int from, int to) {
    FibonacciHeap<Vertex> unvisited = new FibonacciHeap<Vertex>();

    for (int i = 1; i <= vertexCount; i++) {
      vertices[i].distance = vertexCount + 1;
      vertices[i].visited = false;
    }

    vertices[from].distance = 0;
    for (int i = 1; i <= vertexCount; i++)
      vertices[i].heapEntry = unvisited.enqueue(vertices[i], vertices[i].distance);

    while (unvisited.size() > 0) {
      Vertex v = unvisited.dequeueMin().getValue();

      if (v.index == to || v.distance > vertexCount) return v.distance;
      v.relaxEdges(unvisited);
    }

    return vertices[to].distance;
  }
Esempio n. 22
0
 private void writeVertexProperties(Writer writer, Vertex e) throws IOException {
   Object blueprintsId = e.getId();
   if (!useId) {
     writeKey(writer, vertexIdKey);
     if (blueprintsId instanceof Number) {
       writeNumberProperty(writer, (Number) blueprintsId);
     } else {
       writeStringProperty(writer, blueprintsId);
     }
   }
   writeProperties(writer, e);
 }
 public void search(Vertex[] nodes, int start) {
   LinkedList<Vertex> queue = new LinkedList<>();
   nodes[start].numPaths = 1;
   nodes[start].minDistance = 0;
   queue.addLast(nodes[start]);
   while (!queue.isEmpty()) {
     Vertex curr = queue.removeFirst();
     for (Edge e : curr.edges) {
       Vertex other = e.end;
       if (!other.checked) {
         other.checked = true;
         queue.addLast(other);
       }
       if (curr.minDistance + e.weight < other.minDistance) {
         other.minDistance = curr.minDistance + e.weight;
         other.numPaths = curr.numPaths;
       } else if (curr.minDistance + e.weight == other.minDistance) {
         other.numPaths += curr.numPaths;
       }
     }
   }
 }
  /**
   * M&eacute;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";
  }
  private void showResult() {
    if (this.alState != StateAlgorithm.SOLVED) return;

    this.pnGraph.showResult = true;
    this.endVertex.state = State.LABELED;
    this.startVertex.state = State.LABELED;
    if (this.curEdge != null) this.curEdge.edgeState = State.UNLABELED;
    this.jTextStatus.setText("Solved");

    if (this.endVertex.getPred() == null)
      this.jSolution.append(
          "There is no shorttest path from vertex "
              + Integer.toString(this.startVertex.getData())
              + " to vertex "
              + Integer.toString(this.endVertex.getData())
              + "\n");
    else {
      this.jSolution.append("Path:\n");
      ArrayList<Vertex> result = new ArrayList<Vertex>();
      Vertex tailN = this.endVertex;
      do {
        tailN.state = State.LABELED;
        result.add(tailN);
        Vertex headN = tailN.getPred();
        if (headN == null) break;
        tailN.getIncomingEdge(headN).edgeState = State.LABELED;
        tailN = headN;
      } while (tailN != null);
      for (int i = result.size() - 1; i > 0; i--)
        this.jSolution.append("Vertex " + Integer.toString(result.get(i).getData()) + " -> ");
      this.jSolution.append("Vertex " + Integer.toString(result.get(0).getData()) + "\n");
      this.jSolution.append("\tDistance: " + Integer.toString(this.endVertex.getKey()));
      this.pnGraph.repaint();
      this.pnSolution.repaint();
    }
  }
 /**
  * Method to initialize a graph 1) Sets the parent of every vertex as null 2) Sets the seen
  * attribute of every vertex as false 3) Sets the distance of every vertex as infinite
  *
  * @param g : Graph - The reference to the graph
  */
 void initialize() {
   int i = 1;
   for (Vertex u : this) {
     u.seen = false;
     u.parent = null;
     u.weight = INFINITY;
     u.mActive = false;
     u.mIndegree = 0;
   }
 }
  private void biasForFriend() {
    Vertex f = Vertex.vertexFromEmployee(Employee.getEmployeeFromId(ProjectParams.FRIEND_ID));

    List<Vertex> neighbors = f.getNeighbors();
    for (Vertex v : neighbors) {
      if (flowsForward(v, f)) {
        v.moveToFrontOfNeighbors(f);
      } else {
        v.moveToBackOfNeighbors(f);
      }
    }
  }
  private void relabel(Vertex u) {
    // System.out.println("Relabeling " + u);
    assert (u.getExcess() > 0) : "u not overflowing";

    List<Vertex> neighbors = u.getNeighbors();
    int minHeight = Integer.MAX_VALUE;
    for (Vertex v : neighbors) {
      int residCapacity = getResidualCapacity(u, v);
      assert (residCapacity == 0 || u.getHeight() <= v.getHeight());
      if (residCapacity > 0) {
        int partnerHeight = v.getHeight();
        minHeight = partnerHeight < minHeight ? partnerHeight : minHeight;
      }
    }
    u.setHeight(1 + minHeight);
  }
  private void initialize() {
    Set<Employee> Lset = pp.getEmployees(0);
    Set<Employee> Rset = pp.getEmployees(1);

    // FIXME!!!
    // flow = new HashMap<Vertex, Map<Vertex, Integer>>(2 * (Lset.size() + Rset.size()));
    // capacity = new HashMap<Vertex, Map<Vertex, Integer>>(2 * (Lset.size() + Rset.size()));
    flow = new TreeMap<Vertex, Map<Vertex, Integer>>();
    capacity = new TreeMap<Vertex, Map<Vertex, Integer>>();

    setupSourceSide(Lset);
    setupSinkSide(Rset);

    setupLRNeighbors();
    biasForFriend();

    source.setHeight(V.size() + 2);
  }
  private void setupLRNeighbors() {
    List<Team> teams = pp.getTeams();
    for (Team t : teams) {
      // System.out.println(t);
      Vertex u = Vertex.vertexFromEmployee(t.getEmployee(0));
      Vertex v = Vertex.vertexFromEmployee(t.getEmployee(1));

      u.addToNeighbors(v);
      v.addToNeighbors(u);

      setCapacity(u, v, 1);
      setFlow(u, v, 0);
    }
  }