PartiallyMatchedCrossover.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.2.0).
003  * Copyright (c) 2007-2018 Franz Wilhelmstötter
004  *
005  * Licensed under the Apache License, Version 2.0 (the "License");
006  * you may not use this file except in compliance with the License.
007  * You may obtain a copy of the License at
008  *
009  *      http://www.apache.org/licenses/LICENSE-2.0
010  *
011  * Unless required by applicable law or agreed to in writing, software
012  * distributed under the License is distributed on an "AS IS" BASIS,
013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014  * See the License for the specific language governing permissions and
015  * limitations under the License.
016  *
017  * Author:
018  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
019  */
020 package io.jenetics;
021 
022 import static java.lang.String.format;
023 
024 import java.util.Random;
025 
026 import io.jenetics.internal.math.comb;
027 import io.jenetics.internal.util.Equality;
028 import io.jenetics.internal.util.Hash;
029 import io.jenetics.util.MSeq;
030 import io.jenetics.util.RandomRegistry;
031 
032 /**
033  * The {@code PartiallyMatchedCrossover} (PMX) guarantees that all {@link Gene}s
034  * are found exactly once in each chromosome. No gene is duplicated by this
035  * crossover. The PMX can be applied usefully in the TSP or other permutation
036  * problem encodings. Permutation encoding is useful for all problems where the
037  * fitness only depends on the ordering of the genes within the chromosome. This
038  * is the case in many combinatorial optimization problems. Other crossover
039  * operators for combinatorial optimization are:
040  <ul type="square">
041  *     <li>order crossover</li>
042  *     <li>cycle crossover</li>
043  *     <li>edge recombination crossover</li>
044  *     <li>edge assembly crossover</li>
045  </ul>
046  <p>
047  * The PMX is similar to the two-point crossover. A crossing region is chosen
048  * by selecting two crossing points.
049  <pre>
050  *     C1 = 012|345|6789
051  *     C2 = 987|654|3210
052  </pre>
053  * After performing the crossover we normally got two invalid chromosomes.
054  <pre>
055  *     C1 = 012|654|6789
056  *     C2 = 987|345|3210
057  </pre>
058  * Chromosome {@code C1} contains the value 6  twice and misses the value
059  * 3. On  the other side chromosome {@code C2} contains the value 3 twice and
060  * misses the value 6. We can observe that this crossover is equivalent
061  * to the exchange of the values {@code 3 -> 6}, {@code 4 -> 5} and
062  * {@code 5 -> 4}. To repair the two
063  * chromosomes we have to apply this exchange outside the crossing region.
064  <pre>
065  *     C1 = 012|654|3789
066  *     C2 = 987|345|6210
067  </pre>
068  *
069  <em>The {@code PartiallyMatchedCrossover} class requires chromosomes with the
070  * same length. An {@code IllegalArgumentException} is thrown at runtime if this
071  * requirement is not fulfilled.</em>
072  *
073  @see PermutationChromosome
074  *
075  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
076  @since 1.0
077  @version 4.0
078  */
079 public final class PartiallyMatchedCrossover<T, C extends Comparable<? super C>>
080     extends Crossover<EnumGene<T>, C>
081 {
082 
083     public PartiallyMatchedCrossover(final double probability) {
084         super(probability);
085     }
086 
087     @Override
088     protected int crossover(
089         final MSeq<EnumGene<T>> that,
090         final MSeq<EnumGene<T>> other
091     ) {
092         if (that.length() != other.length()) {
093             throw new IllegalArgumentException(format(
094                 "Required chromosomes with same length: %s != %s",
095                 that.length(), other.length()
096             ));
097         }
098 
099         if (that.length() >= 2) {
100             final Random random = RandomRegistry.getRandom();
101             final int[] points = comb.subset(that.length()2, random);
102 
103             that.swap(points[0], points[1], other, points[0]);
104             repair(that, other, points[0], points[1]);
105             repair(other, that, points[0], points[1]);
106         }
107 
108         return 1;
109     }
110 
111     private static <T> void repair(
112         final MSeq<T> that, final MSeq<T> other,
113         final int begin, final int end
114     ) {
115         for (int i = 0; i < begin; ++i) {
116             int index = that.indexOf(that.get(i), begin, end);
117             while (index != -1) {
118                 that.set(i, other.get(index));
119                 index = that.indexOf(that.get(i), begin, end);
120             }
121         }
122         for (int i = end, n = that.length(); i < n; ++i) {
123             int index = that.indexOf(that.get(i), begin, end);
124             while (index != -1) {
125                 that.set(i, other.get(index));
126                 index = that.indexOf(that.get(i), begin, end);
127             }
128         }
129     }
130 
131     @Override
132     public int hashCode() {
133         return Hash.of(getClass()).and(super.hashCode()).value();
134     }
135 
136     @Override
137     public boolean equals(final Object obj) {
138         return Equality.of(this, obj).test(super::equals);
139     }
140 
141     @Override
142     public String toString() {
143         return format("%s[p=%f]", getClass().getSimpleName(), _probability);
144     }
145 
146 }