-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSolver.java
More file actions
519 lines (455 loc) · 17 KB
/
Copy pathSolver.java
File metadata and controls
519 lines (455 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package arcade.core.util;
import java.util.ArrayList;
import java.util.logging.Logger;
import arcade.core.util.Matrix.Value;
import static arcade.core.util.Matrix.*;
/**
* Static utility class implementing various numerical solvers.
*
* <p>Implemented solvers include:
*
* <ul>
* <li><em>forward Euler</em>: first-order method for ODEs
* <li><em>classic Runge–Kutta (RK4)</em>: fourth-order method for ODEs
* <li><em>Cash–Karp</em>: adaptive step size method for ODEs
* <li><em>successive over-relaxation (SOR)</em>: variant of the Gauss–Seidel method for solving a
* linear system of equations
* </ul>
*/
public class Solver {
/** Logger for {@code Solver}. */
private static final Logger LOGGER = Logger.getLogger(Solver.class.getName());
/** Error tolerance for Cash-Karp. */
private static final double ERROR = 1E-5;
/** Epsilon value for Cash-Karp. */
private static final double EPSILON = 1E-10;
/** Maximum number of steps for Cash-Karp. */
private static final int MAX_STEPS = 100;
/** Safety value for Cash-Karp. */
private static final double SAFETY = 0.9;
/** Relaxation factor for SOR. */
private static final double OMEGA = 1.4;
/** Maximum number of iterations. */
private static final int MAX_ITERS = 10000;
/** Error tolerance for SOR. */
private static final double TOLERANCE = 1E-8;
/** Convergence delta for bisection method. */
private static final double DELTA = 1E-5;
/** Matrix size threshold for dense representation. */
private static final int MATRIX_THRESHOLD = 100;
/** Defines ODE equations for numerical solvers. */
public interface Equations {
/**
* Applies equations to inputs.
*
* @param t the time step
* @param y the array of inputs
* @return the array of outputs
*/
double[] dydt(double t, double[] y);
}
/** Defines a continuous function. */
public interface Function {
/**
* Applies function to input.
*
* @param x the input value
* @return the output value
*/
double f(double x);
}
/** Hidden constructor for {@code Solver} utility class. */
protected Solver() {
throw new UnsupportedOperationException();
}
/**
* Solves a system of ODEs using forward Euler.
*
* @param eq the system of equations
* @param t0 the initial time
* @param y0 the array of initial values
* @param tf the final time
* @param h the time step
* @return the array of final values
*/
public static double[] euler(Equations eq, double t0, double[] y0, double tf, double h) {
int n = y0.length;
double t = t0;
double[] dydt = new double[n];
double[] y = y0.clone();
// Adjust number of steps.
int nSteps = (int) ((tf - t0) / h);
h = (tf - t0) / nSteps;
// Iterate through steps.
for (int j = 0; j < nSteps; j++) {
t = t0 + j * h;
dydt = eq.dydt(t, y);
for (int i = 0; i < n; i++) {
y[i] += h * dydt[i];
}
}
return y;
}
/**
* Solves a system of ODEs using classic Runge-Kutta.
*
* @param eq the system of equations
* @param t0 the initial time
* @param y0 the array of initial values
* @param tf the final time
* @param h the time step
* @return the array of final values
*/
public static double[] rungeKutta(Equations eq, double t0, double[] y0, double tf, double h) {
int n = y0.length;
double t = t0;
double[] k1 = new double[n];
double[] k2 = new double[n];
double[] k3 = new double[n];
double[] k4 = new double[n];
double[] dydt = new double[n];
double[] y = y0.clone();
double[] w = new double[n];
// Adjust number of steps.
int nSteps = (int) ((tf - t0) / h);
h = (tf - t0) / nSteps;
// Iterate through steps.
for (int j = 0; j < nSteps; j++) {
t = t0 + j * h;
dydt = eq.dydt(t, y);
for (int i = 0; i < n; i++) {
k1[i] = h * dydt[i];
w[i] = y[i] + k1[i] / 2;
}
dydt = eq.dydt(t + h / 2, w);
for (int i = 0; i < n; i++) {
k2[i] = h * dydt[i];
w[i] = y[i] + k2[i] / 2;
}
dydt = eq.dydt(t + h / 2, w);
for (int i = 0; i < n; i++) {
k3[i] = h * dydt[i];
w[i] = y[i] + k3[i];
}
dydt = eq.dydt(t + h, w);
for (int i = 0; i < n; i++) {
k4[i] = h * dydt[i];
y[i] += k1[i] / 6 + k2[i] / 3 + k3[i] / 3 + k4[i] / 6;
}
}
return y;
}
/**
* Solves a system of ODEs using adaptive timestep Cash-Karp with default maximum steps.
*
* @param eq the system of equations
* @param t0 the initial time
* @param y0 the array of initial values
* @param tf the final time
* @param h the time step
* @return the array of final values
*/
public static double[] cashKarp(Equations eq, double t0, double[] y0, double tf, double h) {
return cashKarp(eq, t0, y0, tf, h, MAX_STEPS);
}
/**
* Solves a system of ODEs using adaptive timestep Cash-Karp.
*
* @param eq the system of equations
* @param t0 the initial time
* @param y0 the array of initial values
* @param tf the final time
* @param h the time step
* @param maxSteps the maximum number of steps
* @return the array of final values
*/
public static double[] cashKarp(
Equations eq, double t0, double[] y0, double tf, double h, int maxSteps) {
int n = y0.length;
int steps = 0;
double t = t0;
double[] k1 = new double[n];
double[] k2 = new double[n];
double[] k3 = new double[n];
double[] k4 = new double[n];
double[] k5 = new double[n];
double[] k6 = new double[n];
double[] dydt;
double[] y = y0.clone();
double[] y5 = y0.clone();
double[] y6 = y0.clone();
double[] w = new double[n];
double err;
double maxErr;
double tol;
while (t < tf && steps < maxSteps) {
steps++;
dydt = eq.dydt(t, y);
for (int i = 0; i < n; i++) {
k1[i] = h * dydt[i];
w[i] = y[i] + k1[i] / 5.0;
}
dydt = eq.dydt(t + h / 5.0, w);
for (int i = 0; i < n; i++) {
k2[i] = h * dydt[i];
w[i] = y[i] + (3 * k1[i] + 9 * k2[i]) / 40.0;
}
dydt = eq.dydt(t + 3 * h / 10.0, w);
for (int i = 0; i < n; i++) {
k3[i] = h * dydt[i];
w[i] = y[i] + (3 * k1[i] - 9 * k2[i] + 12 * k3[i]) / 10.0;
}
dydt = eq.dydt(t + 3 * h / 5.0, w);
for (int i = 0; i < n; i++) {
k4[i] = h * dydt[i];
w[i] =
y[i]
- 11 * k1[i] / 54.0
+ 5 * k2[i] / 2.0
- 70 * k3[i] / 27.0
+ 35 * k4[i] / 27.0;
}
dydt = eq.dydt(t + h, w);
for (int i = 0; i < n; i++) {
k5[i] = h * dydt[i];
w[i] =
y[i]
+ 1631 * k1[i] / 55296.0
+ 175 * k2[i] / 512.0
+ 575 * k3[i] / 13824.0
+ 44275 * k4[i] / 110592.0
+ 253 * k5[i] / 4096.0;
}
dydt = eq.dydt(t + 7 * h / 8.0, w);
maxErr = 0.0;
for (int i = 0; i < n; i++) {
k6[i] = h * dydt[i];
y5[i] =
y[i]
+ 2825.0 * k1[i] / 27648.0
+ 18575.0 * k3[i] / 48384.0
+ 13525.0 * k4[i] / 55296.0
+ 277.0 * k5[i] / 14336.0
+ k6[i] / 4.0;
y6[i] =
y[i]
+ 37 * k1[i] / 378.0
+ 250.0 * k3[i] / 621.0
+ 125.0 * k4[i] / 594.0
+ 512.0 * k6[i] / 1771.0;
err = Math.abs(y6[i] - y5[i]);
tol = Math.abs(y5[i]) * ERROR + EPSILON;
maxErr = Math.max(maxErr, err / tol);
}
if (maxErr > 1) { // reduce step size with max 10-fold reduction
h *= Math.max(0.1, SAFETY * Math.pow(maxErr, -0.25));
} else { // increase step size with max 5-fold increase
t += h;
h *= Math.min(5.0, Math.max(SAFETY * Math.pow(maxErr, -0.2), 1.0));
h = (t + h > tf ? tf - t : h);
y = y5.clone();
}
}
return y;
}
/**
* Solves a linear system of equations using successive over-relaxation with default sparse
* representation thresholding and maximum iterations.
*
* <p>Based on matrix size, the algorithm with use a dense or sparse approach.
*
* @param mat the matrix of coefficients
* @param vec the right-hand side vector
* @param x0 the initial guess for the left-hand side vector
* @return the vector of final values
*/
public static double[] sor(double[][] mat, double[] vec, double[] x0) {
return sor(mat, vec, x0, MATRIX_THRESHOLD, MAX_ITERS, TOLERANCE);
}
/**
* Solves a linear system of equations using successive over-relaxation.
*
* <p>Based on matrix size, the algorithm with use a dense or sparse approach.
*
* @param mat the matrix of coefficients
* @param vec the right-hand side vector
* @param x0 the initial guess for the left-hand side vector
* @param matrixThreshold the threshold for matrix size
* @param maxIters the maximum number of iterations
* @param tolerance the error tolerance
* @return the vector of final values
*/
public static double[] sor(
double[][] mat,
double[] vec,
double[] x0,
int matrixThreshold,
int maxIters,
double tolerance) {
int n = mat.length;
if (n < matrixThreshold) {
return denseSOR(mat, vec, x0, maxIters, tolerance);
} else {
return sparseSOR(mat, vec, x0, maxIters, tolerance);
}
}
/**
* Solves linear system of equations using SOR with dense matrix representation.
*
* @param mat the matrix of coefficients
* @param vec the right-hand side vector
* @param x0 the initial guess for the left-hand side vector
* @param maxIters the maximum number of iterations
* @param tolerance the error tolerance
* @return the vector of final values
*/
private static double[] denseSOR(
double[][] mat, double[] vec, double[] x0, int maxIters, double tolerance) {
int i = 0;
double error = Double.POSITIVE_INFINITY;
// Calculate iteration factors
double[] c = forwardSubstitution(mat, vec);
double[][] t = forwardSubstitution(mat);
t = scale(t, -1);
// Set initial guess.
double[] xCurr = x0;
double[] xPrev = x0;
// Iterate until convergence.
while (i < maxIters && error > tolerance) {
// Calculate new guess for x.
xCurr = add(scale(add(multiply(t, xPrev), c), OMEGA), scale(xPrev, 1 - OMEGA));
// Set previous to copy of current and increment iteration count.
xPrev = xCurr;
i++;
// Calculate L2 norm of residuals to check for convergence.
double[] r = subtract(vec, multiply(mat, xCurr));
error = normalize(r);
}
return xCurr;
}
/**
* Solves linear system of equations using SOR with sparse matrix representation.
*
* @param mat the matrix of coefficients
* @param vec the right-hand side vector
* @param x0 the initial guess for the left-hand side vector
* @param maxIters the maximum number of iterations
* @param tolerance the error tolerance
* @return the vector of final values
*/
private static double[] sparseSOR(
double[][] mat, double[] vec, double[] x0, int maxIters, double tolerance) {
int i = 0;
double error = Double.POSITIVE_INFINITY;
// Convert to sparse representation.
ArrayList<Value> sparseA = toSparse(mat);
// Calculate iteration factors
double[] c = forwardSubstitution(sparseA, vec);
ArrayList<Value> t = forwardSubstitution(sparseA);
t = scale(t, -1);
// Set initial guess.
double[] xCurr = x0;
double[] xPrev = x0;
// Iterate until convergence.
while (i < maxIters && error > tolerance) {
// Calculate new guess for x.
xCurr = add(scale(add(multiply(t, xPrev), c), OMEGA), scale(xPrev, 1 - OMEGA));
// Set previous to copy of current and increment iteration count.
xPrev = xCurr;
i++;
// Calculate L2 norm of residuals to check for convergence.
double[] r = subtract(vec, multiply(sparseA, xCurr));
error = normalize(r);
}
return xCurr;
}
/**
* Finds root using bisection method.
*
* <p>Root is found by repeatedly bisecting the interval and selecting the interval in which the
* function changes sign. If no root is found, the simulation will throw an ArithmeticException.
*
* @param func the function
* @param a the lower bound on the interval
* @param b the upper bound on the interval
* @param maxIters the maximum number of iterations
* @param tolerance the error tolerance
* @return the root of the function
*/
public static double bisection(
Function func, double a, double b, int maxIters, double tolerance) {
double c;
double fc;
int i = 0;
if (a > b) {
a = a + b;
b = a - b;
a = a - b;
}
// Check that given bounds are opposite signs.
if (Math.signum(func.f(a)) == Math.signum(func.f(b))) {
throw new ArithmeticException("Bisection cannot find root with given bounds.");
}
while (i < maxIters) {
// Calculate new midpoint.
c = (a + b) / 2;
fc = func.f(c);
// Check for exit conditions.
if (fc == 0 || (b - a) / 2 < tolerance) {
return c;
} else {
if (Math.signum(fc) == Math.signum(func.f(a))) {
a = c;
} else {
b = c;
}
i++;
}
}
return Double.NaN;
}
/**
* Finds root using bisection method with default maximum iterations and tolerance.
*
* <p>Root is found by repeatedly bisecting the interval and selecting the interval in which the
* function changes sign. If no root is found, the simulation will throw an ArithmeticException.
*
* @param func the function
* @param a the lower bound on the interval
* @param b the upper bound on the interval
* @return the root of the function
*/
public static double bisection(Function func, double a, double b) {
return bisection(func, a, b, MAX_ITERS, DELTA);
}
/**
* Finds root using bisection method with default maximum iterations.
*
* <p>Root is found by repeatedly bisecting the interval and selecting the interval in which the
* function changes sign. If no root is found, the simulation will throw an ArithmeticException.
*
* @param func the function
* @param a the lower bound on the interval
* @param b the upper bound on the interval
* @param tolerance the error tolerance
* @return the root of the function
*/
public static double bisection(Function func, double a, double b, double tolerance) {
return bisection(func, a, b, MAX_ITERS, tolerance);
}
/**
* Finds root using bisection method with default tolerance.
*
* <p>Root is found by repeatedly bisecting the interval and selecting the interval in which the
* function changes sign. If no root is found, the simulation will throw an ArithmeticException.
*
* @param func the function
* @param a the lower bound on the interval
* @param b the upper bound on the interval
* @param maxIters the maximum number of iterations
* @return the root of the function
*/
public static double bisection(Function func, double a, double b, int maxIters) {
return bisection(func, a, b, maxIters, TOLERANCE);
}
}