def test_rk4_solver(self): theta = -1.2 eqn = SimpleEquation(theta) u_exact = lambda t: eqn.solution(t)[0] ti = 0 tf = 5*math.pi/3 u0 = u_exact(ti) rk = RKSolver(ti, tf) rk.equation = eqn rk.set_initial_condition(u0) n = 4 err = np.zeros((n,)) dt = np.zeros((n,)) n_steps = 100 for i in range(n): n_steps *= (i+1) dt[i] = 1./n_steps rk.n_steps = n_steps rk.solve() err[i] = abs(rk.state() - u_exact(tf)) conv_rate = np.polyfit(np.log(dt), np.log(err), 1)[0] self.assertAlmostEqual(conv_rate, 4.0, 1)
def test_rk4_gradient_computation(self): theta = -1.2 eqn = SimpleEquation(theta) ti = 0 tf = 5*math.pi/3 (u0, du0_dp) = eqn.solution(ti) rk = RKSolver(ti, tf) rk.equation = eqn rk.set_initial_condition(u0, du0_dp) rk.set_output_gradient_flag(True) n = 4 err_soln = np.zeros((n,)) err_grad = np.zeros((n,)) dt = np.zeros((n,)) n_steps = 100 for i in range(n): n_steps *= (i+1) dt[i] = 1./n_steps rk.n_steps = n_steps rk.solve() err_soln[i] = abs(rk.state()[0] - eqn.solution(tf)[0]) err_grad[i] = abs(rk.state()[1] - eqn.solution(tf)[1]) conv_rate = np.polyfit(np.log(dt), np.log(err_soln), 1)[0] self.assertAlmostEqual(conv_rate, 4.0, 1) conv_rate = np.polyfit(np.log(dt), np.log(err_grad), 1)[0] self.assertAlmostEqual(conv_rate, 4.0, 1)
def test_interface(self): rk = RKSolver(0, 1) rk.initial_time = 0.5 rk.final_time = 5 rk.n_steps = 10 self.assertEqual(rk.initial_time,0.5) self.assertEqual(rk.final_time,5) self.assertEqual(rk.n_steps,10) eqn = Seir() rk.equation = eqn self.assertEqual(rk.equation, eqn) rk.output_frequency = 20 self.assertEqual(rk.output_frequency, 20)