Exemplo n.º 1
0
  /**
   * Verifica que no hayan partes de red aisladas. Todos los nodos deben estar conectados a una
   * misma red.
   */
  private void checkIsolatedNetworks() {

    Routing routing = SimulationBase.getInstance().getGridSimulatorModel().getRouting();
    Boolean foundIsolatedNetworks = false;

    if (routing instanceof RoutingViaJung) {
      // System.out.println("Entro a:RoutingViaJung");
      Graph networkRoutingGraph = ((RoutingViaJung) routing).getHybridNetwork();
      GridVertex pivotVertex = null;

      Iterator<GridVertex> itVertexes = networkRoutingGraph.getVertices().iterator();
      while (itVertexes.hasNext() && !foundIsolatedNetworks) {
        GridVertex vertex = itVertexes.next();

        if (pivotVertex == null) {
          pivotVertex = vertex;
          continue;
        }

        if (pivotVertex.getTheEntity().getHopCount(vertex.getTheEntity()) == -1) {
          addError(
              SimulationBase.getInstance().getGridSimulatorModel(),
              " \n►Contiene redes disconexas.");
          foundIsolatedNetworks = true;
        }
      }
    } else if (routing instanceof ShortesPathRouting) {
      // System.out.println("Entro a:ShortesPathRouting");
      NetworkProxy networkProxy = new NetworkProxy();
      networkProxy.setHyrbidNetwork(((ShortesPathRouting) routing).getHyrbidNetwork());
      NetworkRouting networkRouting = ((ShortesPathRouting) routing).getHybridNetworkRouting();

      String pivotVertexID = null;

      Iterator<String> itVertexesID = networkProxy.getNodeIDs().iterator();
      while (itVertexesID.hasNext() && !foundIsolatedNetworks) {

        String vertexID = itVertexesID.next();

        if (pivotVertexID == null) {
          pivotVertexID = vertexID;
          continue;
        }

        Iterator<Connection> itConns =
            networkRouting.findConnections(pivotVertexID, vertexID).iterator();

        while (itConns.hasNext()) {
          Connection conn = itConns.next();

          if (conn.getRoute() == null) {
            addError(
                SimulationBase.getInstance().getGridSimulatorModel(),
                " \n►Contiene redes disconexas.");
            foundIsolatedNetworks = true;
          }
        }
      }
    }
  }
Exemplo n.º 2
0
  @Override
  public int checkFitness(
      Graph<ColorableVertex, ?> graph,
      List<ColorableVertex> gVertices,
      Colony<ColorableVertex> colony) {
    Collections.sort(
        colony,
        new Comparator<ColorableVertex>() {
          @Override
          public int compare(ColorableVertex o1, ColorableVertex o2) {
            return o1.getId() - o2.getId();
          }
        });

    for (int i = 0; i < gVertices.size(); i++) {
      if (gVertices.get(i).getId() != colony.get(i).getId())
        throw new IllegalStateException("DUPA");
      gVertices.get(i).setColor(colony.get(i).getColor());
    }

    // Sprawdzenie czy rozwiązanie jest poprawne
    int bad = 0;
    for (ColorableVertex v : graph.getVertices()) {
      for (ColorableVertex c : graph.getNeighbors(v)) {
        if ((c.getColor() == v.getColor()) && (c != v)) bad++;
      }
    }

    return bad;
  }
