/** {@inheritDoc} */
  @Override
  public void absorb(Niche algorithm) {
    for (PopulationBasedAlgorithm pba : algorithm.getPopulations()) {
      RadiusVisitor radiusVisitor = new RadiusVisitor();
      pba.accept(radiusVisitor);

      double radius = radiusVisitor.getResult().doubleValue();

      Topology<? extends Entity> mainSwarmTopology = algorithm.getMainSwarm().getTopology();
      for (int i = 0; i < mainSwarmTopology.size(); i++) {
        Entity entity = mainSwarmTopology.get(i);
        double distance =
            distanceMeasure.distance(
                entity.getCandidateSolution(),
                Topologies.getBestEntity(pba.getTopology()).getCandidateSolution());
        if (distance <= radius) {
          Particle p = (Particle) entity;
          p.setVelocityProvider(new GCVelocityProvider());
          p.setNeighbourhoodBest((Particle) Topologies.getBestEntity(pba.getTopology()));
          Topology<Particle> topology = (Topology<Particle>) pba.getTopology();
          topology.add(p);
          algorithm.getMainSwarm().getTopology().remove(entity);
        }
      }
    }
  }
  /** {@inheritDoc} */
  @Override
  public Vector get(Particle particle) {
    Vector localGuide = (Vector) particle.getLocalGuide();
    Vector globalGuide = (Vector) particle.getGlobalGuide();

    PSO pso = (PSO) AbstractAlgorithm.get();
    List<Entity> positions = getRandomParentEntities(pso.getTopology());

    // select three random individuals, all different and different from particle
    ProbabilityDistributionFuction pdf = new UniformDistribution();

    Vector position1 = (Vector) positions.get(0).getCandidateSolution();
    Vector position2 = (Vector) positions.get(1).getCandidateSolution();
    //        Vector position3 = (Vector) positions.get(2).getContents();

    Vector.Builder builder = Vector.newBuilder();
    for (int i = 0; i < particle.getDimension(); ++i) {
      double r = pdf.getRandomNumber(0, 1);
      double attractor = r * localGuide.doubleValueOf(i) + (1 - r) * globalGuide.doubleValueOf(i);
      double stepSize =
          this.rand3.getRandomNumber(0, 1)
              * (position1.doubleValueOf(i) - position2.doubleValueOf(i));

      if (this.rand2.getRandomNumber(0, 1) > this.crossoverProbability.getParameter()) {
        builder.add(attractor + stepSize);
      } else {
        builder.add(((Vector) particle.getPosition()).doubleValueOf(i)); // position3.getReal(i));
      }
    }
    return builder.build();
  }
 private Particle createParticle(Vector vector) {
   Particle particle = new StandardParticle();
   particle.getProperties().put(EntityType.CANDIDATE_SOLUTION, vector);
   particle.getProperties().put(EntityType.Particle.VELOCITY, Vector.of(0.0));
   particle.getProperties().put(EntityType.Particle.BEST_POSITION, vector.getClone());
   return particle;
 }
  /**
   * Structure of Dynamic Heterogeneous iteration strategy:
   *
   * <ol>
   *   <li>For each particle:
   *   <li>Check if particle must change its behavior
   *   <li>If particle must change its behavior:
   *       <ol>
   *         <li>Select a new behavior to the particle from the behavior pool
   *       </ol>
   *   <li>Perform normal iteration
   * </ol>
   *
   * @see
   *     net.sourceforge.cilib.pso.iterationstrategies.SynchronousIterationStrategy#performIteration()
   */
  @Override
  public void performIteration(PSO algorithm) {
    checkState(
        behaviorPool.size() > 0, "You must add particle behaviors to the behavior pool first.");

    for (Entity e : algorithm.getTopology()) {
      Particle p = (Particle) e;

      if (detectionStrategy.detect(p)) {
        p.setParticleBehavior(behaviorSelectionRecipe.on(behaviorPool).select());
      }
    }

    iterationStrategy.performIteration(algorithm);
  }
  /** Test velocity clamping. */
  @Test
  public void testClamping() {
    Particle particle = createParticle(Vector.of(0.0));
    Particle nBest = createParticle(Vector.of(1.0));
    particle.setNeighbourhoodBest(nBest);
    nBest.setNeighbourhoodBest(nBest);

    ClampingVelocityProvider velocityProvider = new ClampingVelocityProvider();
    velocityProvider.setVMax(new ConstantControlParameter(0.5));
    Vector velocity = velocityProvider.get(particle);

    for (Numeric number : velocity) {
      Assert.assertTrue(Double.compare(number.doubleValue(), 0.5) <= 0);
      Assert.assertTrue(Double.compare(number.doubleValue(), -0.5) >= 0);
    }
  }
