private boolean edgesCompatible(int edge1, int edge2) {
   E e1 = edgeList1.get(edge1);
   E e2 = edgeList2.get(edge2);
   boolean result = false;
   // edge label must be the same
   if (e1.getLabel().equals(e2.getLabel())) {
     // check connecting vertex labels
     L v1SourceLbl = g1.getEdgeSource(e1).getLabel(),
         v1TargetLbl = g1.getEdgeTarget(e1).getLabel(),
         v2SourceLbl = g2.getEdgeSource(e2).getLabel(),
         v2TargetLbl = g2.getEdgeTarget(e2).getLabel();
     // checks if the pair of source vertices have the same label, and checks the same for the
     // target vertices
     boolean sourceTargetMatch =
         v1SourceLbl.equals(v2SourceLbl) && v1TargetLbl.equals(v2TargetLbl);
     if (directed) {
       result = sourceTargetMatch;
     } else {
       // checks if source1,target2 have the same label and if target1,source2 have the same label
       boolean sourceTargetInverseMatch =
           v1SourceLbl.equals(v2TargetLbl) && v1TargetLbl.equals(v2SourceLbl);
       result = (sourceTargetMatch || sourceTargetInverseMatch);
     }
   }
   return result;
 }
示例#2
0
  /**
   * @param vertexNumber the number which identifies the vertex v in this order.
   * @return the identifying numbers of all vertices which are connected to v by an edge incoming to
   *     v.
   */
  public int[] getInEdges(int vertexNumber) {
    if (cacheEdges && (incomingEdges[vertexNumber] != null)) {
      return incomingEdges[vertexNumber];
    }

    V v = getVertex(vertexNumber);
    Set<E> edgeSet;

    if (graph instanceof DirectedGraph<?, ?>) {
      edgeSet = ((DirectedGraph<V, E>) graph).incomingEdgesOf(v);
    } else {
      edgeSet = graph.edgesOf(v);
    }

    int[] vertexArray = new int[edgeSet.size()];
    int i = 0;

    for (E edge : edgeSet) {
      V source = graph.getEdgeSource(edge), target = graph.getEdgeTarget(edge);
      vertexArray[i++] = mapVertexToOrder.get(source.equals(v) ? target : source);
    }

    if (cacheEdges) {
      incomingEdges[vertexNumber] = vertexArray;
    }

    return vertexArray;
  }
  protected Graph<String, DefaultWeightedEdge> createWithBias(boolean negate) {
    Graph<String, DefaultWeightedEdge> g;
    double bias = 1;
    if (negate) {
      // negative-weight edges are being tested, so only a directed graph
      // makes sense
      g = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
      bias = -1;
    } else {
      // by default, use an undirected graph
      g = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
    }

    g.addVertex(V1);
    g.addVertex(V2);
    g.addVertex(V3);
    g.addVertex(V4);
    g.addVertex(V5);

    e12 = Graphs.addEdge(g, V1, V2, bias * 2);

    e13 = Graphs.addEdge(g, V1, V3, bias * 3);

    e24 = Graphs.addEdge(g, V2, V4, bias * 5);

    e34 = Graphs.addEdge(g, V3, V4, bias * 20);

    e45 = Graphs.addEdge(g, V4, V5, bias * 5);

    e15 = Graphs.addEdge(g, V1, V5, bias * 100);

    return g;
  }
