コード例 #1
0
  private void calculateAbsoluteAverages(PSO pso) {

    int dimension = pso.getTopology().last().getDimension();
    absoluteAverageVelocityVector = Vector.of();
    averageSpeedVector = Vector.of();

    for (Entity e : pso.getTopology()) {
      Vector velocity = (Vector) e.getProperties().get(EntityType.Particle.VELOCITY);
      for (int i = 0; i < dimension; i++) {
        if (absoluteAverageVelocityVector.size() < dimension) {
          absoluteAverageVelocityVector.add(velocity.get(i));
          averageSpeedVector.add(Real.valueOf(Math.abs(velocity.doubleValueOf(i))));
        } else {
          absoluteAverageVelocityVector.setReal(
              i, absoluteAverageVelocityVector.doubleValueOf(i) + velocity.doubleValueOf(i));
          averageSpeedVector.setReal(
              i, averageSpeedVector.doubleValueOf(i) + Math.abs(velocity.doubleValueOf(i)));
        }
      }
    }

    for (int i = 0; i < dimension; i++) {
      absoluteAverageVelocityVector.setReal(
          i, Math.abs(absoluteAverageVelocityVector.doubleValueOf(i) / (double) dimension));
      averageSpeedVector.setReal(i, averageSpeedVector.doubleValueOf(i) / (double) dimension);
    }
  }
コード例 #2
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();
  }
コード例 #3
0
  @Test
  public void testCreation() {
    Particle p1 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(3.0), Vector.of(0.0, 1.0));
    Particle p2 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(2.0), Vector.of(1.0, 1.0));
    Particle p3 =
        NichingFunctionsTest.createParticle(new MinimisationFitness(1.0), Vector.of(2.0, 2.0));

    PSO pso = new PSO();
    pso.getTopology().addAll(Arrays.asList(p1, p2, p3));

    ClosestNeighbourNicheCreationStrategy creator = new ClosestNeighbourNicheCreationStrategy();
    creator.setSwarmBehavior(new ParticleBehavior());
    NichingSwarms swarms =
        creator.f(NichingSwarms.of(pso, List.<PopulationBasedAlgorithm>nil()), p1);

    Assert.assertEquals(1, swarms._1().getTopology().size());
    Assert.assertEquals(
        Vector.of(2.0, 2.0), swarms._1().getTopology().get(0).getCandidateSolution());
    Assert.assertEquals(2, swarms._2().head().getTopology().size());
    Assert.assertEquals(
        Vector.of(0.0, 1.0), swarms._2().head().getTopology().get(0).getCandidateSolution());
    Assert.assertEquals(
        Vector.of(1.0, 1.0), swarms._2().head().getTopology().get(1).getCandidateSolution());
  }
コード例 #4
0
  /** {@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();
  }
コード例 #5
0
  @Override
  public Topology<Particle> f(PSO pso) {
    Topology<Particle> newTopology = pso.getTopology().getClone();
    newTopology.clear();

    for (Particle p : pso.getTopology()) {
      newTopology.add(function.f(p));
    }

    return newTopology;
  }
コード例 #6
0
  @Test
  public void value() {
    PSO pso = new PSO();
    MeasuredStoppingCondition maximumIterations =
        new MeasuredStoppingCondition(new Iterations(), new Maximum(), 100);
    pso.addStoppingCondition(maximumIterations);

    for (int i = 0; i < 10; i++) pso.performIteration();

    PercentageComplete percentageComplete = new PercentageComplete();
    Assert.assertEquals(0.1, percentageComplete.getValue(pso).doubleValue(), 0.001);
  }
コード例 #7
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);
  }
コード例 #8
0
  @Override
  public double getPercentageCompleted(PSO algorithm) {
    DiameterVisitor diameterVisitor = new DiameterVisitor();
    algorithm.accept(diameterVisitor);
    double diameter = diameterVisitor.getResult();

    if (diameter <= minimumSwarmDiameter) {
      return 1;
    }
    return minimumSwarmDiameter / diameter;
  }
コード例 #9
0
  @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());
    }
  }
コード例 #10
0
ファイル: ParticlePositions.java プロジェクト: Salihu/cilib
  /** {@inheritDoc} */
  @Override
  public StringType getValue(Algorithm algorithm) {
    final StringBuilder tmp = new StringBuilder();
    final PSO pso = (PSO) algorithm;
    for (Particle particle : pso.getTopology()) {
      tmp.append("\nParticle: ");
      tmp.append(" Current Fitness: ");
      tmp.append(particle.getFitness().getValue());
      tmp.append(" Best Fitness: ");
      tmp.append(particle.getBestFitness().getValue());
      tmp.append(" Position: ");

      Vector v = (Vector) particle.getPosition();
      for (int j = 0; j < particle.getDimension(); ++j) {
        tmp.append(v.doubleValueOf(j));
        tmp.append(" ");
      }
    }

    return new StringType(tmp.toString());
  }
