CompositeAlterer.java
001 /*
002  * Java Genetic Algorithm Library (jenetics-2.0.2).
003  * Copyright (c) 2007-2014 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;
021 
022 import static java.lang.String.format;
023 import static java.util.Objects.requireNonNull;
024 import static org.jenetics.internal.util.object.NonNull;
025 import static org.jenetics.internal.util.object.eq;
026 
027 import java.util.Deque;
028 import java.util.LinkedList;
029 import java.util.List;
030 import java.util.concurrent.atomic.AtomicInteger;
031 
032 import org.jenetics.internal.util.HashBuilder;
033 
034 import org.jenetics.util.Array;
035 import org.jenetics.util.Function;
036 import org.jenetics.util.ISeq;
037 import org.jenetics.util.Seq;
038 
039 /**
040  * Combines several alterers to one.
041  *
042  @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
043  @since 1.0
044  @version 2.0 &mdash; <em>$Date: 2014-03-30 $</em>
045  */
046 public final class CompositeAlterer<G extends Gene<?, G>>
047     extends AbstractAlterer<G>
048 {
049 
050     private final ISeq<Alterer<G>> _alterers;
051 
052     /**
053      * Combine the given alterers.
054      *
055      @param alterers the alterers to combine.
056      @throws NullPointerException if one of the alterers is {@code null}.
057      */
058     public CompositeAlterer(final Seq<Alterer<G>> alterers) {
059         super(1.0);
060 
061         alterers.forAll(NonNull("Alterer"));
062         _alterers = normalize(alterers).toISeq();
063     }
064 
065     private static <G extends Gene<?, G>>
066     Array<Alterer<G>> normalize(final Seq<Alterer<G>> alterers) {
067         final Deque<Alterer<G>> stack = new LinkedList<>(alterers.asList());
068 
069         final List<Alterer<G>> normalized = new LinkedList<>();
070 
071         while (!stack.isEmpty()) {
072             final Alterer<G> alterer = stack.pollFirst();
073 
074             if (alterer instanceof CompositeAlterer<?>) {
075                 final CompositeAlterer<G> calterer = (CompositeAlterer<G>)alterer;
076 
077                 for (int i = calterer.getAlterers().length(); --i >= 0;) {
078                     stack.addFirst(calterer.getAlterers().get(i));
079                 }
080             else {
081                 normalized.add(alterer);
082             }
083         }
084 
085         return Array.of(normalized);
086     }
087 
088     @Override
089     public <C extends Comparable<? super C>>
090     int alter(final Population<G, C> population, final int generation) {
091         final AtomicInteger alterations = new AtomicInteger(0);
092 
093         _alterers.forEach(new Function<Alterer<G>, Void>() {
094             @Override public Void apply(final Alterer<G> alterer) {
095                 alterations.addAndGet(alterer.alter(population, generation));
096                 return null;
097             }
098         });
099 
100         return alterations.get();
101     }
102 
103     /**
104      * Create a new CompositeAlterer with the given alterer appended.
105      *
106      @param alterer the alterer to append.
107      @return a new CompositeAlterer.
108      @throws NullPointerException if the given alterer is {@code null}.
109      */
110     public CompositeAlterer<G> append(final Alterer<G> alterer) {
111         return CompositeAlterer.of(this, requireNonNull(alterer, "Alterer"));
112     }
113 
114     /**
115      * Return the alterers this alterer consists of. The returned array is sealed
116      * and cannot be changed.
117      *
118      @return the alterers this alterer consists of.
119      */
120     public ISeq<Alterer<G>> getAlterers() {
121         return _alterers;
122     }
123 
124     @Override
125     public int hashCode() {
126         return HashBuilder.of(getClass()).and(_alterers).value();
127     }
128 
129     @Override
130     public boolean equals(final Object obj) {
131         if (obj == this) {
132             return true;
133         }
134         if (obj == null || obj.getClass() != getClass()) {
135             return false;
136         }
137 
138         final CompositeAlterer<?> alterer = (CompositeAlterer<?>)obj;
139         return eq(_alterers, alterer._alterers);
140     }
141 
142     @Override
143     public String toString() {
144         return format("%s[%s]", getClass().getSimpleName(), _alterers);
145     }
146 
147     /**
148      * Combine the given alterers.
149      *
150      @param <G> the gene type
151      @param alterers the alterers to combine.
152      @return a new alterer which consists of the given one
153      @throws NullPointerException if one of the alterers is {@code null}.
154      */
155     @SafeVarargs
156     public static <G extends Gene<?, G>>
157     CompositeAlterer<G> of(final Alterer<G>... alterers) {
158         return new CompositeAlterer<>(Array.of(alterers));
159     }
160 
161     /**
162      * Joins the given alterer and returns a new CompositeAlterer object. If one
163      * of the given alterers is a CompositeAlterer the sub alterers of it are
164      * unpacked and appended to the newly created CompositeAlterer.
165      *
166      @param <T> the gene type of the alterers.
167      @param a1 the first alterer.
168      @param a2 the second alterer.
169      @return a new CompositeAlterer object.
170      @throws NullPointerException if one of the given alterer is {@code null}.
171      */
172     public static <T extends Gene<?, T>> CompositeAlterer<T> join(
173         final Alterer<T> a1,
174         final Alterer<T> a2
175     ) {
176         return CompositeAlterer.of(a1, a2);
177     }
178 }