示例#4
0
  @Override
  public BufferedImage getView() {
    if (img == null) {
      return img;
    }

    Graphics2D gpcs = (Graphics2D) img.getGraphics();
    gpcs.scale(
        windowSize.getWidth() / canvasSize.getWidth(),
        windowSize.getHeight() / canvasSize.getHeight());

    gpcs.setColor(Color.WHITE);
    gpcs.fillRect(0, 0, (int) canvasSize.getWidth(), (int) canvasSize.getHeight());

    for (Edge e : graph.edgeSet()) {
      if (e.isEnabled()) {
        gpcs.setColor(e.getStrokeColor());
        gpcs.draw(e);
      }
    }

    for (Vertex v : graph.vertexSet()) {
      if (v.isEnabled()) {
        gpcs.setColor(v.getStrokeColor());
        gpcs.draw(v);
        gpcs.setColor(v.getFillColor());
        gpcs.fill(v);
      }
    }

    return img;
  }
  @Override
  public TraversalGraph<V, E> reconstructTraversalGraph() {

    if (currentStartNode == null) {
      throw new IllegalStateException(
          "You must call #calculate before " + "reconstructing the traversal graph.");
    }

    TraversalGraph<V, E> traversalGraph =
        new TraversalGraph<V, E>(graph.getEdgeFactory(), currentStartNode);
    for (V v : graph.vertexSet()) {
      Set<E> predEdges = (Set<E>) v.getPredecessorEdges();
      for (E e : predEdges) {
        V source = graph.getEdgeSource(e);
        V target = graph.getEdgeTarget(e);
        traversalGraph.addVertex(source);
        traversalGraph.addVertex(target);
        if (v.equals(source)) {
          traversalGraph.addEdge(target, source).setBaseGraphEdge(e);
        } else if (v.equals(target)) {
          traversalGraph.addEdge(source, target).setBaseGraphEdge(e);
        } else {
          throw new IllegalStateException(
              "A vertex has a predecessor " + "edge not ending on itself.");
        }
      }
    }

    return traversalGraph;
  }
  private void init(Graph<V, E> g, Set<V> vertexSet, Set<E> edgeSet) {
    // create a map between vertex value to its order(1st,2nd,etc)
    // "CAT"=1 "DOG"=2 "RHINO"=3

    this.mapVertexToOrder = new HashMap<V, Integer>(vertexSet.size());

    int counter = 0;
    for (V vertex : vertexSet) {
      mapVertexToOrder.put(vertex, new Integer(counter));
      counter++;
    }

    // create a friendlier representation of an edge
    // by order, like 2nd->3rd instead of B->A
    // use the map to convert vertex to order
    // on directed graph, edge A->B must be (A,B)
    // on undirected graph, edge A-B can be (A,B) or (B,A)

    this.labelsEdgesSet = new HashSet<LabelsEdge>(edgeSet.size());
    for (E edge : edgeSet) {
      V sourceVertex = g.getEdgeSource(edge);
      Integer sourceOrder = mapVertexToOrder.get(sourceVertex);
      int sourceLabel = sourceOrder.intValue();
      int targetLabel = (mapVertexToOrder.get(g.getEdgeTarget(edge))).intValue();

      LabelsEdge lablesEdge = new LabelsEdge(sourceLabel, targetLabel);
      this.labelsEdgesSet.add(lablesEdge);

      if (g instanceof UndirectedGraph<?, ?>) {
        LabelsEdge oppositeEdge = new LabelsEdge(targetLabel, sourceLabel);
        this.labelsEdgesSet.add(oppositeEdge);
      }
    }
  }
    /**
     * Find the maximum weight matching of a path using dynamic programming.
     *
     * @param path a list of edges. The code assumes that the list of edges is a valid simple path,
     *     and that is not a cycle.
     * @return a maximum weight matching of the path
     */
    public Pair<Double, Set<E>> getMaximumWeightMatching(Graph<V, E> g, LinkedList<E> path) {
      int pathLength = path.size();

      // special cases
      switch (pathLength) {
        case 0:
          // special case, empty path
          return Pair.of(Double.valueOf(0d), Collections.emptySet());
        case 1:
          // special case, one edge
          E e = path.getFirst();
          double eWeight = g.getEdgeWeight(e);
          if (comparator.compare(eWeight, 0d) > 0) {
            return Pair.of(eWeight, Collections.singleton(e));
          } else {
            return Pair.of(Double.valueOf(0d), Collections.emptySet());
          }
      }

      // make sure work array has enough space
      if (a.length < pathLength + 1) {
        a = new double[pathLength + 1];
      }

      // first pass to find solution
      Iterator<E> it = path.iterator();
      E e = it.next();
      double eWeight = g.getEdgeWeight(e);
      a[0] = 0d;
      a[1] = (comparator.compare(eWeight, 0d) > 0) ? eWeight : 0d;
      for (int i = 2; i <= pathLength; i++) {
        e = it.next();
        eWeight = g.getEdgeWeight(e);
        if (comparator.compare(a[i - 1], a[i - 2] + eWeight) > 0) {
          a[i] = a[i - 1];
        } else {
          a[i] = a[i - 2] + eWeight;
        }
      }

      // reverse second pass to build solution
      Set<E> matching = new HashSet<>();
      it = path.descendingIterator();
      int i = pathLength;
      while (i >= 1) {
        e = it.next();
        if (comparator.compare(a[i], a[i - 1]) > 0) {
          matching.add(e);
          // skip next edge
          if (i > 1) {
            e = it.next();
          }
          i--;
        }
        i--;
      }

      // return solution
      return Pair.of(a[pathLength], matching);
    }
  /**
   * Returns a List with unique elements,
   *
   * @param v1 vertex from g1
   * @return
   */
  public List<V> getPrioritySubset(V v1) {
    // The resulting list
    List<V> result = new ArrayList<V>();

    // list of already mapped vertices that neighbour v1
    List<V> v1Others = new ArrayList<V>();

    V v1other;
    V v2other;
    for (E e1 : g1.edgesOf(v1)) {
      v1other = Graphs.getOppositeVertex(g1, e1, v1);
      if (mappedVerticesFromG1.contains(v1other)) {
        v1Others.add(v1other);
      }
    }
    for (V v2 : g2.vertexSet()) {
      // if v2's label is the same of v1's label and v2 has not been mapped yet
      if (v1.getLabel().equals(v2.getLabel()) && !mappedVerticesFromG2.contains(v2)) {
        // test if there is an edge to a vertex which has already been mapped
        for (E e2 : g2.edgesOf(v2)) {
          v2other = Graphs.getOppositeVertex(g2, e2, v2);
          // if the vertex v2other has already been mapped
          if (mappedVerticesFromG2.contains(v2other)) {
            // labels are not checked, this is done at a later stage anyway and doing it twice is
            // not needed and takes too much time
            result.add(v2);
            break;
          }
        }
      }
    }
    return result;
  }
