/**********************************************************************
# Copyright (c) EWA Systems Inc. 1998 - 2005 All Rights Reserved
#               No part of this program may be photocopied, reproduced,
#               or translated to another programming language without
#               the prior written consent of EWA Systems.
**********************************************************************/

package com.ewasystems.opt.ga.test;

import com.ewasystems.opt.ga.GeneticAlleleSet;
import com.ewasystems.opt.ga.GeneticEngine;
import com.ewasystems.opt.ga.GeneticGene;
import com.ewasystems.opt.ga.GeneticProblem;
import com.ewasystems.opt.ga.GeneticRunTask;

/**
 * <p>Genetic Algorithm Test Case: Spheres</p>
 * <p>Description: Minimize f(x) = sum((x(i)-1)^2) where X = [-5, 5] by .001</p>
 * <p>Copyright: EWASystems Copyright (c) 1998 - 2005</p>
 * <p>Company: EWASystems</p>
 * @author Lincoln Evans-Beauchamp
 * @version 1.0
 */
public class Spheres extends GeneticProblem
{
  /**
   * Problem Constructor
   */
  public Spheres()
  {
    super("Spheres", "Minimize f(x) = sum((x(i)-1)^2) where X = [-5, 5] by .001");
  }

  /**
   * The Objective Function
   * @param gene The Genetic Gene to Test
   * @return double: The Genetic Gene's Fitness
   */
  public double f(GeneticGene gene)
  {
    double fitness = 0d;
    for (int i=0; i<5; i++)
    {
      double x = ((Double)gene.getGeneValue(i)).doubleValue();
      fitness += Math.pow(x-1, 2d);
    }
    return fitness;
  }

  /**
   * Gets the Allele Set for the Problem
   * @return GeneticAlleleSet: The Allele Set
   */
  public GeneticAlleleSet getAlleleSet()
  {
    GeneticAlleleSet gas = new GeneticAlleleSet();
    Double[] values = new Double[] {new Double(-5d), new Double(.001d), new Double(5d)};
    gas.addContinuousAllele("Double [-5, 5] by .001", values, 5);
    return gas;
  }

  /**
   * Gets the Objective Type
   * @return int: The Objective Type
   */
  public int getObjectiveType()
    {return OBJECTIVE_TYPE_MIN;}

  /**
   * Main for Running the Problem
   * @param args Not Used
   */
  public static final void main(String[] args)
  {
    GeneticEngine ge = new GeneticEngine();
    GeneticRunTask grt = ge.createGeneticTask(new Spheres());
    grt.getConfig().setMaxGenerations(10000);
    grt.getConfig().setShowFinalReport(true);
    grt.run();
  }
}