コード例 #11
0
  /** @param pso The {@link PSO} to have an iteration applied. */
  @Override
  public void performIteration(final PSO pso) {
    final fj.data.List<Particle> topology = pso.getTopology();
    this.calculateAbsoluteAverages(pso);
    this.updateInertia(pso);
    final F<Particle, Particle> first =
        new F<Particle, Particle>() {
          @Override
          public Particle f(Particle current) {
            WeightedInertiaVelocityProvider wp =
                (WeightedInertiaVelocityProvider) current.getVelocityProvider(); // put
            wp.setInertiaWeight(inertiaWeight);
            current.updateVelocity();
            current.updatePosition();

            boundaryConstraint.enforce(current);
            return current;
          }
        };

    final F<Particle, Particle> second =
        new F<Particle, Particle>() {
          public Particle f(Particle current) {
            current.calculateFitness();
            for (Particle other : pso.getNeighbourhood().f(topology, current)) {
              if (current
                      .getSocialFitness()
                      .compareTo(other.getNeighbourhoodBest().getSocialFitness())
                  > 0) {
                other.setNeighbourhoodBest(current);
              }
            }

            return current;
          }
        };

    pso.setTopology(topology.map(first).map(second));
  }
コード例 #12
0
  /**
   * 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);
  }
コード例 #13
0
  /**
   * This is an Synchronous strategy:
   *
   * <ol>
   *   <li>For all particles:
   *       <ol>
   *         <li>Update the particle velocity
   *         <li>Update the particle position
   *       </ol>
   *   <li>For all particles:
   *       <ol>
   *         <li>Calculate the particle fitness
   *         <li>For all particles in the current particle's neighbourhood:
   *             <ol>
   *               <li>Update the neighbourhood best
   *             </ol>
   *       </ol>
   * </ol>
   *
   * @see
   *     net.sourceforge.cilib.PSO.IterationStrategy#performIteration(net.sourceforge.cilib.PSO.PSO)
   * @param pso The {@link PSO} to have an iteration applied.
   */
  @Override
  public void performIteration(PSO pso) {
    Topology<Particle> topology = pso.getTopology();

    for (Particle current : topology) {
      current.updateVelocity();
      current.updatePosition(); // TODO: replace with visitor (will simplify particle interface)

      boundaryConstraint.enforce(current);
    }

    Problem problem = AbstractAlgorithm.getAlgorithmList().get(0).getOptimisationProblem();

    for (Particle current : topology) {
      current.calculateFitness();
      for (Particle other : topology.neighbourhood(current)) {
        Particle p1 = current.getNeighbourhoodBest().getClone();
        Particle p2 = other.getNeighbourhoodBest().getClone();
        OptimisationSolution s1 =
            new OptimisationSolution(
                p1.getCandidateSolution().getClone(),
                problem.getFitness(p1.getCandidateSolution().getClone()));
        OptimisationSolution s2 =
            new OptimisationSolution(
                p2.getCandidateSolution().getClone(),
                problem.getFitness(p2.getCandidateSolution().getClone()));
        MOFitness fitness1 = (MOFitness) s1.getFitness();
        MOFitness fitness2 = (MOFitness) s2.getFitness();
        //                System.out.println("fitness1 = ");
        //                for (int i=0; i < fitness1.getDimension(); i++)
        //                    System.out.println(fitness1.getFitness(i).getValue());
        //
        //                System.out.println("fitness2 = ");
        //                for (int i=0; i < fitness2.getDimension(); i++)
        //                    System.out.println(fitness2.getFitness(i).getValue());
        if (fitness1.compareTo(fitness2) > 0) {
          other.setNeighbourhoodBest(current);
        }
      }
    }
  }
  @Test
  public void algorithmExecution() {
    NNDataTrainingProblem problem = new NNDataTrainingProblem();
    problem.getDataTableBuilder().setDataReader(new ARFFFileReader());
    problem.getDataTableBuilder().setSourceURL("library/src/test/resources/datasets/iris.arff");
    problem.setTrainingSetPercentage(0.7);
    problem.setGeneralizationSetPercentage(0.3);

    problem
        .getNeuralNetwork()
        .getArchitecture()
        .setArchitectureBuilder(new CascadeArchitectureBuilder());
    problem.getNeuralNetwork().setOperationVisitor(new CascadeVisitor());
    problem
        .getNeuralNetwork()
        .getArchitecture()
        .getArchitectureBuilder()
        .addLayer(new LayerConfiguration(4));
    problem
        .getNeuralNetwork()
        .getArchitecture()
        .getArchitectureBuilder()
        .addLayer(new LayerConfiguration(0));
    problem
        .getNeuralNetwork()
        .getArchitecture()
        .getArchitectureBuilder()
        .addLayer(new LayerConfiguration(1));
    problem
        .getNeuralNetwork()
        .getArchitecture()
        .getArchitectureBuilder()
        .getLayerBuilder()
        .setDomain("R(-3:3)");
    problem.initialise();

    PSO pso = new PSO();
    pso.getInitialisationStrategy().setEntityType(new DynamicParticle());
    pso.addStoppingCondition(new MeasuredStoppingCondition());
    pso.setOptimisationProblem(problem);
    pso.performInitialisation();

    CascadeNetworkExpansionReactionStrategy reaction =
        new CascadeNetworkExpansionReactionStrategy();

    Assert.assertEquals(5, ((Vector) pso.getBestSolution().getPosition()).size());
    Assert.assertEquals(5, problem.getNeuralNetwork().getWeights().size());

    for (int i = 0; i < Topologies.getBestEntity(pso.getTopology()).getDimension(); ++i) {
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getPosition())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition())
          .set(i, Real.valueOf(0.0));
    }
    reaction.performReaction(pso);
    Assert.assertEquals(11, ((Vector) pso.getBestSolution().getPosition()).size());
    Assert.assertEquals(11, problem.getNeuralNetwork().getWeights().size());
    Assert.assertEquals(
        Vector.of(
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getPosition());
    Assert.assertEquals(
        Vector.of(
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity());
    Assert.assertEquals(
        Vector.of(
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition());

    for (int i = 0; i < Topologies.getBestEntity(pso.getTopology()).getDimension(); ++i) {
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getPosition())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition())
          .set(i, Real.valueOf(0.0));
    }
    reaction.performReaction(pso);
    Assert.assertEquals(18, ((Vector) pso.getBestSolution().getPosition()).size());
    Assert.assertEquals(18, problem.getNeuralNetwork().getWeights().size());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getPosition());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition());

    for (int i = 0; i < Topologies.getBestEntity(pso.getTopology()).getDimension(); ++i) {
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getPosition())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity())
          .set(i, Real.valueOf(0.0));
      ((Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition())
          .set(i, Real.valueOf(0.0));
    }
    reaction.performReaction(pso);
    Assert.assertEquals(26, ((Vector) pso.getBestSolution().getPosition()).size());
    Assert.assertEquals(26, problem.getNeuralNetwork().getWeights().size());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getPosition());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getVelocity());
    Assert.assertEquals(
        Vector.of(
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            Double.NaN,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            0.0,
            Double.NaN),
        (Vector) Topologies.getBestEntity(pso.getTopology()).getBestPosition());
  }
コード例 #15
0
 @Override
 public boolean apply(PSO input) {
   DiameterVisitor diameterVisitor = new DiameterVisitor();
   input.accept(diameterVisitor);
   return (diameterVisitor.getResult() <= minimumSwarmDiameter);
 }
コード例 #16
0
  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));//;
      }
    }
  }
コード例 #17
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);
    //        }
  }