示例#9
0
  /**
   * Constructs a new JGraph model adapter for the specified JGraphT graph.
   *
   * @param jGraphTGraph the JGraphT graph for which JGraph model adapter to be created. <code>null
   *     </code> is NOT permitted.
   * @param defaultVertexAttributes a default map of JGraph attributes to format vertices. <code>
   *     null</code> is NOT permitted.
   * @param defaultEdgeAttributes a default map of JGraph attributes to format edges. <code>null
   *     </code> is NOT permitted.
   * @param cellFactory a {@link CellFactory} to be used to create the JGraph cells. <code>null
   *     </code> is NOT permitted.
   * @throws IllegalArgumentException
   */
  public JGraphModelAdapter(
      Graph<V, E> jGraphTGraph,
      AttributeMap defaultVertexAttributes,
      AttributeMap defaultEdgeAttributes,
      CellFactory<V, E> cellFactory) {
    super();

    if ((jGraphTGraph == null)
        || (defaultVertexAttributes == null)
        || (defaultEdgeAttributes == null)
        || (cellFactory == null)) {
      throw new IllegalArgumentException("null is NOT permitted");
    }

    jtGraph = new ShieldedGraph(jGraphTGraph);
    setDefaultVertexAttributes(defaultVertexAttributes);
    setDefaultEdgeAttributes(defaultEdgeAttributes);
    this.cellFactory = cellFactory;

    if (jGraphTGraph instanceof ListenableGraph<?, ?>) {
      ListenableGraph<V, E> g = (ListenableGraph<V, E>) jGraphTGraph;
      g.addGraphListener(new JGraphTListener());
    }

    for (Iterator<V> i = jGraphTGraph.vertexSet().iterator(); i.hasNext(); ) {
      handleJGraphTAddedVertex(i.next());
    }

    for (Iterator<E> i = jGraphTGraph.edgeSet().iterator(); i.hasNext(); ) {
      handleJGraphTAddedEdge(i.next());
    }

    this.addGraphModelListener(new JGraphListener());
  }
  /**
   * Creates a new iterator for the specified graph. Iteration will start at the specified start
   * vertex. If the specified start vertex is <code>
   * null</code>, Iteration will start at an arbitrary graph vertex.
   *
   * @param g the graph to be iterated.
   * @param startVertex the vertex iteration to be started.
   * @throws IllegalArgumentException if <code>g==null</code> or does not contain <code>startVertex
   *     </code>
   */
  public CrossComponentIterator(Graph<V, E> g, V startVertex) {
    super();

    if (g == null) {
      throw new IllegalArgumentException("graph must not be null");
    }
    graph = g;

    specifics = createGraphSpecifics(g);
    vertexIterator = g.vertexSet().iterator();
    setCrossComponentTraversal(startVertex == null);

    reusableEdgeEvent = new FlyweightEdgeEvent<V, E>(this, null);
    reusableVertexEvent = new FlyweightVertexEvent<V>(this, null);

    if (startVertex == null) {
      // pick a start vertex if graph not empty
      if (vertexIterator.hasNext()) {
        this.startVertex = vertexIterator.next();
      } else {
        this.startVertex = null;
      }
    } else if (g.containsVertex(startVertex)) {
      this.startVertex = startVertex;
    } else {
      throw new IllegalArgumentException("graph must contain the start vertex");
    }
  }
