package weka.clusterers.forMetisMQI;

import java.util.Iterator;
import java.util.Stack;

import weka.clusterers.forMetisMQI.coarse.CoarserGraphElement;
import weka.clusterers.forMetisMQI.graph.Bisection;
import weka.clusterers.forMetisMQI.graph.Node;
import weka.clusterers.forMetisMQI.graph.Subgraph;
import weka.clusterers.forMetisMQI.graph.UndirectedGraph;

public class Uncoarse {
	
	private boolean projectedBelongs(Node u, Bisection partition, CoarserGraphElement cge) {
		Subgraph s = partition.getSubgraph();
		Node mappedNode = cge.getMap().get(u);
		return s.contains(mappedNode);
	}
	
	/**
	 * Given the projected graph and the partition of the coarser graph, it builds
	 * the projected partition.
	 * @param partition
	 * @param cge
	 */
	public Bisection uncoarseOneStep(Bisection partition, CoarserGraphElement cge) {
		UndirectedGraph projected = cge.getProjected();
		Subgraph part = new Subgraph(projected);
		Iterator<Node> projectedIterator = projected.getVertices().iterator();
		while(projectedIterator.hasNext()) {
			Node u = projectedIterator.next();
			if(projectedBelongs(u,partition,cge))
				part.addVertex(u);
		}
		return new Bisection(part);
	}
	
	public Bisection uncoarse(Stack<CoarserGraphElement> stack, Bisection partition) {
		while(stack.size() > 0) {
			CoarserGraphElement element = stack.pop();
			partition = uncoarseOneStep(partition,element);
		}
		return partition;
	}
	
	public Uncoarse() {
	}

}