Exemplo n.º 3
0
  public static <V, E> Neo4jTopology loadTopology(Neo4jWorkspaceSettings settings)
      throws Exception {
    String db = DatabaseConfiguration.readDatabase(settings);
    Logger.getLogger(Neo4jWorkspace.class).info("using db " + db);

    // Get neo4j stuffs
    GraphDatabaseFactory factory = new GraphDatabaseFactory();
    GraphDatabaseService database = factory.newEmbeddedDatabase(db);
    GlobalGraphOperations operation = GlobalGraphOperations.at(database);

    ViewsManager views = new ViewsManager();
    views.load(settings);

    // Setup graph model
    Neo4jGraphModelIO gio = new Neo4jGraphModelIO();
    gio.read(SimpleFile.read(settings.getModelPath()));
    Neo4jGraphModel typeModel = gio.getGraphModel();

    // Build graph
    INeo4jGraphReader r = views.getFirst().getFilter();
    Graph<IPropertyNode, IPropertyEdge> graph = r.read(operation, typeModel);
    Logger.getLogger(Neo4jWorkspace.class)
        .info("filtered graph has " + graph.getVertexCount() + " nodes using db " + db);

    // Build topology using graph typing model
    String topologyName = views.getFirst().getTopologyName();
    Neo4jTopologyFactory tfact = new Neo4jTopologyFactory();
    Neo4jTopology topology = tfact.newTopology(topologyName, graph, typeModel);

    return topology;
  }
  /**
   * Saves a given graph to a dot file, it also creates the file, or overwrites the old one
   *
   * @param g : The jung graph to save
   * @param filename : A string that points to the destination of the save
   * @param labeler : A node object -> Node name converter object
   * @param graphName : The name of the graph to export (usually this is set the project's name)
   * @throws IOException On IO error
   */
  public void save(Graph<V, E> g, String filename, Transformer<V, String> labeler, String graphName)
      throws IOException {
    SortedSet<V> nodes = new TreeSet<V>();
    Map<V, SortedSet<V>> successors = new HashMap<V, SortedSet<V>>();
    for (V source : g.getVertices()) {
      Collection<V> actSuccessors = g.getSuccessors(source);
      SortedSet<V> successorTree = new TreeSet<V>();
      for (V destination : actSuccessors) {
        successorTree.add(destination);
      }

      nodes.add(source);
      successors.put(source, successorTree);
    }

    BufferedWriter writer =
        new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
    writer.write("digraph \"" + graphName + "\" {\n");
    for (V from : nodes) {
      Collection<V> actSuccessors = successors.get(from);
      for (V to : actSuccessors) {
        writer.write(
            "\t\"" + labeler.transform(from) + "\" -> \"" + labeler.transform(to) + "\";\n");
      }

      if (g.getPredecessorCount(from) == 0 && actSuccessors.isEmpty()) {
        writer.write("\t\"" + labeler.transform(from) + "\";\n");
      }
    }

    writer.write("}");
    writer.close();
  }
Exemplo n.º 5
0
 protected Graph<Cell, CellsLink> getDirectedGraph(Mine mine) {
   Graph<Cell, CellsLink> graph = new DirectedSparseGraph<Cell, CellsLink>();
   for (CellsLink link : getCellLinks(mine)) {
     graph.addEdge(link, link.getSource(), link.getTarget());
   }
   return graph;
 }
  /**
   * 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;
  }
Exemplo n.º 7
0
  /**
   * Converts the prefuse graph data into the jung graph data.
   *
   * @param vg the prefuse visual graph
   * @return graph the jung graph data
   */
  public static edu.uci.ics.jung.graph.Graph<String, String> convertJungGraph(VisualGraph vg) {

    edu.uci.ics.jung.graph.Graph<String, String> graph =
        new UndirectedSparseGraph<String, String>();

    if (vg != null) {
      Iterator<?> nodeIter = vg.nodes();
      while (nodeIter.hasNext()) {
        VisualItem node = (VisualItem) nodeIter.next();
        String nodeId = node.getString("id");
        // System.out.println("node id == " + nodeId);
        graph.addVertex(nodeId);
      }

      Iterator<?> edgeIter = vg.edges();
      while (edgeIter.hasNext()) {
        VisualItem edge = (VisualItem) edgeIter.next();
        String node1 = edge.getString("node1");
        String node2 = edge.getString("node2");
        String edgeId = node1 + node2;
        // System.out.println("edge id == " + edgeId);
        graph.addEdge(edgeId, node1, node2, EdgeType.UNDIRECTED);
      }
    }
    return graph;
  }