示例#11
0
  public int[] getEdgeNumbers(E e) {
    V v1 = graph.getEdgeSource(e), v2 = graph.getEdgeTarget(e);

    int[] edge = new int[2];
    edge[0] = mapVertexToOrder.get(v1);
    edge[1] = mapVertexToOrder.get(v2);

    return edge;
  }
示例#12
0
    E addEdge(V jtSource, V jtTarget) {
      E jtEdge = graph.getEdgeFactory().createEdge(jtSource, jtTarget);
      jtElementsBeingAdded.add(jtEdge);

      boolean added = graph.addEdge(jtSource, jtTarget, jtEdge);
      jtElementsBeingAdded.remove(jtEdge);

      return added ? jtEdge : null;
    }
  /** Calculates the matrix of all shortest paths, but does not populate the paths map. */
  private void lazyCalculateMatrix() {
    if (d != null) {
      // already done
      return;
    }

    int n = vertices.size();

    // init the backtrace matrix
    backtrace = new int[n][n];
    for (int i = 0; i < n; i++) {
      Arrays.fill(backtrace[i], -1);
    }

    // initialize matrix, 0
    d = new double[n][n];
    for (int i = 0; i < n; i++) {
      Arrays.fill(d[i], Double.POSITIVE_INFINITY);
    }

    // initialize matrix, 1
    for (int i = 0; i < n; i++) {
      d[i][i] = 0.0;
    }

    // initialize matrix, 2
    Set<E> edges = graph.edgeSet();
    for (E edge : edges) {
      V v1 = graph.getEdgeSource(edge);
      V v2 = graph.getEdgeTarget(edge);

      int v_1 = vertices.indexOf(v1);
      int v_2 = vertices.indexOf(v2);

      d[v_1][v_2] = graph.getEdgeWeight(edge);
      if (!(graph instanceof DirectedGraph<?, ?>)) {
        d[v_2][v_1] = graph.getEdgeWeight(edge);
      }
    }

    // run fw alg
    for (int k = 0; k < n; k++) {
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          double ik_kj = d[i][k] + d[k][j];
          if (ik_kj < d[i][j]) {
            d[i][j] = ik_kj;
            backtrace[i][j] = k;
          }
        }
      }
    }
  }
 /**
  * Compute all vertices that have positive degree by iterating over the edges on purpose. This
  * keeps the complexity to O(m) where m is the number of edges.
  *
  * @param graph the graph
  * @return set of vertices with positive degree
  */
 private Set<V> initVisibleVertices(Graph<V, E> graph) {
   Set<V> visibleVertex = new HashSet<>();
   for (E e : graph.edgeSet()) {
     V s = graph.getEdgeSource(e);
     V t = graph.getEdgeTarget(e);
     if (!s.equals(t)) {
       visibleVertex.add(s);
       visibleVertex.add(t);
     }
   }
   return visibleVertex;
 }
  /**
   * Returns a graph, each vertex corresponding with an vector in R, and edges connecting vertices
   * (vectors) if they are obtuse or at right angles.
   *
   * @param TOL > 0 decides how close to zero is considered zero.
   */
  public static Graph<Matrix, DefaultEdge> obtuseConnectedGraph(Set<Matrix> R, double TOL) {
    Graph G = new SimpleGraph<>(DefaultEdge.class);
    for (Matrix v : R) G.addVertex(v); // graph contains the relevant vectors
    int N = R.size();
    Matrix[] b = new Matrix[N];
    R.toArray(b); // build an array with pointers to vectors in R (also vertices in G)

    // add edges between obtuse relevant vectors.
    for (int i = 0; i < N; i++)
      for (int j = i + 1; j < N; j++) if (dot(b[i], b[j]) < Math.abs(TOL)) G.addEdge(b[i], b[j]);

    return G;
  }
  /**
   * Compute weight and add edge to the graph
   *
   * @param way
   * @param from
   * @param to
   */
  private void addEdge(Way way, Node from, Node to) {
    LatLon fromLL = from.getCoor();
    LatLon toLL = from.getCoor();
    if (fromLL == null || toLL == null) {
      return;
    }
    double length = fromLL.greatCircleDistance(toLL);

    OsmEdge edge = new OsmEdge(way, from, to);
    edge.setSpeed(12.1);
    graph.addEdge(from, to, edge);
    // weight = getWeight(way);
    double weight = getWeight(way, length);
    setWeight(edge, length);
    logger.debug(
        "edge for way "
            + way.getId()
            + "(from node "
            + from.getId()
            + " to node "
            + to.getId()
            + ") has weight: "
            + weight);
    ((DirectedWeightedMultigraph<Node, OsmEdge>) graph).setEdgeWeight(edge, weight);
  }
