@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;
  }
  /**
   * 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());
  }
Exemple #3
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;
 }
 /**
  * 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;
 }
  /** 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;
          }
        }
      }
    }
  }
Exemple #6
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;
 }
 public Marcs(Graph<V, E> g1, Graph<V, E> g2, boolean connectedOnly, int labelSize) {
   this.g1 = g1;
   this.g2 = g2;
   edgeList1 = new ArrayList<E>(g1.edgeSet());
   edgeList2 = new ArrayList<E>(g2.edgeSet());
   mappedVerticesFromG1 = new ArrayList<V>();
   mappedVerticesFromG2 = new ArrayList<V>();
   dimx = edgeList1.size();
   dimy = edgeList2.size();
   directed = g1 instanceof DirectedGraph && g2 instanceof DirectedGraph;
   this.connectedOnly = connectedOnly;
   matrix = new boolean[dimx][dimy];
   rowOrs = new boolean[dimx];
   for (int x = 0; x < dimx; x++) {
     rowOrs[x] = true;
     for (int y = 0; y < dimy; y++) {
       matrix[x][y] = edgesCompatible(x, y);
     }
   }
   labelCount = new int[labelSize];
   for (int i = 0; i < labelSize; i++) {
     labelCount[i] = 0;
   }
 }
Exemple #8
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.");
  }
  // the algorithm (improved with additional heuristics)
  private Pair<Double, Set<E>> runWithHeuristics(Graph<V, E> graph) {
    // lookup all relevant vertices
    Set<V> visibleVertex = initVisibleVertices(graph);

    // create solver for paths
    DynamicProgrammingPathSolver pathSolver = new DynamicProgrammingPathSolver();

    Set<E> matching = new HashSet<>();
    double matchingWeight = 0d;
    Set<V> matchedVertices = new HashSet<>();

    // run algorithm
    while (!visibleVertex.isEmpty()) {
      // find vertex arbitrarily
      V x = visibleVertex.stream().findAny().get();

      // grow path from x
      LinkedList<E> path = new LinkedList<>();
      while (x != null) {
        // first heaviest edge incident to vertex x (among visible neighbors)
        double maxWeight = 0d;
        E maxWeightedEdge = null;
        V maxWeightedNeighbor = null;
        for (E e : graph.edgesOf(x)) {
          V other = Graphs.getOppositeVertex(graph, e, x);
          if (visibleVertex.contains(other) && !other.equals(x)) {
            double curWeight = graph.getEdgeWeight(e);
            if (comparator.compare(curWeight, 0d) > 0
                && (maxWeightedEdge == null || comparator.compare(curWeight, maxWeight) > 0)) {
              maxWeight = curWeight;
              maxWeightedEdge = e;
              maxWeightedNeighbor = other;
            }
          }
        }

        // add edge to path and remove x
        if (maxWeightedEdge != null) {
          path.add(maxWeightedEdge);
        }
        visibleVertex.remove(x);

        // go to next vertex
        x = maxWeightedNeighbor;
      }

      // find maximum weight matching of path using dynamic programming
      Pair<Double, Set<E>> pathMatching = pathSolver.getMaximumWeightMatching(graph, path);

      // add it to result while keeping track of matched vertices
      matchingWeight += pathMatching.getFirst();
      for (E e : pathMatching.getSecond()) {
        V s = graph.getEdgeSource(e);
        V t = graph.getEdgeTarget(e);
        if (!matchedVertices.add(s)) {
          throw new RuntimeException("Set is not a valid matching, please submit a bug report");
        }
        if (!matchedVertices.add(t)) {
          throw new RuntimeException("Set is not a valid matching, please submit a bug report");
        }
        matching.add(e);
      }
    }

    // extend matching to maximal cardinality (out of edges with positive weight)
    for (E e : graph.edgeSet()) {
      double edgeWeight = graph.getEdgeWeight(e);
      if (comparator.compare(edgeWeight, 0d) <= 0) {
        // ignore zero or negative weight
        continue;
      }
      V s = graph.getEdgeSource(e);
      if (matchedVertices.contains(s)) {
        // matched vertex, ignore
        continue;
      }
      V t = graph.getEdgeTarget(e);
      if (matchedVertices.contains(t)) {
        // matched vertex, ignore
        continue;
      }
      // add edge to matching
      matching.add(e);
      matchingWeight += edgeWeight;
    }

    // return extended matching
    return Pair.of(matchingWeight, matching);
  }
 /**
  * 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());
 }
 /**
  * Return the number of edges.
  *
  * @return the number of edges.
  */
 public int getEdgeCount() {
   int value = 0;
   if (graph != null) value = graph.edgeSet().size();
   return value;
 }
  /**
   * 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());
  }
Exemple #13
0
 public int getNumberOfEdges() {
   return myGraph.edgeSet().size();
 }
Exemple #14
0
 public List<Edge> getAllEdges() {
   return new ArrayList<>(myGraph.edgeSet());
 }
  public UnweightedCommunity(Graph<Integer, DefaultWeightedEdge> g) {
    graph = g;

    totalEdges = graph.edgeSet().size();
    totalVolume = 2 * totalEdges;
  }
  /**
   * @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;
  }