CharacterGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-5.2.0).
003  * Copyright (c) 2007-2020 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.util.Objects.requireNonNull;
023 import static io.jenetics.internal.util.Hashes.hash;
024 
025 import java.io.Serializable;
026 import java.util.Objects;
027 import java.util.Random;
028 
029 import io.jenetics.internal.math.Randoms;
030 import io.jenetics.util.CharSeq;
031 import io.jenetics.util.ISeq;
032 import io.jenetics.util.IntRange;
033 import io.jenetics.util.MSeq;
034 import io.jenetics.util.RandomRegistry;
035 
036 /**
037  * Character gene implementation.
038  *
039  <p>This is a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html">
040  * value-based</a> class; use of identity-sensitive operations (including
041  * reference equality ({@code ==}), identity hash code, or synchronization) on
042  * instances of {@code CharacterGene} may have unpredictable results and should
043  * be avoided.
044  *
045  @see CharacterChromosome
046  *
047  * @implNote
048  * This class is immutable and thread-safe.
049  *
050  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
051  @since 1.0
052  @version 5.2
053  */
054 public final class CharacterGene
055     implements
056         Gene<Character, CharacterGene>,
057         Comparable<CharacterGene>,
058         Serializable
059 {
060     private static final long serialVersionUID = 3L;
061 
062     /**
063      * The default character set used by this gene.
064      */
065     public static final CharSeq DEFAULT_CHARACTERS = new CharSeq(
066         "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" +
067         " !\"$%&/()=?`{[]}\\+~*#';.:,-_<>|@^'"
068     );
069 
070     private final char _character;
071     private final CharSeq _validCharacters;
072 
073     private CharacterGene(final CharSeq chars, final int index) {
074         _character = chars.get(index);
075         _validCharacters = chars;
076     }
077 
078     /**
079      * Create a new character gene from the given {@code character} and the
080      * given set of valid characters.
081      *
082      @param character the char this gene represents
083      @param validChars the set of valid characters.
084      @throws NullPointerException if one of the arguments is {@code null}.
085      */
086     private CharacterGene(final char character, final CharSeq validChars) {
087         _character = character;
088         _validCharacters = requireNonNull(validChars);
089     }
090 
091     @Override
092     public boolean isValid() {
093         return _validCharacters.contains(_character);
094     }
095 
096     @Deprecated
097     @Override
098     public Character getAllele() {
099         return _character;
100     }
101 
102     /**
103      * Return the {@code char} value of this character gene.
104      *
105      @return the {@code char} value.
106      */
107     public char charValue() {
108         return _character;
109     }
110 
111     /**
112      * Test, if the given character is valid.
113      *
114      @param character The character to test.
115      @return true if the character is valid, false otherwise.
116      */
117     public boolean isValidCharacter(final Character character) {
118         return _validCharacters.contains(character);
119     }
120 
121     /**
122      * Return a (unmodifiable) set of valid characters.
123      *
124      @return the {@link CharSeq} of valid characters.
125      */
126     public CharSeq validChars() {
127         return _validCharacters;
128     }
129 
130     /**
131      * Return a (unmodifiable) set of valid characters.
132      *
133      @return the {@link CharSeq} of valid characters.
134      @deprecated Use {@link #validChars()} instead
135      */
136     @Deprecated
137     public CharSeq getValidCharacters() {
138         return _validCharacters;
139     }
140 
141     /**
142      @see java.lang.Character#compareTo(java.lang.Character)
143      @param that The other gene to compare.
144      @return the value 0 if the argument Character is equal to this Character;
145      *         a value less than 0 if this Character is numerically less than
146      *         the Character argument; and a value greater than 0 if this
147      *         Character is numerically greater than the Character argument
148      *         (unsigned comparison). Note that this is strictly a numerical
149      *         comparison; it is not local-dependent.
150      */
151     @Override
152     public int compareTo(final CharacterGene that) {
153         return Character.compare(_character, that._character);
154     }
155 
156     @Override
157     public int hashCode() {
158         return hash(_character, hash(_validCharacters));
159     }
160 
161     @Override
162     public boolean equals(final Object obj) {
163         return obj == this ||
164             obj instanceof CharacterGene &&
165             ((CharacterGene)obj)._character == _character &&
166             Objects.equals(((CharacterGene)obj)._validCharacters, _validCharacters);
167     }
168 
169     @Override
170     public String toString() {
171         return Character.toString(_character);
172     }
173 
174 
175     /* *************************************************************************
176      *  Factory methods
177      * ************************************************************************/
178 
179     @Override
180     public CharacterGene newInstance() {
181         return of(_validCharacters);
182     }
183 
184     /**
185      * Create a new character gene from the given character. If the character
186      * is not within the {@link #validChars()}, an invalid gene will be
187      * created.
188      *
189      @param character the character value of the created gene.
190      @return a new character gene.
191      @throws NullPointerException if the given {@code character} is
192      *         {@code null}.
193      */
194     @Override
195     public CharacterGene newInstance(final Character character) {
196         return of(character, _validCharacters);
197     }
198 
199 
200     /* *************************************************************************
201      *  Static object creation methods
202      * ************************************************************************/
203 
204     /**
205      * Create a new CharacterGene with a randomly chosen character from the
206      * set of valid characters.
207      *
208      @param validCharacters the valid characters for this gene.
209      @return a new valid, <em>random</em> gene,
210      @throws NullPointerException if the {@code validCharacters} are
211      *         {@code null}.
212      */
213     public static CharacterGene of(final CharSeq validCharacters) {
214         return new CharacterGene(
215             validCharacters,
216             RandomRegistry.random().nextInt(validCharacters.length())
217         );
218     }
219 
220     /**
221      * Create a new character gene from the given character. If the character
222      * is not within the {@link #DEFAULT_CHARACTERS}, an invalid gene will be
223      * created.
224      *
225      @param character the character value of the created gene.
226      @return a new character gene.
227      */
228     public static CharacterGene of(final char character) {
229         return new CharacterGene(character, DEFAULT_CHARACTERS);
230     }
231 
232     /**
233      * Create a new random character gene, chosen from the
234      {@link #DEFAULT_CHARACTERS}.
235      *
236      @return a new random character gene.
237      */
238     public static CharacterGene of() {
239         return new CharacterGene(
240             DEFAULT_CHARACTERS,
241             RandomRegistry.random().nextInt(DEFAULT_CHARACTERS.length())
242         );
243     }
244 
245     /**
246      * Create a new CharacterGene from the give character.
247      *
248      @param character The allele.
249      @param validCharacters the valid characters fo the new gene
250      @return a new {@code CharacterGene} with the given parameter
251      @throws NullPointerException if one of the arguments is {@code null}.
252      @throws IllegalArgumentException if the {@code validCharacters} are empty.
253      */
254     public static CharacterGene of(
255         final char character,
256         final CharSeq validCharacters
257     ) {
258         return new CharacterGene(character, validCharacters);
259     }
260 
261     static ISeq<CharacterGene> seq(
262         final CharSeq chars,
263         final IntRange lengthRange
264     ) {
265         final Random r = RandomRegistry.random();
266 
267         return MSeq.<CharacterGene>ofLength(Randoms.nextInt(lengthRange, r))
268             .fill(() -> new CharacterGene(chars, r.nextInt(chars.length())))
269             .toISeq();
270     }
271 
272 }