1 10 package org.jgap.impl; 11 12 import java.util.*; 13 import org.jgap.*; 14 15 31 public class SwappingMutationOperator 32 extends MutationOperator { 33 34 private final static String CVS_REVISION = "$Revision: 1.18 $"; 35 36 private int m_startOffset = 1; 37 38 46 public SwappingMutationOperator() 47 throws InvalidConfigurationException { 48 super(); 49 } 50 51 58 public SwappingMutationOperator(final Configuration a_config) 59 throws InvalidConfigurationException { 60 super(a_config); 61 } 62 63 75 public SwappingMutationOperator(final Configuration a_config, 76 final IUniversalRateCalculator 77 a_mutationRateCalculator) 78 throws InvalidConfigurationException { 79 super(a_config, a_mutationRateCalculator); 80 } 81 82 96 public SwappingMutationOperator(final Configuration a_config, 97 final int a_desiredMutationRate) 98 throws InvalidConfigurationException { 99 super(a_config, a_desiredMutationRate); 100 } 101 102 115 public void operate(final Population a_population, 116 List a_candidateChromosomes) { 117 final IUniversalRateCalculator m_mutationRateCalc = getMutationRateCalc(); 119 if (getMutationRate() == 0 && m_mutationRateCalc == null) { 123 return; 124 } 125 int currentRate; 130 if (m_mutationRateCalc != null) { 131 currentRate = m_mutationRateCalc.calculateCurrentRate(); 132 } 133 else { 134 currentRate = getMutationRate(); 135 } 136 RandomGenerator generator = getConfiguration().getRandomGenerator(); 137 int size = a_population.size(); 142 for (int i = 0; i < size; i++) { 143 IChromosome x = a_population.getChromosome(i); 144 IChromosome xm = operate(x, currentRate, generator); 146 if (xm != null) { 147 a_candidateChromosomes.add(xm); 148 } 149 } 150 } 151 152 162 protected IChromosome operate(final IChromosome a_x, final int a_rate, 163 final RandomGenerator a_generator) { 164 IChromosome chromosome = null; 165 for (int j = m_startOffset; j < a_x.size(); j++) { 167 if (a_generator.nextInt(a_rate) == 0) { 170 if (chromosome == null) { 171 chromosome = (IChromosome) a_x.clone(); 172 } 173 Gene[] genes = chromosome.getGenes(); 174 Gene[] mutated = operate(a_generator, j, genes); 175 try { 179 chromosome.setGenes(mutated); 180 } 181 catch (InvalidConfigurationException cex) { 182 throw new Error ("Gene type not allowed by constraint checker", cex); 183 } 184 } 185 } 186 return chromosome; 187 } 188 189 202 protected Gene[] operate(final RandomGenerator a_generator, 203 final int a_target_gene, final Gene[] a_genes) { 204 int other = m_startOffset 208 + a_generator.nextInt(a_genes.length - m_startOffset); 209 Gene t = a_genes[a_target_gene]; 210 a_genes[a_target_gene] = a_genes[other]; 211 a_genes[other] = t; 212 return a_genes; 213 } 214 215 226 public void setStartOffset(final int a_offset) { 227 m_startOffset = a_offset; 228 } 229 230 241 public int getStartOffset() { 242 return m_startOffset; 243 } 244 } 245 | Popular Tags |