001 /*
002 * Java Genetic Algorithm Library (jenetics-6.0.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.prog.op;
021
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 import static io.jenetics.internal.util.Hashes.hash;
025
026 import java.io.Serializable;
027 import java.lang.reflect.Array;
028 import java.util.Objects;
029 import java.util.Random;
030
031 import io.jenetics.util.ISeq;
032 import io.jenetics.util.RandomRegistry;
033
034 import io.jenetics.ext.util.FlatTree;
035 import io.jenetics.ext.util.Tree;
036 import io.jenetics.ext.util.TreeNode;
037
038 /**
039 * This class composes a given operation tree to a new operation. which can
040 * serve as a sub <em>program</em> in an other operation tree.
041 *
042 * @param <T> the argument type of the operation
043 *
044 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
045 * @version 4.1
046 * @since 3.9
047 */
048 public class Program<T> implements Op<T>, Serializable {
049
050 private static final long serialVersionUID = 1L;
051
052 private final String _name;
053 private final Tree<? extends Op<T>, ?> _tree;
054
055 /**
056 * Create a new program with the given name and the given operation tree.
057 * The arity of the program is calculated from the given operation tree and
058 * set to the maximal arity of the operations of the tree.
059 *
060 * @param name the program name
061 * @param tree the operation tree
062 * @throws NullPointerException if one of the given arguments is {@code null}
063 * @throws IllegalArgumentException if the given operation tree is invalid,
064 * which means there is at least one node where the operation arity
065 * and the node child count differ.
066 */
067 public Program(final String name, final Tree<? extends Op<T>, ?> tree) {
068 _name = requireNonNull(name);
069 _tree = requireNonNull(tree);
070 check(tree);
071 }
072
073 @Override
074 public String name() {
075 return _name;
076 }
077
078 @Override
079 public int arity() {
080 return 0;
081 }
082
083 /**
084 * Return the underlying expression tree.
085 *
086 * @since 4.1
087 *
088 * @return the underlying expression tree
089 */
090 public Tree<Op<T>, ?> tree() {
091 return TreeNode.ofTree(_tree);
092 }
093
094 @Override
095 public T apply(final T[] args) {
096 if (args.length < arity()) {
097 throw new IllegalArgumentException(format(
098 "Arguments length is smaller than program arity: %d < %d",
099 args.length, arity()
100 ));
101 }
102
103 return eval(_tree, args);
104 }
105
106 /**
107 * Convenient method, which lets you apply the program function without
108 * explicitly create a wrapper array.
109 *
110 * @see #apply(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 * @throws IllegalArgumentException if the length of the arguments array
116 * is smaller than the program arity
117 */
118 @SafeVarargs
119 public final T eval(final T... args) {
120 return apply(args);
121 }
122
123 @Override
124 public int hashCode() {
125 return hash(_name, hash(_tree));
126 }
127
128 @Override
129 public boolean equals(final Object obj) {
130 return obj == this ||
131 obj instanceof Program &&
132 Objects.equals(((Program)obj)._name, _name) &&
133 Objects.equals(((Program)obj)._tree, _tree);
134 }
135
136 @Override
137 public String toString() {
138 return _name;
139 }
140
141
142 /* *************************************************************************
143 * Static helper methods.
144 * ************************************************************************/
145
146 /**
147 * Evaluates the given operation tree with the given variables.
148 *
149 * @param <T> the argument type
150 * @param tree the operation tree
151 * @param variables the input variables
152 * @return the result of the operation tree evaluation
153 * @throws NullPointerException if one of the arguments is {@code null}
154 * @throws IllegalArgumentException if the length of the variable array
155 * is smaller than the program arity
156 */
157 @SafeVarargs
158 public static <T> T eval(
159 final Tree<? extends Op<T>, ?> tree,
160 final T... variables
161 ) {
162 requireNonNull(tree);
163 requireNonNull(variables);
164
165 final Op<T> op = tree.value();
166 return op.isTerminal()
167 ? evalOp(op, variables)
168 : evalOp(op, evalChildren(tree, variables));
169 }
170
171 @SafeVarargs
172 private static <T> T evalOp(final Op<T> op, final T... variables) {
173 if (op instanceof Var && ((Var)op).index() >= variables.length) {
174 throw new IllegalArgumentException(format(
175 "No value for variable '%s' given.", op
176 ));
177 }
178
179 return op.apply(variables);
180 }
181
182 @SafeVarargs
183 private static <T> T[] evalChildren(
184 final Tree<? extends Op<T>, ?> node,
185 final T... variables
186 ) {
187 final T[] result = newArray(variables.getClass(), node.childCount());
188 for (int i = 0; i < node.childCount(); ++i) {
189 result[i] = eval(node.childAt(i), variables);
190 }
191 return result;
192 }
193
194 @SuppressWarnings("unchecked")
195 private static <T> T[] newArray(final Class<?> arrayType, final int size) {
196 return (T[])Array.newInstance(arrayType.getComponentType(), size);
197 }
198
199 /**
200 * Validates the given program tree.
201 *
202 * @param program the program to validate
203 * @throws NullPointerException if the given {@code program} is {@code null}
204 * @throws IllegalArgumentException if the given operation tree is invalid,
205 * which means there is at least one node where the operation arity
206 * and the node child count differ.
207 */
208 public static void check(final Tree<? extends Op<?>, ?> program) {
209 program.forEach(Program::checkArity);
210 }
211
212 private static void checkArity(final Tree<? extends Op<?>, ?> node) {
213 if (node.value() != null &&
214 node.value().arity() != node.childCount())
215 {
216 throw new IllegalArgumentException(format(
217 "Op arity != child count: %d != %d",
218 node.value().arity(), node.childCount()
219 ));
220 }
221 }
222
223 /**
224 * Create a new, random program from the given (non) terminal operations
225 * with the desired depth. The created program tree is a <em>full</em> tree.
226 *
227 * @since 4.1
228 *
229 * @param name the program name
230 * @param depth the desired depth of the program tree
231 * @param operations the list of <em>non</em>-terminal operations
232 * @param terminals the list of terminal operations
233 * @param <A> the operational type
234 * @return a new program
235 * @throws NullPointerException if one of the given operations is
236 * {@code null}
237 * @throws IllegalArgumentException if the given tree depth is smaller than
238 * zero
239 */
240 public static <A> Program<A> of(
241 final String name,
242 final int depth,
243 final ISeq<? extends Op<A>> operations,
244 final ISeq<? extends Op<A>> terminals
245 ) {
246 return new Program<>(name, of(depth, operations, terminals));
247 }
248
249 /**
250 * Create a new, random program from the given (non) terminal operations
251 * with the desired depth. The created program tree is a <em>full</em> tree.
252 *
253 * @since 4.1
254 *
255 * @param name the program name
256 * @param depth the desired depth of the program tree
257 * @param operations the list of <em>non</em>-terminal operations
258 * @param terminals the list of terminal operations
259 * @param random the random engine used for creating the program
260 * @param <A> the operational type
261 * @return a new program
262 * @throws NullPointerException if one of the given operations is
263 * {@code null}
264 * @throws IllegalArgumentException if the given tree depth is smaller than
265 * zero
266 */
267 public static <A> Program<A> of(
268 final String name,
269 final int depth,
270 final ISeq<? extends Op<A>> operations,
271 final ISeq<? extends Op<A>> terminals,
272 final Random random
273 ) {
274 return new Program<>(name, of(depth, operations, terminals, random));
275 }
276
277 /**
278 * Create a new, random program tree from the given (non) terminal
279 * operations with the desired depth. The created program tree is a
280 * <em>full</em> tree.
281 *
282 * @param depth the desired depth of the program tree
283 * @param operations the list of <em>non</em>-terminal operations
284 * @param terminals the list of terminal operations
285 * @param <A> the operational type
286 * @return a new program tree
287 * @throws NullPointerException if one of the given operations is
288 * {@code null}
289 * @throws IllegalArgumentException if the given tree depth is smaller than
290 * zero
291 */
292 public static <A> TreeNode<Op<A>> of(
293 final int depth,
294 final ISeq<? extends Op<A>> operations,
295 final ISeq<? extends Op<A>> terminals
296 ) {
297 return of(depth, operations, terminals, RandomRegistry.random());
298 }
299
300 /**
301 * Create a new, random program tree from the given (non) terminal
302 * operations with the desired depth. The created program tree is a
303 * <em>full</em> tree.
304 *
305 * @since 4.1
306 *
307 * @param depth the desired depth of the program tree
308 * @param operations the list of <em>non</em>-terminal operations
309 * @param terminals the list of terminal operations
310 * @param random the random engine used for creating the program
311 * @param <A> the operational type
312 * @return a new program tree
313 * @throws NullPointerException if one of the given operations is
314 * {@code null}
315 * @throws IllegalArgumentException if the given tree depth is smaller than
316 * zero
317 */
318 public static <A> TreeNode<Op<A>> of(
319 final int depth,
320 final ISeq<? extends Op<A>> operations,
321 final ISeq<? extends Op<A>> terminals,
322 final Random random
323 ) {
324 if (depth < 0) {
325 throw new IllegalArgumentException(
326 "Tree depth is smaller than zero: " + depth
327 );
328 }
329 if (!operations.forAll(o -> !o.isTerminal())) {
330 throw new IllegalArgumentException(
331 "Operation list contains terminal op."
332 );
333 }
334 if (!terminals.forAll(Op::isTerminal)) {
335 throw new IllegalArgumentException(
336 "Terminal list contains non-terminal op."
337 );
338 }
339
340 final TreeNode<Op<A>> root = TreeNode.of();
341 fill(depth, root, operations, terminals, random);
342 return root;
343 }
344
345 private static <A> void fill(
346 final int level,
347 final TreeNode<Op<A>> tree,
348 final ISeq<? extends Op<A>> operations,
349 final ISeq<? extends Op<A>> terminals,
350 final Random random
351 ) {
352 final Op<A> op = level == 0
353 ? terminals.get(random.nextInt(terminals.size()))
354 : operations.get(random.nextInt(operations.size()));
355
356 tree.value(op);
357
358 if (level > 1) {
359 for (int i = 0; i < op.arity(); ++i) {
360 final TreeNode<Op<A>> node = TreeNode.of();
361 fill(level - 1, node, operations, terminals, random);
362 tree.attach(node);
363 }
364 } else {
365 for (int i = 0; i < op.arity(); ++i) {
366 final Op<A> term = terminals.get(random.nextInt(terminals.size()));
367 tree.attach(TreeNode.of(term));
368 }
369 }
370 }
371
372 /**
373 * Creates a valid program tree from the given flattened sequence of
374 * op nodes. The given {@code operations} and {@code termination} nodes are
375 * used for <em>repairing</em> the program tree, if necessary.
376 *
377 * @param nodes the flattened, possible corrupt, program tree
378 * @param terminals the usable non-terminal operation nodes to use for
379 * reparation
380 * @param <A> the operation argument type
381 * @return a new valid program tree build from the flattened program tree
382 * @throws NullPointerException if one of the arguments is {@code null}
383 * @throws IllegalArgumentException if the {@code nodes} sequence is empty
384 */
385 public static <A> TreeNode<Op<A>> toTree(
386 final ISeq<? extends FlatTree<? extends Op<A>, ?>> nodes,
387 final ISeq<? extends Op<A>> terminals
388 ) {
389 if (nodes.isEmpty()) {
390 throw new IllegalArgumentException("Tree nodes must not be empty.");
391 }
392
393 final Op<A> op = requireNonNull(nodes.get(0).value());
394 final TreeNode<Op<A>> tree = TreeNode.of(op);
395 return toTree(
396 tree,
397 0,
398 nodes,
399 offsets(nodes),
400 terminals,
401 RandomRegistry.random()
402 );
403 }
404
405 private static <A> TreeNode<Op<A>> toTree(
406 final TreeNode<Op<A>> root,
407 final int index,
408 final ISeq<? extends FlatTree<? extends Op<A>, ?>> nodes,
409 final int[] offsets,
410 final ISeq<? extends Op<A>> terminals,
411 final Random random
412 ) {
413 if (index < nodes.size()) {
414 final FlatTree<? extends Op<A>, ?> node = nodes.get(index);
415 final Op<A> op = node.value();
416
417 for (int i = 0; i < op.arity(); ++i) {
418 assert offsets[index] != -1;
419
420 final TreeNode<Op<A>> treeNode = TreeNode.of();
421 if (offsets[index] + i < nodes.size()) {
422 treeNode.value(nodes.get(offsets[index] + i).value());
423 } else {
424 treeNode.value(terminals.get(random.nextInt(terminals.size())));
425 }
426
427 toTree(
428 treeNode,
429 offsets[index] + i,
430 nodes,
431 offsets,
432 terminals,
433 random
434 );
435 root.attach(treeNode);
436 }
437 }
438
439 return root;
440 }
441
442 /**
443 * Create the offset array for the given nodes. The offsets are calculated
444 * using the arity of the stored operations.
445 *
446 * @param nodes the flattened tree nodes
447 * @return the offset array for the given nodes
448 */
449 static int[]
450 offsets(final ISeq<? extends FlatTree<? extends Op<?>, ?>> nodes) {
451 final int[] offsets = new int[nodes.size()];
452
453 int offset = 1;
454 for (int i = 0; i < offsets.length; ++i) {
455 final Op<?> op = nodes.get(i).value();
456
457 offsets[i] = op.isTerminal() ? -1 : offset;
458 offset += op.arity();
459 }
460
461 return offsets;
462 }
463
464 }
|