1
2
3
4
5
6
7
8
9
10 package edu.uci.ics.jung.algorithms.util;
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 public abstract class IterativeProcess implements IterativeContext {
35
36
37
38 private int iterations;
39
40
41
42 private int maximumIterations = 50;
43
44
45
46 private double desiredPrecision = Double.MIN_VALUE;
47
48
49
50 private double precision;
51
52
53
54
55
56 public IterativeProcess() {
57 }
58
59
60
61
62
63
64 public void evaluate() {
65 iterations = 0;
66 initializeIterations();
67 while (iterations++ < maximumIterations) {
68 step();
69 precision = getPrecision();
70 if (hasConverged())
71 break;
72 }
73 finalizeIterations();
74 }
75
76
77
78
79 abstract public void step();
80
81
82
83
84
85 protected void finalizeIterations() {
86 }
87
88
89
90
91 public double getDesiredPrecision() {
92 return desiredPrecision;
93 }
94
95
96
97
98 public int getIterations() {
99 return iterations;
100 }
101
102
103
104
105 public int getMaximumIterations() {
106 return maximumIterations;
107 }
108
109
110
111
112 public double getPrecision() {
113 return precision;
114 }
115
116
117
118
119 public void setPrecision(double precision) {
120 this.precision = precision;
121 }
122
123
124
125
126
127
128 public boolean hasConverged() {
129 return precision < desiredPrecision;
130 }
131
132 public boolean done() {
133 return hasConverged();
134 }
135
136
137
138
139 protected void initializeIterations() {
140 }
141
142
143
144
145 public void reset() {
146 }
147
148
149
150
151
152
153 public double relativePrecision(double epsilon, double x) {
154 return x > desiredPrecision ? epsilon / x: epsilon;
155 }
156
157
158
159
160 public void setDesiredPrecision(double prec) throws IllegalArgumentException {
161 if (prec <= 0)
162 throw new IllegalArgumentException("Non-positive precision: " + prec);
163 desiredPrecision = prec;
164 }
165
166
167
168
169 public void setMaximumIterations(int maxIter) throws IllegalArgumentException {
170 if (maxIter < 1)
171 throw new IllegalArgumentException("Non-positive maximum iteration: " + maxIter);
172 maximumIterations = maxIter;
173 }
174 }