示例#1
0
  @Override
  public Vector get(Particle particle) {
    Vector velocity = (Vector) particle.getVelocity();
    Vector position = (Vector) particle.getPosition();
    PSO algorithm = (PSO) AbstractAlgorithm.get();
    int ns = (int) nSize.getParameter();
    fj.data.List<Particle> neighbours =
        algorithm
            .getTopology()
            .sort(
                Ord.ord(
                    VectorBasedFunctions.sortByDistance(particle, new EuclideanDistanceMeasure())))
            .take(ns);

    Vector.Builder builder = Vector.newBuilder();
    for (int i = 0; i < particle.getDimension(); ++i) {
      double informationSum = 0.0;
      double randomSum = 0;

      for (Particle currentTarget : neighbours) {
        Vector currentTargetPosition = (Vector) currentTarget.getBestPosition();
        double randomComponent = Rand.nextDouble() * (4.1 / ns);
        informationSum += randomComponent * currentTargetPosition.doubleValueOf(i);
        randomSum += randomComponent;
      }

      double value =
          inertiaWeight.getParameter()
              * (velocity.doubleValueOf(i)
                  + randomSum * ((informationSum / (ns * randomSum) - position.doubleValueOf(i))));
      builder.add(value);
    }

    return builder.build();
  }
  /** {@inheritDoc} */
  @Override
  public <T extends Entity> T create(T targetEntity, T current, Topology<T> topology) {
    T bestEntity = Topologies.getBestEntity(topology);
    List<T> participants =
        Selection.copyOf(topology)
            .exclude(targetEntity, bestEntity, current)
            .orderBy(new RandomArrangement())
            .select(Samples.first((int) numberOfDifferenceVectors.getParameter()).unique());
    Vector differenceVector = determineDistanceVector(participants);

    Vector targetVector =
        ((Vector) targetEntity.getCandidateSolution())
            .multiply(1 - greedynessParameter.getParameter());
    Vector bestVector =
        ((Vector) bestEntity.getCandidateSolution()).multiply(greedynessParameter.getParameter());

    Vector trialVector =
        bestVector.plus(
            targetVector.plus(differenceVector.multiply(scaleParameter.getParameter())));

    T trialEntity = (T) current.getClone();
    trialEntity.setCandidateSolution(trialVector);

    return trialEntity;
  }
示例#3
0
  @Override
  public boolean apply(PopulationBasedAlgorithm input) {
    updateControlParameters();
    calculatedDiversity = (diversity.getValue(input)).doubleValue();
    maximumDiversity = Math.max(maximumDiversity, calculatedDiversity);

    iterations = calculatedDiversity < minimumDiversity.getParameter() ? iterations + 1 : 0;

    return iterations >= consecutiveIterations.getParameter();
  }
  @Override
  public void initialize(Enum<?> key, E entity) {
    Type type = entity.getProperties().get(key);
    Vector velocity = (Vector) type;

    for (int i = 0; i < velocity.size(); i++) {
      changeBoundsForNextDimension(i);
      velocity.setReal(
          i, random.getRandomNumber(lowerBound.getParameter(), upperBound.getParameter()));
    }
  }
  @Override
  public void performIteration(PSO algorithm) {
    delegate.performIteration(algorithm);
    Topology<Particle> topology = algorithm.getTopology();

    // calculate vAvg
    Vector avgV =
        Vectors.mean(
            Lists.transform(
                topology,
                new Function<Particle, Vector>() {
                  @Override
                  public Vector apply(Particle f) {
                    return (Vector) f.getVelocity();
                  }
                }));

    Vector.Builder builder = Vector.newBuilder();
    for (Numeric n : avgV) {
      if (Math.abs(n.doubleValue()) > vMax.getParameter()) {
        builder.add(vMax.getParameter());
      } else {
        builder.add(n);
      }
    }

    avgV = builder.build();

    // mutation
    Particle gBest = Topologies.getBestEntity(topology, new SocialBestFitnessComparator());
    Particle mutated = gBest.getClone();
    Vector pos = (Vector) gBest.getBestPosition();
    final Bounds bounds = pos.boundsOf(0);

    pos =
        pos.plus(
            avgV.multiply(
                new Supplier<Number>() {
                  @Override
                  public Number get() {
                    return distribution.getRandomNumber() * bounds.getRange()
                        + bounds.getLowerBound();
                  }
                }));

    mutated.setCandidateSolution(pos);
    mutated.calculateFitness();

    if (gBest.getBestFitness().compareTo(mutated.getFitness()) < 0) {
      gBest.getProperties().put(EntityType.Particle.BEST_FITNESS, mutated.getBestFitness());
      gBest.getProperties().put(EntityType.Particle.BEST_POSITION, mutated.getBestPosition());
    }
  }
  public void setNumberOfSentries(ControlParameter parameter) {
    if (parameter.getParameter() <= 0) {
      throw new IllegalArgumentException("It doesn't make sense to have <= 0 sentry points");
    }

    numberOfSentries = parameter;
  }