示例#17
0
  /**
   * @param graph the graph to be ordered
   * @param orderByDegree should the vertices be ordered by their degree. This speeds up the VF2
   *     algorithm.
   * @param cacheEdges if true, the class creates a adjacency matrix and two arrays for incoming and
   *     outgoing edges for fast access.
   */
  public GraphOrdering(Graph<V, E> graph, boolean orderByDegree, boolean cacheEdges) {
    this.graph = graph;
    this.cacheEdges = cacheEdges;

    List<V> vertexSet = new ArrayList<>(graph.vertexSet());
    if (orderByDegree) {
      java.util.Collections.sort(vertexSet, new GeneralVertexDegreeComparator<>(graph));
    }

    vertexCount = vertexSet.size();
    mapVertexToOrder = new HashMap<>();
    mapOrderToVertex = new ArrayList<>(vertexCount);

    if (cacheEdges) {
      outgoingEdges = new int[vertexCount][];
      incomingEdges = new int[vertexCount][];
      adjMatrix = new Boolean[vertexCount][vertexCount];
    }

    Integer i = 0;
    for (V vertex : vertexSet) {
      mapVertexToOrder.put(vertex, i++);
      mapOrderToVertex.add(vertex);
    }
  }
 public static Set outgoingEdgesOf(Graph g, Object node) {
   if (g instanceof DirectedGraph) {
     return ((DirectedGraph) g).outgoingEdgesOf(node);
   } else {
     return g.edgesOf(node);
   }
 }
  @Override
  public <N extends Node, E extends Edge> Graph<N, E> createGraph(
      VertexFactory<N> vfac, EdgeFactory<N, E> efac) {
    Integer inp =
        InputDialog.getIntegerInput("Game Tree Factory", "No. of levels?", 2, Integer.MAX_VALUE);
    if (inp == null) {
      return null;
    }

    int levels = inp;
    final double levelSep = ((2 << levels - 1) * (5.0 + 5.0)) / (Math.PI * levels);
    final double shift = levels * levelSep;
    Graph<N, E> graph = new SimpleGraph<>(efac);
    List<N> parents = new LinkedList<>();
    List<N> children = new LinkedList<>();
    Node.PropChanger npr = Node.PropChanger.create();

    N n = vfac.createVertex();
    npr.setPosition(n, polarToCartesian(0, 0, shift));
    graph.addVertex(n);
    parents.add(n);

    for (int i = 1; i <= levels; i++) {
      final double curRadius = i * levelSep;
      double th = 0;
      final double thDelta = Math.PI / parents.size();

      for (N p : parents) {
        N c1 = vfac.createVertex();
        N c2 = vfac.createVertex();
        npr.setPosition(c1, polarToCartesian(curRadius, th + 0.5 * thDelta, shift));
        npr.setPosition(c2, polarToCartesian(curRadius, th + 1.5 * thDelta, shift));
        th += 2 * thDelta;
        graph.addVertex(c1);
        graph.addVertex(c2);
        graph.addEdge(p, c1);
        graph.addEdge(p, c2);
        children.add(c1);
        children.add(c2);
      }
      parents = children;
      children = new LinkedList<>();
    }

    return graph;
  }
