Package com.niacin.main

Source Code of com.niacin.main.Niacin

package com.niacin.main;

import java.lang.reflect.Method;
import java.util.Vector;

import com.google.common.eventbus.EventBus;
import com.niacin.annotation.Input;
import com.niacin.annotation.Optimize;
import com.niacin.event.InjectInputEvent;
import com.niacin.event.MeasureFitnessEvent;
import com.niacin.event.NiacinEventHandler;
import com.niacin.input.IntegerVariable;
import com.niacin.input.Variable;
import com.niacin.metaheuristic.Metaheuristic;
import com.niacin.metaheuristic.MetaheuristicFactory;
import com.niacin.problem.Problem;

public class Niacin
{
  private static Niacin instance = null;
  private static EventBus eventBus = new EventBus();

  public static Niacin initialise(Class<?> klassInput, Class<?> klassFitness)
  {
    if (Niacin.instance == null)
    {
      Niacin.instance = new Niacin(klassInput, klassFitness);
    }
    return Niacin.instance;
  }

  public static Niacin initialise(Class<?> klass)
  {
    if (Niacin.instance == null)
    {
      Niacin.instance = new Niacin(klass, klass);
    }
    return Niacin.instance;
  }

  private Niacin(Class<?> klassInput, Class<?> klassFitness)
  {
    Optimize opt = getOptimization(klassFitness);
    Vector<Variable<?>> variables = getVariables(klassInput);
    Problem problem = new Problem(opt.name(), variables, opt.direction(), opt.trials());
    Metaheuristic metaheuristic = MetaheuristicFactory.create(opt.method(), problem);

    eventBus.register(NiacinEventHandler.initialise(klassInput, klassFitness, problem, metaheuristic));
  }

  public static void start(Object source)
  {
    eventBus.post(new InjectInputEvent(source));
  }

  public static void end(Object source)
  {
    eventBus.post(new MeasureFitnessEvent(source));
  }

  private Optimize getOptimization(Class<?> klass)
  {
    for (Method m : klass.getMethods())
      if (m.isAnnotationPresent(Optimize.class))
        return m.getAnnotation(Optimize.class);
    return null;
  }

  private Vector<Variable<?>> getVariables(Class<?> klass)
  {
    Vector<Variable<?>> variables = new Vector<Variable<?>>();
    for (Method m : klass.getMethods())
      if (m.isAnnotationPresent(Input.class))
      {
        if (m.getParameterTypes()[0] == Integer.class || m.getParameterTypes()[0].getName().equals("int"))
        {
          IntegerVariable iv = IntegerVariable.parse(m);
          variables.add(iv);
        }
      }
    return variables;
  }
}
TOP

Related Classes of com.niacin.main.Niacin

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.