def create_N_vs_t(filename, N_list=None): """ Iteratively runs run_hydrodynamics for several N in order to create the data for the N vs. wallclock-time plot. Writes data to hdf5 file.""" if N_list: N = N_list else: a = range(100,1000,100) b = range(1000,10000,1000) N = a+b total_runtimes = AdaptingVectorQuantity() for nr_particles in N: start_time = time.time() |units.s run_hydrodynamics(N=nr_particles, n_steps=1) end_time = time.time() |units.s total_runtime = end_time - start_time total_runtimes.append(total_runtime) N_as_vq = N | units.no_unit data = {'N':N_as_vq, 'runtimes':total_runtimes} results = HydroResults(data) write_to_hdf5('hydroresults/'+filename,\ results.__dict__) pngfilename = options.N_vs_t.split('.')[0]+'.png' plot_steptimes(results, filepath = "plots/"+pngfilename)
def create_N_vs_t(filename, N_list=None): """ Iteratively runs run_hydrodynamics for several N in order to create the data for the N vs. wallclock-time plot. Writes data to hdf5 file.""" if N_list: N = N_list else: a = range(100, 1000, 100) b = range(1000, 10000, 1000) N = a + b total_runtimes = AdaptingVectorQuantity() for nr_particles in N: start_time = time.time() | units.s run_hydrodynamics(N=nr_particles, n_steps=1) end_time = time.time() | units.s total_runtime = end_time - start_time total_runtimes.append(total_runtime) N_as_vq = N | units.no_unit data = {'N': N_as_vq, 'runtimes': total_runtimes} results = HydroResults(data) write_to_hdf5('hydroresults/'+filename,\ results.__dict__) pngfilename = options.N_vs_t.split('.')[0] + '.png' plot_steptimes(results, filepath="plots/" + pngfilename)
def create_N_vs_E(filename, N_list=None): """ Iteratively runs run_hydrodynamics for several N in order to create the data for the N vs. Energy error plot. Writes data to hdf5 file.""" if N_list: N = N_list else: N = range(100, 1000, 50) energy_errors = AdaptingVectorQuantity() for nr_particles in N: results = run_hydrodynamics(N=nr_particles, n_steps=50) energy_begin = results.total_energy[0] energy_end = results.total_energy[-1] energy_error = (energy_begin - energy_end) / energy_end energy_error = energy_error | units.no_unit energy_errors.append(energy_error) N_as_vq = N | units.no_unit data = {'N': N_as_vq, 'energy_errors': energy_errors} results = HydroResults(data) write_to_hdf5('hydroresults/'+filename,\ results.__dict__) pngfilename = options.N_vs_E.split('.')[0] + '.png' plot_energy(results, filepath="plots/" + pngfilename)
def create_N_vs_E(filename, N_list = None): """ Iteratively runs run_hydrodynamics for several N in order to create the data for the N vs. Energy error plot. Writes data to hdf5 file.""" if N_list: N = N_list else: N = range(100, 1000, 50) energy_errors = AdaptingVectorQuantity() for nr_particles in N: results = run_hydrodynamics(N=nr_particles, n_steps=50) energy_begin = results.total_energy[0] energy_end = results.total_energy[-1] energy_error = (energy_begin-energy_end)/energy_end energy_error = energy_error |units.no_unit energy_errors.append(energy_error) N_as_vq = N | units.no_unit data = {'N':N_as_vq, 'energy_errors':energy_errors} results = HydroResults(data) write_to_hdf5('hydroresults/'+filename,\ results.__dict__) pngfilename = options.N_vs_E.split('.')[0]+'.png' plot_energy(results, filepath = "plots/"+pngfilename)
def get_potential_at_point(self,radius,x,y,z): part=Particles(0) for s in self.systems: part.add_particles(s.particles) phi=AdaptingVectorQuantity() for rr,xx,yy,zz in zip(radius,x,y,z): dr2=((part.x-xx)**2+(part.y-yy)**2+(part.z-zz)**2+rr**2+part.radius**2) phi.append( (-self.G*part.mass/dr2**0.5).sum() ) return phi
def get_gravity_at_point(self, pos): phi_0 = self.get_potential_at_point(pos) grav = AdaptingVectorQuantity() dpos = 0.001*pos.length() for ii in range(len(pos)): ppos = 1.0*pos ppos[ii] += dpos phi_1 = self.get_potential_at_point(ppos) grav.append((phi_1 - phi_0)/dpos) return grav
def get_gravity_at_point(self, pos): phi_0 = self.get_potential_at_point(pos) grav = AdaptingVectorQuantity() dpos = 0.001 * pos.length() for ii in range(len(pos)): ppos = 1.0 * pos ppos[ii] += dpos phi_1 = self.get_potential_at_point(ppos) grav.append((phi_1 - phi_0) / dpos) return grav
def run_pyth(te=100): dt = 0.01 | nbody_system.time t_end = te | nbody_system.time code = ph4() code.parameters.timestep_parameter = dt.value_in(nbody_system.time) code.particles.add_particles(new_particles()) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() t = 0. | nbody_system.time eccents_12 = [] eccents_23 = [] eccents_31 = [] semmajaxs_12 = [] semmajaxs_23 = [] semmajaxs_31 = [] times = [] while(t < t_end-dt/2): t=t+dt code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) mass1, mass2, semimajor_axis_12, eccentricity_12, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[0], code.particles[1]]) mass2, mass3, semimajor_axis_23, eccentricity_23, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[1], code.particles[2]]) mass3, mass1, semimajor_axis_31, eccentricity_31, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary([code.particles[2], code.particles[0]]) eccents_12.append(eccentricity_12) eccents_23.append(eccentricity_23) eccents_31.append(eccentricity_31) semmajaxs_12.append(semimajor_axis_12.value_in(nbody_system.length)) semmajaxs_23.append(semimajor_axis_23.value_in(nbody_system.length)) semmajaxs_31.append(semimajor_axis_31.value_in(nbody_system.length)) times.append(t.value_in(nbody_system.time)) code.stop() return x,y,times,semmajaxs_12,semmajaxs_23,semmajaxs_31,eccents_12,eccents_23,eccents_31
def run_pyth(interface, tend=100, dt=0.125, parameters=[]): code = interface() for name, value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(new_particles()) code.commit_particles() x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() t = 0. | nbody_system.time while(t < tend-dt/2): t = t+dt code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) code.stop() return x, y
def run_pyth(interface, tend=100, dt=0.125, parameters=[]): code = interface() for name, value in parameters: setattr(code.parameters, name, value) code.particles.add_particles(new_particles()) code.commit_particles() x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() t = 0. | nbody_system.time while (t < tend - dt / 2): t = t + dt code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) code.stop() return x, y
def run_pyth(interface,tend=100,dt=0.125, label=""): code = interface() code.parameters.timestep_parameter = dt.value_in(nbody_system.time) code.particles.add_particles(new_particles()) Ekin = code.kinetic_energy Epot = code.potential_energy Einit = Ekin + Epot Energy = [Einit.value_in(nbody_system.energy)] x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() t = 0. | nbody_system.time Times = [t.value_in(nbody_system.time)] while(t < tend-dt/2): t=t+dt code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) Ekin = code.kinetic_energy Epot = code.potential_energy Etot = Ekin + Epot Energy.append(Etot.value_in(nbody_system.energy)) Times.append(t.value_in(nbody_system.time)) code.stop() return x,y,Times,Energy
def get_gravity_at_point(self,radius,x,y,z): part=Particles(0) for s in self.systems: part.add_particles(s.particles) ax=AdaptingVectorQuantity() ay=AdaptingVectorQuantity() az=AdaptingVectorQuantity() for rr,xx,yy,zz in zip(radius,x,y,z): dr2=((part.x-xx)**2+(part.y-yy)**2+(part.z-zz)**2+rr**2+part.radius**2) ax.append( (self.G*part.mass*(part.x-xx)/dr2**1.5).sum() ) ay.append( (self.G*part.mass*(part.y-yy)/dr2**1.5).sum() ) az.append( (self.G*part.mass*(part.z-zz)/dr2**1.5).sum() ) return ax,ay,az
def aggregate_mass(self,too_close): corrected_masses = AdaptingVectorQuantity() corrected_positions = AdaptingVectorQuantity() corrected_velocities = AdaptingVectorQuantity() corrected_angular_momenta = AdaptingVectorQuantity() for subset, m, pos, vel, Lin in zip(too_close, self.mass, self.position, self.velocity, self.angular_momentum): if len(subset): total_mass = subset.total_mass() + m cmpos=(m*pos + subset.total_mass()*subset.center_of_mass())/total_mass cmvel=(m*vel + subset.total_mass()*subset.center_of_mass_velocity())/total_mass L=Lin+angular_momentum(m,pos-cmpos,vel-cmvel)+angular_momentum(subset.mass,subset.position-cmpos,subset.velocity-cmvel).sum(axis=0) corrected_masses.append(total_mass) corrected_positions.append(cmpos) corrected_velocities.append(cmvel) corrected_angular_momenta.append(L) else: corrected_masses.append(m) corrected_positions.append(pos) corrected_velocities.append(vel) corrected_angular_momenta.append(Lin) self.mass = corrected_masses self.position = corrected_positions self.velocity = corrected_velocities self.angular_momentum = corrected_angular_momenta
def calculate_escape_time(index, number_of_systems): numpy.random.seed() # from amuse.community.smallN.muse_dynamics_mpi import SmallN print "start of subprocess", index x0 = AdaptingVectorQuantity() y0 = AdaptingVectorQuantity() x1 = AdaptingVectorQuantity() y1 = AdaptingVectorQuantity() x2 = AdaptingVectorQuantity() y2 = AdaptingVectorQuantity() m0 = AdaptingVectorQuantity() m1 = AdaptingVectorQuantity() m2 = AdaptingVectorQuantity() tends = AdaptingVectorQuantity() try: for x in range(number_of_systems): gravity = Hermite() particles = new_initial_system() code = SimulateTripleSystemUntilDecay(gravity, particles, index, x) tend = code.evolve_model_until_escape() print index, x, tend code.stop() x0.append(particles[0].x) y0.append(particles[0].y) x1.append(particles[1].x) y1.append(particles[1].y) x2.append(particles[2].x) y2.append(particles[2].y) m0.append(particles[0].mass) m1.append(particles[1].mass) m2.append(particles[2].mass) tends.append(tend) except KeyboardInterrupt: pass print "end of subprocess", index return x0, y0, x1, y1, x2, y2, m0, m1, m2, tends
print "doing statistics" sorted_times = data[-1].sorted() t = 0 | nbody_system.time tend = 1000 | nbody_system.time dt = 1 | nbody_system.time while t < tend: i = 0 while i < len(sorted_times): tn = sorted_times[i] i += 1 if tn < t: continue else: break times.append(t) counts.append((len(sorted_times) - i) | units.none) t += dt output = text.CsvFileText( filename="triple_statistics_{0:03}.csv".format(rank)) output.quantities = (times, counts) output.attribute_names = ("t", "n(t)") output.store() print "done" """ set logscale xy """
def main(): dots = Dots() line = Line() f = h5py.File(args.filename, 'r') fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) for intr in f.values(): timesteps_vq = AdaptingVectorQuantity() final_smas_p0_vq = AdaptingVectorQuantity() final_smas_p1_vq = AdaptingVectorQuantity() for sim in intr.values(): timesteps_vq.append(sim['timestep'][0] | retrieve_unit(sim['timestep'])) final_smas_p0_vq.append(sim['p0/sma'][-1]| retrieve_unit(sim['p0/sma'])) final_smas_p1_vq.append(sim['p1/sma'][-1]| retrieve_unit(sim['p1/sma'])) timesteps = timesteps_vq.value_in(units.yr) final_smas_p0 = final_smas_p0_vq.value_in(units.AU) final_smas_p1 = final_smas_p1_vq.value_in(units.AU) ax1.plot(timesteps, final_smas_p0, marker='o', label=intr.name, picker=5) ax2.plot(timesteps, final_smas_p1, marker='o', label=intr.name, picker=5) ax1.set_xlabel('Mass update interval [yr]') ax2.set_xlabel('Mass update interval [yr]') ax1.set_ylabel('final sma inner [AU]') ax2.set_ylabel('final sma outer [AU]') dset = f.values()[0].values()[0] #first dset available time = quantify_dset(dset['time']).value_in(units.yr) mass = quantify_dset(dset['mass']).value_in(units.MSun) inner_sma0 = quantify_dset(dset['p0/sma']).value_in(units.AU) outer_sma0 = quantify_dset(dset['p1/sma']).value_in(units.AU) inner_sma_final_adiabatic_approx = sma_analytical(inner_sma0[0], 1.244e-5, time[-1], mass[0].sum() ) outer_sma_final_adiabatic_approx = sma_analytical(outer_sma0[0], 1.244e-5, time[-1], mass[0].sum() ) ax1.axhline(inner_sma_final_adiabatic_approx, xmin=0, xmax=1, c='m', label='adiabatic approx') ax1.legend(loc='best') ax2.axhline(outer_sma_final_adiabatic_approx, xmin=0, xmax=1, c='m', label='adiabatic approx') ax2.legend(loc='best') if args.logscale: ax1.set_xscale('log') ax2.set_xscale('log') if args.ylim1: ax1.set_ylim(args.ylim1) if args.ylim2: ax2.set_ylim(args.ylim2) if args.xlim1: ax1.set_xlim(args.xlim1) if args.xlim2: ax2.set_xlim(args.xlim2) def onpick(event): print("artist:{} ind:{}".format(event.artist, event.ind)) print("button: {}".format(event.mouseevent.button)) intr = f[event.artist.get_label()] sim = intr.values()[event.ind] time_vq = quantify_dset(sim['time']) time = time_vq.value_in(units.yr) position_vq = quantify_dset(sim['position']) position = position_vq.value_in(units.AU) CM_position_vq = quantify_dset(sim['CM_position']) CM_position = CM_position_vq.value_in(units.AU) x, y = 0, 1 central_x, central_y = position[:, 0, x] - CM_position[:,x], position[:, 0, y] - CM_position[:,y] inner_x, inner_y = position[:, 1, x] - CM_position[:,x], position[:, 1, y] - CM_position[:,y] outer_x, outer_y = position[:, 2, x] - CM_position[:,x], position[:, 2, y] - CM_position[:,y] mass_vq = quantify_dset(sim['mass']) mass = mass_vq[:,0].value_in(units.MSun) if event.mouseevent.button == 1: mu0 = quantify_dset(sim['mass'])[0].sum() period_vq = quantify_dset(sim['p0/period']) period = period_vq.value_in(units.yr) true_anomaly = sim['p0/true_anomaly'].value argument_of_periapsis = sim['p0/argument_of_periapsis'].value sma_vq = quantify_dset(sim['p0/sma']) sma = sma_vq.value_in(units.AU) sma_an_vq = sma_analytical(sma_vq[0], 1.244e-5|(units.MSun/units.yr), time_vq, mu0) sma_an = sma_an_vq.value_in(units.AU) eccentricity = sim['p0/eccentricity'].value newfig = plt.figure() newax1 = newfig.add_subplot(511) newax2 = newfig.add_subplot(512) newax3 = newfig.add_subplot(513) newax4 = newfig.add_subplot(514) newax5 = newfig.add_subplot(515) newax1.plot(time, sma, label='numerical') newax1.plot(time, sma_an, label='analytical_adiabatic') newax1.set_xlabel('time [yr]') newax1.set_ylabel('sma [AU]') newax1.legend(loc='best') newax2.plot(time, eccentricity) newax2.set_xlabel('time [yr]') newax2.set_ylabel('eccentricity ') newax3.plot(time, true_anomaly) newax3.set_xlabel('time [yr]') newax3.set_ylabel('true anomaly [degrees] ') newax4.plot(time, argument_of_periapsis) newax4.set_xlabel('time [yr]') newax4.set_ylabel('argument of periapsis [degrees] ') newax5.plot(time, period) newax5.set_xlabel('time [yr]') newax5.set_ylabel('period') else: newfig = plt.figure() newax1 = newfig.add_subplot(321) newax2 = newfig.add_subplot(322) newax3 = newfig.add_subplot(323) newax4 = newfig.add_subplot(324) newax5 = newfig.add_subplot(325) newax6 = newfig.add_subplot(326) mass_vq = quantify_dset(sim['mass']) mass = mass_vq.value_in(units.MSun) kinetic_energy = sim['kinetic_energy'].value potential_energy = sim['potential_energy'].value total_energy = sim['total_energy'].value CM_velocity_vq = quantify_dset(sim['CM_velocity']) CM_velocity_mod = CM_velocity_vq.lengths().value_in(units.km/units.hour) walltime = sim['walltime'].value - sim['walltime'][0] newax1.plot(time, mass) newax1.set_ylabel('central mass [MSun]') newax1.set_xlabel('time [yr]') newax2.plot(time, kinetic_energy, label='kinetic', **line.red) newax2.plot(time, potential_energy,label='potential', **line.orange) newax2.plot(time, total_energy, label='total', **line.white) newax2.set_xlabel('time [yr]') newax2.legend() newax3.plot(central_x, central_y, **dots.white) newax3.plot(inner_x, inner_y, **dots.red) newax3.plot(outer_x, outer_y, **dots.yellow) newax3.set_xlabel('x [AU]') newax3.set_ylabel('y [AU]') newax4.plot(CM_position[:, x], CM_position[:, y] ) newax4.set_xlim(-5, 5) newax4.set_xlabel('CM position x [AU]') newax4.set_ylabel('CM position y [AU]') newax5.plot(time, CM_velocity_mod) newax5.set_ylim(20, 30) newax5.set_xlabel('time [yr]') newax5.set_ylabel('CM velocity [km/hour]') newax6.plot(time, walltime) newax6.set_xlabel('time [yr]') newax6.set_ylabel('walltime [s]') newfig.show() fig.canvas.mpl_connect('pick_event', onpick) plt.show()
def calculate_escape_time(index, number_of_systems): numpy.random.seed() # from amuse.community.smallN.muse_dynamics_mpi import SmallN print "start of subprocess", index x0 = AdaptingVectorQuantity() y0 = AdaptingVectorQuantity() x1 = AdaptingVectorQuantity() y1 = AdaptingVectorQuantity() x2 = AdaptingVectorQuantity() y2 = AdaptingVectorQuantity() m0 = AdaptingVectorQuantity() m1 = AdaptingVectorQuantity() m2 = AdaptingVectorQuantity() tends = AdaptingVectorQuantity() try: for x in range(number_of_systems): gravity = Hermite() particles = new_initial_system() code = SimulateTripleSystemUntilDecay(gravity, particles, index, x) tend = code.evolve_model_until_escape() print index, x, tend code.stop() x0.append(particles[0].x) y0.append(particles[0].y) x1.append(particles[1].x) y1.append(particles[1].y) x2.append(particles[2].x) y2.append(particles[2].y) m0.append(particles[0].mass) m1.append(particles[1].mass) m2.append(particles[2].mass) tends.append(tend) except KeyboardInterrupt: pass print "end of subprocess", index return x0, y0, x1, y1, x2, y2, m0, m1, m2, tends
def evolve_gravity(bodies, number_of_planets, converter, t_end, n_steps, n_snapshots, path): #Particles that will be saved in the file bodies_to_save = Particles(number_of_planets+2) #Positions and velocities centered on the center of mass bodies.move_to_center() time = 0. | nbody_system.time dt = t_end / float(n_steps) dt_snapshots = t_end / float(n_snapshots) gravity = initialize_code(bodies, timestep_parameter = dt.value_in(nbody_system.time)) channel_from_gr_to_framework = gravity.particles.new_channel_to(bodies) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() times = AdaptingVectorQuantity() system_energies = AdaptingVectorQuantity() E_initial = gravity.kinetic_energy + gravity.potential_energy DeltaE_max = 0.0 | nbody_system.energy snapshot_number = 1 os.system('mkdir ./files/'+path) while time<=t_end: gravity.evolve_model(time) channel_from_gr_to_framework.copy() bodies.collection_attributes.timestamp = time gravity.particles.collection_attributes.timestamp = time x.append(bodies.x) y.append(bodies.y) times.append(time) E = gravity.kinetic_energy + gravity.potential_energy system_energies.append(E) DeltaE = abs(E-E_initial) if ( DeltaE > DeltaE_max ): DeltaE_max = DeltaE #Orbital Elements star = bodies[0] ffp = bodies[1] bp = bodies[2] #Star and FFP binary = [star, ffp] m1, m2, sma_star_ffp, e_star_ffp = my_orbital_elements_from_binary(binary) bodies[1].eccentricity = e_star_ffp bodies[1].semimajoraxis = sma_star_ffp #Star and BP binary = [star, bp] m1, m2, sma_star_bp, e_star_bp = my_orbital_elements_from_binary(binary) bodies[2].eccentricity = e_star_bp bodies[2].semimajoraxis = sma_star_bp save_particles_to_file(bodies, bodies_to_save, './files/'+path+'/'+str(snapshot_number)+'.hdf5', time, converter) # if (snapshot_number == 5): # break time += dt_snapshots snapshot_number += 1 #To get last orbital elements #Star and FFP binary = [star, ffp] b1_mass1, b1_mass2, b1_semimajor_axis, b1_eccentricity, b1_true_anomaly, b1_inclination, b1_long_asc_node, b1_arg_per = orbital_elements_from_binary(binary) #Star and BP binary = [star, bp] b2_mass1, b2_mass2, b2_semimajor_axis, b2_eccentricity, b2_true_anomaly, b2_inclination, b2_long_asc_node, b2_arg_per = orbital_elements_from_binary(binary) #To check Hill stability #Star+BP and FFP cm_x = (star.mass*star.x + bp.mass*bp.x)/(star.mass+bp.mass) cm_y = (star.mass*star.y + bp.mass*bp.y)/(star.mass+bp.mass) cm_vx = (star.mass*star.vx + bp.mass*bp.vx)/(star.mass+bp.mass) cm_vy = (star.mass*star.vy + bp.mass*bp.vy)/(star.mass+bp.mass) star_bp = Particles(1) star_bp.mass = star.mass + bp.mass star_bp.position = [cm_x, cm_y, 0.0 | nbody_system.length] star_bp.velocity = [cm_vx, cm_vy, 0.0 | nbody_system.speed] binary = [star_bp[0], ffp] m1, m2, sma_starbp_ffp, e_starbp_ffp = my_orbital_elements_from_binary(binary) bodies[1].eccentricity = e_starbp_ffp bodies[1].semimajoraxis = sma_starbp_ffp max_energy_change = DeltaE_max/E_initial is_stable = is_hill_stable(bodies.mass, bodies.semimajoraxis, bodies.eccentricity, converter) gravity.stop() return x, y, times, system_energies, max_energy_change, is_stable,converter.to_si(b1_semimajor_axis).value_in(units.AU), b1_eccentricity, b1_true_anomaly, b1_inclination, b1_long_asc_node, b1_arg_per, converter.to_si(b2_semimajor_axis).value_in(units.AU), b2_eccentricity, b2_true_anomaly, b2_inclination, b2_long_asc_node, b2_arg_per
def evolve_gravity(bodies, number_of_planets, converter, t_end, n_steps): #Positions and velocities centered on the center of mass bodies.move_to_center() time = 0. | nbody_system.time dt = t_end / float(n_steps) gravity = initialize_code(bodies, timestep_parameter = dt.value_in(nbody_system.time)) channel_from_gr_to_framework = gravity.particles.new_channel_to(bodies) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() times = AdaptingVectorQuantity() #Order: 12, 23, 31 eccentricities = [] semimajoraxes = [] Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot = Etot_init DeltaE_max = 0.0 | nbody_system.energy times.append(time) system_energies = [Etot.value_in(nbody_system.energy)] while time<=t_end: gravity.evolve_model(time) channel_from_gr_to_framework.copy() bodies.collection_attributes.timestamp = time gravity.particles.collection_attributes.timestamp = time x.append(bodies.x) y.append(bodies.y) times.append(time) for i in range(0,number_of_planets+2): for j in range(i+1,number_of_planets+2): binary = [bodies[i], bodies[j]] massA, massB, semimajor_axis, eccentricity, true_anomaly, inclination, long_asc_node, arg_per = orbital_elements_from_binary(binary) eccentricities.append(eccentricity) semimajoraxes.append(semimajor_axis.value_in(nbody_system.length)) Etot = gravity.kinetic_energy + gravity.potential_energy DeltaE = abs(Etot-Etot_init) system_energies.append(Etot.value_in(nbody_system.energy)) if ( DeltaE > DeltaE_max ): DeltaE_max = DeltaE time += dt print "Energy Change: max(|E_j - E_initial|)/E_initial = ", DeltaE_max/Etot_init results = ['flyby', 'temporary capture', 'exchange','nothing'] #results = [0,1,2,-1] planets_star_energies = [] for i in range(0,number_of_planets): planet_star_energy = energies_binaries(bodies, 0, i+2).value_in(nbody_system.energy) planets_star_energies.append(planet_star_energy) planets_star_energy = sum(planets_star_energies) ffp_star_energy = energies_binaries(bodies, 0, 1).value_in(nbody_system.energy) if (planets_star_energy<0 and ffp_star_energy>0): res = results[0] elif (planets_star_energy<0 and ffp_star_energy<0): res = results[1] elif (planets_star_energy>0 and ffp_star_energy<0): res = results[2] else: #res = 'something that is not flyby, exchange or temporary capture has happened!' res = results[3] print res gravity.stop() return x,y,times,numpy.array(system_energies),numpy.array(eccentricities),numpy.array(semimajoraxes)
def aggregate_mass(self,too_close): corrected_masses = AdaptingVectorQuantity() corrected_positions = AdaptingVectorQuantity() corrected_velocities = AdaptingVectorQuantity() corrected_angular_momenta = AdaptingVectorQuantity() for subset, m, pos, vel, Lin in zip(too_close, self.mass, self.position, self.velocity, self.angular_momentum): if len(subset): total_mass = subset.total_mass() + m cmpos=(m*pos + subset.total_mass()*subset.center_of_mass())/total_mass cmvel=(m*vel + subset.total_mass()*subset.center_of_mass_velocity())/total_mass L=Lin+angular_momentum(m,pos-cmpos,vel-cmvel)+angular_momentum(subset.mass,subset.position-cmpos,subset.velocity-cmvel).sum(axis=0) corrected_masses.append(total_mass) corrected_positions.append(cmpos) corrected_velocities.append(cmvel) corrected_angular_momenta.append(L) else: corrected_masses.append(m) corrected_positions.append(pos) corrected_velocities.append(vel) corrected_angular_momenta.append(Lin) self.mass = corrected_masses self.position = corrected_positions self.velocity = corrected_velocities self.angular_momentum = corrected_angular_momenta
def main(): dots = Dots() line = Line() f = h5py.File(args.filename, 'r') fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) for intr in f.values(): etas = [] final_smas_p0_vq = AdaptingVectorQuantity() final_smas_p1_vq = AdaptingVectorQuantity() for sim in intr.values(): etas.append(sim['eta'][0]) final_smas_p0_vq.append(sim['p0/sma'][-1]| retrieve_unit(sim['p0/sma'])) final_smas_p1_vq.append(sim['p1/sma'][-1]| retrieve_unit(sim['p1/sma'])) final_smas_p0 = final_smas_p0_vq.value_in(units.AU) final_smas_p1 = final_smas_p1_vq.value_in(units.AU) ax1.plot(etas, final_smas_p0, marker='o', label=intr.name, picker=5) ax2.plot(etas, final_smas_p1, marker='o', label=intr.name, picker=5) ax1.set_xlabel('eta') ax2.set_xlabel('eta') ax1.set_ylabel('final sma inner [AU]') ax2.set_ylabel('final sma outer [AU]') dset = f.values()[0].values()[0] #first dset available time = quantify_dset(dset['time']).value_in(units.yr) mass = quantify_dset(dset['mass']).value_in(units.MSun) inner_sma0 = quantify_dset(dset['p0/sma']).value_in(units.AU) outer_sma0 = quantify_dset(dset['p1/sma']).value_in(units.AU) inner_sma_final_adiabatic_approx = sma_analytical(inner_sma0[0], 1.244e-5, time[-1], mass[0].sum() ) outer_sma_final_adiabatic_approx = sma_analytical(outer_sma0[0], 1.244e-5, time[-1], mass[0].sum() ) ax1.axhline(inner_sma_final_adiabatic_approx, xmin=0, xmax=1, c='m', label='adiabatic approx') ax1.legend(loc='best') ax2.axhline(outer_sma_final_adiabatic_approx, xmin=0, xmax=1, c='m', label='adiabatic approx') ax2.legend(loc='best') if args.logscale: ax1.set_xscale('log') ax2.set_xscale('log') if args.ylim1: ax1.set_ylim(args.ylim1) if args.ylim2: ax2.set_ylim(args.ylim2) if args.xlim1: ax1.set_xlim(args.xlim1) if args.xlim2: ax2.set_xlim(args.xlim2) def onpick(event): print("artist:{} ind:{}".format(event.artist, event.ind)) print("button: {}".format(event.mouseevent.button)) intr = f[event.artist.get_label()] sim = intr.values()[event.ind] time_vq = quantify_dset(sim['time']) time = time_vq.value_in(units.yr) position_vq = quantify_dset(sim['position']) position = position_vq.value_in(units.AU) CM_position_vq = quantify_dset(sim['CM_position']) CM_position = CM_position_vq.value_in(units.AU) x, y = 0, 1 central_x, central_y = position[:, 0, x] - CM_position[:,x], position[:, 0, y] - CM_position[:,y] inner_x, inner_y = position[:, 1, x] - CM_position[:,x], position[:, 1, y] - CM_position[:,y] outer_x, outer_y = position[:, 2, x] - CM_position[:,x], position[:, 2, y] - CM_position[:,y] mass_vq = quantify_dset(sim['mass']) mass = mass_vq[:,0].value_in(units.MSun) if event.mouseevent.button == 1: mu0 = quantify_dset(sim['mass'])[0].sum() period_vq = quantify_dset(sim['p0/period']) period = period_vq.value_in(units.yr) true_anomaly = sim['p0/true_anomaly'].value argument_of_periapsis = sim['p0/argument_of_periapsis'].value sma_vq = quantify_dset(sim['p0/sma']) sma = sma_vq.value_in(units.AU) sma_an_vq = sma_analytical(sma_vq[0], 1.244e-5|(units.MSun/units.yr), time_vq, mu0) sma_an = sma_an_vq.value_in(units.AU) eccentricity = sim['p0/eccentricity'].value newfig = plt.figure() newax1 = newfig.add_subplot(511) newax2 = newfig.add_subplot(512) newax3 = newfig.add_subplot(513) newax4 = newfig.add_subplot(514) newax5 = newfig.add_subplot(515) newax1.plot(time, sma, label='numerical') newax1.plot(time, sma_an, label='analytical_adiabatic') newax1.set_xlabel('time [yr]') newax1.set_ylabel('sma [AU]') newax1.legend(loc='best') newax2.plot(time, eccentricity) newax2.set_xlabel('time [yr]') newax2.set_ylabel('eccentricity ') newax3.plot(time, true_anomaly) newax3.set_xlabel('time [yr]') newax3.set_ylabel('true anomaly [degrees] ') newax4.plot(time, argument_of_periapsis) newax4.set_xlabel('time [yr]') newax4.set_ylabel('argument of periapsis [degrees] ') newax5.plot(time, period) newax5.set_xlabel('time [yr]') newax5.set_ylabel('period') else: newfig = plt.figure() newax1 = newfig.add_subplot(321) newax2 = newfig.add_subplot(322) newax3 = newfig.add_subplot(323) newax4 = newfig.add_subplot(324) newax5 = newfig.add_subplot(325) newax6 = newfig.add_subplot(326) mass_vq = quantify_dset(sim['mass']) mass = mass_vq.value_in(units.MSun) kinetic_energy = sim['kinetic_energy'].value potential_energy = sim['potential_energy'].value total_energy = sim['total_energy'].value CM_velocity_vq = quantify_dset(sim['CM_velocity']) CM_velocity_mod = CM_velocity_vq.lengths().value_in(units.km/units.hour) walltime = sim['walltime'].value - sim['walltime'][0] newax1.plot(time, mass) newax1.set_ylabel('central mass [MSun]') newax1.set_xlabel('time [yr]') newax2.plot(time, kinetic_energy, label='kinetic', **line.red) newax2.plot(time, potential_energy,label='potential', **line.orange) newax2.plot(time, total_energy, label='total', **line.white) newax2.set_xlabel('time [yr]') newax2.legend() newax3.plot(central_x, central_y, **dots.white) newax3.plot(inner_x, inner_y, **dots.red) newax3.plot(outer_x, outer_y, **dots.yellow) newax3.set_xlabel('x [AU]') newax3.set_ylabel('y [AU]') newax4.plot(CM_position[:, x], CM_position[:, y] ) newax4.set_xlim(-5, 5) newax4.set_xlabel('CM position x [AU]') newax4.set_ylabel('CM position y [AU]') newax5.plot(time, CM_velocity_mod) newax5.set_ylim(20, 30) newax5.set_xlabel('time [yr]') newax5.set_ylabel('CM velocity [km/hour]') newax6.plot(time, walltime) newax6.set_xlabel('time [yr]') newax6.set_ylabel('walltime [s]') newfig.show() fig.canvas.mpl_connect('pick_event', onpick) plt.show()
def test_run(): three=binary_with_planet( m1=0.6897 | units.MSun,m2=0.20255 | units.MSun,m_planet=0.333 | units.MJupiter, r1=0.6489 | units.RSun,r2=0.22623 | units.RSun,r_planet=0.754 | units.RJupiter, ecc_binary=0.15944,P_binary=41.08| units.day,ecc_planet=0.00685,a_planet=.7048 | units.AU, pangle_planet=0.) convert=nbody_system.nbody_to_si(1|units.MSun,1|units.AU) code=Huayno(convert) code.parameters.inttype_parameter=code.inttypes.SHARED4 code.parameters.timestep_parameter=0.1 # tend=100. | units.yr tend=100. | units.day snapfreq=1 dt=10. | units.day # dt=convert.to_si( 1. | nbody_system.time).in_(units.day) code.particles.add_particles(three) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() z = AdaptingVectorQuantity() vx = AdaptingVectorQuantity() vy = AdaptingVectorQuantity() vz = AdaptingVectorQuantity() x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) ts=[0.] E0=code.potential_energy+code.kinetic_energy dE=[1.e-14] t=0. | units.day i=0 while(t < tend-dt/2): i+=1 t=t+dt if i%snapfreq==0: print t ts.append(t.value_in(units.day)) code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) E=code.potential_energy+code.kinetic_energy dE.append(abs(((E-E0)/E0))) code.stop() a,eps,pangle=elements(three.total_mass(), x[:,2], y[:,2], z[:,2], vx[:,2], vy[:,2], vz[:,2]) x=x.value_in(units.AU) y=y.value_in(units.AU) a=a.value_in(units.AU) eps=eps print a[-1],eps[-1],pangle[-1] f=pyplot.figure(figsize=(8,8)) pyplot.plot(x[:,0],y[:,0],'r.') pyplot.plot(x[:,1],y[:,1],'g.') pyplot.plot(x[:,2],y[:,2],'b.') pyplot.xlim(-3,3) pyplot.ylim(-3,3) pyplot.xlabel('AU') pyplot.savefig('three_16b.eps') f=pyplot.figure(figsize=(8,8)) pyplot.semilogy(ts,dE,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('dE/E0') pyplot.savefig('three_16b_eerr.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,a,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('a (AU)') pyplot.savefig('three_16b_a.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,eps,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('eccentricity') pyplot.savefig('three_16b_ecc.eps') f=pyplot.figure(figsize=(8,8)) pyplot.plot(ts,pangle,'g.') pyplot.xlabel('time (day)') pyplot.ylabel('long. of periapsis') pyplot.savefig('three_16b_pangle.eps')
print "doing statistics" sorted_times = data[-1].sorted() t = 0 | nbody_system.time tend = 1000 | nbody_system.time dt = 1 | nbody_system.time while t < tend: i = 0 while i < len(sorted_times): tn = sorted_times[i] i += 1 if tn < t: continue else: break times.append(t) counts.append((len(sorted_times) - i) | units.none) t += dt output = text.CsvFileText( filename="triple_statistics_{0:03}.csv".format(rank)) output.quantities = (times, counts) output.attribute_names = ("t", "n(t)") output.store() print "done" """ set logscale xy """
def evolve_gravity(bodies, number_of_planets, converter, t_end, n_steps, n_snapshots, bodies_filename): #Particles that will be saved in the file bodies_to_save = Particles(number_of_planets+2) #Positions and velocities centered on the center of mass bodies.move_to_center() time = 0. | nbody_system.time dt = t_end / float(n_steps) dt_snapshots = t_end / float(n_snapshots) gravity = initialize_code(bodies, timestep_parameter = dt.value_in(nbody_system.time)) channel_from_gr_to_framework = gravity.particles.new_channel_to(bodies) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() times = AdaptingVectorQuantity() system_energies = AdaptingVectorQuantity() E_initial = gravity.kinetic_energy + gravity.potential_energy DeltaE_max = 0.0 | nbody_system.energy while time<=t_end: gravity.evolve_model(time) channel_from_gr_to_framework.copy() bodies.collection_attributes.timestamp = time gravity.particles.collection_attributes.timestamp = time x.append(bodies.x) y.append(bodies.y) times.append(time) star = bodies[0] ffp = bodies[1] bp = bodies[2] #Orbital elements for star and bounded_planet binary = [star, bp] m1, m2, sma, e, ta, i, lan, ap = orbital_elements_from_binary(binary) bodies[2].eccentricity = e bodies[2].semimajoraxis = sma #Orbital elements for star+bp and ffp cm_x = (star.mass*star.x + bp.mass*bp.x)/(star.mass+bp.mass) cm_y = (star.mass*star.y + bp.mass*bp.y)/(star.mass+bp.mass) cm_vx = (star.mass*star.vx + bp.mass*bp.vx)/(star.mass+bp.mass) cm_vy = (star.mass*star.vy + bp.mass*bp.vy)/(star.mass+bp.mass) star_bp = Particles(1) star_bp.mass = star.mass + bp.mass star_bp.position = [cm_x, cm_y, 0.0 | units.AU] star_bp.velocity = [cm_vx, cm_vy, 0.0 | units.kms] binary = [star_bp, ffp] m1, m2, sma, e, ta, i, lan, ap = orbital_elements_from_binary(binary) bodies[1].eccentricity = e bodies[1].semimajoraxis = sma print star.mass, bp.mass, ffp.mass print m1, m2 E = gravity.kinetic_energy + gravity.potential_energy system_energies.append(E) DeltaE = abs(E-E_initial) if ( DeltaE > DeltaE_max ): DeltaE_max = DeltaE save_particles_to_file(bodies, bodies_to_save, bodies_filename, time, converter) time += dt_snapshots max_energy_change = DeltaE_max/E_initial gravity.stop() return x,y,times,system_energies,max_energy_change
def test_run(): three = binary_with_planet(m1=0.6897 | units.MSun, m2=0.20255 | units.MSun, m_planet=0.333 | units.MJupiter, r1=0.6489 | units.RSun, r2=0.22623 | units.RSun, r_planet=0.754 | units.RJupiter, ecc_binary=0.15944, P_binary=41.08 | units.day, ecc_planet=0.00685, a_planet=.7048 | units.AU, pangle_planet=0.) convert = nbody_system.nbody_to_si(1 | units.MSun, 1 | units.AU) code = Huayno(convert) code.parameters.inttype_parameter = code.inttypes.SHARED4 code.parameters.timestep_parameter = 0.1 # tend=100. | units.yr tend = 100. | units.day snapfreq = 1 dt = 10. | units.day # dt=convert.to_si( 1. | nbody_system.time).in_(units.day) code.particles.add_particles(three) x = AdaptingVectorQuantity() y = AdaptingVectorQuantity() z = AdaptingVectorQuantity() vx = AdaptingVectorQuantity() vy = AdaptingVectorQuantity() vz = AdaptingVectorQuantity() x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) ts = [0.] E0 = code.potential_energy + code.kinetic_energy dE = [1.e-14] t = 0. | units.day i = 0 while (t < tend - dt / 2): i += 1 t = t + dt if i % snapfreq == 0: print t ts.append(t.value_in(units.day)) code.evolve_model(t) x.append(code.particles.x) y.append(code.particles.y) z.append(code.particles.z) vx.append(code.particles.vx) vy.append(code.particles.vy) vz.append(code.particles.vz) E = code.potential_energy + code.kinetic_energy dE.append(abs(((E - E0) / E0))) code.stop() a, eps, pangle = elements(three.total_mass(), x[:, 2], y[:, 2], z[:, 2], vx[:, 2], vy[:, 2], vz[:, 2]) x = x.value_in(units.AU) y = y.value_in(units.AU) a = a.value_in(units.AU) eps = eps print a[-1], eps[-1], pangle[-1] f = pyplot.figure(figsize=(8, 8)) pyplot.plot(x[:, 0], y[:, 0], 'r.') pyplot.plot(x[:, 1], y[:, 1], 'g.') pyplot.plot(x[:, 2], y[:, 2], 'b.') pyplot.xlim(-3, 3) pyplot.ylim(-3, 3) pyplot.xlabel('AU') pyplot.savefig('three_16b.eps') f = pyplot.figure(figsize=(8, 8)) pyplot.semilogy(ts, dE, 'g.') pyplot.xlabel('time (day)') pyplot.ylabel('dE/E0') pyplot.savefig('three_16b_eerr.eps') f = pyplot.figure(figsize=(8, 8)) pyplot.plot(ts, a, 'g.') pyplot.xlabel('time (day)') pyplot.ylabel('a (AU)') pyplot.savefig('three_16b_a.eps') f = pyplot.figure(figsize=(8, 8)) pyplot.plot(ts, eps, 'g.') pyplot.xlabel('time (day)') pyplot.ylabel('eccentricity') pyplot.savefig('three_16b_ecc.eps') f = pyplot.figure(figsize=(8, 8)) pyplot.plot(ts, pangle, 'g.') pyplot.xlabel('time (day)') pyplot.ylabel('long. of periapsis') pyplot.savefig('three_16b_pangle.eps')