protected void calculateDensestSubgraph() { UndirectedSubgraph<V,E> currentSubGraph = new UndirectedSubgraph<V,E>(graph, graph.vertexSet(), null); double bestDensity = calculateDensity(graph); while (currentSubGraph.vertexSet().size() > 0) { currentSubGraph = new UndirectedSubgraph<V,E>(graph, currentSubGraph.vertexSet(), null); currentSubGraph.removeVertex(getMinDegreeVertex(currentSubGraph)); double density = calculateDensity(currentSubGraph); if (density > bestDensity) { bestDensity = density; bestSubGraph = currentSubGraph; } } }
/** Check whether the graph is connected, that is, if it is possible to connect every node to each other, but only in a subset of vertices (subgraph). * * @param graph The graph to analyze * @param vertices Subset of vertices * @return {@code true} if the subgraph is connected, and false otherwise */ public static boolean isConnected(org.jgrapht.Graph graph, SortedSet vertices) { Subgraph subgraph; if (graph instanceof DirectedGraph) subgraph = new DirectedSubgraph((DirectedGraph) graph, vertices, null); else if (graph instanceof UndirectedGraph) subgraph = new UndirectedSubgraph((UndirectedGraph) graph, vertices, null); else throw new RuntimeException("Bad"); return isConnected(subgraph); }
@Override public void process(SimilarityMatrix matrix, File output) throws Exception { UndirectedGraph<String, DefaultEdge> graph = matrix.toUndirectedUnweightedGraph(threshold); CharikarDensestSubgraph<String, DefaultEdge> estimator = new CharikarDensestSubgraph<String, DefaultEdge>(graph); UndirectedSubgraph<String, DefaultEdge> subgraph = estimator.getDensestSubgraph(); System.out.println("Density is " + CharikarDensestSubgraph.calculateDensity(subgraph)); Set<String> vertices = subgraph.vertexSet(); if (output == null) { for (String s : vertices) System.out.println(s); } else { BufferedWriter bw = new BufferedWriter(new FileWriter(output)); for (String s : vertices) bw.append(s + "\n"); bw.close(); } } }