Skip to content

Commit 6d2a4c1

Browse files
draegerandreasprlic
authored andcommitted
/* How can I make a Genetic Algorithm with BioJava? */
1 parent 5274224 commit 6d2a4c1

File tree

2 files changed

+257
-249
lines changed

2 files changed

+257
-249
lines changed

_wikis/BioJava:CookBook:GA.md

Lines changed: 129 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -41,16 +41,17 @@ GAStoppingCriteria. The actual implementations used are interchangeable.
4141
Further, the 'chromosome(s)' of the Organisms in a Population are just
4242
BioJava SymbolLists and any Alphabet could be used to encode a solution.
4343

44-
The org.biojavax.ga package is available with biojava-live from CVS. It
45-
will also be bundled with the core biojava distribution in version 1.5
46-
when released. The code requires Java 1.4
44+
As biojavax is already available, you can already use the GA package.
45+
However, the example below requires the GA package as it is currently
46+
available only in SVN. So please check it out anonymously to experiment
47+
with this example (have a look on the download section). It will also be
48+
bundled with the next biojava distribution in version 1.7 when released.
4749

4850
### GADemo.java
4951

50-
<java> package GA;
51-
52-
import java.util.Iterator; import org.biojava.bio.dist.Distribution;
53-
import org.biojava.bio.dist.DistributionTools; import
52+
<java> import java.util.Iterator; import
53+
org.biojava.bio.dist.Distribution; import
54+
org.biojava.bio.dist.DistributionTools; import
5455
org.biojava.bio.dist.UniformDistribution; import
5556
org.biojava.bio.symbol.SimpleSymbolList; import
5657
org.biojava.bio.symbol.SymbolList; import
@@ -73,133 +74,137 @@ org.biojavax.ga.functions.SimpleCrossOverFunction;
7374

7475
``
7576

76-
Demos a very Simple GA. It will run until one organism contains
77-
78-
`a chromosome that is 75% ones`
77+
`Demos a very Simple GA. It will run until one organism contains a chromosome`
78+
`* that is 75% ones`
79+
``
7980

8081
`*`
8182
`* @author Mark Schreiber`
82-
`* @version 1.0`
83+
`* @author Susanne Merz`
84+
`* @author Andreas Dräger`
85+
`* @version 1.1`
8386
`*/`
8487