示例#20
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;
 }
示例#21
0
  /**
   * Constructs the shortest path array for the given graph.
   *
   * @param g input graph
   * @param <V> a V object.
   * @param <E> a E object.
   */
  public FloydWarshall(Graph<V, E> g) {
    int sz = g.vertexSet().size();
    d = new double[sz][sz];
    indices = new HashMap<V, Integer>();

    // Initialise distance to infinity, or the neighbours weight, or 0 if
    // same
    for (V v1 : g.vertexSet()) {
      for (V v2 : g.vertexSet()) {
        if (v1 == v2) {
          d[index(v1)][index(v2)] = 0;
        } else {
          E e = g.getEdge(v1, v2);

          if (e == null) {
            d[index(v1)][index(v2)] = Double.POSITIVE_INFINITY;
          } else {
            d[index(v1)][index(v2)] = g.getEdgeWeight(e);
          }
        }
      }
    }

    // now iterate k times
    for (int k = 0; k < sz; k++) {
      for (V v1 : g.vertexSet()) {
        for (V v2 : g.vertexSet()) {
          d[index(v1)][index(v2)] =
              Math.min(d[index(v1)][index(v2)], d[index(v1)][k] + d[k][index(v2)]);
          if (Double.POSITIVE_INFINITY != d[index(v1)][index(v2)])
            diameter = Math.max(diameter, d[index(v1)][index(v2)]);
        }
      }
    }
  }
示例#22
0
 /**
  * @return the amount of arcs that are connected on both sides to nodes that have been mapped so
  *     far
  */
 public int getArcsLeftForMappedVertices() {
   int result = 0;
   boolean columnOr;
   for (int y = 0; y < dimy; y++) {
     columnOr = false;
     for (int x = 0; x < dimx; x++) {
       columnOr |= matrix[x][y];
     }
     if (columnOr) {
       // if Edge edgeList2.get(y) is connected (on both sides) to vertices in mappedVerticesFromG2
       if (mappedVerticesFromG2.contains(g2.getEdgeSource(edgeList2.get(y)))
           && mappedVerticesFromG2.contains(g2.getEdgeSource(edgeList2.get(y)))) {
         result++;
       }
     }
   }
   return result;
 }
  /** {@inheritDoc} */
  public void generateGraph(
      Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap) {
    if (size < 1) {
      return;
    }

    // Add all the vertices to the set
    for (int i = 0; i < size; i++) {
      V newVertex = vertexFactory.createVertex();
      target.addVertex(newVertex);
    }

    /*
     * We want two iterators over the vertex set, one fast and one slow.
     * The slow one will move through the set once. For each vertex,
     * the fast iterator moves through the set, adding an edge to all
     * vertices we haven't connected to yet.
     *
     * If we have an undirected graph, the second addEdge call will return
     * nothing; it will not add a second edge.
     */
    Iterator<V> slowI = target.vertexSet().iterator();
    Iterator<V> fastI;

    while (slowI.hasNext()) { // While there are more vertices in the set

      V latestVertex = slowI.next();
      fastI = target.vertexSet().iterator();

      // Jump to the first vertex *past* latestVertex
      while (fastI.next() != latestVertex) {;
      }

      // And, add edges to all remaining vertices
      V temp;
      while (fastI.hasNext()) {
        temp = fastI.next();
        target.addEdge(latestVertex, temp);
        target.addEdge(temp, latestVertex);
      }
    }
  }
