Exemplo n.º 1
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)]);
        }
      }
    }
  }
Exemplo n.º 2
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);
    }
  }
Exemplo n.º 3
0
  /**
   * 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;
  }
Exemplo n.º 4
0
  /**
   * 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");
    }
  }
  @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;
  }
Exemplo n.º 6
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;
  }
Exemplo n.º 7
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());
  }
Exemplo n.º 8
0
  /** {@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);
      }
    }
  }
Exemplo n.º 9
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);
  }
Exemplo n.º 10
0
 /**
  * Creates a new labels graph according to the regular graph. After its creation they will no
  * longer be linked, thus changes to one will not affect the other.
  *
  * @param regularGraph
  */
 public GraphOrdering(Graph<V, E> regularGraph) {
   this(regularGraph, regularGraph.vertexSet(), regularGraph.edgeSet());
 }
Exemplo n.º 11
0
 /**
  * Return the number of vertices.
  *
  * @return the number of vertices.
  */
 public int getVertexCount() {
   int value = 0;
   if (graph != null) value = graph.vertexSet().size();
   return value;
 }
Exemplo n.º 12
0
  /**
   * Create OSM graph for routing
   *
   * @return
   */
  public void createGraph() {

    logger.debug("Creating Graph...");
    graph = new DirectedWeightedMultigraph<>(OsmEdge.class);
    rgDelegator = new RoutingGraphDelegator(graph);
    rgDelegator.setRouteType(this.routeType);
    // iterate all ways and segments for all nodes:
    for (Way way : data.getWays()) {

      // skip way if not suitable for routing.
      if (way == null || way.isDeleted() || !this.isvalidWay(way) || way.getNodes().size() < 1)
        continue;

      // INIT
      Node from = null;
      Node to = null;
      List<Node> nodes = way.getNodes();
      int nodes_count = nodes.size();

      /*
       * Assume node is A B C D E. The procedure should be
       *
       *  case 1 - bidirectional ways:
       *  1) Add vertex A B C D E
       *  2) Link A<->B, B<->C, C<->D, D<->E as Edges
       *
       *  case 2 - oneway reverse:
       *  1) Add vertex A B C D E
       *  2) Link B->A,C->B,D->C,E->D as Edges. result: A<-B<-C<-D<-E
       *
       *  case 3 - oneway normal:
       *  1) Add vertex A B C D E
       *  2) Link A->B, B->C, C->D, D->E as Edges. result: A->B->C->D->E
       *
       *
       */

      String oneway_val = way.get("oneway"); /*   get (oneway=?) tag for this way.   */
      String junction_val = way.get("junction"); /*   get (junction=?) tag for this way.   */

      from = nodes.get(0); /*   1st node A  */
      graph.addVertex(from); /*   add vertex A */

      for (int i = 1; i < nodes_count; i++) {
        /*   loop from B until E */

        to = nodes.get(i); /*   2nd node B   */

        if (to != null && !to.isDeleted()) {
          graph.addVertex(to); /*   add vertex B */

          // this is where we link the vertices
          if (!routingProfile.isOnewayUsed()) {
            // "Ignore oneways" is selected
            addEdgeBidirectional(way, from, to);

          } else if (oneway_val == null && junction_val == "roundabout") {
            // Case (roundabout): oneway=implicit yes
            addEdgeNormalOneway(way, from, to);

          } else if (oneway_val == null
              || oneway_val == "false"
              || oneway_val == "no"
              || oneway_val == "0") {
            // Case (bi-way): oneway=false OR oneway=unset OR oneway=0 OR oneway=no
            addEdgeBidirectional(way, from, to);

          } else if (oneway_val == "-1") {
            // Case (oneway reverse): oneway=-1
            addEdgeReverseOneway(way, from, to);

          } else if (oneway_val == "1" || oneway_val == "yes" || oneway_val == "true") {
            // Case (oneway normal): oneway=yes OR 1 OR true
            addEdgeNormalOneway(way, from, to);
          }

          from = to; /*   we did A<->B, next loop we will do B<->C, so from=B,to=C for next loop. */
        }
      } // end of looping thru nodes
    } // end of looping thru ways

    logger.debug("End Create Graph");
    logger.debug("Vertex: " + graph.vertexSet().size());
    logger.debug("Edges: " + graph.edgeSet().size());
  }
Exemplo n.º 13
0
 public int getNumberOfNodes() {
   return myGraph.vertexSet().size();
 }
Exemplo n.º 14
0
 public List<Node> getAllNodes() {
   return new ArrayList<>(myGraph.vertexSet());
 }
 public FloydWarshallShortestPaths(Graph<V, E> graph) {
   this.graph = graph;
   this.vertices = new ArrayList<V>(graph.vertexSet());
 }
 /**
  * Creates an object to calculate shortest paths between the start vertex and others vertices
  * using the Bellman-Ford algorithm.
  *
  * @param graph
  * @param startVertex
  */
 public BellmanFordShortestPath(Graph<V, E> graph, V startVertex) {
   this(graph, startVertex, graph.vertexSet().size() - 1);
 }
