| 1 | package weka.clusterers.forMetisMQI; |
|---|
| 2 | |
|---|
| 3 | import java.util.HashSet; |
|---|
| 4 | import java.util.Set; |
|---|
| 5 | import java.util.Stack; |
|---|
| 6 | |
|---|
| 7 | import weka.clusterers.forMetisMQI.graph.Bisection; |
|---|
| 8 | import weka.clusterers.forMetisMQI.graph.Node; |
|---|
| 9 | import weka.clusterers.forMetisMQI.graph.UndirectedGraph; |
|---|
| 10 | import weka.clusterers.forMetisMQI.util.CoarserGraphElement; |
|---|
| 11 | import weka.clusterers.forMetisMQI.util.Util; |
|---|
| 12 | |
|---|
| 13 | public class GraphAlgorithms { |
|---|
| 14 | |
|---|
| 15 | |
|---|
| 16 | /** |
|---|
| 17 | * Given an undirected graph, performs the Kernighan-Li algorithm to find a bisection and |
|---|
| 18 | * then returns it. |
|---|
| 19 | * @param g |
|---|
| 20 | * @return |
|---|
| 21 | */ |
|---|
| 22 | static public Bisection KL(UndirectedGraph g) { |
|---|
| 23 | Bisection partition = new Bisection(g); |
|---|
| 24 | Bisection result = partition; |
|---|
| 25 | int bestEdgeCut = Integer.MAX_VALUE; |
|---|
| 26 | Node u = partition.getCandidate(); |
|---|
| 27 | while (u != null) { |
|---|
| 28 | partition.swap(u); |
|---|
| 29 | if (partition.edgeCut() <= bestEdgeCut) { |
|---|
| 30 | bestEdgeCut = partition.edgeCut(); |
|---|
| 31 | result = partition.copy(); |
|---|
| 32 | } |
|---|
| 33 | u = partition.getCandidate(); |
|---|
| 34 | } |
|---|
| 35 | return result; |
|---|
| 36 | } |
|---|
| 37 | |
|---|
| 38 | static public Bisection metis(UndirectedGraph g, int sizeFinerGraph) { |
|---|
| 39 | Coarse.setFinerSize(sizeFinerGraph); |
|---|
| 40 | Stack<CoarserGraphElement> stack = Coarse.coarse(g); |
|---|
| 41 | Bisection partition = null; |
|---|
| 42 | if (stack.size() > 0) { |
|---|
| 43 | partition = KL(stack.peek().getContracted()); |
|---|
| 44 | partition = Uncoarse.uncoarse(stack, partition); |
|---|
| 45 | } |
|---|
| 46 | return partition; |
|---|
| 47 | } |
|---|
| 48 | |
|---|
| 49 | /** |
|---|
| 50 | * Given an UndirectedGraph, runs metis+mqi for <code>numberOfCluster</code> times and |
|---|
| 51 | * returns a set of clusters. With the third parameter you can control the maximum size of the finer |
|---|
| 52 | * graph during the coarsening phase. |
|---|
| 53 | * @param g |
|---|
| 54 | * @param numberOfCluster |
|---|
| 55 | * @param sizeFinerGraph |
|---|
| 56 | */ |
|---|
| 57 | static public Set<Set<Node>> metisMqi(UndirectedGraph g, int numberOfCluster, int sizeFinerGraph) { |
|---|
| 58 | Set<Set<Node>> clusters = new HashSet<Set<Node>>(); |
|---|
| 59 | Util.viewGraph(g); |
|---|
| 60 | for (int i = 0; i < numberOfCluster; i++) { |
|---|
| 61 | Bisection partition = metis(g,sizeFinerGraph); |
|---|
| 62 | Set<Node> cluster = MQI.mqi(partition); |
|---|
| 63 | clusters.add(cluster); |
|---|
| 64 | System.out.println("CLUSTER "+ i + ": " + cluster); |
|---|
| 65 | } |
|---|
| 66 | return clusters; |
|---|
| 67 | } |
|---|
| 68 | |
|---|
| 69 | } |
|---|