001 /*
002 * Java Genetic Algorithm Library (jenetics-5.1.0).
003 * Copyright (c) 2007-2019 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 int _arity;
054 private final Tree<? extends Op<T>, ?> _tree;
055
056 /**
057 * Create a new program with the given name and the given operation tree.
058 * The arity of the program is calculated from the given operation tree and
059 * set to the maximal arity of the operations of the tree.
060 *
061 * @param name the program name
062 * @param tree the operation tree
063 * @throws NullPointerException if one of the given arguments is {@code null}
064 * @throws IllegalArgumentException if the given operation tree is invalid,
065 * which means there is at least one node where the operation arity
066 * and the node child count differ.
067 */
068 public Program(final String name, final Tree<? extends Op<T>, ?> tree) {
069 _name = requireNonNull(name);
070 _tree = requireNonNull(tree);
071 check(tree);
072 _arity = tree.breadthFirstStream()
073 .filter(t -> t.getValue() instanceof Var)
074 .mapToInt(v -> ((Var)v.getValue()).index() + 1)
075 .max()
076 .orElse(0);
077 }
078
079 @Override
080 public String name() {
081 return _name;
082 }
083
084 @Override
085 public int arity() {
086 return _arity;
087 }
088
089 /**
090 * Return the underlying expression tree.
091 *
092 * @since 4.1
093 *
094 * @return the underlying expression tree
095 */
096 public Tree<? extends Op<T>, ?> tree() {
097 return TreeNode.ofTree(_tree);
098 }
099
100 @Override
101 public T apply(final T[] args) {
102 if (args.length < arity()) {
103 throw new IllegalArgumentException(format(
104 "Arguments length is smaller than program arity: %d < %d",
105 args.length, arity()
106 ));
107 }
108
109 return eval(_tree, args);
110 }
111
112 /**
113 * Convenient method, which lets you apply the program function without
114 * explicitly create a wrapper array.
115 *
116 * @see #apply(Object[])
117 *
118 * @param args the function arguments
119 * @return the evaluated value
120 * @throws NullPointerException if the given variable array is {@code null}
121 * @throws IllegalArgumentException if the length of the arguments array
122 * is smaller than the program arity
123 */
124 @SafeVarargs
125 public final T eval(final T... args) {
126 return apply(args);
127 }
128
129 @Override
130 public int hashCode() {
131 return hash(_name, hash(_arity, hash(_tree)));
132 }
133
134 @Override
135 public boolean equals(final Object obj) {
136 return obj == this ||
137 obj instanceof Program &&
138 Objects.equals(((Program)obj)._name, _name) &&
139 ((Program)obj)._arity == _arity &&
140 Objects.equals(((Program)obj)._tree, _tree);
141 }
142
143 @Override
144 public String toString() {
145 return _name;
146 }
147
148
149 /* *************************************************************************
150 * Static helper methods.
151 * ************************************************************************/
152
153 /**
154 * Evaluates the given operation tree with the given variables.
155 *
156 * @param <T> the argument type
157 * @param tree the operation tree
158 * @param variables the input variables
159 * @return the result of the operation tree evaluation
160 * @throws NullPointerException if one of the arguments is {@code null}
161 * @throws IllegalArgumentException if the length of the variable array
162 * is smaller than the program arity
163 */
164 @SafeVarargs
165 public static <T> T eval(
166 final Tree<? extends Op<T>, ?> tree,
167 final T... variables
168 ) {
169 requireNonNull(tree);
170 requireNonNull(variables);
171
172 final Op<T> op = tree.getValue();
173 return op.isTerminal()
174 ? eval(op, variables)
175 : eval(op,
176 tree.childStream()
177 .map(child -> eval(child, variables))
178 .toArray(size -> newArray(variables.getClass(), size))
179 );
180 }
181
182 @SafeVarargs
183 private static <T> T eval(final Op<T> op, final T... variables) {
184 if (op instanceof Var && ((Var)op).index() >= variables.length) {
185 throw new IllegalArgumentException(format(
186 "No value for variable '%s' given.", op
187 ));
188 }
189
190 return op.apply(variables);
191 }
192
193 @SuppressWarnings("unchecked")
194 private static <T> T[] newArray(final Class<?> arrayType, final int size) {
195 return (T[])Array.newInstance(arrayType.getComponentType(), size);
196 }
197
198 /**
199 * Validates the given program tree.
200 *
201 * @param program the program to validate
202 * @throws NullPointerException if the given {@code program} is {@code null}
203 * @throws IllegalArgumentException if the given operation tree is invalid,
204 * which means there is at least one node where the operation arity
205 * and the node child count differ.
206 */
207 public static void check(final Tree<? extends Op<?>, ?> program) {
208 requireNonNull(program);
209 program.forEach(Program::checkArity);
210 }
211
212 private static void checkArity(final Tree<? extends Op<?>, ?> node) {
213 if (node.getValue() != null &&
214 node.getValue().arity() != node.childCount())
215 {
216 throw new IllegalArgumentException(format(
217 "Op arity != child count: %d != %d",
218 node.getValue().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.getRandom());
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(o -> o.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.setValue(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).getValue());
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.getRandom()
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.getValue();
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.setValue(nodes.get(offsets[index] + i).getValue());
423 } else {
424 treeNode.setValue(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).getValue();
456
457 offsets[i] = op.isTerminal() ? -1 : offset;
458 offset += op.arity();
459 }
460
461 return offsets;
462 }
463
464 }
|