示例#7
0
文件: HS.java 项目: vervas/cilib
 /** {@inheritDoc} */
 @Override
 public void performInitialisation() {
   for (int i = 0; i < harmonyMemorySize.getParameter(); i++) {
     Harmony harmony = new Harmony();
     harmony.initialise(getOptimisationProblem());
     this.harmonyMemory.add(harmony);
   }
 }
示例#8
0
文件: HS.java 项目: vervas/cilib
  /** {@inheritDoc} */
  @Override
  public void algorithmIteration() {
    // TO-DO: Make sure that all fitnesses are evaluated initially, and
    // that FE is incremented only once per iteration

    // calculate a new harmony
    Harmony newHarmony = new Harmony();
    newHarmony.initialise(getOptimisationProblem());
    Vector newHarmonyVector = (Vector) newHarmony.getCandidateSolution();

    OptimisationProblem problem = getOptimisationProblem();
    //        Real newHarmonyValue;
    for (int i = 0; i < problem.getDomain().getDimension(); ++i) {
      if (uniform1.getRandomNumber() < harmonyMemoryConsideringRate.getParameter()) {
        Harmony selectedHarmony =
            this.harmonyMemory.get((int) uniform2.getRandomNumber(0, harmonyMemory.size() - 1));
        Vector selectedHarmonyContents = (Vector) selectedHarmony.getCandidateSolution();
        double newHarmonyValue = selectedHarmonyContents.doubleValueOf(i);
        Bounds bounds = selectedHarmonyContents.boundsOf(i);
        if (uniform1.getRandomNumber() < pitchAdjustingRate.getParameter()) {
          double pitchedValue =
              newHarmonyValue + uniform3.getRandomNumber(-1, 1) * distanceBandwidth.getParameter();
          if ((pitchedValue > bounds.getLowerBound()) && (pitchedValue < bounds.getUpperBound())) {
            newHarmonyValue = pitchedValue;
          }
        }

        newHarmonyVector.setReal(i, newHarmonyValue);
      } else {
        double upper =
            ((Vector) problem.getDomain().getBuiltRepresenation()).boundsOf(i).getUpperBound();
        double lower =
            ((Vector) problem.getDomain().getBuiltRepresenation()).boundsOf(i).getLowerBound();
        newHarmonyVector.setReal(i, uniform3.getRandomNumber(lower, upper));
      }
    }

    newHarmony.calculateFitness();
    harmonyMemory.add(newHarmony);
    harmonyMemory.remove(
        harmonyMemory.get(0) /*getFirst()*/); // Remove the worst harmony in the memory
  }
  @Override
  public <E extends Entity> List<E> crossover(List<E> parentCollection) {
    Preconditions.checkArgument(
        parentCollection.size() == 2, "BlendCrossoverStrategy requires 2 parents.");

    // How do we handle variable sizes? Resizing the entities?
    E offspring1 = (E) parentCollection.get(0).getClone();
    E offspring2 = (E) parentCollection.get(1).getClone();

    Vector parentChromosome1 = (Vector) parentCollection.get(0).getCandidateSolution();
    Vector parentChromosome2 = (Vector) parentCollection.get(1).getCandidateSolution();
    Vector.Builder offspringChromosome1 = Vector.newBuilder();
    Vector.Builder offspringChromosome2 = Vector.newBuilder();

    int sizeParent1 = parentChromosome1.size();
    int sizeParent2 = parentChromosome2.size();

    int minDimension = Math.min(sizeParent1, sizeParent2);

    for (int i = 0; i < minDimension; i++) {
      double gamma =
          (1 + 2 * alpha.getParameter()) * random.getRandomNumber() - alpha.getParameter();
      double value1 =
          (1 - gamma) * parentChromosome1.doubleValueOf(i)
              + gamma * parentChromosome2.doubleValueOf(i);
      double value2 =
          (1 - gamma) * parentChromosome2.doubleValueOf(i)
              + gamma * parentChromosome1.doubleValueOf(i);

      offspringChromosome1.add(Real.valueOf(value1, parentChromosome1.boundsOf(i)));
      offspringChromosome2.add(Real.valueOf(value2, parentChromosome1.boundsOf(i)));
    }

    offspring1.setCandidateSolution(offspringChromosome1.build());
    offspring2.setCandidateSolution(offspringChromosome2.build());

    return Arrays.asList(offspring1, offspring2);
  }
  /**
   * After every {@link #interval} iteration, pick {@link #numberOfSentries a number of} random
   * entities from the given {@link Algorithm algorithm's} topology and compare their previous
   * fitness values with their current fitness values. An environment change is detected when the
   * difference between the previous and current fitness values are &gt;= the specified {@link
   * #epsilon} value.
   *
   * @param algorithm used to get hold of topology of entities and number of iterations
   * @return true if a change has been detected, false otherwise
   */
  @Override
  public <A extends HasTopology & Algorithm & HasNeighbourhood> boolean detect(A algorithm) {
    if ((AbstractAlgorithm.get().getIterations() % interval == 0)
        && (AbstractAlgorithm.get().getIterations() != 0)) {
      List all = Java.List_ArrayList().f(algorithm.getTopology());

      for (int i = 0; i < numberOfSentries.getParameter(); i++) {
        // select random sentry entity
        int random = Rand.nextInt(all.size());
        StandardParticle sentry = (StandardParticle) all.get(random);

        // check for change
        // double previousFitness = sentry.getFitness().getValue();

        boolean detectedChange = false;

        if (sentry.getFitness().getClass().getName().matches("MinimisationFitness")) {
          Fitness previousFitness = sentry.getFitness();
          sentry.calculateFitness();
          Fitness currentFitness = sentry.getFitness();

          if (Math.abs(previousFitness.getValue() - currentFitness.getValue()) >= epsilon) {
            detectedChange = true;
          }
        } else if (sentry.getFitness().getClass().getName().matches("StandardMOFitness")) {
          MOFitness previousFitness = (MOFitness) sentry.getFitness();
          sentry.calculateFitness();
          MOFitness currentFitness = (MOFitness) sentry.getFitness();

          for (int k = 0; k < previousFitness.getDimension(); k++)
            if (Math.abs(
                    previousFitness.getFitness(k).getValue()
                        - currentFitness.getFitness(k).getValue())
                >= epsilon) {
              detectedChange = true;
              break;
            }
        }
        if (detectedChange) {
          System.out.println("Detected a change");
          return true;
        }

        // remove the selected element from the all list preventing it from being selected again
        all.remove(random);
      }
    }
    return false;
  }
