package com.niacin.event;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import com.google.common.eventbus.Subscribe;
import com.niacin.annotation.Input;
import com.niacin.annotation.Optimize;
import com.niacin.input.Solution;
import com.niacin.input.Variable;
import com.niacin.main.Utilities;
import com.niacin.metaheuristic.Metaheuristic;
import com.niacin.problem.Problem;
public class NiacinEventHandler
{
private static NiacinEventHandler instance = null;
private Metaheuristic metaheuristic = null;
private Problem problem = null;
private HashMap<String, Method> setterMap = null;
private Method fitnessSource = null;
public static NiacinEventHandler initialise(Class<?> klassInput, Class<?> klassFitness, Problem p, Metaheuristic m)
{
if (NiacinEventHandler.instance == null)
{
NiacinEventHandler.instance = new NiacinEventHandler(klassInput, klassFitness, p, m);
}
return NiacinEventHandler.instance;
}
private NiacinEventHandler(Class<?> klassInput, Class<?> klassFitness, Problem p, Metaheuristic metaheuristic)
{
this.problem = p;
this.metaheuristic = metaheuristic;
this.fitnessSource = Utilities.findMethodWithAnnotation(klassFitness, Optimize.class);
this.setterMap = new HashMap<String, Method>();
for (Method m : klassInput.getMethods())
{
if (m.isAnnotationPresent(Input.class))
{
Input ann = m.getAnnotation(Input.class);
setterMap.put(ann.name(), m);
}
}
}
@Subscribe
public void injectInput(InjectInputEvent event) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Solution nextSolution = metaheuristic.getNextInput(problem);
for (Variable<?> variable : nextSolution)
{
Method setter = setterMap.get(variable.name());
setter.invoke(event.getSource(), new Object[]{variable.current()});
}
}
@Subscribe
public void recordFitness(MeasureFitnessEvent event) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
Object source = event.getSource();
Object result = fitnessSource.invoke(source, new Object[]{});
Class<?> type = fitnessSource.getAnnotation(Optimize.class).type();
System.out.println("fitness:" + (Double) type.cast(result));
this.metaheuristic.recordFitness(problem, (Double) type.cast(result));
}
}