blob: 5f9dfcc36fdd12628a3f125ea4fc60cb1a47c164 [file] [log] [blame]
Thomas Vachuska58de4162015-09-10 16:15:33 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2015-present Open Networking Laboratory
Thomas Vachuska58de4162015-09-10 16:15:33 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Nikhil Cheerlaf7c2e1a2015-07-09 12:06:37 -070016package org.onlab.graph;
17
18import java.util.ArrayList;
19import java.util.Collections;
20import java.util.List;
21import java.util.Random;
22
23/**
24 * Represents a population of GAOrganisms. This class can be used
25 * to run a genetic algorithm on the population and return the fittest solutions.
26 */
27class GAPopulation<Organism extends GAOrganism> extends ArrayList<Organism> {
28 Random r = new Random();
29
30 /**
31 * Steps the population through one generation. The 75% least fit
32 * organisms are killed off and replaced with the children of the
33 * 25% (as well as some "random" newcomers).
34 */
35 void step() {
36 Collections.sort(this, (org1, org2) -> {
37 double d = org1.fitness() - org2.fitness();
38 if (d < 0) {
39 return -1;
40 } else if (d == 0) {
41 return 0;
42 }
43 return 1;
44 });
45 int maxSize = size();
46 for (int i = size() - 1; i > maxSize / 4; i--) {
47 remove(i);
48 }
49 for (Organism org: this) {
50 if (r.nextBoolean()) {
51 org.mutate();
52 }
53 }
54 while (size() < maxSize * 4 / 5) {
55 Organism org1 = get(r.nextInt(size()));
56 Organism org2 = get(r.nextInt(size()));
57 add((Organism) org1.crossWith(org2));
58 }
59
60 while (size() < maxSize) {
61 Organism org1 = get(r.nextInt(size()));
62 add((Organism) org1.random());
63 }
64 }
65
66 /**
67 * Runs GA for the specified number of iterations, and returns
68 * a sample of the resulting population of solutions.
69 *
70 * @param generations Number of generations to run GA for
71 * @param populationSize Population size of GA
72 * @param sample Number of solutions to ask for
73 * @param template Template GAOrganism to seed the population with
74 * @return ArrayList containing sample number of organisms
75 */
76 List<Organism> runGA(int generations, int populationSize, int sample, Organism template) {
77 for (int i = 0; i < populationSize; i++) {
78 add((Organism) template.random());
79 }
80
81 for (int i = 0; i < generations; i++) {
82 step();
83 }
84 for (int i = size() - 1; i >= sample; i--) {
85 remove(i);
86 }
87 return new ArrayList<>(this);
88 }
89}
90