示例#11
0
文件: ABC.java 项目: Salihu/cilib
  /**
   * Copy constructor. Creates a copy of the provided instance.
   *
   * @param copy ABC reference of which a deep copy is made.
   */
  public ABC(ABC copy) {
    super(copy);

    explorerBee = copy.explorerBee.getClone();
    dancingSelectionStrategy = new RouletteWheelSelector();

    forageLimit = copy.forageLimit.getClone();
    workerBeePercentage = copy.workerBeePercentage.getClone();
    explorerBeeUpdateLimit = copy.explorerBeeUpdateLimit.getClone();

    final int workerBeeCount =
        Double.valueOf(workerBeePercentage.getParameter() * topology.length()).intValue();
    workerBees = topology.take(workerBeeCount);
    onlookerBees = topology.drop(workerBeeCount);
  }
示例#12
0
文件: ABC.java 项目: Salihu/cilib
  /** {@inheritDoc} */
  @Override
  public void algorithmInitialisation() {
    topology =
        fj.data.List.iterableList(initialisationStrategy.<HoneyBee>initialise(optimisationProblem));

    int numWorkerBees = (int) (workerBeePercentage.getParameter() * topology.length());
    P2<fj.data.List<HoneyBee>, fj.data.List<HoneyBee>> split = topology.splitAt(numWorkerBees);
    this.workerBees = split._1();
    this.onlookerBees =
        split
            ._2()
            .map(
                new F<HoneyBee, HoneyBee>() {
                  public HoneyBee f(HoneyBee b) {
                    return new OnlookerBee((WorkerBee) b);
                  }
                });

    explorerBee.setExplorerBeeUpdateLimit(this.explorerBeeUpdateLimit);
  }