Esempio n. 6
0
  /** {@inheritDoc} */
  public Real getValue(Algorithm algorithm) {
    PSO pso = (PSO) algorithm;

    int numberParticles = pso.getTopology().size();

    Iterator<Particle> k = pso.getTopology().iterator();
    Particle particle = k.next();
    Vector averageParticlePosition = (Vector) particle.getPosition().getClone();
    while (k.hasNext()) {
      particle = k.next();
      Vector v = (Vector) particle.getPosition();
      for (int j = 0; j < averageParticlePosition.size(); ++j) {
        averageParticlePosition.setReal(
            j, averageParticlePosition.doubleValueOf(j) + v.doubleValueOf(j));
      }
    }
    for (int j = 0; j < averageParticlePosition.size(); ++j) {
      averageParticlePosition.setReal(
          j, averageParticlePosition.doubleValueOf(j) / numberParticles);
    }

    Iterator<Particle> i = pso.getTopology().iterator();
    double particleSum = 0.0;
    while (i.hasNext()) {
      particle = i.next();

      double dimensionSum = 0.0;
      Vector v = (Vector) particle.getPosition();
      for (int j = 0; j < particle.getDimension(); ++j) {
        dimensionSum +=
            (v.doubleValueOf(j) - averageParticlePosition.doubleValueOf(j))
                * (v.doubleValueOf(j) - averageParticlePosition.doubleValueOf(j));
      }
      particleSum += Math.sqrt(dimensionSum);
    }

    double diversity = particleSum / numberParticles;

    DiameterVisitor diameterVisitor = new DiameterVisitor();
    pso.accept(diameterVisitor);
    double diameter = diameterVisitor.getResult();

    return Real.valueOf(diversity / diameter);
  }
  private Vector applyCrossover(
      Particle particle, List<Vector> parents, CrossoverStrategy crossover) {
    List<Entity> entityParents = Lists.newLinkedList();

    for (Vector v : parents) {
      Entity parent = particle.getClone();
      parent.setCandidateSolution(v);
      entityParents.add(parent);
    }

    return (Vector) crossover.crossover(entityParents).get(0).getCandidateSolution();
  }
  /**
   * Returns the new position
   *
   * @param particle The particle to update
   * @return the particle's new position
   */
  @Override
  public Vector get(Particle particle) {
    particle.setPositionProvider(new LinearPositionProvider());

    Vector solution = (Vector) particle.getCandidateSolution();
    Vector pBest = (Vector) particle.getBestPosition();
    Vector nBest = (Vector) particle.getNeighbourhoodBest().getBestPosition();

    Set<Vector> solutions = new HashSet<Vector>(Arrays.asList(solution, pBest, nBest));

    if (solutions.size() == 3) {
      return applyCrossover(particle, Lists.newLinkedList(solutions), mainCrossover);
    }

    Vector prevPos = (Vector) particle.getProperties().get(EntityType.PREVIOUS_SOLUTION);
    solutions.add(prevPos);

    if (solutions.size() == 3) {
      return applyCrossover(particle, Lists.newLinkedList(solutions), mainCrossover);
    }

    if (solutions.size() == 2) {
      return applyCrossover(particle, Lists.newLinkedList(solutions), alternateCrossover);
    }

    particle.setPositionProvider(new StandardPositionProvider());
    return delegate.get(particle);
  }
  @Test
  public void initialize() {
    final Bounds bounds = new Bounds(-8.0, 8.0);
    Vector vector =
        Vector.newBuilder()
            .addWithin(0.0, bounds)
            .addWithin(0.0, bounds)
            .addWithin(0.0, bounds)
            .build();

    Particle particle = new StandardParticle();
    particle.getProperties().put(EntityType.Particle.VELOCITY, vector);

    DomainPercentageInitializationStrategy<Particle> strategy =
        new DomainPercentageInitializationStrategy<Particle>();
    strategy.setVelocityInitialisationStrategy(new ConstantInitializationStrategy(1.0));
    strategy.initialize(EntityType.Particle.VELOCITY, particle);

    Vector velocity = (Vector) particle.getVelocity();
    for (int i = 0; i < velocity.size(); i++) {
      Assert.assertThat(velocity.doubleValueOf(i), is(lessThanOrEqualTo(0.1)));
    }
  }
  @Override
  public Vector get(Particle particle) {
    Vector localGuide = (Vector) particle.getLocalGuide();
    Vector globalGuide = (Vector) particle.getGlobalGuide();

    Vector.Builder builder = Vector.newBuilder();
    for (int i = 0; i < particle.getDimension(); ++i) {
      if (this.uniform.getRandomNumber(0, 1) < 0.5) {
        builder.add(localGuide.doubleValueOf(i));
      } else {
        // double tmp1 = cognitive.getParameter();
        // double tmp2 = social.getParameter();

        double sigma = Math.abs(localGuide.doubleValueOf(i) - globalGuide.doubleValueOf(i));
        // according to Kennedy
        double mean = (localGuide.doubleValueOf(i) + globalGuide.doubleValueOf(i)) / 2;
        // andries proposal: double mean = (tmp1*personalBestPosition.getReal(i) +
        // tmp2*nBestPosition.getReal(i)) / (tmp1+tmp2);

        builder.add(this.randomDistribution.getRandomNumber(mean, sigma));
      }
    }
    return builder.build();
  }