Exemplo n.º 8
0
  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);
  }
  /**
   * Connect vertices in the graph. Connects vertices if startVertex and endVertex may be connected
   * by a directed edge. Ensures that: * startVertex is a RequiredPort and endVertex is a
   * ProvidedPort * the required port has not yet reached the maximal number of connections {@link
   * RequiredPort.getMaxDegree() getMaxDegree} * the ports do not belong to the same component * the
   * ports are not yet connected
   *
   * @param startVertex
   * @param endVertex
   * @param graph
   * @return true if the two vertexes were connected
   */
  protected boolean connect(NubiSaveVertex startVertex, NubiSaveVertex endVertex) {
    boolean shouldNotConnect = shouldNotConnect(startVertex, endVertex);
    System.out.println("nubisavecomponentgraphmouseplugin: connect");
    if (shouldNotConnect) {
      System.out.println("nubisavecomponentgraphmouseplugin: returning false");
      return false;
    }
    AbstractNubisaveComponent start =
        (AbstractNubisaveComponent) ((RequiredPort) startVertex).getParentComponent();
    AbstractNubisaveComponent end =
        (AbstractNubisaveComponent) ((ProvidedPort) endVertex).getParentComponent();
    if (!isConnected(startVertex, endVertex)) {
      BufferedWriter writer = null;
      try {
        System.out.println("is not connected");
        start.connectToProvidedPort(end);
        WeightedNubisaveVertexEdge edge = edgeFactory.create();
        edge.setWeight(end.getNrOfFilePartsToStore());
        graph.addEdge(edge, startVertex, endVertex, EdgeType.DIRECTED);
        File file = new File(storage_directory + "/" + "connections.txt");
        if (!file.exists()) {
          file.createNewFile();
        }
        writer = new BufferedWriter(new FileWriter(file, true));
        writer.write(start.getUniqueName());
        writer.write(" ");
        writer.write(end.getUniqueName());
        writer.newLine();
        writer.close();
      } catch (IOException ex) {
        Logger.getLogger(AbstractNubisaveComponentEdgeCreator.class.getName())
            .log(Level.SEVERE, null, ex);
      } finally {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(AbstractNubisaveComponentEdgeCreator.class.getName())
              .log(Level.SEVERE, null, ex);
        }
      }

    } else {
      System.out.println("is  connected --> increase weight");
      WeightedNubisaveVertexEdge edge =
          (WeightedNubisaveVertexEdge) graph.findEdge(startVertex, endVertex);
      System.out.println("edge weight: " + edge.getWeight());
      int before = end.getNrOfFilePartsToStore();
      System.out.println("nroffileparts1: " + before);
      end.setNrOfFilePartsToStore(end.getNrOfFilePartsToStore() + 1);
      System.out.println("nroffileparts2: " + end.getNrOfFilePartsToStore());
      assert (end.getNrOfFilePartsToStore() - 1) == before;
      edge.setWeight(end.getNrOfFilePartsToStore());
      assert (edge.getWeight() - 1) == before;
      System.out.println("incrreased edge weight: " + edge.getWeight());
    }
    System.out.println("nubisavecomponentgraphmouseplugin: returning true");
    return true;
  }
Exemplo n.º 10
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();
    }
  }
Exemplo n.º 11
0
 // used to construct graph and call graph algorithm used in JUNG
 public HashMap Closeness_Centrality_Score(
     LinkedList<String> Distinct_nodes,
     LinkedList<String> source_vertex,
     LinkedList<String> target_vertex,
     LinkedList<Double> Edge_Weight) {
   // CREATING weighted directed graph
   Graph<MyNode, MyLink> g = new DirectedSparseGraph<Graph_Algos.MyNode, Graph_Algos.MyLink>();
   // create node objects
   Hashtable<String, MyNode> Graph_Nodes = new Hashtable<String, Graph_Algos.MyNode>();
   LinkedList<MyNode> Source_Node = new LinkedList<Graph_Algos.MyNode>();
   LinkedList<MyNode> Target_Node = new LinkedList<Graph_Algos.MyNode>();
   LinkedList<MyNode> Graph_Nodes_Only = new LinkedList<Graph_Algos.MyNode>();
   // LinkedList<MyLink> Graph_Links = new LinkedList<Graph_Algos.MyLink>();
   // create graph nodes
   for (int i = 0; i < Distinct_nodes.size(); i++) {
     String node_name = Distinct_nodes.get(i);
     MyNode data = new MyNode(node_name);
     Graph_Nodes.put(node_name, data);
     Graph_Nodes_Only.add(data);
   }
   // Now convert all source and target nodes into objects
   for (int t = 0; t < source_vertex.size(); t++) {
     Source_Node.add(Graph_Nodes.get(source_vertex.get(t)));
     Target_Node.add(Graph_Nodes.get(target_vertex.get(t)));
   }
   // Now add nodes and edges to the graph
   for (int i = 0; i < Edge_Weight.size(); i++) {
     g.addEdge(
         new MyLink(Edge_Weight.get(i)),
         Source_Node.get(i),
         Target_Node.get(i),
         EdgeType.DIRECTED);
   }
   Transformer<MyLink, Double> wtTransformer =
       new Transformer<MyLink, Double>() {
         public Double transform(MyLink link) {
           return link.weight;
         }
       };
   edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality<MyNode, MyLink> CC1 =
       new edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality<MyNode, MyLink>(
           g, wtTransformer);
   // Calculating Closeness Centrality score of nodes
   HashMap map = new HashMap();
   for (int i = 0; i < Graph_Nodes_Only.size(); i++) {
     // System.out.println("Graph Node "+Graph_Nodes_Only.get(i)+" Closeness Centrality"
     // +CC1.getVertexScore(Graph_Nodes_Only.get(i)));
     String node = Graph_Nodes_Only.get(i) + "";
     node = node.substring(1, node.length());
     double val = CC1.getVertexScore(Graph_Nodes_Only.get(i));
     if (new Double(val).isNaN()) {
       val = 0.00001;
     }
     map.put(node, val);
   }
   return map;
 }
