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