package multinomad.tools.hierarchicalKmeans;

import multinomad.config.Configuration;
import multinomad.individuals.DoubleIndividual;
import multinomad.individuals.Population;
import multinomad.tools.kmeans.Centroid;

public class FilterWithThreshold {

	// 5.1. Let's n be the number of wished basins of attractions
	//		5.1.1. Initialize a threshold mu with the best fitness found so far
	//		5.1.2. Decrease the threshold until items in c clusters are located above the threshold
	//			   (c can be n + lambda  e.g. lambda = 5)
	public static void filter(Population pop, Population centroids, int lambda) {
		pop.orderPopulation();	
		
		for (DoubleIndividual ind : pop) {
			// 5.1.1.
			double mu = ind.getFitness();
			//System.err.println("Threshold: "+mu);
			// 5.1.2.
			int count = 0;
			for (DoubleIndividual c : centroids) {
				Centroid cent = (Centroid)c;
				if (cent.aboveTheThreshold(mu)) {
					count++;
				}else {
					cent.markForDelete();
				}
			}
			
			if ((count >= Configuration.f.getNoOptima()+lambda) || count == centroids.size()) {
				//System.err.println("Count: "+count);
				break;
			}
		}
	}
	
	// 5.1.3. Delete all clusters (and all data) that are below the threshold
	public static void deleteBelowThreshold(Population pop, Population centroids) {
		for (int i=0;i<centroids.size();i++) {
			Centroid cent = (Centroid)centroids.getP().get(i);
			if (cent.toDelete()) {
				pop.removeAll(cent.getCluster());
				centroids.remove(i);
				i--;
			}
		}
	}
}
