/** * Respond to the environment change and ensure that the neighbourhood best entities are updated. * This method (Template Method) calls two other methods in turn: * * <ul> * <li>{@link #performReaction(PopulationBasedAlgorithm)} * <li>{@link #updateNeighbourhoodBestEntities(Topology)} * </ul> * * @param algorithm some {@link PopulationBasedAlgorithm population based algorithm} */ public <P extends Particle, A extends SinglePopulationBasedAlgorithm<P>> void respond( A algorithm) { performReaction(algorithm); if (hasMemory) { updateNeighbourhoodBestEntities(algorithm.getTopology(), algorithm.getNeighbourhood()); } }
/** * 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; }