1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.optim;
18
19 import org.apache.commons.math4.legacy.exception.TooManyEvaluationsException;
20 import org.apache.commons.math4.legacy.exception.TooManyIterationsException;
21 import org.apache.commons.math4.legacy.core.IntegerSequence;
22
23
24
25
26
27
28
29
30
31 public abstract class AbstractOptimizationProblem<PAIR>
32 implements OptimizationProblem<PAIR> {
33
34
35 private static final MaxEvalCallback MAX_EVAL_CALLBACK = new MaxEvalCallback();
36
37 private static final MaxIterCallback MAX_ITER_CALLBACK = new MaxIterCallback();
38
39
40 private final int maxEvaluations;
41
42 private final int maxIterations;
43
44 private final ConvergenceChecker<PAIR> checker;
45
46
47
48
49
50
51
52
53 protected AbstractOptimizationProblem(final int maxEvaluations,
54 final int maxIterations,
55 final ConvergenceChecker<PAIR> checker) {
56 this.maxEvaluations = maxEvaluations;
57 this.maxIterations = maxIterations;
58 this.checker = checker;
59 }
60
61
62 @Override
63 public IntegerSequence.Incrementor getEvaluationCounter() {
64 return IntegerSequence.Incrementor.create()
65 .withMaximalCount(maxEvaluations)
66 .withCallback(MAX_EVAL_CALLBACK);
67 }
68
69
70 @Override
71 public IntegerSequence.Incrementor getIterationCounter() {
72 return IntegerSequence.Incrementor.create()
73 .withMaximalCount(maxIterations)
74 .withCallback(MAX_ITER_CALLBACK);
75 }
76
77
78 @Override
79 public ConvergenceChecker<PAIR> getConvergenceChecker() {
80 return checker;
81 }
82
83
84 private static final class MaxEvalCallback
85 implements IntegerSequence.Incrementor.MaxCountExceededCallback {
86
87
88
89
90
91 @Override
92 public void trigger(int max) {
93 throw new TooManyEvaluationsException(max);
94 }
95 }
96
97
98 private static final class MaxIterCallback
99 implements IntegerSequence.Incrementor.MaxCountExceededCallback {
100
101
102
103
104
105 @Override
106 public void trigger(int max) {
107 throw new TooManyIterationsException(max);
108 }
109 }
110 }