/** * @param aChromosome * @return double adjusted fitness for aChromosome relative to this specie * @throws IllegalArgumentException if chromosome is not a member if this specie */ public double getChromosomeFitnessValue(Chromosome aChromosome) { if (aChromosome.getFitnessValue() < 0) throw new IllegalArgumentException( "chromosome's fitness has not been set: " + aChromosome.toString()); if (chromosomes.contains(aChromosome) == false) throw new IllegalArgumentException( "chromosome not a member of this specie: " + aChromosome.toString()); return ((double) aChromosome.getFitnessValue()) / chromosomes.size(); }
/** @return Chromosome fittest in this specie */ public synchronized Chromosome getFittest() { if (fittest == null) { Iterator it = chromosomes.iterator(); fittest = (Chromosome) it.next(); while (it.hasNext()) { Chromosome next = (Chromosome) it.next(); if (next.getFitnessValue() > fittest.getFitnessValue()) fittest = next; } } return fittest; }
/** * @return average raw fitness (i.e., not adjusted for specie size) of all chromosomes in specie */ public double getFitnessValue() { long totalRawFitness = 0; Iterator iter = chromosomes.iterator(); while (iter.hasNext()) { Chromosome aChromosome = (Chromosome) iter.next(); if (aChromosome.getFitnessValue() < 0) throw new IllegalStateException( "chromosome's fitness has not been set: " + aChromosome.toString()); totalRawFitness += aChromosome.getFitnessValue(); } return (double) totalRawFitness / chromosomes.size(); }
/** * @return String XML representation of object according to <a * href="http://nevt.sourceforge.net/">NEVT </a>. */ public String toXml() { StringBuffer result = new StringBuffer(); result.append("<").append(SPECIE_TAG).append(" ").append(ID_TAG).append("=\""); result.append(getRepresentativeId()).append("\" ").append(COUNT_TAG).append("=\""); result.append(getChromosomes().size()).append("\">\n"); Iterator chromIter = getChromosomes().iterator(); while (chromIter.hasNext()) { Chromosome chromToStore = (Chromosome) chromIter.next(); result.append("<").append(CHROMOSOME_TAG).append(" ").append(ID_TAG).append("=\""); result.append(chromToStore.getId()).append("\" ").append(FITNESS_TAG).append("=\""); result.append(chromToStore.getFitnessValue()).append("\" />\n"); } result.append("</").append(SPECIE_TAG).append(">\n"); return result.toString(); }
/** * @param aChromosome * @return true if chromosome is added, false if chromosome already is a member of this specie */ public boolean add(Chromosome aChromosome) { if (!match(aChromosome)) throw new IllegalArgumentException("chromosome does not match specie: " + aChromosome); if (chromosomes.contains(aChromosome)) return false; aChromosome.setSpecie(this); fittest = null; return chromosomes.add(aChromosome); }
/** @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object o1, Object o2) { Chromosome c1 = (Chromosome) o1; Chromosome c2 = (Chromosome) o2; int fitness1 = (isSpeciated ? c1.getSpeciatedFitnessValue() : c1.getFitnessValue()); int fitness2 = (isSpeciated ? c2.getSpeciatedFitnessValue() : c2.getFitnessValue()); return isAscending ? fitness1 - fitness2 : fitness2 - fitness1; }
public static void main(String[] args) throws InvalidConfigurationException { // Reading data from xml try { new InputData().readFromFile(XML_TEST_FILENAME); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } // Configuration conf = new DefaultConfiguration(); Configuration conf = new Configuration("myconf"); TimetableFitnessFunction fitnessFunction = new TimetableFitnessFunction(); InitialConstraintChecker timetableConstraintChecker = new InitialConstraintChecker(); // Creating genes Gene[] testGenes = new Gene[CHROMOSOME_SIZE]; for (int i = 0; i < CHROMOSOME_SIZE; i++) { testGenes[i] = new GroupClassTeacherLessonTimeSG( conf, new Gene[] { new GroupGene(conf, 1), new ClassGene(conf, 1), new TeacherGene(conf, 1), new LessonGene(conf, 1), new TimeGene(conf, 1) }); } System.out.println("=================================="); // Creating chromosome Chromosome testChromosome; testChromosome = new Chromosome(conf, testGenes); testChromosome.setConstraintChecker(timetableConstraintChecker); // Setup configuration conf.setSampleChromosome(testChromosome); conf.setPopulationSize(POPULATION_SIZE); conf.setFitnessFunction(fitnessFunction); // add fitness function BestChromosomesSelector myBestChromosomesSelector = new BestChromosomesSelector(conf); conf.addNaturalSelector(myBestChromosomesSelector, false); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); CrossoverOperator myCrossoverOperator = new CrossoverOperator(conf); conf.addGeneticOperator(myCrossoverOperator); TimetableMutationOperator myMutationOperator = new TimetableMutationOperator(conf); conf.addGeneticOperator(myMutationOperator); conf.setKeepPopulationSizeConstant(false); // Creating genotype // Population pop = new Population(conf, testChromosome); // Genotype population = new Genotype(conf, pop); Genotype population = Genotype.randomInitialGenotype(conf); System.out.println("Our Chromosome: \n " + testChromosome.getConfiguration().toString()); System.out.println("------------evolution-----------------------------"); // Begin evolution Calendar cal = Calendar.getInstance(); start_t = cal.getTimeInMillis(); for (int i = 0; i < MAX_EVOLUTIONS; i++) { System.out.println( "generation#: " + i + " population size:" + (Integer) population.getPopulation().size()); if (population.getFittestChromosome().getFitnessValue() >= THRESHOLD) break; population.evolve(); } cal = Calendar.getInstance(); finish_t = cal.getTimeInMillis(); System.out.println("--------------end of evolution--------------------"); Chromosome fittestChromosome = (Chromosome) population.getFittestChromosome(); System.out.println( "-------------The best chromosome---fitness=" + fittestChromosome.getFitnessValue() + "---"); System.out.println(" Group Class Time"); for (int i = 0; i < CHROMOSOME_SIZE; i++) { GroupClassTeacherLessonTimeSG s = (GroupClassTeacherLessonTimeSG) fittestChromosome.getGene(i); System.out.println( "Gene " + i + " contains: " + (Integer) s.geneAt(GROUP).getAllele() + " " + (Integer) s.geneAt(CLASS).getAllele() + " " + (Integer) s.geneAt(TEACHER).getAllele() + " " + (Integer) s.geneAt(LESSON).getAllele() + " " + (Integer) s.geneAt(TIME).getAllele()); // GroupGene gg = (GroupGene)s.geneAt(GROUP); // System.out.println("gg's idGroup"+gg.getAllele()+" gg.getGroupSize()"+ gg.getGroupSize() ); } System.out.println("Elapsed time:" + (double) (finish_t - start_t) / 1000 + "s"); // Display the best solution OutputData od = new OutputData(); od.printToConsole(fittestChromosome); // Write population to the disk try { od.printToFile(population, GENOTYPE_FILENAME, BEST_CHROMOSOME_FILENAME); } catch (IOException e) { System.out.println("IOException raised! " + e.getMessage()); } }
/** * Returns a copy of this Chromosome. The returned instance can evolve independently of this * instance. Note that, if possible, this method will first attempt to acquire a Chromosome * instance from the active ChromosomePool (if any) and set its value appropriately before * returning it. If that is not possible, then a new Chromosome instance will be constructed and * its value set appropriately before returning. * * @return copy of this Chromosome * @throws IllegalStateException instead of CloneNotSupportedException * @author Neil Rotstan * @author Klaus Meffert * @since 1.0 */ public synchronized Object clone() { // Before doing anything, make sure that a Configuration object // has been set on this Chromosome. If not, then throw an // IllegalStateException. // ------------------------------------------------------------ if (getConfiguration() == null) { throw new IllegalStateException( "The active Configuration object must be set on this " + "Chromosome prior to invocation of the clone() method."); } IChromosome copy = null; // Now, first see if we can pull a Chromosome from the pool and just // set its gene values (alleles) appropriately. // ------------------------------------------------------------ IChromosomePool pool = getConfiguration().getChromosomePool(); if (pool != null) { copy = pool.acquireChromosome(); if (copy != null) { Gene[] genes = copy.getGenes(); for (int i = 0; i < size(); i++) { genes[i].setAllele(getGene(i).getAllele()); } } } try { if (copy == null) { // We couldn't fetch a Chromosome from the pool, so we need to create // a new one. First we make a copy of each of the Genes. We explicity // use the Gene at each respective gene location (locus) to create the // new Gene that is to occupy that same locus in the new Chromosome. // ------------------------------------------------------------------- int size = size(); if (size > 0) { Gene[] copyOfGenes = new Gene[size]; for (int i = 0; i < copyOfGenes.length; i++) { copyOfGenes[i] = getGene(i).newGene(); Object allele = getGene(i).getAllele(); if (allele != null) { IJGAPFactory factory = getConfiguration().getJGAPFactory(); if (factory != null) { ICloneHandler cloner = factory.getCloneHandlerFor(allele, allele.getClass()); if (cloner != null) { try { allele = cloner.perform(allele, null, this); } catch (Exception ex) { throw new RuntimeException(ex); } } } } copyOfGenes[i].setAllele(allele); } // Now construct a new Chromosome with the copies of the genes and // return it. Also clone the IApplicationData object later on. // --------------------------------------------------------------- if (getClass() == Chromosome.class) { copy = new Chromosome(getConfiguration(), copyOfGenes); } else { copy = (IChromosome) getConfiguration().getSampleChromosome().clone(); copy.setGenes(copyOfGenes); } } else { if (getClass() == Chromosome.class) { copy = new Chromosome(getConfiguration()); } else { copy = (IChromosome) getConfiguration().getSampleChromosome().clone(); } } } copy.setFitnessValue(m_fitnessValue); // Clone constraint checker. // ------------------------- copy.setConstraintChecker(getConstraintChecker()); } catch (InvalidConfigurationException iex) { throw new IllegalStateException(iex.getMessage()); } // Also clone the IApplicationData object. // --------------------------------------- try { copy.setApplicationData(cloneObject(getApplicationData())); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage()); } // Clone multi-objective object if necessary and possible. // ------------------------------------------------------- if (m_multiObjective != null) { if (getClass() == Chromosome.class) { try { ((Chromosome) copy).setMultiObjectives((List) cloneObject(m_multiObjective)); } catch (Exception ex) { throw new IllegalStateException(ex.getMessage()); } } } return copy; }
/** * Create new specie from representative. Representative is first member of specie, and all other * members of specie are determined by compatibility with representative. Even if representative * dies from population, a reference is kept here to determine specie membership. * * @param aSpeciationParms * @param aRepresentative */ public Specie(SpeciationParms aSpeciationParms, Chromosome aRepresentative) { representative = aRepresentative; aRepresentative.setSpecie(this); chromosomes.add(aRepresentative); speciationParms = aSpeciationParms; }
/** @return unique ID; this is chromosome ID of representative */ public Long getRepresentativeId() { return representative.getId(); }
/** @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object o) { Specie other = (Specie) o; return representative.equals(other.representative); }
/** @see java.lang.Object#hashCode() */ public int hashCode() { return representative.hashCode(); }
/** * @param aChromosome * @return boolean true iff compatibility difference between * <code>aChromosome</code? and representative * is less than speciation threshold */ public boolean match(Chromosome aChromosome) { return (representative.distance(aChromosome, speciationParms) < speciationParms.getSpeciationThreshold()); }