#!/usr/bin/env python3 """Chapter 10, code 0: shooting for a second-order boundary value problem. Solve y'' = f(x,y,y'), with y(a) = alpha and y(b) = beta. Secant iteration finds the initial slope. Each shooting trial is an initial value problem integrated with adaptive Fehlberg RKF45. Example: y'' = y, y(0) = y(1) = 1. Exact solution: cosh(x-0.5)/cosh(0.5). Requires NumPy and Matplotlib. Run: python3 ch10_shooting.py SciPy alternatives: solve_ivp can integrate each shooting trial (its RK45 uses Dormand-Prince, rather than Fehlberg). solve_bvp solves the BVP directly by collocation and requires an initial solution guess. To solve another problem: 1. Edit the interval, boundary values, and slope guesses in main. 2. Edit f, immediately below the driver. 3. Disable check_exact or replace exact_solution. """ import numpy as np import matplotlib.pyplot as plt def main(): # ---------------- Problem and controls: edit here ----------------- a = 0.0 b = 1.0 alpha = 1.0 # y(a) beta = 1.0 # y(b) slope1 = 0.0 # First guess for y'(a) slope2 = 1.0 # Second guess for y'(a) h_first = 0.05 h_max = 0.05 # Maximum spacing between output points ivp_tolerance = 1.0e-10 # Absolute LOCAL tolerance for RKF45 boundary_tolerance = 1.0e-8 # Required |y(b)-beta| capacity = 100001 # Maximum stored points per shooting trial check_exact = True make_plot = True # ----------------------------------------------------------------- print('Boundary value problem: shooting with secant iteration and RKF45') print(f'RKF45 tolerance: {ivp_tolerance:12.4e}') print(f'Boundary tolerance:{boundary_tolerance:12.4e}') x, Y, slope, residual, trials, accepted, rejected = shoot2( f, a, b, alpha, beta, slope1, slope2, h_first, h_max, ivp_tolerance, boundary_tolerance, capacity) # Print and save only the converged trajectory, including endpoints. # Each row of Y is one accepted point: Y[:,0] = y, Y[:,1] = y'. filename = 'ch10_shooting.dat' max_error = 0.0 print() with open(filename, 'w', encoding='utf-8') as data_file: if check_exact: print(f"{'x':>10} {'numerical y':>16} {'dy/dx':>16} " f"{'exact y':>16} {'abs error':>12}") data_file.write('# x y dy_dx exact_y abs_error\n') else: print(f"{'x':>10} {'numerical y':>16} {'dy/dx':>16}") data_file.write('# x y dy_dx\n') for i in range(len(x)): if check_exact: exact = exact_solution(x[i]) abs_error = abs(Y[i, 0]-exact) max_error = max(max_error, abs_error) print(f'{x[i]:10.6f} {Y[i,0]:16.8e} {Y[i,1]:16.8e} ' f'{exact:16.8e} {abs_error:12.4e}') row = (x[i], Y[i,0], Y[i,1], exact, abs_error) else: print(f'{x[i]:10.6f} {Y[i,0]:16.8e} {Y[i,1]:16.8e}') row = (x[i], Y[i,0], Y[i,1]) data_file.write(' '.join(f'{value:24.16e}' for value in row)+'\n') print(f'\nShooting trials: {trials:8d}') print(f'Initial slope: {slope:16.10f}') print(f'Boundary residual: {residual:16.6e}') print(f'Accepted steps: {accepted:8d}') print(f'Rejected trials: {rejected:8d}') if check_exact: print(f'Largest sampled error:{max_error:16.6e}') print('Step counts refer to the final shooting trial.') print(f'Data file: {filename}') # Numerical markers are actual accepted points. The dense exact curve # is used only for comparison, not to interpolate the numerical data. if make_plot: fig, axes = plt.subplots(2, 1, figsize=(7, 7)) axes[0].plot(x, Y[:,0], 'ko-', markersize=3, linewidth=1, label='Numerical') if check_exact: x_plot = np.linspace(a, b, 500) axes[0].plot(x_plot, exact_solution(x_plot), 'k--', linewidth=1.2, label='Exact') axes[0].legend() axes[0].set_xlabel('x') axes[0].set_ylabel('y(x)') axes[0].set_title('Boundary value problem: shooting solution') axes[0].grid(True) axes[1].plot(x, Y[:,1], 'ko-', markersize=3, linewidth=1) axes[1].set_xlabel('x') axes[1].set_ylabel('dy/dx') axes[1].set_title('Derivative of the solution') axes[1].grid(True) fig.tight_layout() plt.show() def f(x, y, dy): """The original second-order equation: y'' = f(x,y,y'). x and dy are available for equations that depend on them. """ return y def exact_solution(x): """Analytic solution for the supplied example; accepts scalars or arrays.""" return np.cosh(x-0.5)/np.cosh(0.5) def shoot2(fcn, a, b, alpha, beta, slope1, slope2, h_first, h_max, ivp_tolerance, boundary_tolerance, capacity): """Find the unknown slope s = y'(a) using secant iteration. Each trial starts with y(a) = alpha, y'(a) = s. The mismatch R(s) = y(b;s)-beta must vanish. Return the converged trajectory. Secant iteration is not bracketed; convergence depends on the guesses. A small boundary residual alone does not establish accuracy: tighten the RKF45 tolerance and compare trajectories for a new problem. """ max_trials = 30 if boundary_tolerance <= 0 or slope1 == slope2: raise ValueError('Use positive boundary tolerance and distinct slope guesses.') print(f"{'trial':>8} {'initial slope':>18} {'boundary residual':>18}") slope = slope1 previous_slope = slope1 previous_residual = 0.0 for trials in range(1, max_trials+1): initial = np.array([alpha, slope], dtype=float) grid, Y, final, accepted, rejected = rkf45_system( fcn, a, initial, b, h_first, h_max, ivp_tolerance, capacity) residual = final[0]-beta print(f'{trials:8d} {slope:18.10e} {residual:18.10e}') if abs(residual) <= boundary_tolerance: return grid, Y, slope, residual, trials, accepted, rejected if trials == max_trials: break if trials == 1: next_slope = slope2 else: denominator = residual-previous_residual scale = max(abs(residual), abs(previous_residual), np.finfo(float).tiny) if abs(denominator) <= np.finfo(float).eps*scale: raise RuntimeError('Secant residuals are indistinguishable; change guesses.') next_slope = slope-residual*(slope-previous_slope)/denominator if not np.isfinite(next_slope): raise RuntimeError('Nonfinite secant slope.') if next_slope == slope: raise RuntimeError('Secant slope cannot advance; check tolerances.') previous_slope = slope previous_residual = residual slope = next_slope raise RuntimeError('Shooting did not converge within the trial limit.') def equations(fcn, x, y): """Two first-order equations: y[0]' = y[1], y[1]' = f(x,y[0],y[1]).""" dy = np.array([y[1], fcn(x, y[0], y[1])], dtype=float) if not np.all(np.isfinite(dy)): raise RuntimeError('Nonfinite derivative in trial integration.') return dy def rkf45_system(fcn, t0, x0, t_end, h_first, h_max, tolerance, capacity): """Adaptive Fehlberg RKF45; all step decisions are inside this routine. Save initial and accepted points. Advance with the fifth-order estimate. The largest absolute embedded component error controls acceptance. One absolute tolerance assumes components of comparable magnitudes and controls LOCAL error. States have two components. """ max_attempts = 100000 if (capacity < 2 or capacity != int(capacity) or t_end <= t0 or h_first <= 0 or h_max <= 0 or tolerance <= 0): raise ValueError('Use integer capacity >= 2, b > a, positive steps and tolerance.') grid = np.zeros(capacity) Y = np.zeros((capacity, 2)) t = t0 h = h_first state = x0.copy() accepted = 0 rejected = 0 attempts = 0 grid[0] = t Y[0] = state while t < t_end: if attempts >= max_attempts: raise RuntimeError('Maximum number of trials exceeded.') h = min(h, h_max, t_end-t) tf = t+h if tf <= t: raise RuntimeError(f'Step too small to advance at t = {t:.16g}.') attempts += 1 # Every k includes h. Both equations use the SAME intermediate state. k1 = h*equations(fcn, t, state) work = state+k1/4 k2 = h*equations(fcn, t+h/4, work) work = state+3*k1/32+9*k2/32 k3 = h*equations(fcn, t+3*h/8, work) work = state+1932*k1/2197-7200*k2/2197+7296*k3/2197 k4 = h*equations(fcn, t+12*h/13, work) work = state+439*k1/216-8*k2+3680*k3/513-845*k4/4104 k5 = h*equations(fcn, t+h, work) work = state-8*k1/27+2*k2-3544*k3/2565+1859*k4/4104-11*k5/40 k6 = h*equations(fcn, t+h/2, work) trial = state+16*k1/135+6656*k3/12825+28561*k4/56430-9*k5/50+2*k6/55 component_error = np.abs(k1/360-128*k3/4275-2197*k4/75240+k5/50+2*k6/55) if not np.all(np.isfinite(trial)) or not np.all(np.isfinite(component_error)): raise RuntimeError('Nonfinite RKF45 result: check model and slope guesses.') err = np.max(component_error) if err <= tolerance: if h == t_end-t: tf = t_end t = tf state = trial accepted += 1 if accepted+1 > capacity: raise RuntimeError('Increase trajectory storage capacity.') grid[accepted] = t Y[accepted] = state else: rejected += 1 # Keep t and state unchanged. if err == 0: factor = 2.0 else: factor = 0.9*(tolerance/err)**0.2 if err <= tolerance: h *= min(2.0, factor) else: h *= max(0.2, factor) return grid[:accepted+1], Y[:accepted+1], state, accepted, rejected # Definitions must be loaded before the driver is called. if __name__ == '__main__': main()