示例#24
0
  @Override
  public void setGraph(Graph<? extends Vertex, ? extends Edge> g) {
    this.graph = g;
    Rectangle r = new Rectangle();

    for (Vertex v : g.vertexSet()) {
      r = r.union(v.getBounds());
    }
    canvasSize =
        new Dimension((int) Math.ceil(r.getWidth()) + 20, (int) Math.ceil(r.getHeight()) + 20);
  }
 private void shortestPathRecur(List<E> edges, int v_a, int v_b) {
   int k = backtrace[v_a][v_b];
   if (k == -1) {
     E edge = graph.getEdge(vertices.get(v_a), vertices.get(v_b));
     if (edge != null) {
       edges.add(edge);
     }
   } else {
     shortestPathRecur(edges, v_a, k);
     shortestPathRecur(edges, k, v_b);
   }
 }
  public long countExternalEdges(Integer i, Set<DefaultWeightedEdge> neighborSet) {

    int numberExternalEdges = 0;

    // count number of external edges
    for (DefaultWeightedEdge edge : neighborSet) {

      // no easy way to get 'other' out of JGraph's undirected graph edge traversal... ugh!
      Integer src = graph.getEdgeSource(edge);
      Integer dst = graph.getEdgeTarget(edge);
      Integer other = src.equals(i) ? dst : src;

      if (contains(other)) {
        numberExternalEdges -= 1;
      } else {
        numberExternalEdges += 1;
      }
    }

    return numberExternalEdges;
  }
示例#27
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;
 }
示例#28
0
  /** {@inheritDoc} */
  public void generateGraph(
      Graph<V, E> target, final VertexFactory<V> vertexFactory, Map<String, V> resultMap) {
    if (size < 1) {
      return;
    }

    // A little trickery to intercept the rim generation.  This is
    // necessary since target may be initially non-empty, meaning we can't
    // rely on its vertex set after the rim is generated.
    final Collection<V> rim = new ArrayList<V>();
    VertexFactory<V> rimVertexFactory =
        new VertexFactory<V>() {
          public V createVertex() {
            V vertex = vertexFactory.createVertex();
            rim.add(vertex);

            return vertex;
          }
        };

    RingGraphGenerator<V, E> ringGenerator = new RingGraphGenerator<V, E>(size - 1);
    ringGenerator.generateGraph(target, rimVertexFactory, resultMap);

    V hubVertex = vertexFactory.createVertex();
    target.addVertex(hubVertex);

    if (resultMap != null) {
      resultMap.put(HUB_VERTEX, hubVertex);
    }

    for (V rimVertex : rim) {
      if (inwardSpokes) {
        target.addEdge(rimVertex, hubVertex);
      } else {
        target.addEdge(hubVertex, rimVertex);
      }
    }
  }
  /** {@inheritDoc} */
  public void generateGraph(
      Graph<V, E> target, VertexFactory<V> vertexFactory, Map<String, V> resultMap) {
    V lastVertex = null;

    for (int i = 0; i < size; ++i) {
      V newVertex = vertexFactory.createVertex();
      target.addVertex(newVertex);

      if (lastVertex == null) {
        if (resultMap != null) {
          resultMap.put(START_VERTEX, newVertex);
        }
      } else {
        target.addEdge(lastVertex, newVertex);
      }

      lastVertex = newVertex;
    }

    if ((resultMap != null) && (lastVertex != null)) {
      resultMap.put(END_VERTEX, lastVertex);
    }
  }
示例#30
0
  @Override
  public void generateGraph(
      Graph<V, E> veGraph, VertexFactory<V> vVertexFactory, Map<String, V> stringVMap) {

    Map<Integer, V> intToNodeMap = new HashMap<Integer, V>();

    for (Integer nodeID : selected.vertices.keySet()) {
      V node = vVertexFactory.createVertex();
      if (!veGraph.containsVertex(node)) veGraph.addVertex(node);
      intToNodeMap.put(nodeID, node);
    }

    for (PajekArc arc : selected.arcs) {
      V source = intToNodeMap.get(arc.source);
      V target = intToNodeMap.get(arc.target);
      E edge = null;
      if (!veGraph.containsEdge(source, target)) edge = veGraph.addEdge(source, target);
      else edge = veGraph.getEdge(source, target);

      if (veGraph instanceof WeightedGraph)
        ((WeightedGraph) veGraph).setEdgeWeight(edge, arc.weight);
    }
  }