Exemplo n.º 12
0
  /**
   * Build full Neo4jWorkspace involving reading files given by settings:
   *
   * <ul>
   *   <li>neo4j database
   *   <li>view
   *   <li>graph model
   *   <li>projection
   * </ul>
   *
   * and build topology & geometrical model according to Neo4j factories
   *
   * @param settings
   * @throws Exception
   */
  public Neo4jWorkspace(Neo4jWorkspaceSettings settings) throws Exception {
    String db = DatabaseConfiguration.readDatabase(settings);
    Logger.getLogger(Neo4jWorkspace.class).info("using db " + db);

    // Get neo4j stuffs
    GraphDatabaseFactory factory = new GraphDatabaseFactory();
    database = factory.newEmbeddedDatabase(db);
    operation = GlobalGraphOperations.at(database);

    views = new ViewsManager();
    views.load(settings);
    layoutML = views.getFirst().getLayout();

    // Setup graph model
    Neo4jGraphModelIO gio = new Neo4jGraphModelIO();
    gio.read(SimpleFile.read(settings.getModelPath()));
    Neo4jGraphModel typeModel = gio.getGraphModel();

    // Build graph
    INeo4jGraphReader r = views.getFirst().getFilter();
    Graph<IPropertyNode, IPropertyEdge> graph = r.read(operation, typeModel);
    Logger.getLogger(Neo4jWorkspace.class)
        .info("filtered graph has " + graph.getVertexCount() + " nodes using db " + db);

    // Build topology using graph typing model
    String topologyName = views.getFirst().getTopologyName();
    Neo4jTopologyFactory tfact = new Neo4jTopologyFactory();
    topology = tfact.newTopology(topologyName, graph, typeModel);

    // Edit topology according to dataprism
    Dataprism dp = loadDataprism(settings);
    if (dp != null) ((Neo4jTopology) topology).edit().apply(dp);

    // Build layout model
    modelFactory = new Neo4jModelFactory(gio.getGraphModel());
    model = (IHierarchicalNodeModel) modelFactory.getLayoutModel(topology);
    edgeModel = model.getEdgeModel();
    applyLayoutMLConfiguration(model, layoutML);

    // Build layout
    layoutFactory = new Neo4jLayoutFactory(typeModel);
    if (layoutML != null) {
      Map<String, String> mapping = extractModelLayoutMapping(layoutML);
      layoutFactory.setModelLayoutMapping(mapping);
    }

    layout = layoutFactory.getLayout(model);
    layout.getEdgeLayout().setEdgePostProcess(null);

    // finalize workspace
    annotationModel = new AnnotationModel();
    metadata = null;
    setName(settings.getName());
    loadMapIfExist();

    this.configuration = new ConfigurationFacade(this);
  }
