public static void saveGraph(Graph g, File f) throws FileNotFoundException, SecurityException { ArrayList<GraphEdge> edgemarks = new ArrayList<GraphEdge>(); PrintStream p = new PrintStream(new FileOutputStream(f)); try { Iterator<GraphNode> n = g.getNodeIterator(); int count = 1; while (n.hasNext()) { GraphNode node = n.next(); ListIterator<GraphEdge> e = node.getEdgeIterator(); while (e.hasNext()) { GraphEdge edge = e.next(); if (g.getNodeById(edge.getTarget().getId()) == null) { e.remove(); continue; } if (!edgemarks.contains(edge)) p.println( "" + (node.getId() + 1) + " " + (edge.getTarget().getId() + 1) + " " + edge.getWeight()); edgemarks.add(edge.getTarget().getEdgeByTargetId(node.getId())); edgemarks.add(edge); } if (count % 100 == 0) System.out.println("Saving. . ." + count++); } } finally { p.close(); } }
public ShortestPaths(Graph g, GraphNode x) throws NegativeEdgeException { this.g = g; Iterator<GraphNode> i = g.getNodeIterator(); while (i.hasNext()) { nodedata.put(i.next(), new SPData()); } generateShortestPathsFrom(x); }
static GraphId[] getOrderedIds(Graph g) { List idList = new ArrayList(); for (Iterator i = g.getNodeIterator(); i.hasNext(); ) { GraphId id = (GraphId) i.next(); idList.add(id.toString()); } GraphId[] result = (GraphId[]) idList.toArray(new GraphId[idList.size()]); Arrays.sort(result); return result; }
static String[] getOrderedEdgeLabels(Graph g) { Set labelSet = new HashSet(); for (Iterator i = g.getNodeIterator(); i.hasNext(); ) { GraphId id = (GraphId) i.next(); labelSet.addAll(g.getEdgeLabels(id)); } log.debug(labelSet.size() + " labels in labelset."); String[] result = (String[]) labelSet.toArray(new String[labelSet.size()]); Arrays.sort(result); return result; }
private void generateShortestPathsFrom(GraphNode source) throws NegativeEdgeException { Iterator<GraphNode> l = g.getNodeIterator(); ListIterator<GraphEdge> m; FibonacciHeap<GraphNode> h = new FibonacciHeap<GraphNode>(); GraphNode t, v; GraphEdge e; h.insert(source, 0); data(source).setPrev(null); data(source).setIncidentEdge(null); this.source = source; while (l.hasNext()) { t = l.next(); if (t == source) continue; data(t).setPrev(null); data(t).setIncidentEdge(null); h.insert(t, Integer.MAX_VALUE); } while (!h.isEmpty()) { t = h.extractMin(); m = t.getEdgeIterator(); while (m.hasNext()) { e = m.next(); if (g.getNodeById(e.getTarget().getId()) == null) { m.remove(); continue; } if (e.getWeight() < 0) { throw new NegativeEdgeException( "Dijkstra's algorithm won't work on graphs with negative edge weights!"); } v = e.getTarget(); if (h.getKey(v) > h.getKey(t) + e.getWeight()) { try { h.decreaseKey(v, h.getKey(t) + e.getWeight()); } catch (KeyNotLessException x) { // can't happen! } data(v).setPrev(t); data(v).setIncidentEdge(e); } } } }