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
//! Adams-Predictor-Corrector 4th Order Variable Step Size Method
use crate::{
error::Error,
interpolate::{Interpolation, cubic_hermite_interpolate},
linalg::norm,
methods::{Adaptive, Ordinary, h_init::InitialStepSize},
ode::{ODE, OrdinaryNumericalMethod},
stats::Evals,
status::Status,
tolerance::Tolerance,
traits::{Real, State},
utils::{constrain_step_size, validate_step_size_parameters},
};
use super::AdamsPredictorCorrector;
impl<T: Real, Y: State<T>> AdamsPredictorCorrector<Ordinary, Adaptive, T, Y, 4> {
///// Adams-Predictor-Corrector 4th Order Variable Step Size Method.
///
/// The Adams-Predictor-Corrector method is an explicit method that
/// uses the previous states to predict the next state. This implementation
/// uses a variable step size to maintain a desired accuracy.
/// It is recommended to start with a small step size so that tolerance
/// can be quickly met and the algorithm can adjust the step size accordingly.
///
/// The First 3 steps are calculated using
/// the Runge-Kutta method of order 4(5) and then the Adams-Predictor-Corrector
/// method is used to calculate the remaining steps until the final time./ Create a Adams-Predictor-Corrector 4th Order Variable Step Size Method instance.
///
/// # Example
///
/// ```
/// use differential_equations::prelude::*;
/// use nalgebra::{SVector, vector};
///
/// struct HarmonicOscillator {
/// k: f64,
/// }
///
/// impl ODE<f64, SVector<f64, 2>> for HarmonicOscillator {
/// fn diff(&self, _t: f64, y: &SVector<f64, 2>, dydt: &mut SVector<f64, 2>) {
/// dydt[0] = y[1];
/// dydt[1] = -self.k * y[0];
/// }
/// }
/// let mut apcv4 = AdamsPredictorCorrector::v4();
/// let t0 = 0.0;
/// let tf = 10.0;
/// let y0 = vector![1.0, 0.0];
/// let system = HarmonicOscillator { k: 1.0 };
/// let results = ODEProblem::new(&system, t0, tf, y0).solve(&mut apcv4).unwrap();
/// let expected = vector![-0.83907153, 0.54402111];
/// assert!((results.y.last().unwrap()[0] - expected[0]).abs() < 1e-6);
/// assert!((results.y.last().unwrap()[1] - expected[1]).abs() < 1e-6);
/// ```
///
///
/// ## Warning
///
/// This method is not suitable for stiff problems and can results in
/// extremely small step sizes and long computation times.```
pub fn v4() -> Self {
Self::default()
}
}
// Implement OrdinaryNumericalMethod Trait for APCV4
impl<T: Real, Y: State<T>> OrdinaryNumericalMethod<T, Y>
for AdamsPredictorCorrector<Ordinary, Adaptive, T, Y, 4>
{
fn init<F>(&mut self, ode: &F, t0: T, tf: T, y0: &Y) -> Result<Evals, Error<T, Y>>
where
F: ODE<T, Y>,
{
let mut evals = Evals::new();
self.tf = tf;
// If h0 is zero, calculate initial step size
if self.h0 == T::zero() {
// Only use adaptive step size calculation if the method supports it
let tol = Tolerance::Scalar(self.tol);
self.h0 = InitialStepSize::<Ordinary>::compute(
ode, t0, tf, y0, 4, &tol, &tol, self.h_min, self.h_max, &mut evals,
);
evals.function += 2;
}
// Check that the initial step size is set
match validate_step_size_parameters::<T, Y>(self.h0, T::zero(), T::infinity(), t0, tf) {
Ok(h0) => self.h = (self.filter)(h0),
Err(status) => return Err(status),
}
// Initialize state
self.t = t0;
self.y = *y0;
self.t_prev[0] = t0;
self.y_prev[0] = *y0;
// Previous saved steps
self.t_old = t0;
self.y_old = *y0;
// Perform the first 3 steps using Runge-Kutta 4 method
let two = T::from_f64(2.0).unwrap();
let six = T::from_f64(6.0).unwrap();
for i in 1..=3 {
// Compute k1, k2, k3, k4 of Runge-Kutta 4
ode.diff(self.t, &self.y, &mut self.k[0]);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[0] * (self.h / two)),
&mut self.k[1],
);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[1] * (self.h / two)),
&mut self.k[2],
);
ode.diff(
self.t + self.h,
&(self.y + self.k[2] * self.h),
&mut self.k[3],
);
// Update State
self.y += (self.k[0] + self.k[1] * two + self.k[2] * two + self.k[3]) * (self.h / six);
self.t += self.h;
self.t_prev[i] = self.t;
self.y_prev[i] = self.y;
evals.function += 4; // 4 evaluations per Runge-Kutta step
if i == 1 {
self.dydt = self.k[0];
self.dydt_old = self.k[0];
}
}
self.status = Status::Initialized;
Ok(evals)
}
fn step<F>(&mut self, ode: &F) -> Result<Evals, Error<T, Y>>
where
F: ODE<T, Y>,
{
let mut evals = Evals::new();
// Check if Max Steps Reached
if self.steps >= self.max_steps {
self.status = Status::Error(Error::MaxSteps {
t: self.t,
y: self.y,
});
return Err(Error::MaxSteps {
t: self.t,
y: self.y,
});
}
self.steps += 1;
// If Step size changed and it takes us to the final time perform a Runge-Kutta 4 step to finish
if self.h != self.t_prev[0] - self.t_prev[1] && self.t + self.h == self.tf {
let two = T::from_f64(2.0).unwrap();
let six = T::from_f64(6.0).unwrap();
// Perform a Runge-Kutta 4 step to finish.
ode.diff(self.t, &self.y, &mut self.k[0]);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[0] * (self.h / two)),
&mut self.k[1],
);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[1] * (self.h / two)),
&mut self.k[2],
);
ode.diff(
self.t + self.h,
&(self.y + self.k[2] * self.h),
&mut self.k[3],
);
evals.function += 4; // 4 evaluations per Runge-Kutta step
// Update State
self.y += (self.k[0] + self.k[1] * two + self.k[2] * two + self.k[3]) * (self.h / six);
self.t += self.h;
return Ok(evals);
}
// Compute derivatives for history
ode.diff(self.t_prev[3], &self.y_prev[3], &mut self.k[0]);
ode.diff(self.t_prev[2], &self.y_prev[2], &mut self.k[1]);
ode.diff(self.t_prev[1], &self.y_prev[1], &mut self.k[2]);
ode.diff(self.t_prev[0], &self.y_prev[0], &mut self.k[3]);
let predictor = self.y_prev[3]
+ (self.k[0] * T::from_f64(55.0).unwrap() - self.k[1] * T::from_f64(59.0).unwrap()
+ self.k[2] * T::from_f64(37.0).unwrap()
- self.k[3] * T::from_f64(9.0).unwrap())
* self.h
/ T::from_f64(24.0).unwrap();
// Corrector step:
ode.diff(self.t + self.h, &predictor, &mut self.k[3]);
let corrector = self.y_prev[3]
+ (self.k[3] * T::from_f64(9.0).unwrap() + self.k[0] * T::from_f64(19.0).unwrap()
- self.k[1] * T::from_f64(5.0).unwrap()
+ self.k[2] * T::from_f64(1.0).unwrap())
* self.h
/ T::from_f64(24.0).unwrap();
// Track number of evaluations
evals.function += 5;
// Calculate sigma for step size adjustment
let sigma = T::from_f64(19.0).unwrap() * norm(corrector - predictor)
/ (T::from_f64(270.0).unwrap() * self.h.abs());
// Check if Step meets tolerance
if sigma <= self.tol {
// Update Previous step states
self.t_old = self.t;
self.y_old = self.y;
self.dydt_old = self.dydt;
// Update state
self.t += self.h;
self.y = corrector;
// Check if previous step rejected
if let Status::RejectedStep = self.status {
self.status = Status::Solving;
}
// Adjust Step Size if needed
let two = T::from_f64(2.0).unwrap();
let four = T::from_f64(4.0).unwrap();
let q = (self.tol / (two * sigma)).powf(T::from_f64(0.25).unwrap());
self.h = if q > four { four * self.h } else { q * self.h };
// Bound Step Size
let tf_t_abs = (self.tf - self.t).abs();
let four_div = tf_t_abs / four;
let h_max_effective = if self.h_max < four_div {
self.h_max
} else {
four_div
};
self.h = constrain_step_size(self.h, self.h_min, h_max_effective);
self.h = (self.filter)(self.h);
// Calculate Previous Steps with new step size
self.t_prev[0] = self.t;
self.y_prev[0] = self.y;
let two = T::from_f64(2.0).unwrap();
let six = T::from_f64(6.0).unwrap();
for i in 1..=3 {
// Compute k1, k2, k3, k4 of Runge-Kutta 4
ode.diff(self.t, &self.y, &mut self.k[0]);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[0] * (self.h / two)),
&mut self.k[1],
);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[1] * (self.h / two)),
&mut self.k[2],
);
ode.diff(
self.t + self.h,
&(self.y + self.k[2] * self.h),
&mut self.k[3],
);
// Update State
self.y +=
(self.k[0] + self.k[1] * two + self.k[2] * two + self.k[3]) * (self.h / six);
self.t += self.h;
self.t_prev[i] = self.t;
self.y_prev[i] = self.y;
self.evals += 4; // 4 evaluations per Runge-Kutta step
if i == 1 {
self.dydt = self.k[0];
}
}
} else {
// Step Rejected
self.status = Status::RejectedStep;
// Adjust Step Size
let two = T::from_f64(2.0).unwrap();
let tenth = T::from_f64(0.1).unwrap();
let q = (self.tol / (two * sigma)).powf(T::from_f64(0.25).unwrap());
self.h = if q < tenth {
tenth * self.h
} else {
q * self.h
};
self.h = (self.filter)(self.h);
// Calculate Previous Steps with new step size
self.t_prev[0] = self.t;
self.y_prev[0] = self.y;
let two = T::from_f64(2.0).unwrap();
let six = T::from_f64(6.0).unwrap();
for i in 1..=3 {
// Compute k1, k2, k3, k4 of Runge-Kutta 4
ode.diff(self.t, &self.y, &mut self.k[0]);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[0] * (self.h / two)),
&mut self.k[1],
);
ode.diff(
self.t + self.h / two,
&(self.y + self.k[1] * (self.h / two)),
&mut self.k[2],
);
ode.diff(
self.t + self.h,
&(self.y + self.k[2] * self.h),
&mut self.k[3],
);
// Update State
self.y +=
(self.k[0] + self.k[1] * two + self.k[2] * two + self.k[3]) * (self.h / six);
self.t += self.h;
self.t_prev[i] = self.t;
self.y_prev[i] = self.y;
self.evals += 4; // 4 evaluations per Runge-Kutta step
}
}
Ok(evals)
}
fn t(&self) -> T {
self.t
}
fn y(&self) -> &Y {
&self.y
}
fn t_prev(&self) -> T {
self.t_old
}
fn y_prev(&self) -> &Y {
&self.y_old
}
fn h(&self) -> T {
// OrdinaryNumericalMethod repeats step size 4 times for each step
// so the ODEProblem inquiring is looking for what the next
// state will be thus the step size is multiplied by 4
self.h * T::from_f64(4.0).unwrap()
}
fn set_h(&mut self, h: T) {
self.h = (self.filter)(h);
}
fn status(&self) -> &Status<T, Y> {
&self.status
}
fn set_status(&mut self, status: Status<T, Y>) {
self.status = status;
}
}
// Implement the Interpolation trait for APCV4
impl<T: Real, Y: State<T>> Interpolation<T, Y>
for AdamsPredictorCorrector<Ordinary, Adaptive, T, Y, 4>
{
fn interpolate(&mut self, t_interp: T) -> Result<Y, Error<T, Y>> {
// Check if t is within the range of the solver
if t_interp < self.t_old || t_interp > self.t {
return Err(Error::OutOfBounds {
t_interp,
t_prev: self.t_old,
t_curr: self.t,
});
}
// Calculate the interpolated value using cubic Hermite interpolation
let y_interp = cubic_hermite_interpolate(
self.t_old,
self.t,
&self.y_old,
&self.y,
&self.dydt_old,
&self.dydt,
t_interp,
);
Ok(y_interp)
}
}