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