ProgramGene.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.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 final ISeq<? extends Op<A>> _operations;
063     private final ISeq<? extends Op<A>> _terminals;
064 
065     ProgramGene(
066         final Op<A> op,
067         final int childOffset,
068         final ISeq<? extends Op<A>> operations,
069         final ISeq<? extends Op<A>> terminals
070     ) {
071         super(requireNonNull(get(op)), childOffset, op.arity());
072         _operations = requireNonNull(operations);
073         _terminals = requireNonNull(terminals);
074     }
075 
076     private static <A> Op<A> get(final Op<A> op) {
077         final Op<A> instance = op.get();
078         if (instance != op && instance.arity() != op.arity()) {
079             throw new IllegalArgumentException(format(
080                 "Original op and created op have different arity: %d != %d,",
081                 instance.arity(), op.arity()
082             ));
083         }
084         return instance;
085     }
086 
087     /**
088      * Evaluates this program gene (recursively) with the given variable values.
089      *
090      @see ProgramGene#eval(Object[])
091      @see ProgramChromosome#eval(Object[])
092      *
093      @param args the input variables
094      @return the evaluated value
095      @throws NullPointerException if the given variable array is {@code null}
096      */
097     @Override
098     public A apply(final A[] args) {
099         checkTreeState();
100         return Program.eval(this, args);
101     }
102 
103     /**
104      * Convenient method, which lets you apply the program function without
105      * explicitly create a wrapper array.
106      *
107      @see ProgramGene#apply(Object[])
108      @see ProgramChromosome#eval(Object[])
109      *
110      @param args the function arguments
111      @return the evaluated value
112      @throws NullPointerException if the given variable array is {@code null}
113      */
114     @SafeVarargs
115     public final A eval(final A... args) {
116         return apply(args);
117     }
118 
119     /**
120      * Return the allowed operations.
121      *
122      @return the allowed operations
123      */
124     public ISeq<? extends Op<A>> getOperations() {
125         return _operations;
126     }
127 
128     /**
129      * Return the allowed terminal operations.
130      *
131      @return the allowed terminal operations
132      */
133     public ISeq<? extends Op<A>> getTerminals() {
134         return _terminals;
135     }
136 
137     @Override
138     public ProgramGene<A> newInstance() {
139         final Random random = RandomRegistry.getRandom();
140 
141         Op<A> operation = getValue();
142         if (isLeaf()) {
143             operation = _terminals.get(random.nextInt(_terminals.length()));
144         else {
145             final ISeq<Op<A>> operations = _operations.stream()
146                 .filter(op -> op.arity() == getValue().arity())
147                 .map(op -> (Op<A>)op)
148                 .collect(ISeq.toISeq());
149 
150             if (operations.length() 1) {
151                 operation = operations.get(random.nextInt(operations.length()));
152             }
153         }
154 
155         return newInstance(operation);
156     }
157 
158     /**
159      * Create a new program gene with the given operation.
160      *
161      @param op the operation of the new program gene
162      @return a new program gene with the given operation
163      @throws NullPointerException if the given {@code op} is {@code null}
164      @throws IllegalArgumentException if the arity of the given operation is
165      *         different from the arity of current operation. This restriction
166      *         ensures that only valid program genes are created by this method.
167      */
168     @Override
169     public ProgramGene<A> newInstance(final Op<A> op) {
170         if (getValue().arity() != op.arity()) {
171             throw new IllegalArgumentException(format(
172                 "New operation must have same arity: %s[%d] != %s[%d]",
173                 getValue().name(), getValue().arity(), op.name(), op.arity()
174             ));
175         }
176         return new ProgramGene<>(op, childOffset(), _operations, _terminals);
177     }
178 
179     /**
180      * Return a new program gene with the given operation and the <em>local</em>
181      * tree structure.
182      *
183      @param op the new operation
184      @param childOffset the offset of the first node child within the
185      *        chromosome
186      @param childCount the number of children of the new tree gene
187      @return a new tree gene with the given parameters
188      @throws IllegalArgumentException  if the {@code childCount} is smaller
189      *         than zero
190      @throws IllegalArgumentException if the operation arity is different from
191      *         the {@code childCount}.
192      @throws NullPointerException if the given {@code op} is {@code null}
193      */
194     @Override
195     public ProgramGene<A> newInstance(
196         final Op<A> op,
197         final int childOffset,
198         final int childCount
199     ) {
200         if (op.arity() != childCount) {
201             throw new IllegalArgumentException(format(
202                 "Operation arity and child count are different: %d, != %d",
203                 op.arity(), childCount
204             ));
205         }
206 
207         return new ProgramGene<>(op, childOffset, _operations, _terminals);
208     }
209 
210 }