package algorithm.objectiveFunction;

import ui.model.DecoratedNetwork;
import ui.model.DecoratedState;
public class SwitchObjectiveFunction {
	
	//weights
	static double w_eb = .5, w_state = .5;
	static double k_eb = 1050000.f, k_state = 10000;
	
	static double squash_subtract = 1.0f / (1.f + (float) Math.exp(5.0));
	
	
	
	static public float getFitnessValueForState(DecoratedState state) {
		double f_eb = 0;
		double f_state = 0;
		double elementCountInNetwork = state.getNetworkList().stream().map(net -> net.getAmountOfElements()).reduce(0, Integer::sum);
		//sum over all objects
		for(DecoratedNetwork net : state.getNetworkList()) {
			
			//weigt
			double w_network = net.getAmountOfElements()/elementCountInNetwork;
			
			//f_eb
			double netEnergyDifference = 0;
			netEnergyDifference += net.getConsumerList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
			netEnergyDifference += net.getConsumerSelfSuppliedList().stream().map(con -> con.getEnergySelfSupplied() - con.getEnergyFromConsumingElemnets()).reduce(0.f, Float::sum);
			netEnergyDifference += net.getSupplierList().stream().map(sup -> sup.getEnergyProducing() - sup.getEnergySelfConsuming()).reduce(0.f, Float::sum);
			//abs
			f_eb += w_network * Math.abs(netEnergyDifference);
			
			
			//f_state
			f_state += w_network * net.getConsumerList().stream().map(con -> supplyPenalty(con.getSupplyBarPercentage())).reduce(0., Double::sum);
		}
		return (float) (w_eb*squash(f_eb, k_eb) + w_state*squash(f_state, k_state));
	}
	
	
	/**
	 * f_sup in paper
	 * @param supply from 0 to 1
	 * @return
	 */
	static public double supplyPenalty(double supply) {
		double supplyPercentage = 100 * supply;
		return (supplyPercentage < 100) ? -0.5 * supplyPercentage + 50: supplyPercentage - 100;
	}
	
	/**
	 * The squashing function in paper
	 * @param x the input
	 * @param kappa the corresponding kappa
	 * @return
	 */
	static public double squash(double x, double kappa) {
		return 100.f/(1.0f + Math.exp(-(10.f * (x - kappa/2.f))/ kappa)) - squash_subtract;
	}
}
