/** * 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(); }
/** * 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; } } } } }
@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; }
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 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); }
/** * 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); } }
@Override public void update() { if (enabled) { try { final Layout<V, E> layout = (Layout<V, E>) layoutClass.getConstructor(Graph.class).newInstance(graph); if (this.size == null) { double border = PADDING * 2 * parent.getScale(); layout.setSize( new Dimension( (int) parent.getWidth() - PADDING * 2, (int) parent.getHeight() - PADDING * 2)); } else { layout.setSize(size); } List<PNode> nodes = new ArrayList<PNode>(); List<Point2D> targetPositions = new ArrayList<Point2D>(); for (V n : graph.getVertices()) { nodes.add(n); Point2D pos = layout.transform(n); pos.setLocation(pos.getX() + parent.getX(), pos.getY() + parent.getY()); targetPositions.add(pos); } PActivity a = new PMultipleNodeTranlate( duration, ANIMATION_DEFAULT_STEP_RATE, System.currentTimeMillis(), nodes, targetPositions); parent.getRoot().addActivity(a); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
public Graph sample(Graph graph, Dictionary parameters) { int totalNeeded = ((Integer) parameters.get(NUMBER_PARAMETER_KEY)).intValue(); List vertices = new ArrayList(graph.getVertices()); Random randomizer = new Random(); Set sampledVertices = new HashSet(); while (vertices.size() > 0 && sampledVertices.size() < totalNeeded) { sampledVertices.add(vertices.remove(randomizer.nextInt(vertices.size()))); } Graph sampledGraph = GraphUtils.vertexSetToGraph(sampledVertices); // according to the algorithm, drop unattached nodes, even if that gets rid of all of them return DropSoloNodesFilter.getInstance().filter(sampledGraph).assemble(); }
private void start() throws ArraysNotSameLengthException { Collection<Integer> vertices = g.getVertices(); List<Integer> vList = new ArrayList<Integer>(vertices); boolean[] chosen = AlgorithmUtil.verifySubDS(vList, this.numOfVertices, this.exactSolutionSize, this.g); if (chosen == null) { // do nothing } else { List<Integer> tempDs = new ArrayList<Integer>(this.exactSolutionSize); for (int i = 0; i < this.numOfVertices; i++) { if (chosen[i]) { tempDs.add(vList.get(i)); } } this.dominatingSet = tempDs; } }
private void getCandidateDomVerMap() throws ExceedLongMaxException { candidateDomVerMap = new LinkedHashMap<String, List<Integer>>(); // the vertex cover's complement set will be an independent set Collection<Integer> vertices = g.getVertices(); Collection<Integer> independentSet = CollectionUtils.subtract(vertices, vertexCover); /* * the vertex cover size will be the parameter k used in the fpt * algorithm */ int vertexCoverSize = vertexCover.size(); byte[] comparedRuler = new byte[vertexCoverSize]; Arrays.fill(comparedRuler, AlgorithmUtil.MARKED); for (Integer isv : independentSet) { Collection<Integer> neighOfIsv = g.getNeighbors(isv); byte ruler[] = new byte[vertexCoverSize]; // initilze the array with 0 Arrays.fill(ruler, AlgorithmUtil.UNMARKED); for (Integer neig : neighOfIsv) { /* * the position of the dominate vertex in the vertex cover will * set 1 */ int pos = vertexCover.indexOf(neig); if (pos != -1) { ruler[pos] = AlgorithmUtil.MARKED; } } // if (Arrays.equals(comparedRuler, ruler)) { // log.debug(isv + " dominates all vc"); // } String rulerStr = AlgorithmUtil.arrayToString(ruler); List<Integer> candidateDomVerSet = candidateDomVerMap.get(rulerStr); if (candidateDomVerSet == null) { candidateDomVerSet = new ArrayList<Integer>(); } // candidateDomVerSet.add(isv); AlgorithmUtil.addElementToList(candidateDomVerSet, isv); candidateDomVerMap.put(rulerStr, candidateDomVerSet); } /* * because the vertices in the vertex cover can also dominate other * vertices in the vertex cover,they are also considered */ for (Integer vcv : vertexCover) { Collection<Integer> neighOfVcv = g.getNeighbors(vcv); byte ruler[] = new byte[vertexCoverSize]; Arrays.fill(ruler, AlgorithmUtil.UNMARKED); // the vertex can dominated by itself int pos = vertexCover.indexOf(vcv); ruler[pos] = AlgorithmUtil.MARKED; for (Integer neig : neighOfVcv) { /* * the position of the dominate vertex in the vertex cover will * set 1 * * a neighbour of the vertex is likely not to be in the vertex * cover */ pos = vertexCover.indexOf(neig); if (pos != -1) { ruler[pos] = AlgorithmUtil.MARKED; } } // if (Arrays.equals(comparedRuler, ruler)) { // log.debug(vcv + " dominates all vc"); // } String rulerStr = AlgorithmUtil.arrayToString(ruler); List<Integer> candidateDomVerSet = candidateDomVerMap.get(rulerStr); if (candidateDomVerSet == null) { candidateDomVerSet = new ArrayList<Integer>(); } // candidateDomVerSet.add(vcv); AlgorithmUtil.addElementToList(candidateDomVerSet, vcv); candidateDomVerMap.put(rulerStr, candidateDomVerSet); } applySubsetRule(candidateDomVerMap); }
/** * 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; }
private void init(Graph<? extends Object, ? extends Object>[] graph_array, double[][][] matrix) { // super("DendrogramView View"); Graph<String, Number> g = (Graph<String, Number>) graph_array[0]; SparseDoubleMatrix2D matrixArray = GraphMatrixOperations.graphToSparseMatrix((Graph<String, Number>) graph_array[0]); /* * matrix=new double[g.getVertexCount()][g.getVertexCount()]; for(int * i=0; i<matrix.length; i++){ matrix[i][i]=0; for(int j=i+1; * j<matrix[i].length; j++) if(g.isNeighbor(String.valueOf(i), * String.valueOf(j))){ matrix[i][j]=1; matrix[j][i]=1; } else{ * matrix[i][j]=0; matrix[j][i]=0; } } */ graph = new DelegateForest<String, Number>(); Collection<String> c = g.getVertices(); // create a simple graph for the demo // graph = new DelegateForest<String,Integer>(); String labels[] = new String[matrix[0].length]; for (int i = 0; i < labels.length; i++) { labels[i] = String.valueOf(i); } mlc = new MultiLevelConcor(labels, matrix); initTree(); treeLayout = new TreeLayout<String, Number>(graph); radialLayout = new BalloonLayout<String, Number>(graph); radialLayout.setSize(new Dimension(600, 600)); vv = new VisualizationViewer<String, Number>(treeLayout, new Dimension(600, 600)); vv.setBackground(Color.white); nfc = new NodeFillColor<String>(vv.getPickedVertexState()); vv.getRenderContext().setVertexFillPaintTransformer(nfc); /* * nh = new NodeHighlight<String>(vv.getPickedVertexState()); nh.ID = 2; * nh.node_no = graph.getVertexCount(); nh.node_count = nh.node_no; * nh.synchroFlag = syncFlag; * vv.getRenderContext().setVertexFillPaintTransformer(nh); */ vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line()); vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller()); // add a listener for ToolTips vv.setVertexToolTipTransformer(new ToStringLabeller()); vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray)); rings = new Rings(radialLayout); // Container content = getContentPane(); // final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv); // content.add(panel); final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse(); vv.setGraphMouse(graphMouse); JComboBox modeBox = graphMouse.getModeComboBox(); modeBox.addItemListener(graphMouse.getModeListener()); graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); final ScalingControl scaler = new CrossoverScalingControl(); JButton plus = new JButton("+"); plus.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); } }); JButton minus = new JButton("-"); minus.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1 / 1.1f, vv.getCenter()); } }); radial = new JToggleButton("Balloon"); radial.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { LayoutTransition<String, Number> lt = new LayoutTransition<String, Number>(vv, treeLayout, radialLayout); Animator animator = new Animator(lt); animator.start(); vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.addPreRenderPaintable(rings); } else { LayoutTransition<String, Number> lt = new LayoutTransition<String, Number>(vv, radialLayout, treeLayout); Animator animator = new Animator(lt); animator.start(); vv.getRenderContext().getMultiLayerTransformer().setToIdentity(); vv.removePreRenderPaintable(rings); } vv.repaint(); } }); JPanel scaleGrid = new JPanel(new GridLayout(1, 0)); scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom")); JPanel controls = new JPanel(); scaleGrid.add(plus); scaleGrid.add(minus); controls.add(radial); controls.add(scaleGrid); controls.add(modeBox); int max = (int) Math.round(Math.log(matrix[0].length) / Math.log(2)); levelControl = new JSlider(JSlider.HORIZONTAL, 1, max, 1); levelControl.setMajorTickSpacing(1); levelControl.setMinorTickSpacing(1); levelControl.setPaintTicks(true); levelControl.addChangeListener(this); levelControl.setPaintLabels(true); Hashtable<Integer, JLabel> ht = new Hashtable<Integer, JLabel>(); for (int i = 1; i <= max; i++) { ht.put(new Integer(i), new JLabel(String.valueOf(i))); } levelControl.setLabelTable(ht); controls.add(levelControl); setBackground(Color.WHITE); setLayout(new BorderLayout()); this.add(vv, BorderLayout.CENTER); this.add(controls, BorderLayout.NORTH); // content.add(controls, BorderLayout.SOUTH); // Dimension preferredSize = new Dimension(600,600); // setSize(preferredSize); // setLocation(600,0); // setVisible(true); // Thread t = new Thread(this); // t.start(); vv.addMouseListener(this); }
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(); }
public void testDirectedSaveLoadSave() throws IOException { Graph<Number, Number> graph1 = directedGraphFactory.get(); for (int i = 0; i < 5; i++) { graph1.addVertex(i); } // GraphUtils.addVertices(graph1, 5); List<Number> id = new ArrayList<Number>(graph1.getVertices()); // Indexer.getIndexer(graph1); GreekLabels<Number> gl = new GreekLabels<Number>(id); int j = 0; 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); // 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)); // } assertEquals(graph1.getEdgeCount(), 6); String testFilename = "dtest.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, directedGraphFactory); // 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(); }
protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) { for (V v : graph.getVertices()) { // initialize the betweenness data for this new vertex for (V s : graph.getVertices()) this.vertex_data.put(s, new BetweennessData()); // if (v.equals(new Integer(0))) // System.out.println("pause"); vertex_data.get(v).numSPs = 1; vertex_data.get(v).distance = 0; Stack<V> stack = new Stack<V>(); // Buffer<V> queue = new UnboundedFifoBuffer<V>(); // queue.add(v); queue.offer(v); while (!queue.isEmpty()) { // V w = queue.remove(); V w = queue.poll(); stack.push(w); BetweennessData w_data = vertex_data.get(w); for (E e : graph.getOutEdges(w)) { // TODO (jrtom): change this to getOtherVertices(w, e) V x = graph.getOpposite(w, e); if (x.equals(w)) continue; double wx_weight = edge_weights.transform(e).doubleValue(); // for(V x : graph.getSuccessors(w)) // { // if (x.equals(w)) // continue; // FIXME: the other problem is that I need to // keep putting the neighbors of things we've just // discovered in the queue, if they're undiscovered or // at greater distance. // FIXME: this is the problem, right here, I think: // need to update position in queue if distance changes // (which can only happen with weighted edges). // for each outgoing edge e from w, get other end x // if x not already visited (dist x < 0) // set x's distance to w's dist + edge weight // add x to queue; pri in queue is x's dist // if w's dist + edge weight < x's dist // update x's dist // update x in queue (MapBinaryHeap) // clear x's incoming edge list // if w's dist + edge weight = x's dist // add e to x's incoming edge list BetweennessData x_data = vertex_data.get(x); double x_potential_dist = w_data.distance + wx_weight; if (x_data.distance < 0) { // queue.add(x); // vertex_data.get(x).distance = // vertex_data.get(w).distance + 1; x_data.distance = x_potential_dist; queue.offer(x); } // note: // (1) this can only happen with weighted edges // (2) x's SP count and incoming edges are updated below if (x_data.distance > x_potential_dist) { x_data.distance = x_potential_dist; // invalidate previously identified incoming edges // (we have a new shortest path distance to x) x_data.incomingEdges.clear(); // update x's position in queue ((MapBinaryHeap<V>) queue).update(x); } // if (vertex_data.get(x).distance == // vertex_data.get(w).distance + 1) // // if (x_data.distance == x_potential_dist) // { // x_data.numSPs += w_data.numSPs; //// vertex_data.get(x).predecessors.add(w); // x_data.incomingEdges.add(e); // } } for (E e : graph.getOutEdges(w)) { V x = graph.getOpposite(w, e); if (x.equals(w)) continue; double e_weight = edge_weights.transform(e).doubleValue(); BetweennessData x_data = vertex_data.get(x); double x_potential_dist = w_data.distance + e_weight; if (x_data.distance == x_potential_dist) { x_data.numSPs += w_data.numSPs; // vertex_data.get(x).predecessors.add(w); x_data.incomingEdges.add(e); } } } while (!stack.isEmpty()) { V x = stack.pop(); // for (V w : vertex_data.get(x).predecessors) for (E e : vertex_data.get(x).incomingEdges) { V w = graph.getOpposite(x, e); double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs * (1.0 + vertex_data.get(x).dependency); vertex_data.get(w).dependency += partialDependency; // E w_x = graph.findEdge(w, x); // double w_x_score = edge_scores.get(w_x).doubleValue(); // w_x_score += partialDependency; // edge_scores.put(w_x, w_x_score); double e_score = edge_scores.get(e).doubleValue(); edge_scores.put(e, e_score + partialDependency); } if (!x.equals(v)) { double x_score = vertex_scores.get(x).doubleValue(); x_score += vertex_data.get(x).dependency; vertex_scores.put(x, x_score); } } } if (graph instanceof UndirectedGraph) { for (V v : graph.getVertices()) { double v_score = vertex_scores.get(v).doubleValue(); v_score /= 2.0; vertex_scores.put(v, v_score); } for (E e : graph.getEdges()) { double e_score = edge_scores.get(e).doubleValue(); e_score /= 2.0; edge_scores.put(e, e_score); } } vertex_data.clear(); }