85-
public class GADemo{
86-
87-
` public static void main(String[] args) throws Exception{`
88-
`   //print the header`
89-
`   System.out.println("gen,average_fitness,best_fitness");`
90-
91-
`   //a uniform Distribution over the binary Alphabet`
92-
`   Distribution bin_dist = new UniformDistribution(GATools.getBinaryAlphabet());`
93-
94-
`   //initialize the population`
95-
`   Population pop = new SimplePopulation("demo population");`
96-
97-
`   //add 100 organisms`
98-
`   for(int i = 0; i < 100; i++){`
99-
`     Organism o = new SimpleOrganism("organism"+i);`
100-
101-
`     //make 1 random chromosome for each organism`
102-
`     SymbolList[] ch = new SymbolList[1];`
103-
`     //the symbols are randomly sampled from bin_dist`
104-
`     ch[0] = new SimpleSymbolList(DistributionTools.generateSequence(`
105-
`         "", bin_dist, 100));`
106-
107-
`     //set the organisms chromosome to be ch`
108-
`     o.setChromosomes(ch);`
109-
110-
`     //add to organism to the population pop`
111-
`     pop.addOrganism(o);`
88+
public class GADemo {
89+
90+
`   public static void main(String[] args) throws Exception {`
91+
`       // print the header`
92+
`       System.out.println("gen,average_fitness,best_fitness");`
93+
94+
`       // a uniform Distribution over the binary Alphabet`
95+
`       Distribution bin_dist = new UniformDistribution(GATools.getBinaryAlphabet());`
96+
97+
`       // initialize the population`
98+
`       Population pop = new SimplePopulation("demo population");`
99+
100+
`       // add 100 organisms`
101+
`       for (int i = 0; i < 100; i++) {`
102+
`           Organism o = new SimpleOrganism("organism" + i);`
103+
104+
`           // make 1 random chromosome for each organism`
105+
`           SymbolList[] ch = new SymbolList[1];`
106+
`           // the symbols are randomly sampled from bin_dist`
107+
`           ch[0] = new SimpleSymbolList(DistributionTools.generateSequence("",`
108+
`               bin_dist, 100));`
109+
110+
`           // set the organisms chromosome to be ch`
111+
`           o.setChromosomes(ch);`
112+
113+
`           // add to organism to the population pop`
114+
`           pop.addOrganism(o);`
115+
`       }`
116+
117+
`       // created a SelectionFunction`
118+
`       SelectionFunction sf = new ProportionalSelection();`
119+
120+
`       // create a new CrossOverFunction`
121+
`       CrossOverFunction cf = new SimpleCrossOverFunction();`
122+
`       // set the max number of cross overs per chromosome`
123+
`       cf.setMaxCrossOvers(1);`
124+
`       // set a uniform cross over probability of 0.01`
125+
`       cf.setCrossOverProbs(new double[] {0.01});`
126+
127+
`       // create a new MutationFunction`
128+
`       MutationFunction mf = new SimpleMutationFunction();`
129+
`       // set a uniform MutationProbability of 0.0001`
130+
`       mf.setMutationProbs(new double[] {0.0001});`
131+
`       // set the mutation spectrum of the function to be a standard`
132+
`       // mutation distribution over the binary Alphabet`
133+
`       mf.setMutationSpectrum(GATools.standardMutationDistribution(GATools`
134+
`           .getBinaryAlphabet()));`
135+
136+
`       // make a GeneticAlgorithm with the above functions`
137+
`       GeneticAlgorithm genAlg = new SimpleGeneticAlgorithm(pop, mf, cf, sf);`
138+
`       // set its FitnessFunction`
139+
`       genAlg.setFitnessFunction(new DemoFitness());`
140+
`       // run the Algorithm until the criteria of DemoStopping are met`
141+
`       genAlg.run(new DemoStopping());`
112142
`   }`
113143

114-
`   //created a SelectionFunction`
115-
`   SelectionFunction sf = new ProportionalSelection();`
116-
`   //set its FitnessFunction`
117-
`   sf.setFitnessFunction(new DemoFitness());`
118-
119-
`   //create a new CrossOverFunction`
120-
`   CrossOverFunction cf = new SimpleCrossOverFunction();`
121-
`   //set the max number of cross overs per chromosome`
122-
`   cf.setMaxCrossOvers(1);`
123-
`   //set a uniform cross over probability of 0.01`
124-
`   cf.setCrossOverProbs(new double[]{0.01});`
125-
126-
`   //create a new MutationFunction`
127-
`   MutationFunction mf = new SimpleMutationFunction();`
128-
`   //set a uniform MutationProbability of 0.0001`
129-
`   mf.setMutationProbs(new double[]{0.0001});`
130-
`   //set the mutation spectrum of the function to be a standard`
131-
`   //mutation distribution over the binary Alphabet`
132-
`   mf.setMutationSpectrum(`
133-
`       GATools.standardMutationDistribution(GATools.getBinaryAlphabet()));`
134-
135-
`   //make a GeneticAlgorithm with the above functions`
136-
`   GeneticAlgorithm genAlg = new SimpleGeneticAlgorithm(pop, mf, cf, sf);`
137-
`   //run the Algorithm until the criteria of DemoStopping are met`
138-
`   genAlg.run(new DemoStopping());`
139-
` }`
140-
141-
` /**`
142-
`  * Basic implementation of GAStopping Criteria`
143-
`  *`
144-
`  */`
145-
` static class DemoStopping implements GAStoppingCriteria{`
146-
147144
`   /**`
148-
`    * Determines when to stop the Algorithm`
145+
`    * Basic implementation of GAStopping Criteria`
149146
`    */`
150-
`   public boolean stop (GeneticAlgorithm genAlg){`
151-
`     System.out.print(genAlg.getGeneration()+",");`
152-
`     Population pop = genAlg.getPopulation();`
153-
`     double totalFit = 0.0;`
154-
155-
`     FitnessFunction ff = genAlg.getSelectionFunction().getFitnessFunction();`
156-
157-
`     double fit = 0.0;`
158-
`     double bestFitness = 0.0;`
159-
160-
`     for (Iterator it = pop.organisms(); it.hasNext(); ) {`
161-
`       Organism o = (Organism)it.next();`
162-
`       fit = ff.fitness(o, pop, genAlg);`
163-
`       bestFitness = Math.max(fit, bestFitness);`
164-
`       totalFit += fit;`
165-
`     }`
166-
167-
`     //print the average fitness`
168-
`     System.out.print((totalFit/ (double) pop.size())+",");`
169-
`     //print the best fitness`
170-
`     System.out.println(bestFitness);`
171-
172-
`     //fitness is 75.0 so stop the algorithm`
173-
`     if(bestFitness >= 75.0){`
174-
`       System.out.println("Organism found with Fitness of 75%");`
175-
`       return true;`
176-
`     }`
177-
178-
`     //no organism is fit enough, continue the algorithm`
179-
`     return false;`
180-
`   }`
181-
` }`
182-
183-
` /**`
184-
`  * A fitness function bases on the most "one" rich chromosome in the organism.`
185-
`  *`
186-
`  */`
187-
` static class DemoFitness implements FitnessFunction{`
188-
`   public double fitness(Organism o, Population p, GeneticAlgorithm genAlg){`
189-
`     double bestfit = 0.0;`
190-
191-
`     for (int i = 0; i < o.getChromosomes().length; i++) {`
192-
`       SymbolList csome = o.getChromosomes()[i];`
193-
`       double fit = 0.0;`
194-
`       for(int j = 1; j <= csome.length(); j++){`
195-
`         if(csome.symbolAt(j) == GATools.one())`
196-
`           fit++;`
147+
`   static class DemoStopping implements GAStoppingCriteria {`
148+
149+
`       /**`
150+
`        * Determines when to stop the Algorithm`
151+
`        */`
152+
`       public boolean stop(GeneticAlgorithm genAlg) {`
153+
`           System.out.print(genAlg.getGeneration() + ",");`
154+
`           Population pop = genAlg.getPopulation();`
155+
`           int i;`
156+
`           double totalFit = 0.0;`
157+
158+
`           FitnessFunction ff = genAlg.getFitnessFunction();`
159+
160+
`           double fit[] = {0.0};`
161+
`           double bestFitness[] = {0.0};`
162+
163+
`           for (Iterator it = pop.organisms(); it.hasNext();) {`
164+
`               Organism o = (Organism) it.next();`
165+
`               fit = ff.fitness(o, pop, genAlg);`
166+
`               for (i = 0; i < fit.length; i++) {`
167+
`                   bestFitness[i] = Math.max(fit[i], bestFitness[i]);`
168+
`                   totalFit += fit[i];`
169+
`               }`
170+
`           }`
171+
172+
`           // print the average fitness`
173+
`           System.out.print((totalFit / (double) pop.size()) + ",");`
174+
`           // print the best fitness`
175+
`           System.out.println(bestFitness[0]);`
176+
177+
`           // fitness is 75.0 so stop the algorithm`
178+
`           boolean good = false;`
179+
`           for (i = 0; (i < bestFitness.length) && !good; i++) {`
180+
`               if (bestFitness[i] >= 75.0) {`
181+
`                   good = true;`
182+
`                   System.out.println("Organism found with Fitness of 75%");`
183+
`               }`
184+
`           }`
185+
`           // organism is fit enough, continue the algorithm`
186+
`           return good;`
197187
`       }`
198-
`       bestfit = Math.max(fit, bestfit);`
199-
`     }`
188+
`   }`
200189

201-
`     return bestfit;`
202-
`   }`
203-
` }`
190+
`   /**`
191+
`    * A fitness function bases on the most "one" rich chromosome in the organism.`
192+
`    */`
193+
`   static class DemoFitness implements FitnessFunction {`
194+
`       public double[] fitness(Organism o, Population p, GeneticAlgorithm genAlg) {`
195+
`           double bestfit[] = {0.0};`
196+
197+
`           for (int i = 0; i < o.getChromosomes().length; i++) {`
198+
`               SymbolList csome = o.getChromosomes()[i];`
199+
`               double fit = 0.0;`
200+
`               for (int j = 1; j <= csome.length(); j++) {`
201+
`                   if (csome.symbolAt(j) == GATools.one()) fit++;`
202+
`               }`
203+
`               bestfit[0] = Math.max(fit, bestfit[0]);`
204+
`           }`
205+
206+
`           return bestfit;`
207+
`       }`
208+
`   }`
204209

205210
} </java>

0 commit comments

Comments
 (0)