/** * 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 >= 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; }
/** * Calculates the fitness of the given solution by setting the neural network weights to the * solution and evaluating the training set in order to calculate the MSE (which is minimized). * * @param solution the weights representing a solution. * @return a new MinimisationFitness wrapping the MSE training error. */ @Override protected Fitness calculateFitness(Type solution) { if (trainingSet == null) { this.initialise(); } int currentIteration = AbstractAlgorithm.get().getIterations(); if (currentIteration != previousShuffleIteration) { try { shuffler.operate(trainingSet); } catch (CIlibIOException exception) { exception.printStackTrace(); } } neuralNetwork.getArchitecture().accept(solutionConversionStrategy.interpretSolution(solution)); double errorTraining = 0.0; OutputErrorVisitor visitor = new OutputErrorVisitor(); Vector error = null; for (StandardPattern pattern : trainingSet) { Vector output = neuralNetwork.evaluatePattern(pattern); visitor.setInput(pattern); neuralNetwork.getArchitecture().accept(visitor); error = visitor.getOutput(); for (Numeric real : error) { errorTraining += real.doubleValue() * real.doubleValue(); } } errorTraining /= trainingSet.getNumRows() * error.size(); return objective.evaluate(errorTraining); }
/** {@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(); }
/** {@inheritDoc} */ public void performReaction(PopulationBasedAlgorithm algorithm) { // select new competitors and re-evaluate PBest vector of Particle PopulationBasedAlgorithm currentAlgorithm = (PopulationBasedAlgorithm) AbstractAlgorithm.get(); // the current sub population algorithm int populationID = -1; for (Entity e : currentAlgorithm.getTopology()) { if (!(e instanceof AbstractParticle)) throw new RuntimeException( "CompetitiveCoevolutionParticleReevaluationResponseStrategy should only be used with Particles"); if (populationID == -1) populationID = ((Int) e.getProperties().get(EntityType.Coevolution.POPULATION_ID)).intValue(); Blackboard<Enum<?>, Type> blackboard = new Blackboard<Enum<?>, Type>(); blackboard.put(EntityType.CANDIDATE_SOLUTION, ((AbstractParticle) e).getBestPosition()); blackboard.put(EntityType.Coevolution.BOARD, new EntityScoreboard()); Fitness val = currentAlgorithm.getOptimisationProblem().getFitness(blackboard); e.getProperties().put(EntityType.Particle.BEST_FITNESS, val); // if currentV is better than re-evaluated pBest, then replace it if (e.getFitness().compareTo(e.getBestFitness()) > 0) { e.getProperties().put(EntityType.Particle.BEST_FITNESS, e.getFitness()); e.getProperties() .put( EntityType.Particle.BEST_POSITION, e.getProperties().get(EntityType.CANDIDATE_SOLUTION).getClone()); } } }
@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(); }
@SuppressWarnings("unchecked") @Override public StructuredType get(Particle particle) { MultiPopulationBasedAlgorithm topLevelAlgorithm = (MultiPopulationBasedAlgorithm) AbstractAlgorithm.getAlgorithmList().get(0); Blackboard<Enum<?>, Type> knowledge = (Blackboard<Enum<?>, Type>) this.knowledgeTransferStrategy.transferKnowledge(topLevelAlgorithm.getPopulations()); return (StructuredType) knowledge.get(EntityType.Particle.BEST_POSITION); }
/** {@inheritDoc} */ @Override public int compare(E o1, E o2) { SinglePopulationBasedAlgorithm populationBasedAlgorithm = (SinglePopulationBasedAlgorithm) AbstractAlgorithm.getAlgorithmList().index(0); MOOptimisationProblem problem = ((MOOptimisationProblem) populationBasedAlgorithm.getOptimisationProblem()); Particle p1 = (Particle) o1; Particle p2 = (Particle) o2; MOFitness fitness1 = ((MOFitness) problem.getFitness(p1.getBestPosition())); MOFitness fitness2 = ((MOFitness) problem.getFitness(p2.getBestPosition())); int value = fitness1.compareTo(fitness2); if (fitness1.compareTo(fitness2) == 0) { int random = Rand.nextInt(20); if (random > 10) value *= -1; } return value; }
/** * 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); } } } }
/** Evaluates the function. */ @Override public Double f(Vector x) { this.tau = AbstractAlgorithm.get().getIterations(); return this.apply(this.tau, x); }
/** {@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); // } }
/** This is used to help with the unit test. i.e. no "empty stack exception" */ public int getIteration() { return AbstractAlgorithm.get().getIterations(); }
/** Evaluates the function. */ @Override public Double apply(Vector x) { int iteration = AbstractAlgorithm.get().getIterations(); return this.apply(iteration, x); }