package de.jungblut.math.minimize;

import junit.framework.TestCase;

import org.junit.Test;

import de.jungblut.math.DoubleVector;
import de.jungblut.math.dense.DenseDoubleVector;
import de.jungblut.math.tuple.Tuple;

public class ParticleSwarmOptimizationTest extends TestCase {

  @Test
  public void testParticleSwarmOptimization() {

    DoubleVector start = new DenseDoubleVector(new double[] { 2, 5 });

    // our function is f(x,y) = x^2+y^2
    CostFunction inlineFunction = new CostFunction() {
      @Override
      public Tuple<Double, DoubleVector> evaluateCost(DoubleVector input) {

        double cost = Math.pow(input.get(0), 2) + Math.pow(input.get(1), 2);

        return new Tuple<Double, DoubleVector>(cost, null);
      }
    };

    DoubleVector minimizeFunction = ParticleSwarmOptimization.minimizeFunction(
        inlineFunction, start, 1000, 0.1, 0.2, 0.4, 100, false);
    // 1E-5 is close enough to zero for the test to pass
    assertTrue(minimizeFunction.get(0) >= 0 && minimizeFunction.get(0) < 1E-5);
    assertTrue(minimizeFunction.get(1) >= 0 && minimizeFunction.get(1) < 1E-5);
  }

}

@@ -1148,11 +1148,916 @@
 %0A  %7D%0D%0A%0D%0A
+  @Test%0D%0A  public void testParticleSwarmOptimizationNonConvex() %7B%0D%0A%0D%0A    DoubleVector start = new DenseDoubleVector(new double%5B%5D %7B 1, 3 %7D);%0D%0A%0D%0A    CostFunction inlineFunction = new CostFunction() %7B%0D%0A      @Override%0D%0A      public Tuple%3CDouble, DoubleVector%3E evaluateCost(DoubleVector input) %7B%0D%0A        double x = input.get(0);%0D%0A        double y = input.get(1);%0D%0A        // that's the rosenbrock function%0D%0A        double cost = Math.pow((1 - x), 2) + 100 * Math.pow((y - x * x), 2);%0D%0A%0D%0A        return new Tuple%3CDouble, DoubleVector%3E(cost, null);%0D%0A      %7D%0D%0A    %7D;%0D%0A%0D%0A    DoubleVector minimizeFunction = ParticleSwarmOptimization.minimizeFunction(%0D%0A        inlineFunction, start, 1000, 2.8, 0.4, 0.8, 65, false);%0D%0A%0D%0A    assertTrue(minimizeFunction.get(0) %3E= 0.95%0D%0A        && minimizeFunction.get(0) %3C 1.05);%0D%0A    assertTrue(minimizeFunction.get(1) %3E= 0.95%0D%0A        && minimizeFunction.get(1) %3C 1.05);%0D%0A  %7D%0D%0A%0D%0A
 %7D%0D%0A

optimize rosenbrock function with PSO