Esempio n. 11
0
  @Override
  public Boolean f(PopulationBasedAlgorithm a, PopulationBasedAlgorithm b) {
    Particle p1 =
        (Particle) Topologies.getBestEntity(a.getTopology(), new SocialBestFitnessComparator());
    Particle p2 =
        (Particle) Topologies.getBestEntity(b.getTopology(), new SocialBestFitnessComparator());
    Vector v1 = ((Vector) p1.getBestPosition()).subtract((Vector) p1.getCandidateSolution());
    Vector v2 = ((Vector) p2.getBestPosition()).subtract((Vector) p2.getCandidateSolution());

    return v1.dot(v2) > 0;
  }
  /** {@inheritDoc} */
  @Override
  public Vector get(Particle particle) {
    double averageParticleVelocity = 0.0;

    Vector averageVelocity = null; // velocity.getClone();
    //        averageVelocity.reset();
    PSO pso = (PSO) AbstractAlgorithm.get();
    for (Particle p : pso.getTopology()) {
      if (averageVelocity == null) {
        averageVelocity = (Vector) p.getVelocity();
        continue;
      }
      Vector particleVelocity = (Vector) p.getVelocity();
      averageVelocity = averageVelocity.plus(particleVelocity);
      averageParticleVelocity += particleVelocity.norm();
    }
    averageVelocity = averageVelocity.divide(particle.getDimension());
    averageParticleVelocity /= particle.getDimension();

    double swarmCenterVelocity = averageVelocity.norm();
    double swarmCoherence = calculateSwarmCoherence(swarmCenterVelocity, averageParticleVelocity);

    double sigmoidValue = this.sigmoid.apply(swarmCoherence);

    Vector standardVelocity = this.delegate.get(particle);

    Vector.Builder builder = Vector.newBuilder();
    for (int i = 0; i < particle.getDimension(); ++i) {
      double coherenceVelocity =
          this.scalingFactor.getParameter()
              * sigmoidValue
              * averageVelocity.doubleValueOf(i)
              * this.randomNumber.getRandomNumber();
      builder.add(coherenceVelocity);
    }
    Vector coherence = builder.build();

    return Vectors.sumOf(standardVelocity, coherence);

    //        float social = socialRandomGenerator.nextFloat();
    //        float cognitive = cognitiveRandomGenerator.nextFloat();
    //
    //        //DistanceMeasure adm = new AbsoluteDistanceMeasure();
    //        //DistanceMeasure dm = new MetricDistanceMeasure();
    //
    //        double avgv = 0.0;
    //        double swv = 0.0;
    //        Topology<Particle> topology = ((PSO)Algorithm.get()).getTopology();
    //          Iterator<? extends Particle> it = topology.neighbourhood(null);
    //          double[] al = new double[particle.getDimension()];
    //           while (it.hasNext()) {
    //               Particle pl = it.next();
    //               double tmpv = 0.0;
    //               //double tmpsv = 0.0;
    //               for(int dim = 0; dim < particle.getDimension(); dim++) {
    //                al[dim] = al[dim]+((Vector)pl.getVelocity()).getReal(dim);
    //                   tmpv += Math.pow(((Vector)pl.getVelocity()).getReal(dim), 2);
    //               }
    //               tmpv = Math.sqrt(tmpv);
    //               avgv += tmpv;
    //           }
    //           for(int i = 0; i < particle.getDimension(); i++) {
    //            //al.set(i, ;
    //            swv += (al[i]/topology.size()) * (al[i]/topology.size());
    //        }
    //        swv = Math.sqrt(swv);
    //
    //        for (int i = 0; i < particle.getDimension(); ++i) {
    //            double tmp = 0.0;
    //            tmp = inertiaWeight.getParameter()*velocity.getReal(i)
    //                + cognitive * (bestPosition.getReal(i) - position.getReal(i)) *
    // cognitiveAcceleration.getParameter()
    //                + social * (nBestPosition.getReal(i) - position.getReal(i)) *
    // socialAcceleration.getParameter();
    //
    //            double avgdim = 0.0;
    //              it = topology.neighbourhood(null);
    //               while (it.hasNext()) {
    //                   avgdim += ((Vector)(it.next().getVelocity())).getReal(i);
    //               }
    //            avgdim /= particle.getDimension();
    //
    //            double cvelocity = MathUtil.sigmoid(swv/avgv)*avgdim*randomNumber.getCauchy();
    //
    //            System.out.println(cvelocity);
    //            tmp += cvelocity;
    //
    //            velocity.setReal(i, tmp);
    //
    //            clamp(velocity, i);
    //        }
  }
  @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());
    }
  }
 @Override
 public void updateGuide(Particle particle, EntityType.Particle.Guide guideType, Vector newGuide) {
   particle.getProperties().put(guideType, newGuide);
 }