GaAlgorithm.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package holeg.algorithm.topologie;
  2. import holeg.algorithm.objective_function.TopologieObjectiveFunction;
  3. import holeg.api.TopologieAlgorithmFramework;
  4. import holeg.model.Model;
  5. import holeg.utility.math.Random;
  6. import java.util.ArrayList;
  7. import java.util.Arrays;
  8. import java.util.LinkedList;
  9. import java.util.List;
  10. import java.util.ListIterator;
  11. import java.util.TreeSet;
  12. public class GaAlgorithm extends TopologieAlgorithmFramework {
  13. private int popsize = 20;
  14. private int maxGenerations = 100;
  15. private double tournamentSize = 2.0;
  16. private double fixedSwapProbability = 0.02;
  17. private boolean useFixedSpawProbability = false;
  18. private double fixedMutateProbability = 0.02;
  19. private boolean useFixedMutateProbability = false;
  20. private boolean useIntervalMutation = false;
  21. private double mutateProbabilityInterval = 0.01;
  22. private double maxMutationPercent = 0.01;
  23. private boolean moreInformation = false;
  24. public GaAlgorithm() {
  25. addIntParameter("popsize", popsize, intValue -> popsize = intValue, () -> popsize, 1);
  26. addIntParameter("maxGenerations", maxGenerations, intValue -> maxGenerations = intValue,
  27. () -> maxGenerations, 1);
  28. addDoubleParameter("tournamentSize", tournamentSize,
  29. doubleValue -> tournamentSize = doubleValue, () -> tournamentSize, 1.0);
  30. addBooleanParameter("useFixedSpawProbability", useFixedSpawProbability,
  31. booleanValue -> useFixedSpawProbability = booleanValue,
  32. Arrays.asList("fixedSwapProbability"), new LinkedList<String>());
  33. addDoubleParameter("fixedSwapProbability", fixedSwapProbability,
  34. doubleValue -> fixedSwapProbability = doubleValue, () -> fixedSwapProbability,
  35. useFixedSpawProbability, 0.0, 1.0);
  36. addSeperator();
  37. addBooleanParameter("Use Interval Mutation", useIntervalMutation,
  38. booleanValue -> useIntervalMutation = booleanValue,
  39. Arrays.asList("Probability for Frequency Mutation", "Scope of Mutation"),
  40. Arrays.asList("Probability for Bit-wise Mutation"));
  41. addDoubleParameter("Probability for Frequency Mutation", mutateProbabilityInterval,
  42. doubleValue -> mutateProbabilityInterval = doubleValue, () -> mutateProbabilityInterval,
  43. useIntervalMutation, 0.0, 1.0);
  44. addDoubleParameter("Probability for Bit-wise Mutation", fixedMutateProbability,
  45. doubleValue -> fixedMutateProbability = doubleValue, () -> fixedMutateProbability,
  46. !useIntervalMutation, 0.0, 1.0);
  47. addDoubleParameter("Scope of Mutation", maxMutationPercent,
  48. doubleValue -> maxMutationPercent = doubleValue, () -> maxMutationPercent,
  49. useIntervalMutation, 0.0, 1.0);
  50. addSeperator();
  51. addBooleanParameter("Print Auxiliary Information", moreInformation,
  52. booleanValue -> moreInformation = booleanValue, new LinkedList<String>(),
  53. new LinkedList<String>());
  54. }
  55. @Override
  56. protected double evaluateState(Model model, int amountOfAddedSwitch, double addedCableMeters,
  57. boolean moreInformation) {
  58. return TopologieObjectiveFunction.getFitnessValueForState(model, amountOfAddedSwitch,
  59. addedCableMeters, moreInformation);
  60. }
  61. @Override
  62. protected Individual executeAlgo() {
  63. resetWildcards();
  64. Individual best = new Individual();
  65. best.position = extractPositionAndAccess();
  66. int problemSize = best.position.size();
  67. best.fitness = evaluatePosition(best.position);
  68. List<Double> runList = new ArrayList<Double>();
  69. runList.add(best.fitness);
  70. console.println("Integer_Array_length: " + best.position.size());
  71. List<Individual> population = initPopuluationRandom(problemSize, best);
  72. for (int generation = 0; generation < maxGenerations; generation++) {
  73. if (moreInformation) {
  74. console.println("Generation" + generation + " start with Fitness: " + best.fitness);
  75. }
  76. for (Individual i : population) {
  77. i.fitness = evaluatePosition(i.position);
  78. if (moreInformation) {
  79. console.println("Fitness" + i.fitness);
  80. }
  81. if (i.fitness < best.fitness) {
  82. best = i;
  83. }
  84. }
  85. runList.add(best.fitness);
  86. List<Individual> childList = new ArrayList<Individual>();
  87. for (int k = 0; k < popsize / 2; k++) {
  88. Individual parentA = selectAParent(population, popsize);
  89. Individual parentB = selectAParent(population, popsize);
  90. Individual childA = new Individual(parentA);
  91. Individual childB = new Individual(parentB);
  92. crossover(childA, childB, problemSize);
  93. if (useIntervalMutation) {
  94. mutateInterval(childA, problemSize);
  95. } else {
  96. mutate(childA, problemSize);
  97. }
  98. if (useIntervalMutation) {
  99. mutateInterval(childB, problemSize);
  100. } else {
  101. mutate(childB, problemSize);
  102. }
  103. childList.add(childA);
  104. childList.add(childB);
  105. }
  106. population = childList;
  107. if (moreInformation) {
  108. console.println("________________");
  109. }
  110. if (cancel) {
  111. return null;
  112. }
  113. }
  114. console.println(" End with:" + best.fitness);
  115. this.runList = runList;
  116. return best;
  117. }
  118. @Override
  119. protected int getProgressBarMaxCount() {
  120. return rounds * maxGenerations * popsize + 1;
  121. }
  122. @Override
  123. protected String algoInformationToPrint() {
  124. return "GaAlgo" + " Rounds:" + rounds
  125. + " maxGenerations:" + maxGenerations
  126. + " popsize:" + popsize
  127. + " tournamentSize:" + tournamentSize
  128. + (useFixedSpawProbability ? " fixedSwapProbability:" + fixedSwapProbability
  129. : " swapProbability:" + "1.0f/problemsize")
  130. + (useIntervalMutation ?
  131. (" mutateProbabilityInterval:" + mutateProbabilityInterval
  132. + " maxMutationPercent:" + maxMutationPercent)
  133. :
  134. (useFixedMutateProbability ? " fixedMutateProbability:" + fixedMutateProbability
  135. : " mutateProbability:" + "1.0f/problemsize"));
  136. }
  137. @Override
  138. protected String plottFileName() {
  139. return "ga-topologie.txt";
  140. }
  141. /**
  142. * Initialize the Population with Individuals that have a random Position.
  143. */
  144. private List<Individual> initPopuluationRandom(int problemSize, Individual startIndidual) {
  145. List<Individual> population = new ArrayList<Individual>();
  146. for (int i = 0; i < popsize - 1; i++) {
  147. population.add(createRandomIndividualWithoutFitness(problemSize));
  148. }
  149. //Add Start Position
  150. population.add(new Individual(startIndidual));
  151. return population;
  152. }
  153. private Individual createRandomIndividualWithoutFitness(int problemSize) {
  154. //create Random Individual Without Fitness
  155. Individual result = new Individual();
  156. result.position = new ArrayList<Integer>();
  157. for (int index = 0; index < problemSize; index++) {
  158. result.position.add(Random.nextIntegerInRange(0, this.getMaximumIndexObjects(index) + 1));
  159. }
  160. //console.println("[" +result.position.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]");
  161. return result;
  162. }
  163. /**
  164. * Algorithm 32 Tournament Selection. The fitnessValues are calculated for the Population List.
  165. * PseudoCode
  166. */
  167. private Individual selectAParent(List<Individual> population, int popsize) {
  168. Individual tournamentBest = population.get(Random.nextIntegerInRange(0, popsize));
  169. double participants;
  170. for (participants = tournamentSize; participants >= 2; participants -= 1.0) {
  171. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  172. if (next.fitness < tournamentBest.fitness) {
  173. tournamentBest = next;
  174. }
  175. }
  176. //if tournament size is not a whole number like 2.5 or 3.6
  177. //the remaining part is the chance to fight another time; 2.7 -> 70% chance to fight a second time
  178. if (participants > 1) {
  179. if (Random.nextDouble() < participants - 1.0) {
  180. //println("Chance to find a match");
  181. Individual next = population.get(Random.nextIntegerInRange(0, popsize));
  182. if (next.fitness < tournamentBest.fitness) {
  183. tournamentBest = next;
  184. }
  185. }
  186. }
  187. return tournamentBest;
  188. }
  189. /**
  190. * Algorithm 25 Uniform Crossover. Probability is set to 1/Problemsize when not changed.
  191. */
  192. private void crossover(Individual childA, Individual childB, int problemSize) {
  193. double probability =
  194. (this.useFixedSpawProbability) ? this.fixedSwapProbability : 1.0 / (double) problemSize;
  195. ListIterator<Integer> iterA = childA.position.listIterator();
  196. ListIterator<Integer> iterB = childB.position.listIterator();
  197. for (int i = 0; i < problemSize; i++) {
  198. int intA = iterA.next();
  199. int intB = iterB.next();
  200. if (Random.nextDouble() <= probability) {
  201. //Swap
  202. iterA.set(intB);
  203. iterB.set(intA);
  204. }
  205. }
  206. }
  207. /**
  208. * Algorithm 22 Bit-Flip Mutation.
  209. */
  210. private void mutate(Individual child, int problemSize) {
  211. double probability =
  212. (this.useFixedMutateProbability) ? this.fixedMutateProbability : 1.0 / (double) problemSize;
  213. ListIterator<Integer> iter = child.position.listIterator();
  214. while (iter.hasNext()) {
  215. int index = iter.nextIndex();
  216. Integer intValue = iter.next();
  217. if (Random.nextDouble() <= probability) {
  218. iter.set(nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  219. }
  220. }
  221. }
  222. /**
  223. * Algorithm rolf
  224. */
  225. private void mutateInterval(Individual child, int problemSize) {
  226. //If not mutate skip
  227. if (Random.nextDouble() > this.mutateProbabilityInterval) {
  228. return;
  229. }
  230. //println("problemSize:" + problemSize + " maxMutationPercent:" + maxMutationPercent);
  231. int maximumAmountOfMutatedBits = Math.max(1,
  232. (int) Math.round(((double) problemSize) * this.maxMutationPercent));
  233. int randomUniformAmountOfMutatedValues = Random.nextIntegerInRange(1,
  234. maximumAmountOfMutatedBits + 1);
  235. //println("max:" + maximumAmountOfMutatedBits + " actual:" + randomUniformAmountOfMutatedValues);
  236. TreeSet<Integer> mutationLocation = new TreeSet<Integer>(); //sortedSet
  237. //Choose the location to mutate
  238. for (int i = 0; i < randomUniformAmountOfMutatedValues; i++) {
  239. boolean success = mutationLocation.add(Random.nextIntegerInRange(0, problemSize));
  240. if (!success) {
  241. i--; //can be add up to some series long loops if maximumAmountOfMutatedBits get closed to problemsize.
  242. }
  243. }
  244. //println("Set:" + mutationLocation);
  245. ListIterator<Integer> iter = child.position.listIterator();
  246. if (mutationLocation.isEmpty()) {
  247. return;
  248. }
  249. int firstindex = mutationLocation.pollFirst();
  250. while (iter.hasNext()) {
  251. int index = iter.nextIndex();
  252. int intValue = iter.next();
  253. if (index == firstindex) {
  254. iter.set(nextIntegerInRangeExcept(0, this.getMaximumIndexObjects(index), intValue));
  255. //println("changed Value["+ index +"]");
  256. if (mutationLocation.isEmpty()) {
  257. break;
  258. }
  259. firstindex = mutationLocation.pollFirst();
  260. }
  261. }
  262. }
  263. /**
  264. * Random Int in Range [min;max[ with UniformDistribution without the value between.
  265. *
  266. * @param min the minimum value
  267. * @param max the maximum value
  268. * @param valueBetween a value between min and max
  269. * @return next random integer value without a value between.
  270. */
  271. public static int nextIntegerInRangeExcept(int min, int max, int valueBetween) {
  272. if (max - min == 1) {
  273. //return the other value
  274. return (valueBetween == min) ? max : min;
  275. }
  276. int result = Random.nextIntegerInRange(min, max -1);
  277. if (result >= valueBetween) {
  278. result++;
  279. }
  280. return result;
  281. }
  282. }