SteadyPopulationLimit.java
01 /*
02  * Java Genetic Algorithm Library (jenetics-3.5.0).
03  * Copyright (c) 2007-2016 Franz Wilhelmstötter
04  *
05  * Licensed under the Apache License, Version 2.0 (the "License");
06  * you may not use this file except in compliance with the License.
07  * You may obtain a copy of the License at
08  *
09  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Author:
18  *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19  */
20 package org.jenetics.engine;
21 
22 import static org.jenetics.stat.DoubleMoments.toDoubleMoments;
23 
24 import java.util.function.Predicate;
25 
26 import org.jenetics.Optimize;
27 import org.jenetics.stat.DoubleMoments;
28 
29 /**
30  * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
31  * @since 3.0
32  * @version 3.0
33  */
34 final class SteadyPopulationLimit<
35     N extends Number & Comparable<? super N>
36 >
37     implements Predicate<EvolutionResult<?, N>>
38 {
39     private final int _generations;
40     private int _stableGenerations = 0;
41     private N _fitness;
42 
43     private SteadyPopulationLimit(final int generations) {
44         _generations = generations;
45     }
46 
47     @Override
48     public boolean test(final EvolutionResult<?, N> result) {
49         final DoubleMoments moments = result.getPopulation().stream()
50             .collect(toDoubleMoments(pt -> pt.getFitness().doubleValue()));
51 
52         boolean proceed = true;
53 
54         if (_fitness == null) {
55             _fitness = result.getBestFitness();
56             _stableGenerations = 1;
57         } else {
58             final Optimize opt = result.getOptimize();
59             if (opt.compare(_fitness, result.getBestFitness()) >= 0) {
60                 proceed = ++_stableGenerations <= _generations;
61             } else {
62                 _fitness = result.getBestFitness();
63                 _stableGenerations = 1;
64             }
65         }
66 
67         return proceed;
68     }
69 }