コード例 #1
0
  public static void convertGraphToImage(Graph grap) {
    try {
      Layout layout = new CircleLayout(grap);

      Dimension dime = new Dimension(grap.getEdgeCount() * 100, grap.getEdgeCount() * 100);

      VisualizationImageServer vv = new VisualizationImageServer(layout, dime);

      Transformer<String, Paint> vertexPaint =
          new Transformer<String, Paint>() {
            @Override
            public Paint transform(String i) {
              return Color.BLUE;
            }
          };

      Transformer<String, Stroke> edgeStrokeTransformer =
          new Transformer<String, Stroke>() {
            @Override
            public Stroke transform(String s) {
              Stroke edgeStroke =
                  new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
              return edgeStroke;
            }
          };

      vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
      vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
      vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
      vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
      vv.getRenderContext()
          .setVertexLabelRenderer(
              new DefaultVertexLabelRenderer(Color.yellow) {
                @Override
                public Font getFont() {
                  return new Font(Font.SERIF, 1, 30);
                }

                @Override
                public Color getForeground() {
                  return Color.YELLOW;
                }
              });
      vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.AUTO);

      BufferedImage bim = (BufferedImage) vv.getImage(new Point(), dime);

      File f =
          new File(Util.dateDataToString(new Date(), "dd-MM-yyyy_HH-mm") + "_imagem_teste.png");

      ImageIO.write(bim, "png", f);

      System.out.println("wrote image for " + f.getAbsolutePath());
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #2
0
 @Test
 public void testBacked() {
   Cluster<Integer, Integer> c = new BackedClusterImpl<Integer, Integer>(graph);
   Graph<Integer, Integer> inducedGraph = c.getInducedGraph();
   assertEquals(0, inducedGraph.getEdgeCount());
   assertEquals(0, c.size());
   c.add(0);
   c.add(1);
   assertEquals(2, c.size());
   assertEquals(1, inducedGraph.getEdgeCount());
 }
コード例 #3
0
  /**
   * Finds the set of clusters which have the strongest "community structure". The more edges
   * removed the smaller and more cohesive the clusters.
   *
   * @param graph the graph
   */
  public Set<Set<V>> transform(Graph<V, E> graph) {

    if (mNumEdgesToRemove < 0 || mNumEdgesToRemove > graph.getEdgeCount()) {
      throw new IllegalArgumentException("Invalid number of edges passed in.");
    }

    edges_removed.clear();

    for (int k = 0; k < mNumEdgesToRemove; k++) {
      BetweennessCentrality<V, E> bc = new BetweennessCentrality<V, E>(graph);
      E to_remove = null;
      double score = 0;
      for (E e : graph.getEdges()) {
        Integer weight = mWeight.get(e);
        if (bc.getEdgeScore(e) / weight > score) {
          to_remove = e;
          score = bc.getEdgeScore(e) / weight;
        }
      }
      edges_removed.put(to_remove, graph.getEndpoints(to_remove));
      graph.removeEdge(to_remove);
    }

    WeakComponentClusterer<V, E> wcSearch = new WeakComponentClusterer<V, E>();
    Set<Set<V>> clusterSet = wcSearch.transform(graph);

    for (Map.Entry<E, Pair<V>> entry : edges_removed.entrySet()) {
      Pair<V> endpoints = entry.getValue();
      graph.addEdge(entry.getKey(), endpoints.getFirst(), endpoints.getSecond());
    }
    return clusterSet;
  }
コード例 #4
0
ファイル: PajekNetIOTest.java プロジェクト: RomaKoks/jung
  public void testNoLabels() throws IOException {
    String test = "*Vertices 3\n1\n2\n3\n*Edges\n1 2\n2 2";
    Reader r = new StringReader(test);

    Graph<Number, Number> g = pnr.load(r, undirectedGraphFactory);
    assertEquals(g.getVertexCount(), 3);
    assertEquals(g.getEdgeCount(), 2);
  }
コード例 #5
0
ファイル: PajekNetIOTest.java プロジェクト: RomaKoks/jung
  /**
   * Tests to see whether these two graphs are structurally equivalent, based on the connectivity of
   * the vertices with matching indices in each graph. Assumes a 0-based index.
   *
   * @param g1
   * @param g2
   */
  private void compareIndexedGraphs(Graph<Number, Number> g1, Graph<Number, Number> g2) {
    int n1 = g1.getVertexCount();
    int n2 = g2.getVertexCount();

    assertEquals(n1, n2);

    assertEquals(g1.getEdgeCount(), g2.getEdgeCount());

    List<Number> id1 = new ArrayList<Number>(g1.getVertices());
    List<Number> id2 = new ArrayList<Number>(g2.getVertices());

    for (int i = 0; i < n1; i++) {
      Number v1 = id1.get(i);
      Number v2 = id2.get(i);
      assertNotNull(v1);
      assertNotNull(v2);

      checkSets(g1.getPredecessors(v1), g2.getPredecessors(v2), id1, id2);
      checkSets(g1.getSuccessors(v1), g2.getSuccessors(v2), id1, id2);
    }
  }
コード例 #6
0
  /**
   * Searches the graph and searches for the shortest path from a given start node to the
   * destination. Returns {@code null} if there are no vertices, edges, or path to the goal,
   * otherwise a list with the order of vertices on the shortest path.
   *
   * @param graph The graph to search
   * @param source The vertex to start the search from
   * @param destination The goal vertex
   * @return A list with the order of vertices on the shortest path, null if no path exists in the
   *     graph.
   */
  public List<V> search(Graph<V, E> graph, V source, V destination) {

    // Check if it is even possible to find a path, return null
    // if the graph has no vertices or edges
    if (graph.getVertexCount() == 0) {
      System.out.println("No nodes in the graph, " + "no shortest path can be found");
      return null;
    } else if (graph.getEdgeCount() == 0) {
      System.out.println("No edges in graph, no path " + "can be found");
      return null;
    }

    // Keep record of distance to each vertex, map each vertex
    // in the graph to it's distance
    HashMap<V, Number> distanceTable = new HashMap<>();

    // Unvisited node queue, uses a pair <Vertex, Double> and ordered
    // by the distance to the vertex
    PriorityQueue<Pair<V, Number>> queue = new PriorityQueue<>(new QueueComparator());

    // Map of nodes on the path, parents is value, key is child
    HashMap<V, V> parent = new HashMap<>();

    Number maxValue;
    E edgeTest = graph.getEdges().iterator().next();

    // This is so ugly, I hate Java Numbers
    int numberType = 0;
    if (edgeTest.getWeight() instanceof Integer) {
      numberType = 1;
    } else if (edgeTest.getWeight() instanceof Double) {
      numberType = 2;
    }
    // Place each vertex in the map, initialize distances and put
    // the pairings into the queue.
    for (V vertex : graph.getVertices()) {
      if (numberType == 1) {
        maxValue = Integer.MAX_VALUE;
        if (vertex.equals(source)) {
          distanceTable.put(source, 0);
          queue.add(new Pair<>(vertex, 0));
        } else {
          distanceTable.put(vertex, Integer.MAX_VALUE);
          queue.add(new Pair<>(vertex, maxValue));
        }
      } else if (numberType == 2) {
        maxValue = Double.MAX_VALUE;
        if (vertex.equals(source)) {
          distanceTable.put(source, 0.0);
          queue.add(new Pair<>(vertex, 0.0));
        } else {
          distanceTable.put(vertex, Double.MAX_VALUE);
          queue.add(new Pair<>(vertex, maxValue));
        }
      }
    }

    parent.put(source, null);

    while (!queue.isEmpty()) {

      Pair<V, Number> topPair = queue.remove();
      V vertex = topPair.getLeft();

      // Goal test, return the list of nodes on the path
      // if we reach the destination
      if (vertex.equals(destination)) {
        return tracePath(parent, destination);
      }

      Collection<V> neighbours = graph.getNeighbors(vertex);

      for (V neighbour : neighbours) {

        E edge = graph.findEdge(vertex, neighbour);
        assert (edge != null);

        // Test for type of number used for weight, work accordingly
        // Did I mention I hate the Java Number class.
        if (numberType == 1) {

          Integer alternateDistance = (Integer) edge.getWeight();

          if (alternateDistance < (Integer) distanceTable.get(neighbour)) {
            distanceTable.put(neighbour, alternateDistance);
            parent.put(neighbour, vertex);
            queue.add(new Pair<>(neighbour, alternateDistance));
          }
        } else if (numberType == 2) {
          Double alternateDistance = (Double) edge.getWeight();

          if (alternateDistance < (Double) distanceTable.get(neighbour)) {
            distanceTable.put(neighbour, alternateDistance);
            parent.put(neighbour, vertex);
            queue.add(new Pair<>(neighbour, alternateDistance));
          }
        }
      }
    }
    // Exhausted all possible paths from source, could not find a path
    // to the goal.
    return null;
  }
コード例 #7
0
ファイル: PajekNetIOTest.java プロジェクト: RomaKoks/jung
  public void testMixedSaveLoadSave() throws IOException {
    Graph<Number, Number> graph1 = new SparseMultigraph<Number, Number>();
    for (int i = 0; i < 5; i++) {
      graph1.addVertex(i);
    }
    int j = 0;

    List<Number> id = new ArrayList<Number>(graph1.getVertices());
    GreekLabels<Number> gl = new GreekLabels<Number>(id);
    Number[] edges = {0, 1, 2, 3, 4, 5};

    graph1.addEdge(j++, 0, 1, EdgeType.DIRECTED);
    graph1.addEdge(j++, 0, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 2, EdgeType.DIRECTED);
    graph1.addEdge(j++, 1, 3);
    graph1.addEdge(j++, 1, 4);
    graph1.addEdge(j++, 4, 3);

    Map<Number, Number> nr = new HashMap<Number, Number>();
    for (int i = 0; i < edges.length; i++) {
      nr.put(edges[i], new Float(Math.random()));
    }

    assertEquals(graph1.getEdgeCount(), 6);

    //        System.err.println(" mixed graph1 = "+graph1);
    //        for(Number edge : graph1.getEdges()) {
    //        	System.err.println("edge "+edge+" is directed? "+graph1.getEdgeType(edge));
    //        }
    //        for(Number v : graph1.getVertices()) {
    //        	System.err.println(v+" outedges are "+graph1.getOutEdges(v));
    //        	System.err.println(v+" inedges are "+graph1.getInEdges(v));
    //        	System.err.println(v+" incidentedges are "+graph1.getIncidentEdges(v));
    //        }

    String testFilename = "mtest.net";
    String testFilename2 = testFilename + "2";

    // assign arbitrary locations to each vertex
    Map<Number, Point2D> locations = new HashMap<Number, Point2D>();
    for (Number v : graph1.getVertices()) {
      locations.put(v, new Point2D.Double(v.intValue() * v.intValue(), 1 << v.intValue()));
    }
    Function<Number, Point2D> vld = Functions.forMap(locations);

    PajekNetWriter<Number, Number> pnw = new PajekNetWriter<Number, Number>();
    pnw.save(graph1, testFilename, gl, Functions.forMap(nr), vld);

    Graph<Number, Number> graph2 = pnr.load(testFilename, graphFactory);
    Function<Number, String> pl = pnr.getVertexLabeller();
    List<Number> id2 = new ArrayList<Number>(graph2.getVertices());
    Function<Number, Point2D> vld2 = pnr.getVertexLocationTransformer();

    assertEquals(graph1.getVertexCount(), graph2.getVertexCount());
    assertEquals(graph1.getEdgeCount(), graph2.getEdgeCount());

    // test vertex labels and locations
    for (int i = 0; i < graph1.getVertexCount(); i++) {
      Number v1 = id.get(i);
      Number v2 = id2.get(i);
      assertEquals(gl.apply(v1), pl.apply(v2));
      assertEquals(vld.apply(v1), vld2.apply(v2));
    }

    // test edge weights
    Function<Number, Number> nr2 = pnr.getEdgeWeightTransformer();
    for (Number e2 : graph2.getEdges()) {
      Pair<Number> endpoints = graph2.getEndpoints(e2);
      Number v1_2 = endpoints.getFirst();
      Number v2_2 = endpoints.getSecond();
      Number v1_1 = id.get(id2.indexOf(v1_2));
      Number v2_1 = id.get(id2.indexOf(v2_2));
      Number e1 = graph1.findEdge(v1_1, v2_1);
      assertNotNull(e1);
      assertEquals(nr.get(e1).floatValue(), nr2.apply(e2).floatValue(), 0.0001);
    }

    pnw.save(graph2, testFilename2, pl, nr2, vld2);

    compareIndexedGraphs(graph1, graph2);

    pnr.setVertexLabeller(null);
    Graph<Number, Number> graph3 = pnr.load(testFilename2, graphFactory);

    compareIndexedGraphs(graph2, graph3);

    File file1 = new File(testFilename);
    File file2 = new File(testFilename2);

    Assert.assertTrue(file1.length() == file2.length());
    file1.delete();
    file2.delete();
  }
コード例 #8
0
ファイル: PajekNetIOTest.java プロジェクト: RomaKoks/jung
  public void testUndirectedSaveLoadSave() throws IOException {
    UndirectedGraph<Number, Number> graph1 = undirectedGraphFactory.get();
    for (int i = 0; i < 5; i++) {
      graph1.addVertex(i);
    }

    List<Number> id = new ArrayList<Number>(graph1.getVertices());
    int j = 0;
    GreekLabels<Number> gl = new GreekLabels<Number>(id);
    graph1.addEdge(j++, 0, 1);
    graph1.addEdge(j++, 0, 2);
    graph1.addEdge(j++, 1, 2);
    graph1.addEdge(j++, 1, 3);
    graph1.addEdge(j++, 1, 4);
    graph1.addEdge(j++, 4, 3);

    assertEquals(graph1.getEdgeCount(), 6);

    //        System.err.println("graph1 = "+graph1);
    //        for(Number edge : graph1.getEdges()) {
    //        	System.err.println("edge "+edge+" is directed? "+graph1.getEdgeType(edge));
    //        }
    //        for(Number v : graph1.getVertices()) {
    //        	System.err.println(v+" outedges are "+graph1.getOutEdges(v));
    //        	System.err.println(v+" inedges are "+graph1.getInEdges(v));
    //        	System.err.println(v+" incidentedges are "+graph1.getIncidentEdges(v));
    //        }

    String testFilename = "utest.net";
    String testFilename2 = testFilename + "2";

    PajekNetWriter<Number, Number> pnw = new PajekNetWriter<Number, Number>();
    pnw.save(graph1, testFilename, gl, null, null);

    Graph<Number, Number> graph2 = pnr.load(testFilename, undirectedGraphFactory);

    //        System.err.println("graph2 = "+graph2);
    //        for(Number edge : graph2.getEdges()) {
    //        	System.err.println("edge "+edge+" is directed? "+graph2.getEdgeType(edge));
    //        }
    //        for(Number v : graph2.getVertices()) {
    //        	System.err.println(v+" outedges are "+graph2.getOutEdges(v));
    //        	System.err.println(v+" inedges are "+graph2.getInEdges(v));
    //        	System.err.println(v+" incidentedges are "+graph2.getIncidentEdges(v));
    //        }

    assertEquals(graph1.getVertexCount(), graph2.getVertexCount());
    assertEquals(graph1.getEdgeCount(), graph2.getEdgeCount());

    pnw.save(graph2, testFilename2, pnr.getVertexLabeller(), null, null);
    compareIndexedGraphs(graph1, graph2);

    Graph<Number, Number> graph3 = pnr.load(testFilename2, graphFactory);
    //        System.err.println("graph3 = "+graph3);
    //        for(Number edge : graph3.getEdges()) {
    //        	System.err.println("edge "+edge+" is directed? "+graph3.getEdgeType(edge));
    //        }
    //        for(Number v : graph3.getVertices()) {
    //        	System.err.println(v+" outedges are "+graph3.getOutEdges(v));
    //        	System.err.println(v+" inedges are "+graph3.getInEdges(v));
    //        	System.err.println(v+" incidentedges are "+graph3.getIncidentEdges(v));
    //        }

    compareIndexedGraphs(graph2, graph3);

    File file1 = new File(testFilename);
    File file2 = new File(testFilename2);

    Assert.assertTrue(file1.length() == file2.length());
    file1.delete();
    file2.delete();
  }