def main(argv=None): if argv is None: argv = sys.argv file_prefix = None try: options, args = getopt.getopt(argv[1:], 'f:') for opt, arg in options: if opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 suffixed = lambda s, suf: None if s is None else '{0}{1}'.format(s, suf) pfunc = pendulum(0.1, 0.1, 0) ts, xs = rungekutta.rk4(pfunc, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.005, 2000) render_plot(xs[0, :], xs[1, :], title='Undriven, Undamped Pendulum', file_prefix=suffixed(file_prefix, '_2a'), xlabel=r'$\theta$', ylabel=r'$\omega$') ts1, xs1 = rungekutta.rk4(pfunc, 0.0, numpy.array([0.01, 0.0], dtype=numpy.float64), 0.005, 2000) render_plot(xs1[0, :], xs1[1, :], title='Undriven, Undamped Pendulum', file_prefix=suffixed(file_prefix, '_2b'), xlabel=r'$\theta$', ylabel=r'$\omega$') make_phase_portrait(pfunc, 'b', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0)$', file_prefix=suffixed(file_prefix, '_3')) pfunc2 = pendulum(0.1, 0.1, 0.25) make_phase_portrait(pfunc2, 'b', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0.25)$', file_prefix=suffixed(file_prefix, '_4')) make_phase_portrait_mod2pi( pfunc2, 'b.', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0.25)$ Mod $2\pi$', file_prefix=suffixed(file_prefix, '_5'), markersize=0.6) return 0
def pr6x2(): vfunc = variational(16, 45, 4) x0 = ic(-13.0, -12.0, 52.0) ts, xs = rungekutta.rk4(vfunc, 0.0, x0, 0.001, 30000) ms = numpy.reshape(xs[3:, -1], (3, 3)) ws, vs = eig(ms) return [numpy.log(numpy.abs(w)) / 30000 for w in ws]
def pr1d(file_prefix): drive_freq = 7.4246 pfunc2 = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1, freq=drive_freq) ts3, xs3 = rungekutta.rk4( pfunc2, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.02, 250000 ) xs3[0,:] = numpy.array( [pendulum.mod2pi(x) for x in xs3[0,:]], dtype=numpy.float64 ) points3 = xs3.transpose() ps4 = poincare.section(ts3, points3, interval=2*numpy.pi/drive_freq) plot.mod2pi( ps4[:,0], ps4[:,1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare section, increased step size', file_prefix=_suffixed(file_prefix, '_1d') )
def main(argv=None): argv = argv or sys.argv file_prefix = None try: options, args = getopt.getopt(argv[1:], 'f:') for opt, arg in options: if opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 df = twobody(1.0, 0.5, 0.5) x0 = numpy.array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 7600) xs = xs.transpose() plot.render(xs[:, 0], xs[:, 1], 'b', xs[:, 6], xs[:, 7], 'r', xbound=(-10.0, 10.0), ybound=(0.0, 20.0), xlabel='x (normalized AU)', ylabel='y (normalized AU)', aspect='equal', title='2-body Orbital Trajectory', legend=('Star A', 'Star B'), file_prefix=file_prefix) return 0
def once(): # INITIAL CONDITIONS lam0 = 10 mod = -1 start_time = time.time() y2, true_y, lam2, step2, err2 = rk.rk4(fun_rk, y0, x0=lam0, num=18000, h_start=0.02, h_max=10**1, h_min=10**-7, h_max_change=1.5, acc=10**-9, experimental=False, cutoff=True) print('Smallest step taken was ', np.min(step2)) print("--- %s seconds ---" % (time.time() - start_time)) pprint.pprint(y2[:, -1]) fig, ax = plt.subplots(figsize=(11, 9)) plot_stuff(true_y, lam2, step2, err2, fig, ax)
def pr2x(file_prefix, step, nsteps, title, suffix): drive_freq = 7.4246 pfunc = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1.0, freq=drive_freq) ts, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), step, nsteps ) xs[0,:] = numpy.array( [pendulum.mod2pi(x) for x in xs[0,:]], dtype=numpy.float64 ) points = xs.transpose() ps = poincare.linear(ts, points, interval=2*numpy.pi/drive_freq) plot.mod2pi( ps[:,0], ps[:,1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title=title, file_prefix=_suffixed(file_prefix, suffix) )
def interceptCostRK4(Pars, Args): # Extract Parameters a = Pars[:, 0] b = Pars[:, 1] c = Pars[:, 2] d = Pars[:, 3] # Extract Observations Obs = Args[0] dt = Args[1] obsTime = Obs[:, 0] obsStor = Obs[:, 1] obsPrec = Obs[:, 2] obsEvap = Obs[:, 3] # Prepare to simulate with Runge-Kutta 4 # Rebundle arguments args = [obsTime, obsPrec, obsEvap, a, b, c, d] # Handle for model function mf = interceptionModel # Initialize output array simStor = np.zeros((obsTime.size, a.size)) # Grab initial conditiion simStor[0, :] = obsStor[0] # Iterate over observation period for i, t in enumerate(obsTime): # Index of rk4 step result j = i + 1 # Prevent out-of-bounds array access if j >= obsTime.size: break # Take an rk4 step simStor[j, :] = rk.rk4(t, simStor[i, :], dt, mf, args) # Return the simulation results and the cost (SSR) return [simStor.T, ssr(simStor.T, obsStor)]
def pr1(file_prefix): df = threebody(1.0, 0.5, 0.5, 0.5) x0 = numpy.array([ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 3000, 0, 0, 0, 0 ], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 7600) xs = xs.transpose() plot.render(xs[:,0], xs[:,1], 'b', xs[:,6], xs[:,7], 'r', xs[:,12], xs[:,13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', xbound=(-10.0, 10.0), ybound=(0.0, 20.0), aspect='equal', title='3-body Orbital Trajectory', legend=('Star A', 'Star B'), file_prefix=suffixed(file_prefix, '_1a') ) plot.render(xs[:,6] - xs[:,0], xs[:,7] - xs[:,1], 'r', xlabel='x (normalized AU)', ylabel='y (normalized AU)', aspect='equal', title='3-body Trajectory, Star A at origin', legend=('Star B',), file_prefix=suffixed(file_prefix, '_1b') )
def pr2(file_prefix): df = threebody(1.0, 0.5, 0.5, 0.5) x0 = numpy.array( [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 20, 0, 0, -0.15, 0], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 50000) xs = xs.transpose() plot.render(xs[:5500, 0], xs[:5500, 1], 'b', xs[:5500, 6], xs[:5500, 7], 'r', xs[:5500, 12], xs[:5500, 13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title='3-body Orbital Interaction', legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_2a')) plot.render(xs[:, 0], xs[:, 1], 'b', xs[:, 12], xs[:, 13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title='3-body Orbital Interaction', legend=('Star A', 'Star C'), file_prefix=suffixed(file_prefix, '_2b'))
def pr1(file_prefix): df = threebody(1.0, 0.5, 0.5, 0.5) x0 = numpy.array([0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 3000, 0, 0, 0, 0], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 7600) xs = xs.transpose() plot.render(xs[:, 0], xs[:, 1], 'b', xs[:, 6], xs[:, 7], 'r', xs[:, 12], xs[:, 13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', xbound=(-10.0, 10.0), ybound=(0.0, 20.0), aspect='equal', title='3-body Orbital Trajectory', legend=('Star A', 'Star B'), file_prefix=suffixed(file_prefix, '_1a')) plot.render(xs[:, 6] - xs[:, 0], xs[:, 7] - xs[:, 1], 'r', xlabel='x (normalized AU)', ylabel='y (normalized AU)', aspect='equal', title='3-body Trajectory, Star A at origin', legend=('Star B', ), file_prefix=suffixed(file_prefix, '_1b'))
def make_phase_portrait(pfunc, *args, **kwargs): ''' Constructs a phase portrait of the system. ''' figure = matplotlib.pyplot.figure() axes = figure.gca() opts, plot_args = split_dict(('title', 'file_prefix'), kwargs) file_prefix = opts.get('file_prefix') title = opts.get('title') for (theta, omega) in PHASE_POINTS: _, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([theta, omega], dtype=numpy.float64), 0.005, 2000) axes.plot(xs[0, :], xs[1, :], *args, **plot_args) axes.set_xlabel(r'$\theta$') axes.set_ylabel(r'$\omega$') axes.set_xbound(-3 * numpy.pi / 2, 3 * numpy.pi / 2) axes.set_xticks((-3 * numpy.pi / 2, -numpy.pi, -numpy.pi / 2, 0, numpy.pi / 2, numpy.pi, 3 * numpy.pi / 2)) axes.set_xticklabels( (r'$-\frac{3\pi}{2}$', r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$')) axes.set_title('Phase Portrait' if title is None else title) if file_prefix is None: figure.show() else: figure.savefig('{0}.png'.format(file_prefix), dpi=220)
def pr2(file_prefix): df = threebody(1.0, 0.5, 0.5, 0.5) x0 = numpy.array([ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 20, 0, 0, -0.15, 0 ], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 50000) xs = xs.transpose() plot.render(xs[:5500,0], xs[:5500,1], 'b', xs[:5500,6], xs[:5500,7], 'r', xs[:5500,12], xs[:5500,13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title='3-body Orbital Interaction', legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_2a') ) plot.render(xs[:,0], xs[:,1], 'b', xs[:,12], xs[:,13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title='3-body Orbital Interaction', legend=('Star A', 'Star C'), file_prefix=suffixed(file_prefix, '_2b') )
def main(argv=None): argv = argv or sys.argv file_prefix = None try: options, args = getopt.getopt(argv[1:], 'f:') for opt, arg in options: if opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 df = twobody(1.0, 0.5, 0.5) x0 = numpy.array([ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0 ], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 7600) xs = xs.transpose() plot.render(xs[:,0], xs[:,1], 'b', xs[:,6], xs[:,7], 'r', xbound=(-10.0, 10.0), ybound=(0.0, 20.0), xlabel='x (normalized AU)', ylabel='y (normalized AU)', aspect='equal', title='2-body Orbital Trajectory', legend=('Star A', 'Star B'), file_prefix=file_prefix ) return 0
def pr1c(file_prefix): drive_freq = 7.4246 pfunc2 = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1, freq=drive_freq) ts2, xs2 = rungekutta.rk4( pfunc2, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.005, 1000000 ) xs2[0,:] = numpy.array( [pendulum.mod2pi(x) for x in xs2[0,:]], dtype=numpy.float64 ) points2 = xs2.transpose() ps3 = poincare.section(ts2, points2, interval=2*numpy.pi/drive_freq) plot.mod2pi( ps3[:,0], ps3[:,1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare Section (Chaotic Trajectory)', file_prefix=_suffixed(file_prefix, '_1c') )
def pr2b(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4(lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 1000000) xs = xxs.transpose() x0 = numpy.array([-30, -40, 4], dtype=numpy.float64) d_cap = find_loglog_slope(xs[100000:400000, :], x0, file_prefix=suffixed(file_prefix, "_2b")) print "Lorenz\tshort\td_cap = {0:.6f}".format(d_cap) return xs
def runit(): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 100000 )
def integrate(x0): ''' Integrates the variational system given an initial condition. Returns: the final resulting matrix of variations. ''' dfunc = variational(16, 45, 4) _, xs = rungekutta.rk4(dfunc, 0.0, x0, 0.001, 100) return numpy.reshape(xs[3:,-1], (3,3))
def main(argv=None): if argv is None: argv = sys.argv file_prefix = None a = 16.0 r = 45.0 b = 4.0 suffixed = lambda s, suf: None if s is None else '{0}{1}'.format(s, suf) try: options, args = getopt.getopt(argv[1:], 'a:r:b:f:') for opt, arg in options: if opt == '-a': a = float(arg) elif opt == '-r': r = float(arg) elif opt == '-b': b = float(arg) elif opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 x0 = numpy.array([-13, -12, 52], dtype=numpy.float64) lfunc = lorenz(a, r, b) ts, xs = rungekutta.ark4(lfunc, 0.0, x0, 20000.0, 0.00001) plot.render3d(xs[0, :], xs[1, :], xs[2, :], 'b.', xlabel='x', ylabel='y', zlabel='z', markersize=0.2, title='Lorenz Attractor', file_prefix=suffixed(file_prefix, '_2a')) ts1, xs1 = rungekutta.ark4(lfunc, 0.0, x0, 2.0, 0.01) ts2, xs2 = rungekutta.rk4(lfunc, 0.0, x0, 0.001, 2000) def _lorenz_2b_callback(axes): axes.plot(xs1[0, :], xs1[1, :], xs1[2, :], 'b', label='ARK4') axes.plot(xs2[0, :], xs2[1, :], xs2[2, :], 'r', label='RK4') axes.legend() plot.render3d(xlabel='x', ylabel='y', zlabel='z', title='RK4 vs. ARK4 Overlay', ax_callback=_lorenz_2b_callback, file_prefix=suffixed(file_prefix, '_2b')) return 0
def main(argv=None): if argv is None: argv=sys.argv file_prefix = None a = 16.0 r = 45.0 b = 4.0 suffixed = lambda s, suf: None if s is None else '{0}{1}'.format(s, suf) try: options, args = getopt.getopt(argv[1:], 'a:r:b:f:') for opt, arg in options: if opt == '-a': a = float(arg) elif opt == '-r': r = float(arg) elif opt == '-b': b = float(arg) elif opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 x0 = numpy.array([-13, -12, 52], dtype=numpy.float64) lfunc = lorenz(a, r, b) ts, xs = rungekutta.ark4(lfunc, 0.0, x0, 20000.0, 0.00001) plot.render3d( xs[0,:], xs[1,:], xs[2,:], 'b.', xlabel='x', ylabel='y', zlabel='z', markersize=0.2, title='Lorenz Attractor', file_prefix=suffixed(file_prefix, '_2a') ) ts1, xs1 = rungekutta.ark4(lfunc, 0.0, x0, 2.0, 0.01) ts2, xs2 = rungekutta.rk4(lfunc, 0.0, x0, 0.001, 2000) def _lorenz_2b_callback(axes): axes.plot(xs1[0,:], xs1[1,:], xs1[2,:], 'b', label='ARK4') axes.plot(xs2[0,:], xs2[1,:], xs2[2,:], 'r', label='RK4') axes.legend() plot.render3d( xlabel='x', ylabel='y', zlabel='z', title='RK4 vs. ARK4 Overlay', ax_callback=_lorenz_2b_callback, file_prefix=suffixed(file_prefix, '_2b') ) return 0
def pr2a(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4(lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 300000) xs = xxs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual("-D", 16000, input=data) tau = first_min(ms) ws = tispy.delay("-d", int(tau), "-m", 7, input=data) x0 = numpy.array([-35, -35], dtype=numpy.float64) zs = numpy.array(zip(ws[100000:, 0], ws[100000:, 5]), dtype=numpy.float64) d_cap = find_loglog_slope(zs, x0, file_prefix=suffixed(file_prefix, "_2a")) print "Lorenz\tembed\td_cap = {0:.6f}".format(d_cap)
def pr2b(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 1000000) xs = xxs.transpose() x0 = numpy.array([-30, -40, 4], dtype=numpy.float64) d_cap = find_loglog_slope(xs[100000:400000, :], x0, file_prefix=suffixed(file_prefix, '_2b')) print 'Lorenz\tshort\td_cap = {0:.6f}'.format(d_cap) return xs
def pr2a(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 300000) xs = xxs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual('-D', 16000, input=data) tau = first_min(ms) ws = tispy.delay('-d', int(tau), '-m', 7, input=data) x0 = numpy.array([-35, -35], dtype=numpy.float64) zs = numpy.array(zip(ws[100000:, 0], ws[100000:, 5]), dtype=numpy.float64) d_cap = find_loglog_slope(zs, x0, file_prefix=suffixed(file_prefix, '_2a')) print 'Lorenz\tembed\td_cap = {0:.6f}'.format(d_cap)
def make_phase_portrait(pfunc, *args, **kwargs): ''' Constructs a phase portrait of the system. ''' figure = matplotlib.pyplot.figure() axes = figure.gca() opts, plot_args = split_dict(('title', 'file_prefix'), kwargs) file_prefix = opts.get('file_prefix') title = opts.get('title') for (theta, omega) in PHASE_POINTS: _, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([theta, omega], dtype=numpy.float64), 0.005, 2000 ) axes.plot(xs[0,:], xs[1,:], *args, **plot_args) axes.set_xlabel(r'$\theta$') axes.set_ylabel(r'$\omega$') axes.set_xbound(-3*numpy.pi/2, 3*numpy.pi/2) axes.set_xticks(( -3*numpy.pi/2, -numpy.pi, -numpy.pi/2, 0, numpy.pi/2, numpy.pi, 3*numpy.pi/2 )) axes.set_xticklabels(( r'$-\frac{3\pi}{2}$', r'$-\pi$', r'$-\frac{\pi}{2}$', '0', r'$\frac{\pi}{2}$', r'$\pi$', r'$\frac{3\pi}{2}$' )) axes.set_title('Phase Portrait' if title is None else title) if file_prefix is None: figure.show() else: figure.savefig('{0}.png'.format(file_prefix), dpi=220)
def extrema(): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4(lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 300000) xs = xxs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual("-D", 16000, input=data) tau = first_min(ms) print "Tau: {0:.6f}".format(tau) ws = tispy.delay("-d", int(tau), "-m", 7, input=data) zs = ws[100000:, :] mins = numpy.empty(7, dtype=numpy.float64) maxs = numpy.empty(7, dtype=numpy.float64) for i in xrange(7): mins[i] = min(zs[:, i]) maxs[i] = max(zs[:, i]) print "Mins: {0}".format(mins) print "Maxs: {0}".format(maxs)
def plot_pfunc(pfunc, *args, **kwargs): ''' Convenience function for experimenting with pendulum functions. ''' opts, plot_args = split_dict(('tstep', 'theta0', 'omega0', 'nsteps'), kwargs) theta0 = opts.get('theta0', 3.0) omega0 = opts.get('omega0', 0.1) tstep = opts.get('tstep', 0.005) nsteps = opts.get('nsteps', 2000) _, xs = rungekutta.rk4(pfunc, 0.0, numpy.array([theta0, omega0], dtype=numpy.float64), tstep, nsteps) fix_domain = lambda x: mod2pi(x) if kwargs.get('mod2pi', False) else x xs[0, :] = numpy.array([fix_domain(theta) for theta in xs[0, :]], dtype=numpy.float64) render_plot(xs[0, :], xs[1, :], *args, **plot_args)
def pr1d(file_prefix): drive_freq = 7.4246 pfunc2 = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1, freq=drive_freq) ts3, xs3 = rungekutta.rk4(pfunc2, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.02, 250000) xs3[0, :] = numpy.array([pendulum.mod2pi(x) for x in xs3[0, :]], dtype=numpy.float64) points3 = xs3.transpose() ps4 = poincare.section(ts3, points3, interval=2 * numpy.pi / drive_freq) plot.mod2pi(ps4[:, 0], ps4[:, 1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare section, increased step size', file_prefix=_suffixed(file_prefix, '_1d'))
def pr1c(file_prefix): drive_freq = 7.4246 pfunc2 = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1, freq=drive_freq) ts2, xs2 = rungekutta.rk4(pfunc2, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.005, 1000000) xs2[0, :] = numpy.array([pendulum.mod2pi(x) for x in xs2[0, :]], dtype=numpy.float64) points2 = xs2.transpose() ps3 = poincare.section(ts2, points2, interval=2 * numpy.pi / drive_freq) plot.mod2pi(ps3[:, 0], ps3[:, 1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare Section (Chaotic Trajectory)', file_prefix=_suffixed(file_prefix, '_1c'))
def pr2x(file_prefix, step, nsteps, title, suffix): drive_freq = 7.4246 pfunc = pendulum.pendulum(0.1, 0.1, 0.25, ampl=1.0, freq=drive_freq) ts, xs = rungekutta.rk4(pfunc, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), step, nsteps) xs[0, :] = numpy.array([pendulum.mod2pi(x) for x in xs[0, :]], dtype=numpy.float64) points = xs.transpose() ps = poincare.linear(ts, points, interval=2 * numpy.pi / drive_freq) plot.mod2pi(ps[:, 0], ps[:, 1], 'k.', xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title=title, file_prefix=_suffixed(file_prefix, suffix))
def pr1a(file_prefix): pfunc = pendulum.pendulum(0.1, 0.1, 0) ts, xs = rungekutta.rk4(pfunc, 0.0, numpy.array([0.01, 0.0], dtype=numpy.float64), 0.005, 80000) points = xs.transpose() ps = poincare.section(ts, points, interval=0.6346975625940523) plot.render(ps[:, 0], ps[:, 1], 'k.', xbound=(-0.015, 0.015), ybound=(-0.15, 0.15), xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare Section (Natural Frequency)', file_prefix=_suffixed(file_prefix, '_1a')) return ts, points
def extrema(): lfunc = lorenz.lorenz(16, 45, 4) ts, xxs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.0001, 300000) xs = xxs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual('-D', 16000, input=data) tau = first_min(ms) print 'Tau: {0:.6f}'.format(tau) ws = tispy.delay('-d', int(tau), '-m', 7, input=data) zs = ws[100000:, :] mins = numpy.empty(7, dtype=numpy.float64) maxs = numpy.empty(7, dtype=numpy.float64) for i in xrange(7): mins[i] = min(zs[:, i]) maxs[i] = max(zs[:, i]) print 'Mins: {0}'.format(mins) print 'Maxs: {0}'.format(maxs)
def pr4(file_prefix): """This is not the problem you are looking for.""" x0 = numpy.array([ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 21.5, 0, 0, -0.15, 0 ], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 8000) xs = xs.transpose() plot.render(xs[:,0], xs[:,1], 'b', xs[:,6], xs[:,7], 'r', xs[:,12], xs[:,13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title=r'3-body Orbital Interaction ($x_{14}=21.5$)', legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_4') )
def pr3(file_prefix): ic = lambda y: numpy.array([ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, y, 0, 0, -0.15, 0 ], dtype=numpy.float64) df = threebody(1.0, 0.5, 0.5, 0.5) for i in xrange(8): ts, xs = rungekutta.rk4(df, 0, ic(0.3*i + 20.0), 0.005, 8000) xs = xs.transpose() plot.render(xs[:,0], xs[:,1], 'b', xs[:,6], xs[:,7], 'r', xs[:,12], xs[:,13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title=r'3-body Orbital Interaction ($x_{14}=%.1f$)' % (0.3*i+20.0), legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_3{0}'.format(chr(97+i))) )
def pr4(file_prefix): """This is not the problem you are looking for.""" x0 = numpy.array( [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 21.5, 0, 0, -0.15, 0], dtype=numpy.float64) ts, xs = rungekutta.rk4(df, 0, x0, 0.005, 8000) xs = xs.transpose() plot.render(xs[:, 0], xs[:, 1], 'b', xs[:, 6], xs[:, 7], 'r', xs[:, 12], xs[:, 13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title=r'3-body Orbital Interaction ($x_{14}=21.5$)', legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_4'))
def pr6(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, vs = rungekutta.rk4(lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.001, 30000) xs = vs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual("-D", 1600, input=data) tau = first_min(ms) ws = tispy.delay("-d", int(tau), "-m", 7, input=data) col1 = 0 col2 = 5 plot.render( ws[:, col1], ws[:, col2], "k.", markersize=0.6, title=r"Delay Coordinate Embedding: {0}, $\tau={1}$ s".format(r"lorenz", 0.001 * tau), xlabel=r"$x(t+{0:.3f})$".format(col1 * 0.001 * tau), ylabel=r"$x(t+{0:.3f})$".format(col2 * 0.001 * tau), file_prefix=suffixed(file_prefix, "_6"), ) return tau
def plot_pfunc(pfunc, *args, **kwargs): ''' Convenience function for experimenting with pendulum functions. ''' opts, plot_args = split_dict(('tstep', 'theta0', 'omega0', 'nsteps'), kwargs) theta0 = opts.get('theta0', 3.0) omega0 = opts.get('omega0', 0.1) tstep = opts.get('tstep', 0.005) nsteps = opts.get('nsteps', 2000) _, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([theta0, omega0], dtype=numpy.float64), tstep, nsteps ) fix_domain = lambda x: mod2pi(x) if kwargs.get('mod2pi', False) else x xs[0,:] = numpy.array([ fix_domain(theta) for theta in xs[0,:] ], dtype=numpy.float64) render_plot(xs[0,:], xs[1,:], *args, **plot_args)
def pr6(file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, vs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.001, 30000) xs = vs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.mutual('-D', 1600, input=data) tau = first_min(ms) ws = tispy.delay('-d', int(tau), '-m', 7, input=data) col1 = 0 col2 = 5 plot.render(ws[:, col1], ws[:, col2], 'k.', markersize=0.6, title=r'Delay Coordinate Embedding: {0}, $\tau={1}$ s'.format( r'lorenz', 0.001 * tau), xlabel=r'$x(t+{0:.3f})$'.format(col1 * 0.001 * tau), ylabel=r'$x(t+{0:.3f})$'.format(col2 * 0.001 * tau), file_prefix=suffixed(file_prefix, '_6')) return tau
def ctc(): # INITIAL CONDITIONS lam0 = 10 mod = -1 t0, x0, u1_0 = 0, 80, 0 u0_0, u1_0 = tools.get_initial_cond(t0, x0, -1, u1=u1_0, sign="minus") #print(u1_1/u0_1) y0 = [u0_0, u1_0, t0, x0] y, true_y, lam, step, err = rk.rk4(fun_rk_ctc, y0, x0=lam0, num=4000, h_start=0.02, h_max=10**1, h_min=10**-7, h_max_change=1.5, acc=10**-9, experimental=True) fig, ax = plt.subplots(figsize=(11, 9)) # PLOTTING mpt = plotting.Plotter(fig, ax, A, R, ALPHA) # Plot circles defining the bubble boundary mpt.plot_bubble() # Plot trajectory and related stuff mpt.plot_trajectory(y, lam, step, err, colormap="local_speed", colorbar="plot", solid=True, nature="ctc", width=5)
def pr3(file_prefix): ic = lambda y: numpy.array( [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, y, 0, 0, -0.15, 0], dtype=numpy.float64) df = threebody(1.0, 0.5, 0.5, 0.5) for i in xrange(8): ts, xs = rungekutta.rk4(df, 0, ic(0.3 * i + 20.0), 0.005, 8000) xs = xs.transpose() plot.render(xs[:, 0], xs[:, 1], 'b', xs[:, 6], xs[:, 7], 'r', xs[:, 12], xs[:, 13], 'g', xlabel='x (normalized AU)', ylabel='y (normalized AU)', title=r'3-body Orbital Interaction ($x_{14}=%.1f$)' % (0.3 * i + 20.0), legend=('Star A', 'Star B', 'Star C'), file_prefix=suffixed(file_prefix, '_3{0}'.format(chr(97 + i))))
def pr6x1(tau, file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, vs = rungekutta.rk4(lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.001, 30000) xs = vs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.lyap_k("-d", int(tau), "-m", 7, "-M", 7, input=data) pargs = cut(ms[:, 0], ms[:, 1]) total = 0.0 count = len(pargs) / 2 for i in xrange(0, len(pargs), 2): xs = 0.31 * pargs[i][:50] ys = pargs[i + 1][:50] ps = numpy.polyfit(xs, ys, 1) total += ps[0] print "Lorenz lyapunov exponent: {0}".format(total / count) plot.render( *pargs, xlabel="Iterations", ylabel="Logarithm of the Stretching Factor", title="Calculating the Lyapunov Exponent", file_prefix=suffixed(file_prefix, "_7") )
def pr6x1(tau, file_prefix=None): lfunc = lorenz.lorenz(16, 45, 4) ts, vs = rungekutta.rk4( lfunc, 0.0, numpy.array([-13.0, -12.0, 52.0], dtype=numpy.float64), 0.001, 30000) xs = vs.transpose()[:, 0] data = numpy.array(zip(xs, ts), dtype=numpy.float64) ms = tispy.lyap_k('-d', int(tau), '-m', 7, '-M', 7, input=data) pargs = cut(ms[:, 0], ms[:, 1]) total = 0.0 count = len(pargs) / 2 for i in xrange(0, len(pargs), 2): xs = 0.31 * pargs[i][:50] ys = pargs[i + 1][:50] ps = numpy.polyfit(xs, ys, 1) total += ps[0] print 'Lorenz lyapunov exponent: {0}'.format(total / count) plot.render(*pargs, xlabel='Iterations', ylabel='Logarithm of the Stretching Factor', title='Calculating the Lyapunov Exponent', file_prefix=suffixed(file_prefix, '_7'))
def pr1a(file_prefix): pfunc = pendulum.pendulum(0.1, 0.1, 0) ts, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([0.01, 0.0], dtype=numpy.float64), 0.005, 80000 ) points = xs.transpose() ps = poincare.section(ts, points, interval=0.6346975625940523) plot.render( ps[:,0], ps[:,1], 'k.', xbound=(-0.015, 0.015), ybound=(-0.15, 0.15), xlabel=r'$\theta$', ylabel=r'$\omega$', markersize=0.6, title='Poincare Section (Natural Frequency)', file_prefix=_suffixed(file_prefix, '_1a') ) return ts, points
def main(argv=None): if argv is None: argv = sys.argv file_prefix = None try: options, args = getopt.getopt(argv[1:], 'f:') for opt, arg in options: if opt == '-f': file_prefix = arg except getopt.GetoptError as err: print str(err) return 2 suffixed = lambda s, suf: None if s is None else '{0}{1}'.format(s, suf) pfunc = pendulum(0.1, 0.1, 0) ts, xs = rungekutta.rk4( pfunc, 0.0, numpy.array([3.0, 0.1], dtype=numpy.float64), 0.005, 2000 ) render_plot(xs[0,:], xs[1,:], title='Undriven, Undamped Pendulum', file_prefix=suffixed(file_prefix, '_2a'), xlabel=r'$\theta$', ylabel=r'$\omega$' ) ts1, xs1 = rungekutta.rk4( pfunc, 0.0, numpy.array([0.01, 0.0], dtype=numpy.float64), 0.005, 2000 ) render_plot(xs1[0,:], xs1[1,:], title='Undriven, Undamped Pendulum', file_prefix=suffixed(file_prefix, '_2b'), xlabel=r'$\theta$', ylabel=r'$\omega$' ) make_phase_portrait( pfunc, 'b', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0)$', file_prefix=suffixed(file_prefix, '_3') ) pfunc2 = pendulum(0.1, 0.1, 0.25) make_phase_portrait( pfunc2, 'b', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0.25)$', file_prefix=suffixed(file_prefix, '_4') ) make_phase_portrait_mod2pi( pfunc2, 'b.', title=r'Phase Portrait ($m=0.1, l=0.1, \beta=0.25)$ Mod $2\pi$', file_prefix=suffixed(file_prefix, '_5'), markersize=0.6 ) return 0
t = np.zeros(N) x = np.zeros(N) v = np.zeros(N) KE = np.zeros(N) ##kinetic energy PE = np.zeros(N) ##potential energy E_total = np.zeros(N) x_an = np.zeros(N) v_an = np.zeros(N) err = 10**-8 y = np.zeros(2) y[0] = x_0 for i in range(0, N): t[i] = i * h + h y = rungekutta.rk4(t[i], y, h, f) x[i] = y[0] v[i] = y[1] KE[i] = 0.5 * m * y[1]**2 ##used to track kinetic energy for the assignment PE[i] = 0.5 * k * y[ 0]**2 ##used to track potential energy for the assignment E_total[i] = KE[i] + PE[i] x_an[i] = x_0 * np.cos( 2 * np.pi * t[i]) ## analytical solution for position v_an[i] = -x_0 * 2 * np.pi * np.sin( 2 * np.pi * t[i]) ## analytical solution for velocity ## if (np.abs(x_an[i] - x[i])/x_an[i] >= err): ## print("The difference between the analytical and numerical solutions for position is too large") ## break ## elif (np.abs(x_an[i] - x[i])/x_an[i] < err):
def sweep(t_range, x_range, steps, num, modulus, u1=np.inf, three_velocity=np.inf, radius=None, angle_range=None, sign="minus", nature="geodesic", plotter=None): # The initial parameter is chosen to be != 0 to avoid strange integration errors due to very small numbers. lam0 = 10 div = steps - 1 if steps != 1 else 1 if not radius: t_step = (t_range[1] - t_range[0]) / div x_step = (x_range[1] - x_range[0]) / div else: angle_step = (angle_range[1] - angle_range[0]) / div if plotter: fig, ax = plotter.fig, plotter.ax else: fig, ax = plt.subplots(figsize=(11, 9)) fun = fun_rk if nature == "geodesic" else fun_rk_ctc # Store all the integrations solutions = [] for i in range(steps): print(i) if not radius: t0 = t_range[0] + t_step * i x0 = x_range[0] + x_step * i else: t0 = radius * np.sin(angle_range[0] + angle_step * i) x0 = radius * np.cos(angle_range[0] + angle_step * i) if u1 != np.inf: u0_0, u1_0 = tools.get_initial_cond(t0, x0, modulus, u1=u1, sign=sign) else: u0_0, u1_0 = tools.get_initial_cond(t0, x0, modulus, three_velocity=three_velocity, sign=sign) y0 = [u0_0, u1_0, t0, x0] y, true_y, lam, step, err = rk.rk4(fun, y0, x0=lam0, num=num, h_start=0.02, h_max=10**1, h_min=10**-10, h_max_change=1.5, acc=10**-9, experimental=True, cutoff=False) solutions.append((y, true_y, lam, step, err)) # PLOTTING if plotter: mpt = plotter else: mpt = plotting.Plotter(fig, ax, A, R, ALPHA) # Plot circles defining the bubble boundary if not mpt.has_bubble: mpt.plot_bubble() # Plot trajectory and related stuff #colormap=[0,0,1,1,1] for sol in solutions: y, true_y, lam, step, err = sol mpt.plot_trajectory(true_y, lam, step, err, colormap=[0, 1, 1, 0, 1], limits=[0, 4], colorbar="once", solid=True, width=2, nature=nature)