Exemplo n.º 13
0
  protected void initialize(Graph<V, E> graph) {
    this.graph = graph;
    this.vertex_scores = new HashMap<V, Double>();
    this.edge_scores = new HashMap<E, Double>();
    this.vertex_data = new HashMap<V, BetweennessData>();

    for (V v : graph.getVertices()) this.vertex_scores.put(v, 0.0);

    for (E e : graph.getEdges()) this.edge_scores.put(e, 0.0);
  }
 /** Creates a new instance of SimpleGraphView */
 public InteractiveGraphView3() {
   // Graph<V, E> where V is the type of the vertices and E is the type of the edges
   g = new SparseMultigraph<Integer, String>();
   // Add some vertices and edges
   g.addVertex((Integer) 1);
   g.addVertex((Integer) 2);
   g.addVertex((Integer) 3);
   g.addEdge("Edge-A", 1, 2);
   g.addEdge("Edge-B", 2, 3);
 }
 @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());
 }
 /**
  * create some vertices
  *
  * @param count how many to create
  * @return the Vertices in an array
  */
 private Vertex[] createVertices(int count) {
   Vertex[] v = new Vertex[count];
   for (int i = 0; i < count; i++) {
     v[i] = graph.addVertex(new DirectedSparseVertex());
   }
   return v;
 }
Exemplo n.º 17
0
 public FSMBuildVisualizer() {
   super("Model Visualizer");
   graph = new DirectedSparseMultigraph<>();
   graph.addVertex(current);
   //    Layout<FSMTransition, String> layout = new CircleLayout<FSMTransition, String>(graph);
   layout = new KKLayout<>(graph);
   layout.setSize(new Dimension(800, 600)); // sets the initial size of the space
   vv = new VisualizationViewer<>(layout);
   vv.setPreferredSize(new Dimension(800, 600)); // Sets the viewing area size
   vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
   vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());
   vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);
   VertexLabelAsShapeRenderer<String, StepCounter> vlasr =
       new VertexLabelAsShapeRenderer<>(vv.getRenderContext());
   //    vv.getRenderContext().setVertexShapeTransformer(vlasr);
   vv.getRenderContext().setVertexShapeTransformer(new EllipseVertexTransformer());
   //    vv.getRenderContext().setVertexLabelRenderer(new
   // TransitionVertextLabelRenderer(Color.GREEN));
   DefaultModalGraphMouse gm = new DefaultModalGraphMouse();
   vv.addKeyListener(gm.getModeKeyListener());
   gm.setMode(ModalGraphMouse.Mode.TRANSFORMING);
   vv.setGraphMouse(gm);
   getContentPane().add(vv);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setSize(1024, 768);
   pack();
   setVisible(true);
 }
Exemplo n.º 18
0
 /**
  * Returns <code>true</code> if this edge and its endpoints in this graph are all included in the
  * collections of elements to be rendered, and <code>false</code> otherwise.
  *
  * @param context the edge and graph to be queried
  * @return <code>true</code> if this edge and its endpoints are all included in the collections of
  *     elements to be rendered, <code>false</code> otherwise.
  */
 protected boolean isEdgeRendered(Context<Graph<V, E>, E> context) {
   Predicate<Context<Graph<V, E>, V>> vertexIncludePredicate =
       vv.getRenderContext().getVertexIncludePredicate();
   Predicate<Context<Graph<V, E>, E>> edgeIncludePredicate =
       vv.getRenderContext().getEdgeIncludePredicate();
   Graph<V, E> g = context.graph;
   E e = context.element;
   boolean edgeTest = edgeIncludePredicate == null || edgeIncludePredicate.apply(context);
   Pair<V> endpoints = g.getEndpoints(e);
   V v1 = endpoints.getFirst();
   V v2 = endpoints.getSecond();
   boolean endpointsTest =
       vertexIncludePredicate == null
           || (vertexIncludePredicate.apply(Context.<Graph<V, E>, V>getInstance(g, v1))
               && vertexIncludePredicate.apply(Context.<Graph<V, E>, V>getInstance(g, v2)));
   return edgeTest && endpointsTest;
 }
Exemplo n.º 19
0
  protected TitledBorder setUpSliderPanel() {
    sliderPanel = new JPanel();
    sliderPanel.setPreferredSize(new Dimension(210, 50));
    int sliderLimit = 50;

    if (graph != null) {
      final Graph<CallGraphNode, CallGraphLink> jungGraph = graph.getJungGraph();
      sliderLimit = jungGraph.getVertexCount();
    }
    configureIterationSlider(sliderLimit);
    sliderPanel.setOpaque(true);
    sliderPanel.add(iterationSlider);
    iterationSlider.setValue(0);
    String eastSize = sliderLabelBase + iterationSlider.getValue();
    TitledBorder sliderBorder = BorderFactory.createTitledBorder(eastSize);
    sliderPanel.setBorder(sliderBorder);
    return sliderBorder;
  }
