RandomKeyMutation.java revision dee0849a9704d532af0b550146cbafbaa6ee1d19
1/* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17package org.apache.commons.math.genetics; 18 19import java.util.ArrayList; 20import java.util.List; 21 22import org.apache.commons.math.MathRuntimeException; 23import org.apache.commons.math.exception.util.LocalizedFormats; 24 25/** 26 * Mutation operator for {@link RandomKey}s. Changes a randomly chosen element 27 * of the array representation to a random value uniformly distributed in [0,1]. 28 * 29 * @since 2.0 30 * @version $Revision: 983921 $ $Date: 2010-08-10 12:46:06 +0200 (mar. 10 août 2010) $ 31 */ 32public class RandomKeyMutation implements MutationPolicy { 33 34 /** 35 * {@inheritDoc} 36 * 37 * @throws IllegalArgumentException if <code>original</code> is not a 38 * {@link RandomKey} instance 39 */ 40 public Chromosome mutate(Chromosome original) { 41 if (!(original instanceof RandomKey<?>)) { 42 throw MathRuntimeException.createIllegalArgumentException( 43 LocalizedFormats.RANDOMKEY_MUTATION_WRONG_CLASS, 44 original.getClass().getSimpleName()); 45 } 46 47 RandomKey<?> originalRk = (RandomKey<?>) original; 48 List<Double> repr = originalRk.getRepresentation(); 49 int rInd = GeneticAlgorithm.getRandomGenerator().nextInt(repr.size()); 50 51 List<Double> newRepr = new ArrayList<Double> (repr); 52 newRepr.set(rInd, GeneticAlgorithm.getRandomGenerator().nextDouble()); 53 54 return originalRk.newFixedLengthChromosome(newRepr); 55 } 56 57} 58