Collections.sort(curEdgesList, edgeComparator);
Iterator<DefaultWeightedEdge> edgeIter = curEdgesList.iterator();
while(edgeIter.hasNext()){
DefaultWeightedEdge curEdge = edgeIter.next();
V neighbourVertex = graph.getEdgeSource(curEdge);
if(neighbourVertex == curVertex){
neighbourVertex = graph.getEdgeTarget(curEdge);
}
if(!verticesInMatching.contains(neighbourVertex)){
// We've found an edge to add to the matching
edgesInMatching.add(curEdge);
verticesInMatching.add(neighbourVertex);
break;
}
}
}
}
// now use the matching to construct the coarser graph
WeightedGraph<Vertex, DefaultWeightedEdge> coarseGraph =
new SimpleWeightedGraph<Vertex, DefaultWeightedEdge>(DefaultWeightedEdge.class);
// add to the coarse graph vertices which correspond to edges in the matching
for(DefaultWeightedEdge curEdge : edgesInMatching){
Vertex newVertex = new Vertex();
V source = graph.getEdgeSource(curEdge);
V target = graph.getEdgeTarget(curEdge);
newVertex.addSubordinate(source);
newVertex.addSubordinate(target);
coarseGraph.addVertex(newVertex);
verticesInMatching.remove(source);
verticesInMatching.remove(target);
}
// verticesInMatching now only contains lone vertices,
// those which weren't assigned a partner in the matching :(
for(V curVertex : verticesInMatching){
Vertex newVertex = new Vertex();
newVertex.addSubordinate(curVertex);
coarseGraph.addVertex(newVertex);
}
// the courseGraph has all the vertices it'll ever get, now it needs the edges
for(DefaultWeightedEdge curEdge : graph.edgeSet()){
Vertex parent1 = graph.getEdgeSource(curEdge).getParent();
Vertex parent2 = graph.getEdgeTarget(curEdge).getParent();
if(parent1 != parent2){
double oldEdgeWeight = graph.getEdgeWeight(curEdge);
DefaultWeightedEdge edgeInCoarseGraph = coarseGraph.getEdge(parent1, parent2);
if(edgeInCoarseGraph != null){
coarseGraph.setEdgeWeight(edgeInCoarseGraph, coarseGraph.getEdgeWeight(edgeInCoarseGraph) + oldEdgeWeight);
}else{
edgeInCoarseGraph = coarseGraph.addEdge(parent1, parent2);