ProgramGene.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-4.3.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.prog;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 
025 import java.util.Random;
026 import java.util.function.Function;
027 
028 import io.jenetics.Gene;
029 import io.jenetics.util.ISeq;
030 import io.jenetics.util.RandomRegistry;
031 
032 import io.jenetics.ext.AbstractTreeGene;
033 
034 import io.jenetics.prog.op.Op;
035 import io.jenetics.prog.op.Program;
036 
037 /**
038  * This gene represents a program, build upon an AST of {@link Op} functions.
039  * Because of the tight coupling with the {@link ProgramChromosome}, a
040  * {@code ProgramGene} can't be created directly. This reduces the the possible
041  <em>error space</em>. Since the {@code ProgramGene} also is a {@code Tree},
042  * it can be easily used as result.
043  *
044  <pre>{@code
045  * final ProgramGene<Double> program = engine.stream()
046  *     .limit(300)
047  *     .collect(EvolutionResult.toBestGenotype())
048  *     .getGene();
049  *
050  * final double result = program.eval(3.4);
051  * }</pre>
052  *
053  @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
054  @version 3.9
055  @since 3.9
056  */
057 public final class ProgramGene<A>
058     extends AbstractTreeGene<Op<A>, ProgramGene<A>>
059     implements Gene<Op<A>, ProgramGene<A>>, Function<A[], A>
060 {
061 
062     private static final long serialVersionUID = 1L;
063 
064     private final ISeq<? extends Op<A>> _operations;
065     private final ISeq<? extends Op<A>> _terminals;
066 
067     ProgramGene(
068         final Op<A> op,
069         final int childOffset,
070         final ISeq<? extends Op<A>> operations,
071         final ISeq<? extends Op<A>> terminals
072     ) {
073         super(requireNonNull(get(op)), childOffset, op.arity());
074         _operations = requireNonNull(operations);
075         _terminals = requireNonNull(terminals);
076     }
077 
078     private static <A> Op<A> get(final Op<A> op) {
079         final Op<A> instance = op.get();
080         if (instance != op && instance.arity() != op.arity()) {
081             throw new IllegalArgumentException(format(
082                 "Original op and created op have different arity: %d != %d,",
083                 instance.arity(), op.arity()
084             ));
085         }
086         return instance;
087     }
088 
089     /**
090      * Evaluates this program gene (recursively) with the given variable values.
091      *
092      @see ProgramGene#eval(Object[])
093      @see ProgramChromosome#eval(Object[])
094      *
095      @param args the input variables
096      @return the evaluated value
097      @throws NullPointerException if the given variable array is {@code null}
098      */
099     @Override
100     public A apply(final A[] args) {
101         checkTreeState();
102         return Program.eval(this, args);
103     }
104 
105     /**
106      * Convenient method, which lets you apply the program function without
107      * explicitly create a wrapper array.
108      *
109      @see ProgramGene#apply(Object[])
110      @see ProgramChromosome#eval(Object[])
111      *
112      @param args the function arguments
113      @return the evaluated value
114      @throws NullPointerException if the given variable array is {@code null}
115      */
116     @SafeVarargs
117     public final A eval(final A... args) {
118         return apply(args);
119     }
120 
121     /**
122      * Return the allowed operations.
123      *
124      @return the allowed operations
125      */
126     public ISeq<? extends Op<A>> getOperations() {
127         return _operations;
128     }
129 
130     /**
131      * Return the allowed terminal operations.
132      *
133      @return the allowed terminal operations
134      */
135     public ISeq<? extends Op<A>> getTerminals() {
136         return _terminals;
137     }
138 
139     @Override
140     public ProgramGene<A> newInstance() {
141         final Random random = RandomRegistry.getRandom();
142 
143         Op<A> operation = getValue();
144         if (isLeaf()) {
145             operation = _terminals.get(random.nextInt(_terminals.length()));
146         else {
147             final ISeq<Op<A>> operations = _operations.stream()
148                 .filter(op -> op.arity() == getValue().arity())
149                 .map(op -> (Op<A>)op)
150                 .collect(ISeq.toISeq());
151 
152             if (operations.length() 1) {
153                 operation = operations.get(random.nextInt(operations.length()));
154             }
155         }
156 
157         return newInstance(operation);
158     }
159 
160     /**
161      * Create a new program gene with the given operation.
162      *
163      @param op the operation of the new program gene
164      @return a new program gene with the given operation
165      @throws NullPointerException if the given {@code op} is {@code null}
166      @throws IllegalArgumentException if the arity of the given operation is
167      *         different from the arity of current operation. This restriction
168      *         ensures that only valid program genes are created by this method.
169      */
170     @Override
171     public ProgramGene<A> newInstance(final Op<A> op) {
172         if (getValue().arity() != op.arity()) {
173             throw new IllegalArgumentException(format(
174                 "New operation must have same arity: %s[%d] != %s[%d]",
175                 getValue().name(), getValue().arity(), op.name(), op.arity()
176             ));
177         }
178         return new ProgramGene<>(op, childOffset(), _operations, _terminals);
179     }
180 
181     /**
182      * Return a new program gene with the given operation and the <em>local</em>
183      * tree structure.
184      *
185      @param op the new operation
186      @param childOffset the offset of the first node child within the
187      *        chromosome
188      @param childCount the number of children of the new tree gene
189      @return a new tree gene with the given parameters
190      @throws IllegalArgumentException  if the {@code childCount} is smaller
191      *         than zero
192      @throws IllegalArgumentException if the operation arity is different from
193      *         the {@code childCount}.
194      @throws NullPointerException if the given {@code op} is {@code null}
195      */
196     @Override
197     public ProgramGene<A> newInstance(
198         final Op<A> op,
199         final int childOffset,
200         final int childCount
201     ) {
202         if (op.arity() != childCount) {
203             throw new IllegalArgumentException(format(
204                 "Operation arity and child count are different: %d, != %d",
205                 op.arity(), childCount
206             ));
207         }
208 
209         return new ProgramGene<>(op, childOffset, _operations, _terminals);
210     }
211 
212 }