Exemplo n.º 20
0
 private void addEdge(String step) {
   String edge = current + "->" + step;
   if (!edges.containsKey(edge)) {
     //      System.out.println("EDGE+" + edge);
     if (!vertices.contains(step)) {
       //        System.out.println("VERTEX+" + t);
       graph.addVertex(step);
       vertices.add(step);
     }
     StepCounter counter = new StepCounter();
     edges.put(edge, counter);
     graph.addEdge(counter, current, step);
     vv.repaint();
   } else {
     edges.get(edge).increment();
   }
   layout.reset();
 }
Exemplo n.º 21
0
  private void initialization() {
    dominatingSet = new ArrayList<Integer>();

    dominatedMap = new HashMap<Integer, Boolean>();
    Collection<Integer> vertices = g.getVertices();
    for (Integer v : vertices) {
      dominatedMap.put(v, false);
    }
  }
 protected int getIndex(Graph<V, E> graph, E e, V v) {
   Collection<E> commonEdgeSet = new HashSet<E>();
   for (E another : graph.getIncidentEdges(v)) {
     V u = graph.getOpposite(v, another);
     if (u.equals(v)) {
       commonEdgeSet.add(another);
     }
   }
   int count = 0;
   for (E other : commonEdgeSet) {
     if (e.equals(other) == false) {
       edge_index.put(other, count);
       count++;
     }
   }
   edge_index.put(e, count);
   return count;
 }
Exemplo n.º 23
0
  private void insertTestData() {
    // TODO Auto-generated method stub
    trafficDataset.addValue(20, "rx", "1");
    trafficDataset.addValue(40, "rx", "2");
    trafficDataset.addValue(10, "rx", "3");
    trafficDataset.addValue(60, "rx", "4");
    trafficDataset.addValue(10, "rx", "5");
    trafficDataset.addValue(20, "rx", "6");
    trafficDataset.addValue(20, "rx", "7");
    trafficDataset.addValue(70, "rx", "8");
    trafficDataset.addValue(25, "rx", "9");
    trafficDataset.addValue(15, "rx", "10");
    trafficDataset.addValue(10, "rx", "11");
    trafficDataset.addValue(20, "rx", "12");

    trafficDataset.addValue(10, "tx", "1");
    trafficDataset.addValue(20, "tx", "2");
    trafficDataset.addValue(30, "tx", "3");
    trafficDataset.addValue(20, "tx", "4");
    trafficDataset.addValue(10, "tx", "5");
    trafficDataset.addValue(20, "tx", "6");
    trafficDataset.addValue(50, "tx", "7");
    trafficDataset.addValue(30, "tx", "8");
    trafficDataset.addValue(35, "tx", "9");
    trafficDataset.addValue(25, "tx", "10");
    trafficDataset.addValue(5, "tx", "11");
    trafficDataset.addValue(20, "tx", "12");

    trafficChart.setTitle("IP : 124.15.65.76");

    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("148.35.124.7", 80, 66357, 343654, 1));
    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("253.27.64.32", 80, 5757, 3446, 1));
    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("124.15.65.76", 22, 345, 7778, 1));
    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("125.76.43.221", 80, 453, 3456, 1));
    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("57.78.3.11", 80, 765, 26754, 1));
    nodeTrafficTableModel.addNodeTraffic(new NodeTraffic("86.34.25.22", 22, 45347, 345346, 1));

    graph.addVertex("Internet");
    for (int i = 1; i <= 6; i++) {
      graph.addVertex("Node" + 1);
      graph.addEdge("rx:node" + i, "Internet", "Node" + i, EdgeType.DIRECTED);
      graph.addEdge("tx:node" + i, "Node" + i, "Internet", EdgeType.DIRECTED);
    }
  }
