01 /*
02 * Java Genetic Algorithm Library (jenetics-6.2.0).
03 * Copyright (c) 2007-2021 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * 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 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext;
21
22 import java.util.Random;
23
24 import io.jenetics.AbstractAlterer;
25 import io.jenetics.Chromosome;
26 import io.jenetics.Gene;
27 import io.jenetics.Mutator;
28 import io.jenetics.MutatorResult;
29 import io.jenetics.internal.math.Combinatorics;
30 import io.jenetics.util.MSeq;
31
32 /**
33 * The reverse sequence mutation, two positions i and j are randomly chosen The
34 * gene order in a chromosome will then be reversed between this two points.
35 * This mutation operator can also be used for combinatorial problems, where no
36 * duplicated genes within a chromosome are allowed, e.g. for the TSP.
37 *
38 * @see io.jenetics.SwapMutator
39 *
40 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
41 * @version 5.0
42 * @since 5.0
43 */
44 public class RSMutator<
45 G extends Gene<?, G>,
46 C extends Comparable<? super C>
47 >
48 extends Mutator<G, C>
49 {
50
51 /**
52 * Constructs an alterer with a given recombination probability.
53 *
54 * @param probability the crossover probability.
55 * @throws IllegalArgumentException if the {@code probability} is not in the
56 * valid range of {@code [0, 1]}.
57 */
58 public RSMutator(final double probability) {
59 super(probability);
60 }
61
62 /**
63 * Default constructor, with default mutation probability
64 * ({@link AbstractAlterer#DEFAULT_ALTER_PROBABILITY}).
65 */
66 public RSMutator() {
67 this(DEFAULT_ALTER_PROBABILITY);
68 }
69
70 @Override
71 protected MutatorResult<Chromosome<G>> mutate(
72 final Chromosome<G> chromosome,
73 final double p,
74 final Random random
75 ) {
76 final MutatorResult<Chromosome<G>> result;
77 if (chromosome.length() > 1) {
78 final int[] points = Combinatorics.subset(chromosome.length() + 1, 2);
79 final MSeq<G> genes = MSeq.of(chromosome);
80 genes.subSeq(points[0], points[1]).reverse();
81
82 result = MutatorResult.of(
83 chromosome.newInstance(genes.toISeq()),
84 points[1] - points[0] - 1
85 );
86 } else {
87 result = MutatorResult.of(chromosome);
88 }
89
90 return result;
91 }
92
93 }
|