示例#13
0
  public void performIteration(final TuningAlgorithm alg) {
    final List<Vector> parameterList = alg.getParameterList();

    // TODO: deal with maximisation problems
    results =
        results.snoc(
            parameterList.map(
                new F<Vector, OptimisationSolution>() {
                  @Override
                  public OptimisationSolution f(Vector a) {
                    return new OptimisationSolution(a, alg.evaluate(a));
                  }
                }));

    // (+1 because iterations start at 0)
    if (alg.getIterations() + 1 >= minProblems.getParameter() && parameterList.length() != 1) {
      List<List<Double>> data =
          results.map(
              List.<OptimisationSolution, Double>map_().f(getFitness().andThen(getValue())));
      P2<Double, Double> friedman = StatsTests.friedman(0.05, data);

      if (friedman._1() > friedman._2()) {
        final List<Integer> indexes = StatsTests.postHoc(0.05, friedman._1(), data);
        alg.setParameterList(indexes.map(flip(Utils.<Vector>index()).f(parameterList)));

        results =
            results.map(
                new F<List<OptimisationSolution>, List<OptimisationSolution>>() {
                  @Override
                  public List<OptimisationSolution> f(final List<OptimisationSolution> a) {
                    return indexes.map(flip(Utils.<OptimisationSolution>index()).f(a));
                  }
                });
      }
    }
  }
  private void updateInertia(PSO pso) {

    int dimension = pso.getTopology().last().getDimension();

    if (inertiaWeight.size() < dimension) {
      Vector.Builder builder = Vector.newBuilder();
      builder.repeat(dimension, Real.valueOf(initialInertiaWeight.getParameter()));
      inertiaWeight = builder.build();
    }
    Vector.Builder builder = Vector.newBuilder();
    for (int i = 0; i < dimension; i++) {
      builder.add(
          Math.sqrt(
              Math.pow(absoluteAverageVelocityVector.doubleValueOf(i), 2)
                  + Math.pow(averageSpeedVector.doubleValueOf(i), 2)));
    }
    Vector d = builder.build(); // get the degree of convergence vector
    double max_d = 0;
    for (Numeric component : d) {
      if (component.doubleValue() > max_d) {
        max_d = component.doubleValue();
      }
    }
    if (max_d != 0) {
      Vector.Builder builder2 = Vector.newBuilder();
      for (Numeric component : d) {
        builder2.add(max_d / (max_d + component.doubleValue()));
      }
      Vector w = builder2.build();

      /*double sum_w = 0;
      for(Numeric component : w) {
          sum_w += component.doubleValue();
      }

      /*
      Vector.Builder builder3 = Vector.newBuilder();
      for(Numeric component : w) {
          builder3.add(Math.pow(dimension * component.doubleValue() / sum_w, pwr.getParameter()));
      } */

      /*
      for(Numeric component : w) {
          //builder3.add(component.doubleValue() - w_mean / w_stdDiv);
          builder3.add(component.doubleValue() * initialInertiaWeight.getParameter());
      }
      for(int i = 0; i < inertiaWeight.size(); i++) {
          builder3.add(w.doubleValueOf(i) * inertiaWeight.doubleValueOf(i));
      }
      */
      /*
      Vector m = builder3.build();
      double sum_m = 0;
      for (Numeric num : m) {
          sum_m += num.doubleValue();
      }

      double m_mean = sum_m / (double) dimension;
      double sum_diff_squared = 0;
      for(Numeric component : m) {
          sum_diff_squared += Math.pow(component.doubleValue() - m_mean, 2);
      }
      double m_stdDiv = Math.sqrt(sum_diff_squared / (double) dimension);
      */
      // System.out.println("VEL: StdDiv of M: " + m_stdDiv + ", mean of M: " + m_mean);

      for (int i = 0; i < inertiaWeight.size(); i++) {
        inertiaWeight.setReal(
            i,
            (1 - filter.getParameter()) * w.doubleValueOf(i)
                + filter.getParameter()
                    * inertiaWeight.doubleValueOf(i)); // w.doubleValueOf(i));//;
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public <E extends Entity> List<E> crossover(List<E> parentCollection) {
    checkState(
        parentCollection.size() >= 3,
        "There must be a minimum of three parents to perform UNDX crossover.");
    checkState(
        numberOfOffspring > 0,
        "At least one offspring must be generated. Check 'numberOfOffspring'.");

    List<Vector> solutions = Entities.<Vector>getCandidateSolutions(parentCollection);
    List<E> offspring = Lists.newArrayListWithCapacity(numberOfOffspring);
    UniformDistribution randomParent = new UniformDistribution();
    final int k = solutions.size();
    final int n = solutions.get(0).size();

    for (int os = 0; os < numberOfOffspring; os++) {
      // get index of main parent and put its solution at the end of the list
      int parent = (int) randomParent.getRandomNumber(0.0, k);
      Collections.swap(solutions, parent, k - 1);

      List<Vector> e_zeta = new ArrayList<Vector>();

      // calculate mean of parents except main parent
      Vector g = Vectors.mean(solutions.subList(0, k - 1));

      // basis vectors defined by parents
      for (int i = 0; i < k - 1; i++) {
        Vector d = solutions.get(i).subtract(g);

        if (!d.isZero()) {
          double dbar = d.length();
          Vector e = d.orthogonalize(e_zeta);

          if (!e.isZero()) {
            e_zeta.add(e.normalize().multiply(dbar));
          }
        }
      }

      final double D = solutions.get(k - 1).subtract(g).length();

      // create the remaining basis vectors
      List<Vector> e_eta = Lists.newArrayList();
      e_eta.add(solutions.get(k - 1).subtract(g));

      for (int i = 0; i < n - e_zeta.size() - 1; i++) {
        Vector d = Vector.newBuilder().copyOf(g).buildRandom();
        e_eta.add(d);
      }

      e_eta = Vectors.orthonormalize(e_eta);

      // construct the offspring
      Vector variables = Vector.copyOf(g);

      if (!useIndividualProviders) {
        for (int i = 0; i < e_zeta.size(); i++) {
          variables =
              variables.plus(
                  e_zeta.get(i).multiply(random.getRandomNumber(0.0, sigma1.getParameter())));
        }

        for (int i = 0; i < e_eta.size(); i++) {
          variables =
              variables.plus(
                  e_eta
                      .get(i)
                      .multiply(
                          D * random.getRandomNumber(0.0, sigma2.getParameter() / Math.sqrt(n))));
        }
      } else {
        for (int i = 0; i < e_zeta.size(); i++) {
          variables =
              variables.plus(
                  e_zeta
                      .get(i)
                      .multiply(
                          new Supplier<Number>() {

                            @Override
                            public Number get() {
                              return random.getRandomNumber(0.0, sigma1.getParameter());
                            }
                          }));
        }

        for (int i = 0; i < e_eta.size(); i++) {
          variables =
              variables.plus(
                  e_eta
                      .get(i)
                      .multiply(
                          new Supplier<Number>() {

                            @Override
                            public Number get() {
                              return D
                                  * random.getRandomNumber(
                                      0.0, sigma2.getParameter() / Math.sqrt(n));
                            }
                          }));
        }
      }

      E child = (E) parentCollection.get(parent).getClone();
      child.setCandidateSolution(variables);

      offspring.add(child);
    }

    return offspring;
  }
 /**
  * Determines if two swarms should be merged based on whether they overlap and if the diversity of
  * the first swarm is below a threshold.
  *
  * @param a a {@linkplain PopulationBasedAlgorithm}.
  * @param b a {@linkplain PopulationBasedAlgorithm}.
  * @return whether the two swarms should be merged.
  */
 @Override
 public Boolean f(SinglePopulationBasedAlgorithm a, SinglePopulationBasedAlgorithm b) {
   return diversityMeasure.getValue(a).doubleValue() < threshold.getParameter();
 }
示例#17
0
 private void updateControlParameters() {
   minimumDiversity.updateParameter();
   consecutiveIterations.updateParameter();
 }
示例#18
0
 @Override
 public double getPercentageCompleted(PopulationBasedAlgorithm algorithm) {
   return 1.0
       - ((calculatedDiversity - minimumDiversity.getParameter())
           / (maximumDiversity - minimumDiversity.getParameter()));
 }