Exemplo n.º 24
0
  public void init(Functionality.Graph g, int _layout_width, int _layout_height) {
    myGraph = g;
    layout_width = _layout_width;
    layout_height = _layout_height;
    qt = new UndirectedSparseGraph();

    Iterator<Functionality.Node> nodeIterator = g.getNodes().iterator();
    while (nodeIterator.hasNext()) {
      qt.addVertex(nodeIterator.next());
    }

    Iterator<Functionality.Edge> edgeIterator = g.getEdges().iterator();
    while (edgeIterator.hasNext()) {
      Functionality.Edge currEdge = edgeIterator.next();
      qt.addEdge(currEdge, currEdge.getNode1(), currEdge.getNode2());
    }

    vv = null;
    layout = null;
  }
Exemplo n.º 25
0
  /**
   * Calculates betweenness scores based on the all-pairs weighted shortest paths in the graph.
   *
   * <p>NOTE: This version of the algorithm may not work correctly on all graphs; we're still
   * working out the bugs. Use at your own risk.
   *
   * @param graph the graph for which the scores are to be calculated
   * @param edge_weights the edge weights to be used in the path length calculations
   */
  public BetweennessCentrality(Graph<V, E> graph, Transformer<E, ? extends Number> edge_weights) {
    // reject negative-weight edges up front
    for (E e : graph.getEdges()) {
      double e_weight = edge_weights.transform(e).doubleValue();
      if (e_weight < 0)
        throw new IllegalArgumentException("Weight for edge '" + e + "' is < 0: " + e_weight);
    }

    initialize(graph);
    computeBetweenness(new MapBinaryHeap<V>(new BetweennessComparator()), edge_weights);
  }
  public Graph<String, String> createGraph() {
    graph = new UndirectedSparseGraph<String, String>();

    Attribute id = exampleSet.getAttributes().getId();
    if (id != null) {
      for (Example example : exampleSet) {
        graph.addVertex(example.getValueAsString(id));
      }
      addEdges();
    }
    return graph;
  }
Exemplo n.º 27
0
  /**
   * 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);
    }
  }
Exemplo n.º 28
0
  public Data[] execute() {

    int numNodes = getInt("numNodes");
    Graph graph = (Graph) data[0].getData();
    graph = (Graph) graph.copy();

    ErrorTolerance et = new ErrorTolerance(graph, numNodes);
    boolean isDone = et.testErrorTolerance();
    Data[] newdata = null;
    if (isDone) {

      Data model = new BasicData(et.getGraph(), Graph.class.getName());
      Dictionary map = model.getMetaData();
      map.put(DataProperty.MODIFIED, new Boolean(true));
      map.put(DataProperty.PARENT, data[0]);
      map.put(DataProperty.TYPE, DataProperty.NETWORK_TYPE);
      map.put(DataProperty.LABEL, "Random Node Deletion (Error Tolerance)");
      newdata = new Data[] {model};
    }
    return newdata;
  }
 protected int getIndex(Graph<V, E> graph, E e, V u, V v) {
   Collection<E> commonEdgeSet = new HashSet<E>(graph.getIncidentEdges(u));
   int count = 0;
   for (E other : commonEdgeSet) {
     if (e.equals(other) == false) {
       edge_index.put(other, count);
       count++;
     }
   }
   edge_index.put(e, count);
   return count;
 }
Exemplo n.º 30
0
  // method for flow graph visualization
  public static void visualizeGraph(int[][] matrix, int N, int k) {
    Graph<Integer, String> graph = new DirectedSparseGraph<Integer, String>();

    for (int i = 0; i < matrix.length; i++) {
      graph.addVertex((Integer) i);
    }

    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        // only select edge that has flow bigger than 0
        if (matrix[i][j] > 0) {
          graph.addEdge(i + "->" + j, i, j, EdgeType.DIRECTED);
        }
      }
    }

    Layout<Integer, String> layout = new CircleLayout<Integer, String>(graph);
    layout.setSize(new Dimension(800, 800));

    BasicVisualizationServer<Integer, String> vv =
        new BasicVisualizationServer<Integer, String>(layout);
    Transformer<Integer, Paint> vertexPaint =
        new Transformer<Integer, Paint>() {
          public Paint transform(Integer i) {
            return Color.YELLOW;
          }
        };

    vv.setPreferredSize(new Dimension(800, 800));
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Integer>());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR);

    JFrame frame = new JFrame("Network Visualization - N = " + N + ", k = " + k);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(vv);
    frame.pack();
    frame.setVisible(true);
  }