Exemplo n.º 17
0
  public static void main(String[] args) throws IOException {
    System.out.println("Enter parameters: N p_w p_r steps:");
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      String paras[] = reader.readLine().split(" ");
      N = Integer.parseInt(paras[0]);
      p_w = Float.parseFloat(paras[1]);
      p_r = Float.parseFloat(paras[2]);
      steps = Integer.parseInt(paras[3]);
    } catch (IOException e) {
      System.out.println("Error reading from user");
    }

    long start = System.currentTimeMillis();

    int simulations = 1;
    for (int t = 1; t <= simulations; t++) {

      // Initialization, generate an empty network of N nodes
      EIM dynamic = new EIM();
      G = new SimpleWeightedGraph<Integer, DefaultWeightedEdge>(DefaultWeightedEdge.class);
      for (int i = 0; i < N; i++) G.addVertex(i);
      String para = "EIM_" + Integer.toString(t);
      String folder = "files/" + "Networks" + "/";
      File f = new File(folder);
      if (f.exists() == false) {
        f.mkdirs();
      }

      // distribution of social space
      socialposition = dynamic.uniform(N);

      for (int s = 0; s < steps; s++) {
        int v = random.nextInt(N);
        // LA process - weighted random walk + link with social distance
        dynamic.localattach(v);
        // GA process
        // no edges, create one random link
        if (G.edgesOf(v).size() == 0) {
          dynamic.globalattach(v);
        } else {
          float prob = random.nextFloat();
          if (prob < p_r) dynamic.globalattach(v);
        }
        // ND process
        int d = random.nextInt(N);
        if (G.edgesOf(d).size() > 0) {
          float prob = random.nextFloat();
          if (prob < p_d) {
            Set<DefaultWeightedEdge> edges = new HashSet(G.edgesOf(d));
            G.removeAllEdges(edges);
          }
        }
        if (s % 100000 == 0) {
          System.out.print("Steps:" + Integer.toString(s) + "	");
          System.out.print("Edges:");
          System.out.print(G.edgeSet().size() + "	");
          System.out.println(
              "Avg_degree: "
                  + Float.toString((float) G.edgeSet().size() * 2 / G.vertexSet().size()));
        }
      }
      // delete isolate nodes
      ArrayList<Integer> nodelist = new ArrayList<Integer>();
      for (int node : G.vertexSet()) nodelist.add(node);
      for (int node : nodelist) {
        if (G.degreeOf(node) == 0) G.removeVertex(node);
      }
      System.out.print("Nodes:");
      System.out.println(G.vertexSet().size());
      System.out.print("Edges:");
      System.out.println(G.edgeSet().size());

      // get largest connected component
      Statistics stat = new Statistics();
      Graph G_LCC = stat.largestConnectedComponent(G);

      ExportGraph export = new ExportGraph();
      export.exportWPairs((SimpleWeightedGraph<Integer, DefaultWeightedEdge>) G_LCC, para, folder);
      System.out.print("Nodes in LCC:");
      System.out.println(G_LCC.vertexSet().size());
      System.out.print("Edges in LCC:");
      System.out.println(G_LCC.edgeSet().size());
      System.out.println("Avg_degree: " + Double.toString(stat.avg_degree(G_LCC)));
      System.out.println("Avg_clustering: " + Double.toString(stat.avg_clustering(G_LCC)));
      System.out.println(
          "Degree assortativity: " + Double.toString(stat.assortativityCoefficient(G_LCC)));
    }

    long elapsedTimeMillis = System.currentTimeMillis() - start;
    float elapsedTimeHour = elapsedTimeMillis / (60 * 60 * 1000F);
    System.out.print("Elapsed time: ");
    System.out.print(elapsedTimeHour);
    System.out.println(" hours.");
  }
Exemplo n.º 18
0
  /**
   * @param connectedOnly if true, the result will be a connected graph
   * @return
   */
  public Graph<V, E> toGraph() {
    if (subgraph != null) return subgraph;
    if (directed) {
      subgraph = new DirectedMultigraph<V, E>(g2.getEdgeFactory());
    } else {
      subgraph = new Multigraph<V, E>(g2.getEdgeFactory());
    }

    E edge;
    V source;
    V target;
    for (int x = 0; x < dimx; x++) {
      for (int y = 0; y < dimy; y++) {
        if (matrix[x][y]) {
          edge = edgeList2.get(y);
          source = g2.getEdgeSource(edge);
          target = g2.getEdgeTarget(edge);
          if (mappedVerticesFromG2.contains(source) && mappedVerticesFromG2.contains(target)) {
            // make sure the source and target vertices have been added, then add the edge
            subgraph.addVertex(source);
            subgraph.addVertex(target);
            subgraph.addEdge(source, target, edge);
          }
        }
      }
    }

    if (connectedOnly) {
      // make sure this subgraph is connected, if it is not return the largest connected part
      List<Set<V>> connectedVertices = new ArrayList<Set<V>>();
      for (V v : subgraph.vertexSet()) {
        if (!SharedStaticMethods.containsV(connectedVertices, v)) {
          connectedVertices.add(SharedStaticMethods.getConnectedVertices(subgraph, v));
        }
      }
      // ConnectedVertices now contains Sets of connected vertices every vertex of the subgraph is
      // contained exactly once in the list
      // if there is more then 1 set, then this method should return the largest connected part of
      // the graph
      if (connectedVertices.size() > 1) {
        Graph<V, E> largestResult = null;
        Graph<V, E> currentGraph;
        int largestSize = -1;
        Set<V> currentSet;
        for (int i = 0; i < connectedVertices.size(); i++) {
          currentSet = connectedVertices.get(i);
          /*note that 'subgraph' is the result from the Mcgregor algorithm, 'currentGraph' is an
           * induced subgraph of 'subgraph'. 'currentGraph' is connected, because the vertices in
           * 'currentSet' are connected with edges in 'subgraph'
           */
          currentGraph = new Subgraph<V, E, Graph<V, E>>(subgraph, currentSet);
          if (currentGraph.edgeSet().size() > largestSize) {
            largestResult = currentGraph;
          }
        }

        return largestResult;
      }
    }

    return subgraph;
  }