repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
amuse
amuse-main/examples/applications/iliev_test5.py
""" Radiative transfer comparison test 5 (Iliev et al 2009). This example demonstrates the coupling of a radiative transfer code to a hydrodynamics code to do radiative hydrodynamic problems. Specifically it calculates the Iliev radiative trasnfer comparison project test 5 (expanding HII region in homogeneous medium) It is simplified somewhat in the sense that it uses the SimpleX without any multifrequency radiative transfer or thermal evolution. This is not a fundamental limitation (the method would work with full thermal evolution available). The coupling interface is with simple functions. Currently fi and simplex are hardcoded as base classes for SPH and radiative transfer. """ import numpy from amuse.units import units from amuse.units import nbody_system from amuse.units import constants from amuse.community.simplex.interface import SimpleX from amuse.community.fi.interface import Fi from amuse.ext.evrard_test import uniform_random_unit_cube, uniform_unit_sphere from amuse.io import write_set_to_file, read_set_from_file from amuse import datamodel try: # from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False """ These define the properties of the medium in front and behind the ionisation front (necessary because no thermal evolution). """ mu = 1. | units.amu muion = 0.5 | units.amu xtrans = 0.06 mutrans = mu/(1+xtrans) Tinit = 100. | units.K Ttrans = 13500. | units.K Tion = 13500. | units.K rhoinit = 0.001 | (units.amu / units.cm**3) uinit = constants.kB * Tinit/mu utrans = constants.kB * Ttrans/mutrans uion = constants.kB * Tion/muion mp = None def fake_internal_energy_from_xion(xion): """ this function fakes an internal energy from the ionisation (this is the main shortcut here) """ # return uinit+(uion-uinit)*xion u = uinit+(utrans-uinit)*xion/xtrans a = numpy.where(xion > xtrans)[0] u[a] = utrans+(uion-utrans)*(xion[a]-xtrans)/(1.-xtrans) return u def glass(N, target_rms=0.05): """ make glass for initial condition generation """ if target_rms < 0.001: print("warning: target_rms highly unlikely to succeed") L = 1 | nbody_system.length dt = 0.01 | nbody_system.time x, y, z = uniform_random_unit_cube(N).make_xyz() vx, vy, vz = uniform_unit_sphere(N).make_xyz() p = datamodel.Particles(N) p.x = L*x p.y = L*y p.z = L*z p.h_smooth = 0. * L p.vx = 0.1*vx | (nbody_system.speed) p.vy = 0.1*vy | (nbody_system.speed) p.vz = 0.1*vz | (nbody_system.speed) p.u = (0.1*0.1) | nbody_system.speed**2 p.mass = (8./N) | nbody_system.mass sph = Fi(use_gl=False, mode='periodic', redirection='none') sph.initialize_code() sph.parameters.use_hydro_flag = True sph.parameters.radiation_flag = False sph.parameters.self_gravity_flag = False sph.parameters.gamma = 1 sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.timestep = dt sph.parameters.verbosity = 0 sph.parameters.pboxsize = 2*L sph.parameters.artificial_viscosity_alpha = 1. sph.parameters.beta = 2. sph.commit_parameters() sph.gas_particles.add_particles(p) sph.commit_particles() # sph.start_viewer() t = 0. | nbody_system.time rms = 1. # i = 0 while rms > target_rms: t = t+(0.25 | nbody_system.time) sph.evolve_model(t) h = sph.particles.h_smooth.value_in(nbody_system.length) rho = h**(-3.) rms = rho.std()/rho.mean() print(rms, target_rms) x = sph.particles.x.value_in(nbody_system.length) y = sph.particles.y.value_in(nbody_system.length) z = sph.particles.z.value_in(nbody_system.length) sph.stop() return x, y, z def iliev_test_5_ic(N=10000, Ns=10, L=15. | units.kpc): """ iliev test 5 particle distributions N= number of gas part Ns= number of sources (recommended to be order 10 for smoothrad distribution L=half boxsize """ mp = rhoinit*(2*L)**3/N # x,y,z=uniform_random_unit_cube(N).make_xyz() x, y, z = glass(N, target_rms=0.05) p = datamodel.Particles(N) p.x = L*x p.y = L*y p.z = L*z p.h_smooth = 0. | units.parsec p.vx = 0. | (units.km/units.s) p.vy = 0. | (units.km/units.s) p.vz = 0. | (units.km/units.s) p.u = uinit p.rho = rhoinit p.mass = mp p.flux = 0. | (units.s**-1) p.xion = 0. sources = datamodel.Particles(Ns) x, y, z = uniform_unit_sphere(Ns).make_xyz() sources.x = L*x*(1./N)**(1./3)/10 sources.y = L*y*(1./N)**(1./3)/10 sources.z = L*z*(1./N)**(1./3)/10 sources.rho = rhoinit/100. sources.flux = (5.e48/Ns) | (units.s**-1) sources.xion = 1. return p, sources iliev_test_5_ic.__test__ = False def iliev_test_5(N=10000, Ns=10, L=15. | units.kpc, dt=None): """ prepare iliev test and return SPH and simplex interfaces """ gas, sources = iliev_test_5_ic(N, Ns, L) conv = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) sph = Fi(conv, use_gl=False, mode='periodic', redirection='none') sph.initialize_code() sph.parameters.use_hydro_flag = True sph.parameters.radiation_flag = False sph.parameters.self_gravity_flag = False sph.parameters.gamma = 1 sph.parameters.isothermal_flag = True sph.parameters.integrate_entropy_flag = False sph.parameters.timestep = dt sph.parameters.verbosity = 0 sph.parameters.pboxsize = 2*L sph.commit_parameters() sph.gas_particles.add_particles(gas) sph.commit_particles() # sph.start_viewer() rad = SimpleX(number_of_workers=1, redirection='none') rad.initialize_code() rad.parameters.box_size = 2*L rad.parameters.hilbert_order = 0 rad.commit_parameters() gas.add_particles(sources) rad.particles.add_particles(gas) rad.commit_particles() return sph, rad iliev_test_5.__test__ = False def update_pos_rho(sys, pa): p = pa.copy() p.rho = 3./4/numpy.pi*8*p.mass/p.radius**3 channel = p.new_channel_to(sys.particles) channel.copy_attributes(["x", "y", "z", "rho"]) def update_u(sys, pa): p = pa.copy() p.u = fake_internal_energy_from_xion(p.xion) channel = p.new_channel_to(sys.particles) channel.copy_attributes(["u"]) def radhydro_evolve(sph, rad, tend, dt): """ evolve function to co-evolve sph under radiative feedback from rad the evolve proceeds as follows (a form of leapfrog integrator): - 1/2 step sph - update positions and densities in rad - full step rad transfer - update internal energies in sph - 1/2 step sph tend=end time dt=time step this function dump snapshots in file dump-.. """ i = 0 write_set_to_file(sph.gas_particles, "dump-%6.6i" % i, "amuse", append_to_file=False) t = 0. | units.Myr while t < tend-dt/2: print(t) print("sph1") sph.evolve_model(t+dt/2) print("rad") update_pos_rho(rad, sph.gas_particles) rad.evolve_model(t+dt) update_u(sph, rad.particles) print("sph2") sph.evolve_model(t+dt) t += dt i += 1 write_set_to_file(sph.gas_particles, "dump-%6.6i" % i, "amuse", append_to_file=False) sph.stop() rad.stop() def average(N, r, dat): n = len(r) a = numpy.argsort(r) i = 0 r_a = [] dat_a = [] while i < n: ra = r[a[i:i+N]].sum()/min(n-i, N) da = dat[a[i:i+N]].sum()/min(n-i, N) r_a.append(ra) dat_a.append(da) i = i+N return numpy.array(r_a), numpy.array(dat_a) # below follow some plotting functions def aplot(i, tag, xyc, xlim=None, ylim=None): pyplot.figure(figsize=(6, 6)) for x, y, c in xyc: xa, ya = average(100, x, y) pyplot.semilogy(xa, ya, c) if xlim is not None: pyplot.xlim(xlim) if ylim is not None: pyplot.ylim(ylim) pyplot.savefig(tag+'-%6.6i.png' % i) def xion_from_u(u): xion = xtrans*(u-uinit)/(utrans-uinit) a = numpy.where(u > utrans)[0] xion[a] = xtrans+(1-xtrans)*(u[a]-utrans)/(uion-utrans) return xion def plots(i): g = read_set_from_file('dump-%6.6i' % i, 'amuse') r = ((g.x**2+g.y**2+g.z**2)**0.5).value_in(units.kpc) v = ((g.vx**2+g.vy**2+g.vz**2)**0.5).value_in(units.kms) cs = (g.u**0.5).value_in(units.kms) xion = xion_from_u(g.u).value_in(units.none) rho = 3./4/numpy.pi*8*g.mass/g.radius**3 dens = (rho).value_in(units.amu/units.cm**3) pres = (g.u*rho).value_in(units.g/units.cm/units.s**2) mach = v/cs pyplot.figure(figsize=(6, 6)) pyplot.semilogy(r/15, xion, 'r .') pyplot.semilogy(r/15, 1-xion, 'g .') pyplot.xlim((0., 1.)) pyplot.ylim((1.e-6, 1.)) pyplot.savefig('xion-part-%6.6i.png' % i) aplot(i, 'xion', ((r/15, xion, 'r'), (r/15, 1-xion, 'g')), xlim=(0., 1.), ylim=(1.e-6, 1.)) aplot(i, 'pres', ((r/15, pres, 'r'),), xlim=(0., 1.), ylim=(1.e-17, 1.e-14)) aplot(i, 'rho', ((r/15, dens, 'r'),), xlim=(0., 1.), ylim=(0.0001, 0.01)) aplot(i, 'mach', ((r/15, mach, 'r'),), xlim=(0., 1.), ylim=(1.e-5, 10.)) # main example if __name__ == "__main__": N = 10000 Ns = 1 L = 15. | units.kpc dt = 1. | units.Myr tend = 100. | units.Myr sph, rad = iliev_test_5(N, Ns, L, dt/2.) radhydro_evolve(sph, rad, tend, dt) if IS_PLOT_AVAILABLE: plots(50) plots(100)
9,751
25.791209
79
py
amuse
amuse-main/examples/applications/test_evrard_collapse.py
import sys import os.path from optparse import OptionParser try: from matplotlib import pyplot HAS_MATPLOTLIB = True from amuse.plot import plot, xlabel, ylabel except ImportError: HAS_MATPLOTLIB = False from amuse.test.amusetest import get_path_to_results from amuse.units import units from amuse.units import constants from amuse.units import nbody_system from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.ext.evrard_test import new_evrard_gas_sphere from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.rfi.core import is_mpd_running usage = """\ usage: amuse.sh %prog [options] This example script will simulate the spherical collapse of an initially-cold adiabatic gas cloud, with a radial density profile proportional to 1/r. """ labels = [['K', 'V', 'U', 'E'], ['K', 'V', 'U', 'E']] fi_gadget_labels = [['K_fi', 'V_fi', 'U_fi', 'E_fi'], ['K_gadget', 'V_gadget', 'U_gadget', 'E_gadget']] convert_generic_units = ConvertBetweenGenericAndSiUnits( 1.0 | units.kpc, 1.0e10 | units.MSun, constants.G) convert_nbody_units = nbody_system.nbody_to_si( 1.0 | units.kpc, 1.0e10 | units.MSun) def run_evrard( hydro_legacy_codes, number_of_particles, random_seed=None, name_of_the_figure="evrard_collapse_test.png"): print( "\nThe spherical collapse of an initially-cold adiabatic gas cloud,\n", "consisting of ", str(number_of_particles), "particles will be simulated...\n" ) # (3 natural timescales) t_end = 3.0 * convert_nbody_units.to_si(1.0 | nbody_system.time) print( "Evolving to (3 natural timescales): ", t_end.as_quantity_in( units.Myr ) ) n_steps = 100 gas = new_evrard_gas_sphere( number_of_particles, convert_nbody_units, do_scale=True, seed=random_seed) gas.h_smooth = 0.01 | units.kpc times = [] | units.Myr kinetic_energies = [] potential_energies = [] thermal_energies = [] for hydro_legacy_code in hydro_legacy_codes: try: hydro_legacy_code.parameters.timestep = t_end / n_steps except Exception as exc: if "parameter is read-only" not in str(exc): raise hydro_legacy_code.gas_particles.add_particles(gas) kinetic_energies.append([] | units.J) potential_energies.append([] | units.J) thermal_energies.append([] | units.J) for time in [i*t_end/n_steps for i in range(1, n_steps+1)]: for i, hydro_legacy_code in enumerate(hydro_legacy_codes): hydro_legacy_code.evolve_model(time) kinetic_energies[i].append(hydro_legacy_code.kinetic_energy) potential_energies[i].append(hydro_legacy_code.potential_energy) thermal_energies[i].append(hydro_legacy_code.thermal_energy) times.append(time) for hydro_legacy_code in hydro_legacy_codes: hydro_legacy_code.stop() energy_plot(times, kinetic_energies, potential_energies, thermal_energies, name_of_the_figure) print("All done!\n") def energy_plot(time, E_kin_list, E_pot_list, E_therm_list, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize=(5, 5)) for i, (E_kin, E_pot, E_therm) in enumerate( zip(E_kin_list, E_pot_list, E_therm_list) ): plot(time, E_kin.as_quantity_in(units.erg), label=labels[i][0]) plot(time, E_pot, label=labels[i][1]) plot(time, E_therm, label=labels[i][2]) plot(time, E_kin+E_pot+E_therm, label=labels[i][3]) xlabel('Time') ylabel('Energy') pyplot.legend(prop={'size': "x-small"}, loc=3) pyplot.savefig(figname) print("\nPlot of energy evolution was saved to: ", figname) pyplot.close() class InstantiateCode(object): def fi(self): return Fi(convert_nbody_units) def gadget(self): return Gadget2(convert_generic_units) def new_code(self, name_of_the_code): if hasattr(self, name_of_the_code): return getattr(self, name_of_the_code)() else: raise Exception( "Cannot instantiate code with name '{0}'".format( name_of_the_code) ) def new_code(name_of_the_code): return InstantiateCode().new_code(name_of_the_code) def test_evrard_fi_short(): assert is_mpd_running() run_evrard( [new_code("fi")], 100, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_fi_100.png") ) def test_evrard_gadget_short(): assert is_mpd_running() run_evrard( [new_code("gadget")], 100, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_gadget_100.png") ) def test_evrard_compare_short(): assert is_mpd_running() global labels labels = fi_gadget_labels run_evrard( [new_code("fi"), new_code("gadget")], 100, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_compare_100.png") ) def slowtest_evrard_fi(): assert is_mpd_running() run_evrard( [new_code("fi")], 10000, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_fi_10000.png") ) def slowtest_evrard_gadget(): assert is_mpd_running() run_evrard( [new_code("gadget")], 10000, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_gadget_10000.png") ) def slowtest_evrard_compare(): assert is_mpd_running() global labels labels = fi_gadget_labels run_evrard( [new_code("fi"), new_code("gadget")], 10000, random_seed=12345, name_of_the_figure=os.path.join( get_path_to_results(), "evrard_test_compare_10000.png") ) def new_commandline_option_parser(): result = OptionParser(usage) result.add_option( "-c", "--code", choices=["fi", "gadget"], default="fi", dest="code", metavar="CODE", help="CODE to use for hydrodynamics" ) result.add_option( "-a", "--all_codes", default=False, action="store_true", dest="all_codes", metavar="ALLCODE", help="ALLCODES flag to use all hydrodynamics solvers" ) result.add_option( "-n", "--number_of_particles", type="int", default=100, dest="number_of_particles", help="Number of particles in the gas cloud" ) result.add_option( "-S", "--seed", type="int", default=None, dest="salpeterSeed", help="Random number generator seed" ) result.add_option( "-p", "--plot_file", type="string", default="evrard_collapse_test.png", dest="plot_filename", help="Name of the file to plot to" ) return result if __name__ == '__main__': if not is_mpd_running(): print("There is no mpd server running. Please do 'mpd &' first.") sys.exit() parser = new_commandline_option_parser() (options, arguments) = parser.parse_args() if arguments: parser.error("unknown arguments '{0}'".format(arguments)) if options.all_codes: code = [new_code("fi"), new_code("gadget")] labels = fi_gadget_labels else: code = [new_code(options.code)] run_evrard( code, options.number_of_particles, random_seed=options.salpeterSeed, name_of_the_figure=options.plot_filename )
7,936
27.448029
83
py
amuse
amuse-main/examples/applications/test_molecular_cloud.py
import os import numpy from amuse.community.fi import interface as interface from amuse.ext.evrard_test import regular_grid_unit_cube from amuse.ext.molecular_cloud import molecular_cloud from amuse.test.amusetest import get_path_to_results from amuse.rfi.core import is_mpd_running try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False def energy_plot(time, ek, ep, eth): if not HAS_MATPLOTLIB: return pyplot.figure(figsize=(5, 5)) pyplot.xlabel(r'time') pyplot.ylabel(r'energy') pyplot.plot(time, ek) pyplot.plot(time, ep) pyplot.plot(time, eth) pyplot.plot(time, ek+ep+eth) test_results_path = get_path_to_results() pyplot.savefig(os.path.join(test_results_path, "test.png")) def run_cloud(x): cloud = molecular_cloud(32, -4., x, base_grid=regular_grid_unit_cube) mass, x, y, z, vx, vy, vz, u = cloud.new_model() smooth = numpy.zeros_like(mass) nb = interface.FiInterface(redirection="none") nb.initialize_code() nb.set_stepout(99999) nb.set_steplog(99999) nb.set_use_hydro(1) nb.set_radiate(0) nb.set_dtime(0.05) nb.set_gdgop(1) nb.set_uentropy(0) nb.set_isotherm(1) nb.set_gamma(1.0) nb.set_verbosity(0) nb.set_unitl_in_kpc(0.01) nb.set_unitm_in_msun(10000.) ids, error = nb.new_sph_particle(mass, x, y, z, vx, vy, vz, u, smooth) if [x for x in error if x != 0] != []: raise Exception nb.commit_particles() if hasattr(nb, "viewer"): nb.viewer() dt = 0.05 tnow = 0. nb.synchronize_model() time, Ek, Ep, Eth = [], [], [], [] time.append(tnow) e, ret = nb.get_kinetic_energy() Ek.append(e) e, ret = nb.get_potential_energy() Ep.append(e) e, ret = nb.get_thermal_energy() Eth.append(e) while tnow < .8: tnow = tnow+dt nb.evolve_model(tnow) nb.synchronize_model() tnow, err = nb.get_time() time.append(tnow) e, ret = nb.get_kinetic_energy() Ek.append(e) e, ret = nb.get_potential_energy() Ep.append(e) e, ret = nb.get_thermal_energy() Eth.append(e) nb.stop() time = numpy.array(time) Ek = numpy.array(Ek) Ep = numpy.array(Ep) Eth = numpy.array(Eth) energy_plot(time, Ek, Ep, Eth) def test_cloud(): if not is_mpd_running(): return run_cloud(1000) if __name__ == "__main__": run_cloud(1000)
2,493
23.213592
74
py
amuse
amuse-main/examples/applications/test_plummer_sphere_on_grid.py
""" In this script we simulate a plummer sphere on a grid """ from amuse.units import constants from amuse.units import units from amuse.units import nbody_system from amuse.units.generic_unit_system import ( time, length, speed, mass, density, ) from amuse.units.generic_unit_converter import ( ConvertBetweenGenericAndSiUnits, ) from amuse.community.athena.interface import Athena, AthenaInterface from amuse.community.capreole.interface import Capreole from amuse.community.phigrape.interface import PhiGRAPE try: from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False import numpy from numpy import pi from optparse import OptionParser from amuse.io import text from amuse.datamodel import Grid from amuse.datamodel import Particles class HydroGridAndNbody(object): def __init__(self, gridcode, nbodycode): self.gridcode = gridcode self.nbodycode = nbodycode def setup_positions_for_potential_grid(self): self.x = self.gridcode.potential_grid.x.flatten() self.y = self.gridcode.potential_grid.y.flatten() self.z = self.gridcode.potential_grid.z.flatten() self.eps = self.x.aszeros() def setup_particles_in_nbodycode(self): staggered_grid_shape = numpy.asarray(self.gridcode.grid.shape) + 2 corner0 = self.gridcode.grid[0][0][0].position corner1 = self.gridcode.grid[-1][-1][-1].position delta = self.gridcode.grid[1][1][1].position - corner0 print(delta.prod()) self.volume = delta.prod() staggered_corner0 = corner0 - delta staggered_corner1 = corner1 self.staggered_grid = Grid.create( staggered_grid_shape, staggered_corner1 - staggered_corner0 + delta) # self.staggered_grid.x += staggered_corner0.x # self.staggered_grid.y += staggered_corner0.x # self.staggered_grid.z += staggered_corner0.x # self.staggered_grid.p000 = 0.0 | mass # self.staggered_grid.p100 = 0.0 | mass # self.staggered_grid.p010 = 0.0 | mass # self.staggered_grid.p110 = 0.0 | mass # self.staggered_grid.p000 = 0.0 | mass # self.staggered_grid.p100 = 0.0 | mass # self.staggered_grid.p011 = 0.0 | mass # self.staggered_grid.p111 = 0.0 | mass # self.staggered_grid.p001 = 0.0 | mass # self.staggered_grid.p101 = 0.0 | mass self.normal_grid = Grid.create( self.gridcode.grid.shape, corner1 - corner0 + delta) particles = Particles(self.normal_grid.size) particles.mass = 0.0 | mass particles.x = self.grid.x.flatten() particles.y = self.grid.y.flatten() particles.z = self.grid.z.flatten() particles.vx = 0.0 | speed particles.vy = 0.0 | speed particles.vz = 0.0 | speed particles.radius = 0.0 | length self.nbodycode.particles.add_particles(particles) self.from_model_to_nbody = particles.new_channel_to( self.nbodycode.particles) self.nbodycode.commit_particles() self.particles = particles @property def grid(self): return self.gridcode.grid @property def parameters(self): return self.gridcode.parameters def commit_parameters(self): self.gridcode.commit_parameters() self.setup_positions_for_potential_grid() self.setup_particles_in_nbodycode() def initialize_grid(self): self.gridcode.initialize_grid() self.position = self.gridcode.grid.position def evolve_model(self, time): # masses = self.gridcode.grid.rho * self.volume * 1.0 / 8.0 # self.staggered_grid.p000[1:,1:,1:] = masses # self.staggered_grid.p100[:-1,1:,1:] = masses # self.staggered_grid.p010[1:,:-1,1:] = masses # self.staggered_grid.p110[:-1,:-1,1:] = masses # self.staggered_grid.p001[1:,1:,:-1] = masses # self.staggered_grid.p101[:-1,1:,:-1] = masses # self.staggered_grid.p011[1:,:-1,:-1] = masses # self.staggered_grid.p111[:-1,:-1,:-1] = masses # self.staggered_grid.masses = ( # self.staggered_grid.p000 + # self.staggered_grid.p100 + # self.staggered_grid.p010 + # self.staggered_grid.p110 + # self.staggered_grid.p001 + # self.staggered_grid.p101 + # self.staggered_grid.p011 + # self.staggered_grid.p111 # ) # self.particles.mass = self.staggered_grid.masses.flatten() self.particles.mass = (self.gridcode.grid.rho * self.volume).flatten() self.from_model_to_nbody.copy_attribute('mass') correction = (length ** 3) / (mass * (time ** 2)) print(correction, nbody_system.G) print("getting potential energy") potential = self.nbodycode.get_potential_at_point( self.eps, self.x, self.y, self.z ) print( potential.shape, self.gridcode.potential_grid.shape, self.grid.shape ) self.staggered_grid.rho = 0.0 | density self.staggered_grid[1:-1, 1:-1, 1:-1].rho = self.gridcode.grid.rho correction = ( (self.staggered_grid.rho * self.volume) / numpy.sqrt(self.nbodycode.parameters.epsilon_squared) ) * nbody_system.G print(correction.flatten().shape, potential.shape) potential = potential + correction.flatten() print("got potential enery") potential = potential.reshape(self.gridcode.potential_grid.shape) self.gridcode.potential_grid.potential = potential print("evolve hydro", time) self.gridcode.evolve_model(time) print("end evolve hydro") class HydroGridAndNbodyWithAccelerationTransfer(object): def __init__(self, gridcode, nbodycode): self.gridcode = gridcode self.nbodycode = nbodycode self.gridcode.grid.add_vector_attribute( "acceleration_field", ["fx", "fy", "fz"]) def setup_positions_for_potential_grid(self): self.x = self.gridcode.acceleration_grid.x.flatten() self.y = self.gridcode.acceleration_grid.y.flatten() self.z = self.gridcode.acceleration_grid.z.flatten() self.eps = self.x.aszeros() def setup_particles_in_nbodycode(self): staggered_grid_shape = numpy.asarray(self.gridcode.grid.shape) + 1 corner0 = self.gridcode.grid[0][0][0].position corner1 = self.gridcode.grid[-1][-1][-1].position delta = self.gridcode.grid[1][1][1].position - corner0 print(delta.prod()) self.volume = delta.prod() staggered_corner0 = corner0 - delta staggered_corner1 = corner1 self.staggered_grid = Grid.create( staggered_grid_shape, staggered_corner1 - staggered_corner0 + delta) self.staggered_grid.x += staggered_corner0.x self.staggered_grid.y += staggered_corner0.x self.staggered_grid.z += staggered_corner0.x self.staggered_grid.p000 = 0.0 | mass self.staggered_grid.p100 = 0.0 | mass self.staggered_grid.p010 = 0.0 | mass self.staggered_grid.p110 = 0.0 | mass self.staggered_grid.p000 = 0.0 | mass self.staggered_grid.p100 = 0.0 | mass self.staggered_grid.p011 = 0.0 | mass self.staggered_grid.p111 = 0.0 | mass self.staggered_grid.p001 = 0.0 | mass self.staggered_grid.p101 = 0.0 | mass self.normal_grid = Grid.create( self.gridcode.grid.shape, corner1 - corner0 + delta) particles = Particles(self.staggered_grid.size) particles.mass = 0.0 | mass particles.x = self.normal_grid.x.flatten() particles.y = self.normal_grid.y.flatten() particles.z = self.normal_grid.z.flatten() particles.vx = 0.0 | speed particles.vy = 0.0 | speed particles.vz = 0.0 | speed particles.radius = 0.0 | length self.nbodycode.particles.add_particles(particles) self.from_model_to_nbody = particles.new_channel_to( self.nbodycode.particles) self.nbodycode.commit_particles() self.particles = particles @property def grid(self): return self.gridcode.grid @property def parameters(self): return self.gridcode.parameters def commit_parameters(self): self.gridcode.commit_parameters() self.setup_positions_for_potential_grid() self.setup_particles_in_nbodycode() def initialize_grid(self): self.gridcode.initialize_grid() self.position = self.gridcode.grid.position def evolve_model(self, time): masses = self.gridcode.grid.rho * self.volume * 1.0 / 8.0 self.staggered_grid.p000[1:, 1:, 1:] = masses self.staggered_grid.p100[:-1, 1:, 1:] = masses self.staggered_grid.p010[1:, :-1, 1:] = masses self.staggered_grid.p110[:-1, :-1, 1:] = masses self.staggered_grid.p001[1:, 1:, :-1] = masses self.staggered_grid.p101[:-1, 1:, :-1] = masses self.staggered_grid.p011[1:, :-1, :-1] = masses self.staggered_grid.p111[:-1, :-1, :-1] = masses self.staggered_grid.masses = ( self.staggered_grid.p000 + self.staggered_grid.p100 + self.staggered_grid.p010 + self.staggered_grid.p110 + self.staggered_grid.p001 + self.staggered_grid.p101 + self.staggered_grid.p011 + self.staggered_grid.p111 ) # self.particles.mass = self.staggered_grid.masses.flatten() self.particles.mass = self.gridcode.grid.rho * self.volume self.from_model_to_nbody.copy_attribute('mass') print("getting acceleration field") acc_x, acc_y, acc_z = self.nbodycode.get_gravity_at_point( self.eps, self.x, self.y, self.z ) print("got acceleration field") acc_x = acc_x.reshape(self.grid.shape) acc_y = acc_y.reshape(self.grid.shape) acc_z = acc_z.reshape(self.grid.shape) self.gridcode.acceleration_grid.set_values_in_store( None, ["fx", "fy", "fz"], [acc_x, acc_y, acc_z]) print("evolve hydro", time) self.gridcode.evolve_model(time) print("end evolve hydro") class CalculateSolutionIn3D(object): size = 10.0 | length number_of_workers = 1 number_of_grid_points = 25 gamma = 5.0/3.0 rho_medium = 0 | density rho_sphere = 0.5 | density center = [1.0 / 2.0, 1.0 / 2.0, 1.0 / 2.0] * size radius = 1.0 | length total_mass = 1.0 | mass name_of_the_code = "athena_selfgravity" convert_generic_units = ConvertBetweenGenericAndSiUnits( 1.0 | units.kpc, 1.0e10 | units.MSun, constants.G) def __init__(self, **keyword_arguments): for x in keyword_arguments: print(x, keyword_arguments[x]) setattr(self, x, keyword_arguments[x]) self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, self.number_of_grid_points ) self.instance = None def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_athena_selfgravity_code(self): result = Athena(mode=AthenaInterface.MODE_SELF_GRAVITY, redirection="none", number_of_workers=1) result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 result.set_grav_mean_rho(self.rho_mean) return result def new_instance_of_athena_code(self): result = Athena(redirection="none", number_of_workers=1) result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 return result def new_instance_of_athena_and_nbody_code(self): gridcode = Athena(redirection="none", number_of_workers=1) gridcode.initialize_code() gridcode.parameters.gamma = self.gamma gridcode.parameters.courant_number = 0.3 gridcode.set_has_external_gravitational_potential(1) nbodycode = PhiGRAPE(mode="gpu") # nbodycode = Octgrav(mode="gpu") nbodycode.initialize_code() nbodycode.parameters.epsilon_squared = ( self.size / (10000.0 * self.number_of_grid_points)) ** 2 nbodycode.commit_parameters() result = HydroGridAndNbody(gridcode, nbodycode) return result def new_instance_of_capreole_and_nbody_code(self): gridcode = Capreole(number_of_workers=self.number_of_workers) gridcode.initialize_code() nbodycode = PhiGRAPE(mode="gpu") # nbodycode = Octgrav(mode="gpu") nbodycode.initialize_code() nbodycode.parameters.epsilon_squared = ( self.size / (10000.0 * self.number_of_grid_points)) ** 2 nbodycode.commit_parameters() result = HydroGridAndNbodyWithAccelerationTransfer(gridcode, nbodycode) return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = self.size instance.parameters.length_y = self.size instance.parameters.length_z = self.size instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") result = instance.commit_parameters() def new_grid(self): density = mass / length**3 density = density momentum = speed * density energy = mass / (time**2 * length) grid = Grid.create(self.dimensions_of_mesh, (10.0, 10.0, 10.0) | length) grid.rho = self.rho_medium grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid_with_plummer_sphere(self, grid): scaled_radius = self.radius # / 1.695 radii = (grid.position - self.center).lengths() selected_radii = radii[radii < self.radius] print( "number of cells in cloud (number of cells in grid)", len(selected_radii), grid.shape, grid.size ) self.rho_sphere = ( (0.75 * self.total_mass / (pi * (scaled_radius ** 3)))) grid.rho = ( self.rho_medium + ( self.rho_sphere * ((1 + (radii ** 2) / (scaled_radius ** 2))**(-5.0/2.0)) ) ) internal_energy = ( (0.25 | potential) * (1.0 | length / mass) * self.total_mass / scaled_radius ) # 1.0 * grid.rho * grid.energy = grid.rho * \ (internal_energy/((1.0+(radii/scaled_radius)**2)**(1.0/2.0))) def setup_code(self): print("setup code") self.grid = self.new_grid() self.initialize_grid_with_plummer_sphere(self.grid) print("Mean density", self.grid.rho.flatten().mean()) self.rho_mean = self.grid.rho.flatten().mean() self.instance = self.new_instance_of_code() self.set_parameters(self.instance) self.from_model_to_code = self.grid.new_channel_to(self.instance.grid) self.from_code_to_model = self.instance.grid.new_channel_to(self.grid) self.from_code_to_model.copy_attributes(("x", "y", "z",)) self.from_model_to_code.copy() self.instance.initialize_grid() def get_solution_at_time(self, time): if self.instance is None: self.setup_code() print("start evolve") self.instance.evolve_model(time) print("copying results") self.from_code_to_model.copy() # print "max,min", max(self.grid.rhovx.flatten()), min(self.grid.rhovx.flatten()) # print "max,min", max(self.grid.rhovy.flatten()), min(self.grid.rhovy.flatten()) # print "max,min", max(self.grid.rhovz.flatten()), min(self.grid.rhovz.flatten()) # print "max,min", max(self.grid.energy.flatten()), min(self.grid.energy.flatten()) # print "max,min", max(self.grid.rho.flatten()), min(self.grid.rho.flatten()) return self.grid def store_attributes(x, rho, rhovx, energy, filename): output = text.TableFormattedText(filename=filename) output.quantities = (x, rho, rhovx, energy) output.attribute_names = ("x", "rho", "rhovx", "energy") output.store() def store_attributes_of_line(grid, yindex=0, zindex=0, **options): store_attributes( grid.x[..., yindex, zindex], grid.rho[..., yindex, zindex], grid.rhovx[..., yindex, zindex], grid.energy[..., yindex, zindex], filename="plummer_sphere_{name_of_the_code}_{number_of_grid_points}_{number_of_workers}_{time}.csv".format( **options) ) def new_option_parser(): result = OptionParser() result.add_option( "-n", "--mesh-size", dest="number_of_grid_points", type="int", default=25, help="number of grid cells in the x, y and z direction" ) result.add_option( "-w", "--workers", dest="number_of_workers", type="int", default=1, help="number of parallel workers to start" ) result.add_option( "-c", "--code", dest="name_of_the_code", default="athena_selfgravity", help="name of the code to use" ) return result def main(**options): center = options['number_of_grid_points'] / 2 print("calculating shock using code") model = CalculateSolutionIn3D(**options) for t in range(50): grid = model.get_solution_at_time(t * 0.1 | time) print("saving data") store_attributes_of_line( grid, yindex=center, zindex=center, time=t, **options) if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
18,609
33.720149
115
py
amuse
amuse-main/examples/applications/test_HRdiagram_tracks.py
import sys import os import warnings from optparse import OptionParser from amuse.units import units from amuse.community.sse.interface import SSE from amuse.community.evtwin.interface import EVtwin from amuse.community.evtwin2sse.interface import EVtwin2SSE from amuse.community.mesa.interface import MESA from amuse.community.cachedse.interface import CachedStellarEvolution from amuse.test.amusetest import get_path_to_results from amuse import datamodel from amuse.rfi.core import is_mpd_running usage = """\ usage: %prog [options] This script will generate HR diagram tracks for stars with specified a masses. """ def stellar_remnant_state(star): return 10 <= star.stellar_type.value_in(units.stellar_type) and \ star.stellar_type.value_in(units.stellar_type) < 16 def simulate_evolution_tracks( stellar_evolution=SSE(), masses=[0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0] | units.MSun, name_of_the_figure="HR_evolution_tracks.png" ): """ For every mass in the `masses' array, a stellar evolution track across the Hertzsprung-Russell diagram will be calculated and plotted. Each star will be created, evolved and removed one by one. This is only necessary because the time span of each track is different (a solar mass star evolution track takes billions of years, but we don't want to also evolve high mass stars for billions of years) In most applications the stars have to be evolved up to a common end time, which can be more easily accomplished by creating an array (stars = datamodel.Stars(number_of_stars)) and using evolve_model(end_time = ...). """ number_of_stars = len(masses) all_tracks_luminosity = [] all_tracks_temperature = [] all_tracks_stellar_type = [] stellar_evolution.commit_parameters() print( "The evolution across the Hertzsprung-Russell diagram of ", str(number_of_stars), " stars with\nvarying masses will be simulated..." ) for j in range(number_of_stars): star = datamodel.Particle() star.mass = masses[j] print("Created new star with mass: ", star.mass) star = stellar_evolution.particles.add_particle(star) stellar_evolution.commit_particles() luminosity_at_time = [] | units.LSun temperature_at_time = [] | units.K stellar_type_at_time = [] | units.stellar_type stopped_evolving = False # Evolve this star until it changes into a compact stellar remnant # (white dwarf, neutron star, or black hole) while not stellar_remnant_state(star) and not stopped_evolving: luminosity_at_time.append(star.luminosity) temperature_at_time.append(star.temperature) stellar_type_at_time.append(star.stellar_type) previous_age = star.age try: stellar_evolution.evolve_model() # Check whether the age has stopped increasing stopped_evolving = (star.age == previous_age) except Exception as ex: print(str(ex)) stopped_evolving = True if stopped_evolving: print("Age did not increase during timestep. Aborted evolving...") else: stellar_type_at_time.append(star.stellar_type) # Fudged: final stellar type annotation at previous (Teff, L); # BHs and neutron stars would otherwise fall off the chart. luminosity_at_time.append(luminosity_at_time[-1]) temperature_at_time.append(temperature_at_time[-1]) print(" ... evolved model to t = " + \ str(star.age.as_quantity_in(units.Myr))) print( "Star has now become a: ", star.stellar_type, "(stellar_type: " + str( star.stellar_type.value_in(units.stellar_type) ) + ")" ) print() all_tracks_luminosity.append(luminosity_at_time) all_tracks_temperature.append(temperature_at_time) all_tracks_stellar_type.append(stellar_type_at_time) # Remove the star before creating the next one. See comments at the top. stellar_evolution.particles.remove_particle(star) stellar_evolution.stop() plot_HR_diagram( masses, all_tracks_luminosity, all_tracks_temperature, all_tracks_stellar_type, name_of_the_figure ) print("All done!") def plot_HR_diagram( masses, luminosity_tracks, temperature_tracks, stellar_type_tracks, plotfile): try: # This removes the need for ssh -X to be able to do plotting import matplotlib matplotlib.use("Agg", warn=False) from matplotlib import pyplot print("Plotting the data...") pyplot.figure(figsize=(7, 8)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) pyplot.xlabel('Effective Temperature (K)') pyplot.ylabel('Luminosity (solar luminosity)') # Define some strings for line formatting (colors, symbols, etc.), used # recurrently when many stars are simulated plot_format_strings_lines = ["r-", "y-", "c-", "b-", "m-"] len_fmt_str_lin = len(plot_format_strings_lines) plot_format_strings_symbols = [ "r^", "y^", "c^", "b^", "m^", "rs", "ys", "cs", "bs", "ms"] len_fmt_str_sym = len(plot_format_strings_symbols) number_of_stars = len(masses) for j in range(number_of_stars): # Plot track of the current star j x_values = temperature_tracks[j].value_in(units.K) y_values = luminosity_tracks[j].value_in(units.LSun) pyplot.loglog(x_values, y_values, plot_format_strings_lines[j % len_fmt_str_lin]) # Plot symbols whenever this star has switched to the next stellar # evolution phase x_values = [] y_values = [] text_values = [] previous_type = 15 | units.stellar_type for i, type in enumerate(stellar_type_tracks[j]): if not type == previous_type: x_values.append(temperature_tracks[j][i].value_in(units.K)) y_values.append( luminosity_tracks[j][i].value_in(units.LSun)) text_values.append( stellar_type_tracks[j][i].value_in(units.stellar_type)) previous_type = type pyplot.loglog(x_values, y_values, plot_format_strings_symbols[j % len_fmt_str_sym]) text_offset_factor_x = 1.05 text_offset_factor_y = 0.6 for i, phase in enumerate(text_values): pyplot.annotate( str(int(phase)), xy=(x_values[i], y_values[i]), xytext=( x_values[i]*text_offset_factor_x, y_values[i]*text_offset_factor_y) ) text_offset_factor_x = 1.1 text_offset_factor_y = 0.9 pyplot.annotate(str(masses[j]), xy=(x_values[0], y_values[0]), xytext=(x_values[0]*text_offset_factor_x, y_values[0]*text_offset_factor_y), color='g', horizontalalignment='right') pyplot.axis([300000., 2500., 1.e-2, 1.e6]) # Or use these axes to also view neutron stars and black holes: # pyplot.axis([1.e7, 2500., 1.e-11, 1.e6]) pyplot.savefig(plotfile) print("Meaning of the stellar evolution phase markers (black numbers):") for i in range(16): print(str(i)+": ", (i | units.stellar_type)) except ImportError: print("Unable to produce plot: couldn't find matplotlib.") class InstantiateCode(object): def sse(self, number_of_stars): return SSE() def evtwin(self, number_of_stars): result = EVtwin() result.initialize_code() if number_of_stars > result.parameters.maximum_number_of_stars: result.parameters.maximum_number_of_stars = number_of_stars warnings.warn( "You're simulating a large number of stars with EVtwin. This may not be such a good idea...") return result def mesa(self, number_of_stars): result = MESA() result.initialize_code() if number_of_stars > (10): warnings.warn( "You're simulating a large number of stars with MESA. This may not be such a good idea...") if number_of_stars > (1000): raise Exception( "You want to simulate with more than 1000 stars using MESA, this is not supported") return result def evtwin2sse(self, number_of_stars): result = EVtwin2SSE() result.initialize_code() # TODO add maximum_number_of_stars parameter to Evtwin2SSE # if number_of_stars > result.parameters.maximum_number_of_stars: # result.parameters.maximum_number_of_stars = number_of_stars # warnings.warn("You're simulating a large number of stars with EVtwin. This may not be such a good idea...") return result def new_code(self, name_of_the_code, number_of_stars): if hasattr(self, name_of_the_code): return getattr(self, name_of_the_code)(number_of_stars) else: raise Exception( "Cannot instantiate code with name '{0}'".format( name_of_the_code ) ) def new_code(name_of_the_code, number_of_stars): return InstantiateCode().new_code(name_of_the_code, number_of_stars) def test_simulate_one_star(): assert is_mpd_running() code = new_code("sse", 1) test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "HR_evolution_tracks.png") simulate_evolution_tracks( code, [20.0] | units.MSun, name_of_the_figure=output_file, ) def new_commandline_option_parser(): result = OptionParser(usage) result.add_option( "-c", "--code", choices=["sse", "evtwin", "mesa", "evtwin2sse"], default="sse", dest="code", metavar="CODE", help="CODE to use for stellar evolution" ) result.add_option( "-C", "--cache", type="string", default=None, dest="cacheDir", help="Use/write cache from directory" ) result.add_option( "-p", "--plot_file", type="string", default="HR_evolution_tracks.png", dest="plot_filename", help="Name of the file to plot to" ) return result if __name__ == '__main__': if not is_mpd_running(): print("There is no mpd server running. Please do 'mpd &' first.") sys.exit() parser = new_commandline_option_parser() (options, arguments) = parser.parse_args() if arguments: parser.error("unknown arguments '{0}'".format(arguments)) mass_list = [0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 30.0] | units.MSun code = new_code(options.code, len(mass_list)) if not (options.cacheDir is None): print("Using cache directory: %s" % (options.cacheDir)) # As a special case, we use caching of the underlying models instead of # the model output for EVtwin2SSE if (options.code == "evtwin2sse"): code.cache_underlying_models(options.cacheDir) else: code = CachedStellarEvolution(code, options.cacheDir) simulate_evolution_tracks( code, masses=mass_list, name_of_the_figure=options.plot_filename )
11,883
36.021807
121
py
amuse
amuse-main/examples/applications/mercury_solarsystem3.py
# import numpy from amuse.community.mercury.interface import MercuryWayWard from amuse.community.sse.interface import SSE from amuse.ext.solarsystem import new_solar_system_for_mercury from amuse.units import units from amuse.units.quantities import VectorQuantity from amuse.plot import ( plot, native_plot, ) try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False def planetplot(): sun, planets = new_solar_system_for_mercury() initial = 12.2138 | units.Gyr final = 12.3300 | units.Gyr step = 10000.0 | units.yr timerange = VectorQuantity.arange(initial, final, step) gd = MercuryWayWard() gd.initialize_code() # gd.stopping_conditions.timeout_detection.disable() gd.central_particle.add_particles(sun) gd.orbiters.add_particles(planets) gd.commit_particles() se = SSE() # se.initialize_code() se.commit_parameters() se.particles.add_particles(sun) se.commit_particles() channelp = gd.orbiters.new_channel_to(planets) channels = se.particles.new_channel_to(sun) for time in timerange: err = gd.evolve_model(time-initial) channelp.copy() # planets.savepoint(time) err = se.evolve_model(time) channels.copy() gd.central_particle.mass = sun.mass print( sun[0].mass.value_in(units.MSun), time.value_in(units.Myr), planets[4].x.value_in(units.AU), planets[4].y.value_in(units.AU), planets[4].z.value_in(units.AU) ) gd.stop() se.stop() for planet in planets: t, x = planet.get_timeline_of_attribute_as_vector("x") t, y = planet.get_timeline_of_attribute_as_vector("y") plot(x, y, '.') native_plot.gca().set_aspect('equal') native_plot.show() if __name__ == "__main__": planetplot()
1,944
26.394366
62
py
amuse
amuse-main/examples/applications/test_supernova.py
import os.path import numpy from amuse.test.amusetest import get_path_to_results try: from matplotlib import pyplot HAS_MATPLOTLIB = True from amuse.plot import plot, xlabel, ylabel except ImportError: HAS_MATPLOTLIB = False from amuse.units import units # from amuse.units import generic_unit_system # from amuse.units import nbody_system from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.support.exceptions import AmuseException from amuse.community.mesa.interface import MESA from amuse.community.gadget2.interface import Gadget2 # from amuse.community.fi.interface import Fi from amuse.ext.star_to_sph import ( pickle_stellar_model, convert_stellar_model_to_SPH, ) from amuse.datamodel import Particles from amuse.datamodel import Grid def inject_supernova_energy(gas_particles): inner = gas_particles.select( lambda pos: pos.length_squared() < 100.0 | units.RSun**2, ["position"] ) print(len(inner), "innermost particles selected.") print("Adding", (1.0e51 | units.erg) / inner.total_mass(), "of supernova " \ "(specific internal) energy to each of them.") inner.u += (1.0e51 | units.erg) / inner.total_mass() def setup_stellar_evolution_model(): out_pickle_file = os.path.join( get_path_to_results(), "super_giant_stellar_structure.pkl") if os.path.exists(out_pickle_file): return out_pickle_file stellar_evolution = MESA(redirection="none") stars = Particles(1) stars.mass = 10.0 | units.MSun stellar_evolution.initialize_module_with_default_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() print( "Evolving a MESA star with mass:", stellar_evolution.particles[0].mass ) try: while True: stellar_evolution.evolve_model() except AmuseException as ex: print("Evolved star to", stellar_evolution.particles[0].age) print("Radius:", stellar_evolution.particles[0].radius) pickle_stellar_model(stellar_evolution.particles[0], out_pickle_file) stellar_evolution.stop() return out_pickle_file def run_supernova(): # options: use_hydro_code = Gadget2 # Fi -or- Gadget2 # e.g. dict(use_gl = True) or dict(redirection = "none") hydro_code_options = dict(number_of_workers=3) number_of_sph_particles = 30000 t_end = 1.0e5 | units.s pickle_file = setup_stellar_evolution_model() print("Creating initial conditions from a MESA stellar evolution model...") model = convert_stellar_model_to_SPH( None, number_of_sph_particles, seed=12345, pickle_file=pickle_file, # base_grid_options = dict(type = "glass", target_rms = 0.01), with_core_particle=True ) core, gas_without_core, core_radius = \ model.core_particle, model.gas_particles, model.core_radius if len(core): print( "Created", len(gas_without_core), "SPH particles and one 'core-particle':\n", core ) print("Setting gravitational smoothing to:", core_radius) else: print("Warning: Only SPH particles created.") inject_supernova_energy(gas_without_core) print("\nEvolving (SPH) to:", t_end) n_steps = 100 unit_converter = ConvertBetweenGenericAndSiUnits( 1.0 | units.RSun, constants.G, t_end) hydro_code = use_hydro_code(unit_converter, **hydro_code_options) try: hydro_code.parameters.timestep = t_end / n_steps except Exception as exc: if "parameter is read-only" not in str(exc): raise hydro_code.parameters.epsilon_squared = core_radius**2 hydro_code.parameters.n_smooth_tol = 0.01 hydro_code.gas_particles.add_particles(gas_without_core) hydro_code.dm_particles.add_particles(core) times = [] | units.s potential_energies = [] | units.J kinetic_energies = [] | units.J thermal_energies = [] | units.J for time, i_step in [(i*t_end/n_steps, i) for i in range(0, n_steps+1)]: hydro_code.evolve_model(time) times.append(time) potential_energies.append(hydro_code.potential_energy) kinetic_energies.append(hydro_code.kinetic_energy) thermal_energies.append(hydro_code.thermal_energy) hydro_plot( [-1.0, 1.0, -1.0, 1.0] * (350 | units.RSun), hydro_code, (100, 100), os.path.join(get_path_to_results(), "supernova_hydro_image{0:=03}.png".format(i_step)) ) energy_plot( times, kinetic_energies, potential_energies, thermal_energies, os.path.join( get_path_to_results(), "supernova_energy_evolution.png" ) ) hydro_code.stop() print("All done!\n") def energy_plot(time, E_kin, E_pot, E_therm, figname): if not HAS_MATPLOTLIB: return pyplot.figure(figsize=(5, 5)) plot(time, E_kin.as_quantity_in(units.erg), label='E_kin') plot(time, E_pot, label='E_pot') plot(time, E_therm, label='E_therm') plot(time, E_kin+E_pot+E_therm, label='E_total') xlabel('Time') ylabel('Energy') pyplot.legend(loc=3) pyplot.savefig(figname) print("\nPlot of energy evolution was saved to: ", figname) pyplot.close() def hydro_plot(view, hydro_code, image_size, figname): """ view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) """ if not HAS_MATPLOTLIB: return shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe = hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-9 | units.g / units.cm**3 max_rho = 1.0e-5 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum( numpy.ones_like(log_v), numpy.maximum( numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))) ) ).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis=2) pyplot.figure(figsize=(image_size[0]/100.0, image_size[1]/100.0), dpi=100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig( figname, transparent=True, dpi = 100, facecolor='k', edgecolor='k' ) print("\nHydroplot was saved to: ", figname) pyplot.close() if __name__ == "__main__": print("Test run to mimic a supernova in SPH") print() print("Details:") print("First a high-mass star is evolved up to the super giant phase using MESA. " \ "Then it is converted to SPH particles with the convert_stellar_model_to_SPH " \ "procedure (with a non-SPH 'core' particle). Finally the internal energies of " \ "the inner particles are increased, such that the star gains the 10^51 ergs " \ "released in supernova explosions.") print() run_supernova()
8,418
34.37395
89
py
amuse
amuse-main/examples/applications/test_HRdiagram_cluster.py
import numpy import os import warnings from optparse import OptionParser from amuse.units import units from amuse.community.sse.interface import SSE from amuse.community.evtwin.interface import EVtwin from amuse.community.mesa.interface import MESA from amuse.community.cachedse.interface import CachedStellarEvolution from amuse.test.amusetest import get_path_to_results from amuse import datamodel from amuse.rfi.core import is_mpd_running from amuse.ic.salpeter import new_salpeter_mass_distribution usage = """\ usage: %prog [options] This script will generate HR diagram for an evolved cluster of stars with a Salpeter mass distribution. """ def simulate_stellar_evolution( stellar_evolution=SSE(), number_of_stars=1000, end_time=1000.0 | units.Myr, name_of_the_figure="cluster_HR_diagram.png", ): """ A cluster of stars will be created, with masses following a Salpeter IMF. The stellar evolution will be simulated using any of the legacy codes (SSE, EVtwin, or MESA). Finally, a Hertzsprung-Russell diagram will be produced for the final state of the simulation. """ print( "The evolution of", str(number_of_stars), "stars will be ", "simulated until t =", str(end_time), "..." ) stellar_evolution.commit_parameters() print( "Deriving a set of", str(number_of_stars), "random masses", "following a Salpeter IMF between 0.1 and 125 MSun (alpha = -2.35)." ) salpeter_masses = new_salpeter_mass_distribution(number_of_stars) print("Initializing the particles") stars = datamodel.Particles(number_of_stars) stars.mass = salpeter_masses print("Stars to evolve:") print(stars) stars = stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() # print stars.temperature print("Start evolving...") stellar_evolution.evolve_model(end_time) print("Evolved model successfully.") temperatures = stars.temperature luminosities = stars.luminosity stellar_evolution.stop() plot_HR_diagram(temperatures, luminosities, name_of_the_figure, end_time) print("All done!") def plot_HR_diagram(temperatures, luminosities, name_of_the_figure, end_time): try: # This removes the need for ssh -X to be able to do plotting import matplotlib matplotlib.use("Agg", warn=False) from matplotlib import pyplot print("Plotting the data...") number_of_stars = len(temperatures) pyplot.figure(figsize=(7, 8)) pyplot.title('Hertzsprung-Russell diagram', fontsize=12) pyplot.xlabel(r'T$_{\rm eff}$ (K)') pyplot.ylabel(r'Luminosity (L$_\odot$)') pyplot.loglog(temperatures.value_in(units.K), luminosities.value_in(units.LSun), "ro") xmin, xmax = 20000.0, 2500.0 ymin, ymax = 1.e-4, 1.e4 pyplot.text(xmin*.75, ymax*0.1, str(number_of_stars) + " stars\nt="+str(end_time)) pyplot.axis([xmin, xmax, ymin, ymax]) pyplot.savefig(name_of_the_figure) except ImportError: print("Unable to produce plot: couldn't find matplotlib.") class InstantiateCode(object): def sse(self, number_of_stars): return SSE() def evtwin(self, number_of_stars): result = EVtwin() result.initialize_code() if number_of_stars > result.parameters.maximum_number_of_stars: result.parameters.maximum_number_of_stars = number_of_stars warnings.warn( "You're simulating a large number of stars with EVtwin. This may not be such a good idea...") return result def mesa(self, number_of_stars): result = MESA() result.initialize_code() if number_of_stars > (10): warnings.warn( "You're simulating a large number of stars with MESA. This may not be such a good idea...") if number_of_stars > (1000): raise Exception( "You want to simulate with more than 1000 stars using MESA, this is not supported") return result def new_code(self, name_of_the_code, number_of_stars): if hasattr(self, name_of_the_code): return getattr(self, name_of_the_code)(number_of_stars) else: raise Exception( "Cannot instantiate code with name '{0}'".format( name_of_the_code) ) def new_code(name_of_the_code, number_of_stars): return InstantiateCode().new_code(name_of_the_code, number_of_stars) def test_simulate_short(): assert is_mpd_running() code = new_code("sse", 100) test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "cluster_HR_diagram.png") simulate_stellar_evolution( code, number_of_stars=100, end_time=2.0 | units.Myr, name_of_the_figure=output_file ) def new_commandline_option_parser(): result = OptionParser(usage) result.add_option( "-c", "--code", choices=["sse", "evtwin", "mesa"], default="sse", dest="code", metavar="CODE", help="CODE to use for stellar evolution" ) result.add_option( "-n", "--number_of_stars", type="int", default=10, dest="number_of_stars", help="Number of stars in the cluster" ) result.add_option( "-t", "--end_time", type="float", default=1000.0, dest="end_time", help="Time to evolve to in Myr" ) result.add_option( "-C", "--cache", type="string", default=None, dest="cacheDir", help="Use/write cache from directory" ) result.add_option( "-S", "--seed", type="int", default=None, dest="salpeterSeed", help="Random number generator seed" ) result.add_option( "-p", "--plot_file", type="string", default="cluster_HR_diagram.png", dest="plot_filename", help="Name of the file to plot to" ) return result if __name__ == '__main__': parser = new_commandline_option_parser() (options, arguments) = parser.parse_args() if arguments: parser.error("unknown arguments '{0}'".format(arguments)) code = new_code(options.code, options.number_of_stars) if not (options.cacheDir is None): print("Using cache directory: %s" % (options.cacheDir)) code = CachedStellarEvolution(code, options.cacheDir) if not (options.salpeterSeed is None): numpy.random.seed(options.salpeterSeed) simulate_stellar_evolution( code, number_of_stars=options.number_of_stars, end_time=options.end_time | units.Myr, name_of_the_figure=options.plot_filename )
7,013
28.225
109
py
amuse
amuse-main/examples/applications/test_riemann_shock_tube_problem.py
""" In this script we simulate the riemann shock tube problem in 3d. .. quote: The test set-up consists of two fluids of different densities and pressures separated by a membrane that is then removed. The resulting solution shows all three types of fluid discontinuties; a shock wave moving from the high density fluid to the low density one, a rarefraction (sound) wave moving in the opposite direction and a contact discontinuity which marks the current location of the interface between the two fluids. We follow the directions in the paper: :title: A test suite for quantitative comparison of hydrodynamic codes in astrophyics :authors: Elizabeth J. Tasker, Riccardo Brunino, Nigel L. Mitchell, Dolf Michielsen, Stephen Hopton, Frazer R. Pearce, Greg L. Bryan, Tom Theuns :journal: Monthly Notices of the Royal Astronomical Society :issue: Volume 390, Issue 3, pages 1267-1281, November 2008 :doi: DOI: 10.1111/j.1365-2966.2008.13836.x See also: :site: http://www.astro.ufl.edu/~tasker/codecomparison2/codecomparison_riemann.html Exact solution is based on fortran code from Frank Timmer (who based it on code from Bruce Fryxell), see: http://cococubed.asu.edu/code_pages/exact_riemann.shtml """ # from amuse.support.core import late # from amuse import io from amuse.io import text from amuse.units import (units, constants) from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.units.nbody_system import nbody_to_si from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, speed, mass, density, ) from amuse.community.athena.interface import Athena from amuse.community.capreole.interface import Capreole from amuse.community.mpiamrvac.interface import MpiAmrVac from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.grid_to_sph import convert_grid_to_SPH import numpy try: from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False from numpy import sqrt, arange, searchsorted from optparse import OptionParser from amuse.datamodel import Grid from amuse.datamodel import Particles from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation from amuse.datamodel.grids import SamplePointOnCellCenter class CalculateExactSolutionIn1D(object): number_of_points = 1000 rho1 = 4.0 | density p1 = 1.0 | mass / (length * (time**2)) u1 = 0.0 | speed rho5 = 1.0 | density p5 = 0.1795 | mass / (length * (time**2)) u5 = 0.0 | speed gamma = 5.0/3.0 def get_post_shock_pressure_p4( self, maximum_number_of_iterations=20, maxium_allowable_relative_error=1e-5): """solve for post-shock pressure by secant method""" p40 = self.p1 p41 = self.p5 p4 = p41 f0 = self.calculate_p4_from_previous_value(p40) for x in range(maximum_number_of_iterations): f1 = self.calculate_p4_from_previous_value(p41) if (f1 == f0): return p4 p4 = p41 - (p41 - p40) * f1 / (f1 - f0) error = abs(p4 - p41) / p41 if (error < maxium_allowable_relative_error): return p4 p40 = p41 p41 = p4 f0 = f1 raise Exception( "solution did not converge in less than {0!r} steps.".format( maximum_number_of_iterations)) def get_post_shock_density_and_velocity_and_shock_speed(self, p4): z = (p4 / self.p5 - 1.0) c5 = (self.gamma * self.p5 / self.rho5).sqrt() gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 gmfac1 = 0.5 * gm1 / self.gamma gmfac2 = 0.5 * gp1 / self.gamma fact = sqrt(1. + gmfac2 * z) u4 = c5 * z / (self.gamma * fact) rho4 = self.rho5 * (1.0 + gmfac2 * z) / (1.0 + gmfac1 * z) return u4, rho4, c5 * fact def calculate_p4_from_previous_value(self, p4): c1 = sqrt(self.gamma * self.p1 / self.rho1) c5 = sqrt(self.gamma * self.p5 / self.rho5) gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 g2 = 2.0 * self.gamma z = (p4 / self.p5 - 1.0) fact = gm1 / g2 * (c5 / c1) * z / sqrt(1. + gp1 / g2 * z) fact = (1. - fact) ** (g2 / gm1) return self.p1 * fact - p4 def get_solution_at_time(self, t): p4 = self.get_post_shock_pressure_p4() u4, rho4, w = self.get_post_shock_density_and_velocity_and_shock_speed( p4) # compute values at foot of rarefaction p3 = p4 u3 = u4 rho3 = self.rho1 * (p3 / self.p1)**(1. / self.gamma) c1 = sqrt(self.gamma * self.p1 / self.rho1) c3 = sqrt(self.gamma * p3 / rho3) xi = 0.5 | length xr = 1.0 | length xl = 0.0 | length xsh = xi + w * t xcd = xi + u3 * t xft = xi + (u3 - c3) * t xhd = xi - c1 * t gm1 = self.gamma - 1.0 gp1 = self.gamma + 1.0 dx = (xr - xl) / (self.number_of_points - 1) x = xl + dx * arange(self.number_of_points) rho = VectorQuantity.zeros(self.number_of_points, density) p = VectorQuantity.zeros( self.number_of_points, mass / (length * time**2)) u = VectorQuantity.zeros(self.number_of_points, speed) for i in range(self.number_of_points): if x[i] < xhd: rho[i] = self.rho1 p[i] = self.p1 u[i] = self.u1 elif x[i] < xft: u[i] = 2. / (self.gamma + 1.0) * (c1 + (x[i] - xi) / t) fact = 1. - 0.5 * gm1 * u[i] / c1 rho[i] = self.rho1 * fact ** (2. / gm1) p[i] = self.p1 * fact ** (2. * self.gamma / gm1) elif x[i] < xcd: rho[i] = rho3 p[i] = p3 u[i] = u3 elif x[i] < xsh: rho[i] = rho4 p[i] = p4 u[i] = u4 else: rho[i] = self.rho5 p[i] = self.p5 u[i] = self.u5 return x, rho, p, u class CalculateSolutionIn3D(object): number_of_workers = 1 number_of_grid_points = 10 gamma = 5.0/3.0 name_of_the_code = "capreole" hydro_code_options = dict() # redirection="none") convert_generic_units = ConvertBetweenGenericAndSiUnits( 1.0 | units.kpc, 1.0e10 | units.MSun, constants.G) convert_nbody_units = nbody_to_si( 1.0 | units.kpc, 1.0e10 | units.MSun) def __init__(self, **keyword_arguments): for x in keyword_arguments: print(x, keyword_arguments[x]) setattr(self, x, keyword_arguments[x]) self.dimensions_of_mesh = ( self.number_of_grid_points * 3, self.number_of_grid_points, self.number_of_grid_points ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_athena_code(self): result = Athena(number_of_workers=self.number_of_workers, **self.hydro_code_options) result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 return result def new_instance_of_mpiamrvac_code(self): result = MpiAmrVac( number_of_workers=self.number_of_workers, **self.hydro_code_options) result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def new_instance_of_capreole_code(self): result = Capreole( number_of_workers=self.number_of_workers, **self.hydro_code_options) result.initialize_code() return result grid_hydro_codes = ("athena", "mpiamrvac", "capreole") def new_instance_of_gadget2_code(self): result = Gadget2( self.convert_generic_units, number_of_workers=self.number_of_workers, mode="periodic", **self.hydro_code_options) result.initialize_code() return result def new_instance_of_fi_code(self): result = Fi( self.convert_nbody_units, number_of_workers=self.number_of_workers, mode="periodic", **self.hydro_code_options) result.initialize_code() result.parameters.self_gravity_flag = False result.parameters.timestep = 0.01 | time return result sph_hydro_codes = ("gadget2", "fi") def set_parameters(self, instance): if self.name_of_the_code in self.sph_hydro_codes: instance.parameters.periodic_box_size = 1.0 | length else: instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ( "periodic", "periodic") instance.parameters.y_boundary_conditions = ( "periodic", "periodic") instance.parameters.z_boundary_conditions = ( "periodic", "periodic") result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid_with_shock(self, grid): energy = mass / (time**2 * length) halfway = self.dimensions_of_mesh[0]/2 - 1 firsthalf = grid.x <= 0.5 | length secondhalf = grid.x > 0.5 | length grid[firsthalf].rho = 4.0 | density grid[firsthalf].energy = (1.0 | energy) / (self.gamma - 1) grid[secondhalf].rho = 1.0 | density grid[secondhalf].energy = (0.1795 | energy) / (self.gamma - 1) def set_initial_conditions(self, instance): if self.name_of_the_code in self.sph_hydro_codes: initial_grid = self.new_grid() self.initialize_grid_with_shock(initial_grid) if self.name_of_the_code == "fi": initial_grid.position -= 0.5 | length sph_particles = convert_grid_to_SPH( initial_grid, self.number_of_particles) instance.gas_particles.add_particles(sph_particles) else: for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid_with_shock(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() instance.initialize_grid() def copy_results(self, instance): if self.name_of_the_code in self.sph_hydro_codes: n_samples = self.number_of_grid_points * 3 result = Particles(n_samples) result.position = [ (x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, n_samples) ] x, y, z = result.x, result.y, result.z if self.name_of_the_code == "fi": x -= (0.5 | length) y -= (0.5 | length) z -= (0.5 | length) no_speed = [0.0]*n_samples | speed result.rho, result.rhovx, result.rhovy, result.rhovz, result.energy = [ self.convert_generic_units.to_generic(quantity) for quantity in instance.get_hydro_state_at_point(x, y, z, no_speed, no_speed, no_speed)] else: result = [] for x in instance.itergrids(): result.append(x.copy()) return result def get_solution_at_time(self, time): instance = self.new_instance_of_code() self.set_parameters(instance) self.set_initial_conditions(instance) print("start evolve") instance.evolve_model(time) print("copying results") result = self.copy_results(instance) print("terminating code") instance.stop() return result def store_attributes(x, rho, rhovx, energy, filename): output = text.CsvFileText(filename=filename) output.quantities = (x, rho, rhovx, energy) output.attribute_names = ("x", "rho", "rhovx", "energy") output.store() def store_attributes_of_line(grid, yindex=0, zindex=0, **options): store_attributes( grid.x[..., yindex, zindex], grid.rho[..., yindex, zindex], grid.rhovx[..., yindex, zindex], grid.energy[..., yindex, zindex], filename="riemann_shock_tube_{name_of_the_code}_{number_of_grid_points}_{number_of_workers}.csv".format(**options) ) def new_option_parser(): result = OptionParser() result.add_option( "-n", "--mesh-size", dest="number_of_grid_points", type="int", default=10, help="number of grid cells in the x, y and z direction" ) result.add_option( "-w", "--workers", dest="number_of_workers", type="int", default=1, help="number of parallel workers to start" ) result.add_option( "-c", "--code", dest="name_of_the_code", default="athena", help="name of the code to use" ) result.add_option( "-p", "--number_of_particles", dest="number_of_particles", type="int", default=10000, help="number of particles, in case code is an SPH code" ) return result def test_riemann_shocktube_problem(): exact = CalculateExactSolutionIn1D() x, rho, p, u = exact.get_solution_at_time(0.12 | time) model = CalculateSolutionIn3D() model.name_of_the_code = "capreole" model.dimensions_of_mesh = (500, 1, 1) grids = model.get_solution_at_time(0.12 | time) grid = grids[0] model_x = grid.x[..., 0, 0] density = grid.rho[..., 0, 0] index_in_model = searchsorted(model_x.value_in(length), 0.56) index_in_exact = searchsorted(x.value_in(length), 0.56) # store_attributes_of_line(grid, name_of_the_code = "athena-test", number_of_grid_points = 500, number_of_workers = 1) assert abs((rho[index_in_exact] - density[index_in_model]) / density[index_in_model]) < 1.e-3 | units.none def main(**options): print("calculating shock using exact solution") exact = CalculateExactSolutionIn1D() xpositions, rho, p, u = exact.get_solution_at_time(0.12 | time) print("calculating shock using code") model = CalculateSolutionIn3D(**options) grids = model.get_solution_at_time(0.12 | time) print("sampling grid") if model.name_of_the_code in model.sph_hydro_codes: samples = grids else: samplepoints = [ (x, 0.5, 0.5) | length for x in numpy.linspace(0.0, 1.0, 2000)] print(len(grids)) samples = SamplePointsOnMultipleGrids( grids, samplepoints, SamplePointOnCellCenter) print(len(samples)) samples.filterout_duplicate_indices() print(len(samples)) print("saving data") store_attributes(xpositions, rho, u, p, filename="exact_riemann_shock_tube_problem.csv") store_attributes(samples.x, samples.rho, samples.rhovx, samples.energy, filename="riemann_shock_tube_problem.csv") if IS_PLOT_AVAILABLE: print("plotting solution") plot.plot(xpositions, rho) plot.scatter(samples.x, samples.rho) pyplot.xlim(0.3, 0.7) pyplot.ylim(0.5, 4.5) pyplot.savefig("riemann_shock_tube_rho_"+model.name_of_the_code+".png") pyplot.show() if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
16,622
32.246
126
py
amuse
amuse-main/examples/applications/vader_ring.py
import numpy as np import matplotlib.pyplot as plt import scipy.constants as physcons from scipy.special import ive from amuse.units import units from amuse.community.vader.interface import Vader kB = physcons.k*1e7 | units.erg/units.K mH = 1e3*physcons.physical_constants['atomic mass constant'][0]*1.00794 | units.g mu = 2.33 def setup_vader (ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc): viscous = Vader(mode='ring', redirection='none') viscous.parameters.alpha_function = True viscous.parameters.inner_pressure_boundary_type = 3 viscous.parameters.inner_boundary_function = True viscous.parameters.outer_pressure_boundary_type = 3 viscous.parameters.outer_boundary_function = True viscous.parameters.gamma = 1.000001 viscous.parameters.minimum_timestep = 1e-20 viscous.parameters.number_of_user_parameters = 5 viscous.parameters.verbosity = 1 viscous.initialize_keplerian_grid(4096, True, 1.5e12|units.cm, 1.5e14|units.cm, 1.99e33|units.g) idx = np.argmax(viscous.grid.r > ring_loc) init_col = ring_mass / viscous.grid.area[idx] viscous.set_parameter(0, kinematic_visc.value_in(units.cm**2/units.s)) viscous.set_parameter(1, ring_loc.value_in(units.cm)) viscous.set_parameter(2, ring_mass.value_in(units.g)) viscous.set_parameter(3, init_col.value_in(units.g/units.cm**2)/col_ratio) viscous.set_parameter(4, (init_temp*kB/(mu*mH)).value_in((units.cm/units.s)**2)) return viscous def setup_initial_conditions (viscous, ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc): t0 = ring_loc**2/(12.*kinematic_visc) col0 = ring_mass / (np.pi*ring_loc**2) pres0 = col0 * init_temp*kB/(mu*mH) idx = np.argmax(viscous.grid.r > ring_loc) init_col = ring_mass / viscous.grid.area[idx] col = np.ones(len(viscous.grid.r))*init_col/col_ratio col[idx] = init_col pres = col*init_temp*kB/(mu*mH) viscous.grid.column_density = col viscous.grid.pressure = pres def plot_results (viscous, times, col, ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc): fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) colors = ['k', 'r', 'g', 'b'] x = viscous.grid.r/ring_loc t0 = ring_loc**2/(12.*kinematic_visc) col0 = ring_mass / (np.pi*ring_loc**2) idx = np.argmax(x > 1.) init_col = ring_mass / viscous.grid.area[idx] for i in range(len(times)): ax1.scatter(x[::64], (col[i]/col0)[::64], c=colors[i]) col_analytic = (col0 / (times[i]/t0) * x**-0.25 * np.exp(-(1-x)**2 / \ (times[i]/t0)) * ive(0.25, 2*x/(times[i]/t0))) ax1.plot(x, col_analytic/col0, c=colors[i], label='$t/t_0=$'+str(times[i]/t0)) ax2.plot(x, np.abs((col[i] - col_analytic - init_col/col_ratio) / \ (col_analytic + init_col/col_ratio**0.5)), c=colors[i]) ax1.set_yscale('log') ax2.set_yscale('log') ax1.set_xlim(0., 2.) ax1.set_ylim(1e-6, 1e7) ax2.set_xlim(0., 2.) ax2.set_ylim(1e-6, 1e-1) ax2.set_xlabel('r/R$_0$') ax1.set_ylabel('$\\Sigma/\\Sigma_0$') ax2.set_ylabel('Error') ax1.axes.get_xaxis().set_visible(False) ax1.legend() plt.subplots_adjust(hspace=0) plt.savefig('KrumholzForbes2015_Fig4.pdf') def run_ring (ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc): viscous = setup_vader(ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc) setup_initial_conditions(viscous, ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc) grid_copy = viscous.grid.copy() ch_from_code = viscous.grid.new_channel_to(grid_copy) t0 = ring_loc**2/(12.*kinematic_visc) times = np.array([0.004, 0.008, 0.032, 0.128]) * t0 col = np.zeros((len(times),len(grid_copy))) | units.g/units.cm**2 for i in range(len(times)): viscous.evolve_model( times[i] ) ch_from_code.copy() col[i] = grid_copy.column_density plot_results(viscous, times, col, ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc) if __name__ == '__main__': ring_mass = 1.99e27 | units.g init_temp = 1e2 | units.K col_ratio = 1e10 ring_loc = 7.5e13 | units.cm kinematic_visc = 5.93e12 | units.cm**2/units.s print ("(Partial) reproduction of Figure 4 in Krumholz & Forbes 2015") run_ring(ring_mass, init_temp, col_ratio, ring_loc, kinematic_visc)
4,473
28.434211
84
py
amuse
amuse-main/examples/applications/mercury_solarsystem4.py
import numpy from amuse.community.mercury.interface import MercuryWayWard from amuse.community.sse.interface import SSE from amuse.ext.solarsystem import new_solar_system_for_mercury from amuse.units import units # from amuse.units.quantities import VectorQuantity from amuse.plot import ( plot, native_plot, plot3 ) try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False class SSEWithMassEvolve(SSE): def __init__(self, **options): SSE.__init__(self, convert_nbody=None, **options) def evolve_mass(self, mass): current_mass = self.particles[0].mass current_time = self.particles[0].age rc = 60.0 | (units.Gyr / units.MSun) print("find") while current_mass > mass: timestep = rc * (current_mass - mass) current_time += timestep # print timestep, current_time self.evolve_model(current_time) current_mass = self.particles[0].mass print("done") return current_time, current_mass def setup_codes(sun, planets): gd = MercuryWayWard() # debugger='xterm') gd.initialize_code() gd.central_particle.add_particles(sun) gd.orbiters.add_particles(planets) gd.commit_particles() se = SSEWithMassEvolve() se.commit_parameters() se.particles.add_particles(sun) se.commit_particles() return gd, se def testsse(): sse = SSEWithMassEvolve() sse.commit_parameters() sun, planets = new_solar_system_for_mercury() sse.particles.add_particles(sun) sse.commit_particles() channel = sse.particles.new_channel_to(sun) channel.copy() massrange = units.MSun(numpy.arange(1, 0.8, -0.001)) masses = [] | units.MSun timerange = [] | units.Myr for mass in massrange: sse.evolve_mass(mass) t, m = sse.evolve_mass(mass) timerange.append(t) channel.copy() masses.append(sse.particles[0].mass) sse.stop() plot(massrange, timerange, '.') native_plot.show() def polyevolve(): sun, planets = Solarsystem.new_solarsystem() gd, se = setup_codes(sun, planets) channelp = gd.orbiters.new_channel_to(planets) channels = se.particles.new_channel_to(sun) prev_mass = sun[0].mass massrange = units.MSun(numpy.arange(0.9, 0.89999, -1e-9)) masses = [] | units.MSun timerange = [] | units.Myr for i, mass in enumerate(massrange): time, dummymass = se.evolve_mass(mass) if i == 0: initialtime = time print(time,mass,"evolving gd") gdtime = time-initialtime print(gdtime) err = gd.evolve_model(gdtime) channelp.copy() planets.savepoint(time) channels.copy() gd.central_particle.mass = sun[0].mass print(sun[0].mass) print( sun[0].mass.value_in(units.MSun), time.value_in(units.Myr), planets[4].x.value_in(units.AU), planets[4].y.value_in(units.AU), planets[4].z.value_in(units.AU), ) gd.stop() se.stop() for planet in planets: t, x = planet.get_timeline_of_attribute_as_vector("x") t, y = planet.get_timeline_of_attribute_as_vector("y") t, z = planet.get_timeline_of_attribute_as_vector("z") plot3(x, y, z, '.') native_plot.gca().set_aspect('equal') native_plot.show() if __name__ == '__main__': testsse() # polyevolve()
3,567
25.827068
62
py
amuse
amuse-main/examples/applications/linear_wave.py
""" In this script we simulate a 1d linear wave in a 2d field """ import numpy # from amuse.support.core import late # from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, speed, mass, density ) from amuse.community.capreole.interface import Capreole from amuse import io # from amuse.io import text from amuse.datamodel import Grid # from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation # from amuse.datamodel.grids import SamplePointOnCellCenter try: # from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False class CalculateLinearWave1D(object): gamma = 5.0/3.0 wave_flag = 0 def __init__(self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="athena", amplitude=1e-4 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=10, ): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.amplitude = amplitude self.vflow_factor = vflow_factor self.grid_length = 1.0 | length self.number_of_steps = number_of_steps self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 1 ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 3 ) result.parameters.gamma = self.gamma return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena(number_of_workers=self.number_of_workers) result.parameters.gamma = self.gamma result.parameters.courant_number = 0.8 return result def new_instance_of_mpiamrvac_code(self): from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac( mode="2d", number_of_workers=self.number_of_workers, debugger="xterm") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = self.grid_length instance.parameters.length_y = self.grid_length instance.parameters.length_z = self.grid_length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def new_rhoe_right_eigenmatrix(self, velocity, amplitude, enthalpy): right_eigenmatrix = numpy.zeros((5, 5)) | speed right_eigenmatrix[0][0] = 1.0 | speed right_eigenmatrix[1][0] = velocity[0] - amplitude right_eigenmatrix[2][0] = velocity[1] right_eigenmatrix[3][0] = velocity[2] right_eigenmatrix[4][0] = ( 1.0 | time/length) * (enthalpy - velocity[0]*amplitude) # right_eigenmatrix[0][1] = 0.0; # right_eigenmatrix[1][1] = 0.0; right_eigenmatrix[2][1] = 1.0 | speed # right_eigenmatrix[3][1] = 0.0; right_eigenmatrix[4][1] = velocity[1] # right_eigenmatrix[0][2] = 0.0; */ # right_eigenmatrix[1][2] = 0.0; */ # right_eigenmatrix[2][2] = 0.0; */ right_eigenmatrix[3][2] = 1.0 | speed right_eigenmatrix[4][2] = velocity[2] right_eigenmatrix[0][3] = 1.0 | speed right_eigenmatrix[1][3] = velocity[0] right_eigenmatrix[2][3] = velocity[1] right_eigenmatrix[3][3] = velocity[2] right_eigenmatrix[4][3] = 0.5*velocity.length() right_eigenmatrix[0][4] = 1.0 | speed right_eigenmatrix[1][4] = velocity[0] + amplitude right_eigenmatrix[2][4] = velocity[1] right_eigenmatrix[3][4] = velocity[2] right_eigenmatrix[4][4] = ( 1.0 | time/length) * (enthalpy + velocity[0]*amplitude) return right_eigenmatrix def initialize_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) rho = 1.0 | density pressure = (1.0/self.gamma) | (mass / (length * time**2)) vx = (self.gamma * pressure / rho).sqrt() velocity = self.vflow_factor * vx * [1.0, 0.0, 0.0] velocity_squared = velocity.length() energy = (pressure/(self.gamma - 1.0) + (0.5 | length / time)*rho*velocity_squared) enthalpy = (energy + pressure)/rho amplitude_squared = (self.gamma - 1.0) * max( enthalpy - (0.5 | length/time) * velocity_squared, 1e-100 | enthalpy.unit) amplitude = amplitude_squared.sqrt() nwave = 5 eigenvalues = ([0] * nwave) | speed eigenvalues[0] = velocity[0] - amplitude eigenvalues[1] = velocity[0] eigenvalues[2] = velocity[0] eigenvalues[3] = velocity[0] eigenvalues[4] = velocity[0] + amplitude right_eigenmatrix = self.new_rhoe_right_eigenmatrix( velocity, amplitude, enthalpy) grid.rho = rho grid.energy = energy grid.rhovy = rho*self.vflow_factor*(1.0 | speed) wave = self.amplitude*numpy.sin(grid.y * (2.0 | length**-1)*numpy.pi) grid.rho += wave * \ right_eigenmatrix[0][self.wave_flag] * \ (1.0 | mass * time**2 / length**5) grid.rhovx += wave * \ right_eigenmatrix[3][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.rhovy += wave * \ right_eigenmatrix[1][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.rhovz += wave * \ right_eigenmatrix[2][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.energy += wave * \ right_eigenmatrix[4][self.wave_flag] * (1.0 | mass / length**3) def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "linear_wave_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def get_solution_at_time(self, time): instance = self.new_instance_of_code() self.set_parameters(instance) self.start_grids = [] for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid(inmem) self.start_grids.append(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() print("start evolve") dt = time / self.number_of_steps t = dt step = 1 while t <= time: if t == time: instance.parameters.must_evolve_to_exact_time = True else: instance.parameters.must_evolve_to_exact_time = False instance.evolve_model(t) # , instance.parameters.must_evolve_to_exact_time print("time : ", t, instance.model_time) t += dt step += 1 print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def main(): number_of_grid_points = 64 name_of_the_code = 'athena' model = CalculateLinearWave1D( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code, amplitude=0.1 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=5 ) if not IS_PLOT_AVAILABLE: return grids = model.get_solution_at_time(1.0 | time) rho0 = model.start_grids[0].rho[..., ..., 0].value_in(density) rho = grids[0].rho[..., ..., 0].value_in(density) drho = rho - rho0 print(drho.sum(), rho[0][0], rho0[0][0], drho[0][0]) x = grids[0].x[..., ..., 0].value_in(length) y = grids[0].y[..., ..., 0].value_in(length) figure = pyplot.figure(figsize=(10, 10)) plot = figure.add_subplot(1, 1, 1, projection='3d') plot.plot_surface(x, y, drho) plot.plot_surface(x, y, rho) figure.savefig('kelvin_helmholtz_{0}_{1}.png'.format( name_of_the_code, number_of_grid_points)) pyplot.show() if __name__ == "__main__": main()
9,855
32.753425
77
py
amuse
amuse-main/examples/applications/cloudshock.py
import numpy try: from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False from amuse.ext import cloud from amuse.units import generic_unit_system from amuse.community.capreole.interface import Capreole from amuse import io from amuse import datamodel class CalculateCloudShock(object): number_of_workers = 1 number_of_grid_points = 10 mesh_length = 10.0 | generic_unit_system.length gamma = 5.0/3.0 name_of_the_code = "athena" def __init__( self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="capreole"): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points * 4, self.number_of_grid_points, ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) result.initialize_code() result.parameters.x_boundary_conditions = ("reflective", "reflective") result.parameters.y_boundary_conditions = ("outflow", "outflow") result.parameters.z_boundary_conditions = ("reflective", "reflective") return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena( number_of_workers=self.number_of_workers, redirection="none") result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 result.parameters.x_boundary_conditions = ("reflective", "reflective") result.parameters.y_boundary_conditions = ("outflow", "outflow") result.parameters.z_boundary_conditions = ("reflective", "reflective") return result def new_instance_of_mpiamrvac_code(self): from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac(number_of_workers=self.number_of_workers) # , redirection="none") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() result.parameters.maximum_number_of_grid_levels = 3 result.parameters.spatial_discretization_method = 'tvdmu' result.parameters.predictor_step_discretization_method = 'tvdmu' result.parameters.entropy_type = 'powell' result.parameters.courant_number = 0.8 result.parameters.x_boundary_conditions = ("cont", "cont") result.parameters.y_boundary_conditions = ("cont", "cont") result.parameters.z_boundary_conditions = ("cont", "cont") return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = self.mesh_length instance.parameters.length_y = 4 * self.mesh_length instance.parameters.length_z = self.mesh_length result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [ 1, 1, 1] | generic_unit_system.length) self.clear_grid(grid) return grid def initialize_grid(self, grid): center = self.mesh_length/2.0 * [1.0, 1.0, 1.0] cloud.fill_grid_with_cloud_shock( grid, center=center, radius=1.0 | generic_unit_system.length, subgridsize=4 ) def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "cloudshock_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def refine_grid(self, instance): if hasattr(instance, 'refine_grid'): must_refine = True while must_refine: must_refine = instance.refine_grid() for x in instance.itergrids(): inmem = x.copy() self.initialize_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() def get_tau(self): rc = 1. xi = 10. cs = numpy.sqrt((self.gamma-1.0)) cs_out = numpy.sqrt((self.gamma-1.0)*xi) vs = cs_out*2.7 return (1.6*2*rc*xi**0.5/vs) | generic_unit_system.time def get_solution_at_time(self, time): instance = self.new_instance_of_code() self.set_parameters(instance) for x in instance.itergrids(): inmem = x.copy() self.initialize_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() self.refine_grid(instance) instance.initialize_grid() self.store_grids(instance.itergrids(), 0) if time > 0.0 | generic_unit_system.time: print("start evolve") dt = time / 10.0 t = dt step = 1 while t <= time: instance.evolve_model(t) print("time : ", t) #self.store_grids(instance.itergrids(), step) t += dt step += 1 print("sampling results") sample = datamodel.Grid.create( (1000, 4000), (10.0, 40) | generic_unit_system.length ) sample.z = 5.0 | generic_unit_system.length rho, rhovx, rhovy, rhovx, rhoen = instance.get_hydro_state_at_point( sample.x.flatten(), sample.y.flatten(), sample.z.flatten()) sample.rho = rho.reshape(sample.shape) sample.rhovx = rhovx.reshape(sample.shape) sample.rhovy = rhovy.reshape(sample.shape) sample.rhovz = rhovx.reshape(sample.shape) sample.energy = rhoen.reshape(sample.shape) print("terminating code") instance.stop() return sample def main(): number_of_grid_points = 40 name_of_the_code = 'athena' model = CalculateCloudShock( number_of_grid_points=number_of_grid_points, number_of_workers=6, name_of_the_code=name_of_the_code ) result = model.get_solution_at_time(0.75 * model.get_tau()) rho = result.rho.value_in(generic_unit_system.density) print("done") if not IS_PLOT_AVAILABLE: return levels = numpy.linspace(numpy.min(rho), numpy.max(rho), 255) figure = pyplot.figure(figsize=(10, 10)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('cloudshock_{0}_{1}.png'.format( name_of_the_code, number_of_grid_points)) pyplot.show() if __name__ == "__main__": main()
7,222
31.102222
93
py
amuse
amuse-main/examples/applications/mercury_example.py
import numpy from amuse.community.mercury.interface import MercuryInterface try: # from amuse import plot from matplotlib import pyplot HAS_MATPLOTLIB = True IS_PLOT_AVAILABLE = True except ImportError: HAS_MATPLOTLIB = False IS_PLOT_AVAILABLE = False # from amuse.support.core import late # from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, speed, mass, density ) from amuse.community.capreole.interface import Capreole from amuse import io # from amuse.io import text from amuse.datamodel import Grid # from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation # from amuse.datamodel.grids import SamplePointOnCellCenter class CalculateKelvinHelmholtzInstability(object): number_of_workers = 1 number_of_grid_points = 10 gamma = 1.4 # 5.0/3.0 name_of_the_code = "capreole" def __init__( self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="capreole"): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 1 ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) result.initialize_code() self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 3 ) return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena( number_of_workers=self.number_of_workers, debugger="xterm") result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.8 print(result.define_subgrid(1, 800, 200, 1, 0, 500, 0)) print(result.define_subgrid(1, 800, 200, 1, 0, 100, 0)) return result def new_instance_of_mpiamrvac_code(self): from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac( mode="2d", number_of_workers=self.number_of_workers, debugger="xterm") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid(self, grid): vx = 0.5 | speed p = 2.5 | (mass / (length * time**2)) halfway = self.dimensions_of_mesh[0]/2 - 1 outerregion = numpy.logical_or( grid.y <= 0.25 | length, grid.y >= 0.75 | length) innerregion = numpy.logical_and( grid.y > 0.25 | length, grid.y < 0.75 | length) grid[outerregion].rho = 1 | density grid[outerregion].rhovx = vx * grid[outerregion].rho grid[innerregion].rho = 2.0 | density grid[innerregion].rhovx = -vx * grid[innerregion].rho grid.energy = p / (self.gamma - 1) def pertubate_grid(self, grid): amplitude = 0.01 | speed grid.rhovx += grid.rho * amplitude * \ (numpy.random.rand(*grid.shape) - 0.5) grid.rhovy += grid.rho * amplitude * \ (numpy.random.rand(*grid.shape) - 0.5) grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "kelvin_helmholtz_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def get_solution_at_time(self, time): instance = self.new_instance_of_code() self.set_parameters(instance) for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid(inmem) self.pertubate_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() self.store_grids(instance.itergrids(), 0) instance.initialize_grid() self.store_grids(instance.itergrids(), 0) print("start evolve") dt = time / 10.0 t = dt step = 1 while t < time: instance.evolve_model(t) print("time : ", t) self.store_grids(instance.itergrids(), step) t += dt step += 1 print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def main(): number_of_grid_points = 400 name_of_the_code = 'athena' model = CalculateKelvinHelmholtzInstability( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code ) if not IS_PLOT_AVAILABLE: return grids = model.get_solution_at_time(1.0 | time) rho = grids[0].rho[..., ..., 0].value_in(density) figure = pyplot.figure(figsize=(20, 20)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('kelvin_helmholtz_{0}_{1}.png'.format( name_of_the_code, number_of_grid_points)) pyplot.show() if __name__ == "__main__": instance = MercuryInterface() instance.initialize_code() mass = 3.04043264264672381E-06 dens = 5.52 x = 2.42093942183383037E-01 y = -9.87467766698604366E-01 z = -4.54276292555233496E-06 vx = 1.64294055023289365E-02 vy = 4.03200725816140870E-03 vz = 1.13609607260006795E-08 sx = sy = sz = 0. celimit = 20. pid, err = instance.new_orbiter( mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit) instance.commit_particles() t_end = 365.25*1e6 time = 0 xx = [x] yy = [y] while time < t_end: time = time+365.25*1e3 err = instance.evolve_model(time) mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit, err = \ instance.get_orbiter_state(pid) print(x, y) xx.append(x) yy.append(y) instance.stop()
7,777
29.147287
76
py
amuse
amuse-main/examples/applications/christmas_card_2010.py
import os.path from amuse.test.amusetest import get_path_to_results try: from matplotlib import pyplot HAS_MATPLOTLIB = True # from amuse.plot import plot, semilogy, xlabel, ylabel, loglog except ImportError: HAS_MATPLOTLIB = False from amuse.units import units from amuse.units import constants from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits # from amuse.support.exceptions import AmuseException from amuse.community.mesa.interface import MESA # from amuse.community.gadget2.interface import Gadget2 from amuse.community.fi.interface import Fi from amuse.ext.star_to_sph import convert_stellar_model_to_SPH import numpy from amuse.datamodel import Particles from amuse.datamodel import ParticlesSuperset from amuse.datamodel import Grid def head_on_stellar_merger( masses=[0.3, 3.0] | units.MSun, star_age=310.0 | units.Myr, initial_separation=4.0 | units.RSun, angle=numpy.pi / 3, initial_speed=3000.0 | units.km / units.s, initial_speed_perpendicular=30.0 | units.km / units.s, number_of_sph_particles=50000, t_end=1.0e4 | units.s, sph_code=Fi, ): """ masses: Mass of the two stars star_age: Initial age of the stars number_of_sph_particles: Total number of particles of both stars, divided according to their masses t_end: (Physical, not computational) duration of the hydrodynamics simulation sph_code: Code to use for the hydrodynamics simulation """ # Convert some of the input parameters to string, for use in output file # names: n_string = "n" + ("%1.0e" % (number_of_sph_particles) ).replace("+0", "").replace("+", "") t_end_string = "t" + ("%1.0e" % (t_end.value_in(units.s)) ).replace("+0", "").replace("+", "") base_output_file_name = os.path.join( get_path_to_results(), "stellar_merger_"+n_string+"_"+t_end_string) stars = Particles(2) stars.mass = masses try: stellar_evolution = MESA() stellar_evolution.initialize_code() except: print("MESA was not built. Returning.") return stellar_evolution.commit_parameters() stellar_evolution.particles.add_particles(stars) stellar_evolution.commit_particles() print("Evolving stars with MESA...") stellar_evolution.evolve_model(star_age) number_of_sph_particles_1 = int( round( number_of_sph_particles * ( stellar_evolution.particles[0].mass / stellar_evolution.particles.mass.sum() ) ) ) number_of_sph_particles_2 = ( number_of_sph_particles - number_of_sph_particles_1 ) print("Creating initial conditions from a MESA stellar evolution model:") print( stellar_evolution.particles[0].mass, "star consisting of", number_of_sph_particles_1, "particles." ) sph_particles_1 = convert_stellar_model_to_SPH( stellar_evolution.particles[0], number_of_sph_particles_1, seed=12345 ).gas_particles print( stellar_evolution.particles[1].mass, "star consisting of", number_of_sph_particles_2, "particles." ) sph_particles_2 = convert_stellar_model_to_SPH( stellar_evolution.particles[1], number_of_sph_particles_2 ).gas_particles initial_separation += stellar_evolution.particles.radius.sum() sph_particles_2.x += numpy.cos(angle) * initial_separation sph_particles_2.y += numpy.sin(angle) * initial_separation sph_particles_1.vx += numpy.cos(angle) * initial_speed - \ numpy.sin(angle) * initial_speed_perpendicular sph_particles_1.vy += numpy.cos(angle) * initial_speed_perpendicular + \ numpy.sin(angle) * initial_speed view = [-0.5, 0.5, -0.5, 0.5] * \ (initial_separation + stellar_evolution.particles.radius.sum()) stellar_evolution.stop() all_sph_particles = ParticlesSuperset([sph_particles_1, sph_particles_2]) all_sph_particles.move_to_center() unit_converter = ConvertBetweenGenericAndSiUnits( 1.0 | units.RSun, constants.G, t_end) hydro_legacy_code = sph_code(unit_converter) n_steps = 100 hydro_legacy_code.parameters.n_smooth = 96 try: hydro_legacy_code.parameters.timestep = t_end / n_steps except Exception as exc: if "parameter is read-only" not in str(exc): raise hydro_legacy_code.gas_particles.add_particles(all_sph_particles) print("Evolving to t =", t_end, " (using", sph_code.__name__, "SPH code).") for time, i_step in [(i*t_end/n_steps, i) for i in range(1, n_steps+1)]: hydro_legacy_code.evolve_model(time) if not i_step % 4: hydro_plot( view, hydro_legacy_code, (300, 300), base_output_file_name + "_hydro_image{0:=03}.png".format(i_step) ) hydro_legacy_code.stop() print("All done!\n") def hydro_plot(view, hydro_code, image_size, figname): """ view: the (physical) region to plot [xmin, xmax, ymin, ymax] hydro_code: hydrodynamics code in which the gas to be plotted is defined image_size: size of the output image in pixels (x, y) """ shape = (image_size[0], image_size[1], 1) size = image_size[0] * image_size[1] axis_lengths = [0.0, 0.0, 0.0] | units.m axis_lengths[0] = view[1] - view[0] axis_lengths[1] = view[3] - view[2] grid = Grid.create(shape, axis_lengths) grid.x += view[0] grid.y += view[2] speed = grid.z.reshape(size) * (0 | 1/units.s) rho, rhovx, rhovy, rhovz, rhoe = \ hydro_code.get_hydro_state_at_point( grid.x.reshape(size), grid.y.reshape(size), grid.z.reshape(size), speed, speed, speed) min_v = 800.0 | units.km / units.s max_v = 3000.0 | units.km / units.s min_rho = 3.0e-4 | units.g / units.cm**3 max_rho = 0.1 | units.g / units.cm**3 min_E = 1.0e11 | units.J / units.kg max_E = 1.0e13 | units.J / units.kg v_sqr = (rhovx**2 + rhovy**2 + rhovz**2) / rho**2 E = rhoe / rho log_v = numpy.log((v_sqr / min_v**2)) / numpy.log((max_v**2 / min_v**2)) log_rho = numpy.log((rho / min_rho)) / numpy.log((max_rho / min_rho)) log_E = numpy.log((E / min_E)) / numpy.log((max_E / min_E)) red = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_rho)).reshape(shape) green = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_v)).reshape(shape) blue = numpy.minimum(numpy.ones_like(rho.number), numpy.maximum( numpy.zeros_like(rho.number), log_E)).reshape(shape) alpha = numpy.minimum( numpy.ones_like(log_v), numpy.maximum( numpy.zeros_like(log_v), numpy.log((rho / (10*min_rho))) ) ).reshape(shape) rgba = numpy.concatenate((red, green, blue, alpha), axis=2) pyplot.figure(figsize=(image_size[0]/100.0, image_size[1]/100.0), dpi=100) im = pyplot.figimage(rgba, origin='lower') pyplot.savefig(figname, transparent=True, dpi = 100) print("\nHydroplot was saved to: ", figname) pyplot.close() if __name__ == "__main__": print("Running the simulation that formed the basis of the christmas card of Leiden Observatory of 2010.") print() print("Details:") print("The ornaments are the result of a smoothed particle simulation " \ "with 50000 equal mass particles of a 310 Myr star of 0.3 solar mass, " \ "which is ejected from a distance of 4 solar radii (left) " \ "with a velocity of 3000 km/s into a 3.0 solar mass star at an " \ "age of 310 Myr. The calculation was performed using the AMUSE " \ "(amusecode.org) software environment in which the stars were evolved " \ "using MESA to an age of 310 Myr before the encounter was performed " \ "using Fi. Each ornament, generated using pyplot, is a snapshot from the " \ "simulation, from top left to bottom right. The peak is created from a " \ "blend of all snapshots. The colors of the ornaments are, red: log " \ "of the density, green: log of the speed and for blue we used " \ "the log of the specific internal energy.") print() if HAS_MATPLOTLIB: head_on_stellar_merger() else: print("matplotlib is not installed. Install it in the site-packages folder of your Python installation. Returning.")
8,724
37.436123
124
py
amuse
amuse-main/examples/applications/vader_ringrad.py
import numpy as np import matplotlib.pyplot as plt import scipy.constants as physcons from scipy.special import ive from amuse.units import units from amuse.community.vader.interface import Vader kB = physcons.k*1e7 | units.erg/units.K mH = 1e3*physcons.physical_constants['atomic mass constant'][0]*1.00794 | units.g mu = 0.61 sigma = physcons.sigma*1e3 | units.erg/units.s / units.cm**2 / units.K**4 c = physcons.c*1e2 | units.cm/units.s a = 4*sigma/c dyne = units.g*units.cm/units.s**2 def setup_vader (ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc): viscous = Vader(mode='ringrad', redirection='none') viscous.parameters.alpha_function = True viscous.parameters.inner_boundary_function = True viscous.parameters.inner_pressure_boundary_type = 3 viscous.parameters.outer_boundary_function = True viscous.parameters.outer_pressure_boundary_type = 3 viscous.parameters.equation_of_state_function = True viscous.parameters.minimum_timestep = 1e-20 viscous.parameters.maximum_tolerated_change = 1. viscous.parameters.use_backwards_euler = True viscous.parameters.verbosity = 1 viscous.parameters.number_of_user_parameters = 5 viscous.parameters.interpolation_order = 1 viscous.initialize_keplerian_grid(4096, True, 1.5e10|units.cm, 1.5e12|units.cm, 5.97e33|units.g) idx = np.argmax(viscous.grid.r > ring_loc) init_col = ring_mass / viscous.grid.area[idx] viscous.set_parameter(0, kinematic_visc.value_in(units.cm**2/units.s)) viscous.set_parameter(1, ring_loc.value_in(units.cm)) viscous.set_parameter(2, ring_mass.value_in(units.g)) viscous.set_parameter(3, init_col.value_in(units.g/units.cm**2)/col_ratio) viscous.set_parameter(4, (init_teff*kB/(mu*mH)).value_in((units.cm/units.s)**2)) return viscous def setup_initial_conditions (viscous, ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc): gamma = 5./3. idx = np.argmax(viscous.grid.r > ring_loc) init_col = ring_mass / viscous.grid.area[idx] col = np.ones(len(viscous.grid.r)) * init_col/col_ratio col[idx] = init_col pres = col * init_teff*kB / (mu*mH) + 1./3.*f_z0*a*init_teff**4 eInt = col * init_teff*kB / (mu*mH*(gamma-1.)) + f_z0*a*init_teff**4 viscous.grid.column_density = col viscous.grid.pressure = pres viscous.grid.internal_energy = eInt def plot_results (viscous, times, pres, ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc): colors = ['k', 'r', 'g'] fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) x = viscous.grid.r/ring_loc t0 = ring_loc**2/(12.*kinematic_visc) #col0 = ring_mass / (np.pi*ring_loc**2) idx = np.argmax(x > 1.) init_col = ring_mass / viscous.grid.area[idx] fig = plt.figure() ax = fig.add_subplot(111) for i in range(len(times)): ax.plot(x, (pres[i]/f_z0).value_in(dyne/units.cm**2), c=colors[i], label='$t/t_0=${a}'.format(a=times[i]/t0)) ax.set_yscale('log') ax.set_xlim(0., 2.) ax.set_ylim(1e3, 1e9) ax.set_xlabel('$r/R_0$') ax.set_ylabel('$P/f_{z_0}$ [dyn cm$^{-2}$]') ax.legend(loc='upper right') plt.savefig('KrumholzForbes2015_Fig8.pdf') def run_ringrad (ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc, f_z0): viscous = setup_vader(ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc) setup_initial_conditions(viscous, ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc) grid_copy = viscous.grid.copy() ch_from_code = viscous.grid.new_channel_to(grid_copy) t0 = ring_loc**2/(12.*kinematic_visc) times = np.array([0.002, 0.032, 0.128]) * t0 pres = np.zeros((len(times),len(grid_copy))) | units.g/units.s**2 for i in range(len(times)): viscous.evolve_model( times[i] ) ch_from_code.copy() pres[i] = grid_copy.pressure plot_results(viscous, times, pres, ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc) if __name__ == '__main__': ring_mass = 1.99e27 | units.g init_teff = 1e4 | units.K col_ratio = 1e10 ring_loc = 7.5e11 | units.cm kinematic_visc = 1.483e11 | units.cm**2/units.s f_z0 = 7.5e9 | units.cm print ("(Partial) reproduction of Figure 8 in Krumholz & Forbes 2015") run_ringrad(ring_mass, init_teff, col_ratio, ring_loc, kinematic_visc, f_z0)
4,443
29.231293
84
py
amuse
amuse-main/examples/applications/kelvin_helmholtz.py
""" In this script we simulate Kelvin-Helmholtz Instability in 3d. """ import numpy # from amuse.support.core import late # from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, mass, speed, density ) from amuse.community.capreole.interface import Capreole from amuse import io # from amuse.io import text from amuse.datamodel import Grid # from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation # from amuse.datamodel.grids import SamplePointOnCellCenter try: # from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False class CalculateKelvinHelmholtzInstability(object): number_of_workers = 1 number_of_grid_points = 10 gamma = 1.4 # 5.0/3.0 name_of_the_code = "capreole" def __init__( self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="capreole"): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 1 ) def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) result.initialize_code() self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 3 ) return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena( number_of_workers=self.number_of_workers, debugger="xterm") result.initialize_code() result.parameters.gamma = self.gamma result.parameters.courant_number = 0.8 print(result.define_subgrid(1, 800, 200, 1, 0, 500, 0)) print(result.define_subgrid(1, 800, 200, 1, 0, 100, 0)) return result def new_instance_of_mpiamrvac_code(self): from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac( mode="2d", number_of_workers=self.number_of_workers, debugger="xterm") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def set_parameters(self, instance): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = 1 | length instance.parameters.length_y = 1 | length instance.parameters.length_z = 1 | length instance.parameters.x_boundary_conditions = ("periodic", "periodic") instance.parameters.y_boundary_conditions = ("periodic", "periodic") instance.parameters.z_boundary_conditions = ("periodic", "periodic") result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def initialize_grid(self, grid): vx = 0.5 | speed p = 2.5 | (mass / (length * time**2)) halfway = self.dimensions_of_mesh[0]/2 - 1 outerregion = numpy.logical_or( grid.y <= 0.25 | length, grid.y >= 0.75 | length) innerregion = numpy.logical_and( grid.y > 0.25 | length, grid.y < 0.75 | length) grid[outerregion].rho = 1 | density grid[outerregion].rhovx = vx * grid[outerregion].rho grid[innerregion].rho = 2.0 | density grid[innerregion].rhovx = -vx * grid[innerregion].rho grid.energy = p / (self.gamma - 1) def pertubate_grid(self, grid): amplitude = 0.01 | speed grid.rhovx += grid.rho * amplitude * \ (numpy.random.rand(*grid.shape) - 0.5) grid.rhovy += grid.rho * amplitude * \ (numpy.random.rand(*grid.shape) - 0.5) grid.energy += 0.5 * (grid.rhovx ** 2 + grid.rhovy ** 2 + grid.rhovz ** 2) / grid.rho def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "kelvin_helmholtz_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def get_solution_at_time(self, time): instance = self.new_instance_of_code() self.set_parameters(instance) for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid(inmem) self.pertubate_grid(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() self.store_grids(instance.itergrids(), 0) instance.initialize_grid() self.store_grids(instance.itergrids(), 0) print("start evolve") dt = time / 10.0 t = dt step = 1 while t < time: instance.evolve_model(t) print("time : ", t) self.store_grids(instance.itergrids(), step) t += dt step += 1 print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def main(): number_of_grid_points = 400 name_of_the_code = 'athena' model = CalculateKelvinHelmholtzInstability( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code ) if not IS_PLOT_AVAILABLE: return grids = model.get_solution_at_time(1.0 | time) rho = grids[0].rho[..., ..., 0].value_in(density) figure = pyplot.figure(figsize=(20, 20)) plot = figure.add_subplot(1, 1, 1) plot.imshow(rho, origin='lower') figure.savefig('kelvin_helmholtz_{0}_{1}.png'.format( name_of_the_code, number_of_grid_points)) pyplot.show() if __name__ == "__main__": main()
6,921
29.493392
76
py
amuse
amuse-main/examples/applications/asterisk_example.py
import numpy.random from amuse.units import units, nbody_system from amuse.ic.flatimf import new_flat_mass_distribution from amuse.ic.plummer import new_plummer_model from amuse.ext.particles_with_color import new_particles_with_blackbody_color from amuse.community.seba.interface import SeBa from amuse.community.bhtree.interface import BHTree from amuse.community.asterisk.interface import Asterisk def new_stellar_evolution(particles): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) return stellar_evolution def new_gravity(particles, converter): gravity = BHTree(converter) gravity.particles.add_particles(particles) return gravity if __name__ in ('__main__', '__plot__'): number_of_particles = 100 # create a Plummer sphere with a number of stars numpy.random.seed(12345) masses = new_flat_mass_distribution(number_of_particles) converter = nbody_system.nbody_to_si(1.0 | units.parsec, masses.sum()) particles = new_plummer_model(number_of_particles, converter) particles.mass = masses particles.move_to_center() # create simulation codes gravity = new_gravity(particles, converter) stellar_evolution = new_stellar_evolution(particles) # create channels to and from the local particle set and the simulations from_gravity_to_local = gravity.particles.new_channel_to(particles) from_stellar_evolution_to_local = \ stellar_evolution.particles.new_channel_to(particles) from_stellar_evolution_to_local.copy() # creating colored particles particles = new_particles_with_blackbody_color(particles) particles.alpha = 1.0 particles.radius = stellar_evolution.particles.radius.sqrt() * \ (1e4 | units.parsec).sqrt() # creating visualization code converter = nbody_system.nbody_to_si(10.0 | units.parsec, masses.sum()) visualization = Asterisk(converter, redirection="none") # optional: change OpenGL perspective settings # visualization.set_field_of_view(45.0) # visualization.set_z_near(0.1 | units.parsec) # visualization.set_z_far(3000.0 | units.parsec) # initialize code (creates gui windows) visualization.initialize_code() # optional: set the zoom and rotation of the visualization # visualization.parameters.rotation = (15, -15, 45) # visualization.parameters.camera_distance = 100 | units.parsec # add (now colored) particles to visualization visualization.particles.add_particles(particles) from_local_to_viz = particles.new_channel_to(visualization.particles) visualization.store_view(0 | units.Myr) # evolve module for some time for i in range(1, 100): print('starting evolve to time = ', (i * 0.1 | units.Myr)) target_time = i * 0.1 | units.Myr gravity.evolve_model(target_time) from_gravity_to_local.copy() stellar_evolution.evolve_model(target_time) from_stellar_evolution_to_local.copy() from_local_to_viz.copy_attributes( ["x", "y", "z", "red", "green", "blue"] ) visualization.particles.radius = ( stellar_evolution.particles.radius.sqrt() * (1e4 | units.parsec).sqrt() ) print('updating visualization to time = ', target_time) visualization.store_view(target_time) visualization.stop() gravity.stop() stellar_evolution.stop()
3,433
35.531915
77
py
amuse
amuse-main/examples/applications/asterisk_movie_example.py
# import time import numpy.random from amuse.ic.flatimf import new_flat_mass_distribution from amuse.ic.plummer import new_plummer_model from amuse.units import nbody_system as nbody # from amuse.community.asterisk.interface import AsteriskInterface from amuse.community.asterisk.interface import Asterisk # from matplotlib import pyplot from amuse.units import units # from amuse.datamodel import Particles # from amuse.ic.brokenimf import new_scalo_mass_distribution from amuse.ext.particles_with_color import new_particles_with_blackbody_color from amuse.community.seba.interface import SeBa from amuse.community.bhtree.interface import BHTree def new_stellar_evolution(particles): stellar_evolution = SeBa() stellar_evolution.particles.add_particles(particles) return stellar_evolution def new_gravity(particles, converter): gravity = BHTree(converter) gravity.particles.add_particles(particles) return gravity if __name__ in ('__main__', '__plot__'): number_of_particles = 100 # create a Plummer sphere with a number of stars numpy.random.seed(12345) masses = new_flat_mass_distribution(number_of_particles) converter = nbody.nbody_to_si(1.0 | units.parsec, masses.sum()) particles = new_plummer_model(number_of_particles, converter) particles.mass = masses particles.move_to_center() # create simulation codes gravity = new_gravity(particles, converter) stellar_evolution = new_stellar_evolution(particles) # create channels to and from the local particle set and the simulations from_gravity_to_local = gravity.particles.new_channel_to(particles) from_stellar_evolution_to_local = \ stellar_evolution.particles.new_channel_to(particles) from_stellar_evolution_to_local.copy() # creating colored particles particles = new_particles_with_blackbody_color(particles) particles.alpha = 1.0 particles.radius = ( stellar_evolution.particles.radius.sqrt() * (1e4 | units.parsec).sqrt() ) # creating visualization code converter = nbody.nbody_to_si(10.0 | units.parsec, masses.sum()) visualization = Asterisk(converter, redirection="none") visualization.initialize_code() # optional: set the zoom and rotation of the visualization # visualization.parameters.rotation = (15, -15, 45) # visualization.parameters.camera_distance = 100 | units.parsec # add (now colored) particles to visualization visualization.particles.add_particles(particles) from_local_to_viz = particles.new_channel_to(visualization.particles) visualization.store_view(0 | units.Myr) # evolve module for some time for i in range(1, 100): target_time = i * 0.05 | units.Myr print('starting evolve to time = ', target_time) gravity.evolve_model(target_time) from_gravity_to_local.copy() stellar_evolution.evolve_model(target_time) from_stellar_evolution_to_local.copy() from_local_to_viz.copy_attributes( ["x", "y", "z", "red", "green", "blue"] ) visualization.particles.radius = ( stellar_evolution.particles.radius.sqrt() * (1e4 | units.parsec).sqrt() ) print('updating visualization to time = ', target_time) visualization.store_view(target_time) #give the user an opportunity to change the visualization settings input("\n\nTweak your visualization settings and press 'Enter' to continue... ") # generate screenshots while changing some visual parameters. for i in range(1, 100): visualization.parameters.rotation = (15, -i * 10, 0) visualization.parameters.camera_distance = ( 15.0 - (0.1 * i)) | units.parsec visualization.parameters.scene = i filename = "screenshot-%05d.png" % i visualization.screenshot(filename) visualization.stop() gravity.stop() stellar_evolution.stop()
3,988
35.935185
84
py
amuse
amuse-main/examples/applications/distributed_sunandearth.py
""" Example of usage of the distributed code based on the 'sunandearth' simple example. Evolves the dynamic evolution of the earth around the sun. """ from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse.community.hermite.interface import Hermite from amuse.community.distributed.interface import ( # DistributedAmuseInterface, DistributedAmuse, ) from amuse.community.distributed.interface import ( # Resource, # Resources, Pilot, # Pilots, ) from matplotlib import pyplot from amuse import datamodel import webbrowser def start_distributed_amuse(): print("Creating distributed amuse") distributed_amuse = DistributedAmuse(redirection='none') distributed_amuse.parameters.debug = True distributed_amuse.parameters.webinterface_port = 4556 distributed_amuse.use_for_all_workers() # open the address of the webinterface in a brower window webbrowser.open(distributed_amuse.get_webinterface_url()) # Add some resources # resource = Resource() # resource.name='some.machine' # resource.location="user@fs0.das4.cs.vu.nl" # resource.scheduler_type="sge" # resource.amuse_dir="/home/user/amuse" # distributed_amuse.resources.add_resource(resource) print("Resources:") print(distributed_amuse.resources) # Claim nodes on the resources. In this example simply the "local" machine pilot = Pilot() pilot.resource_name = 'local' pilot.node_count = 1 pilot.time = 2 | units.hour pilot.slots_per_node = 22 pilot.label = 'local' distributed_amuse.pilots.add_pilot(pilot) print("Pilots:") print(distributed_amuse.pilots) print("Waiting for pilots") distributed_amuse.wait_for_pilots() print("setting distributed as default channel") distributed_amuse.use_for_all_workers() return distributed_amuse def new_system_of_sun_and_earth(): stars = datamodel.Particles(2) sun = stars[0] sun.mass = 1.0 | units.MSun sun.position = (0.0, 0.0, 0.0) | units.m sun.velocity = (0.0, 0.0, 0.0) | (units.m / units.s) sun.radius = 1.0 | units.RSun earth = stars[1] earth.mass = 5.9736e24 | units.kg earth.radius = 6371.0 | units.km earth.position = (149.5e6, 0.0, 0.0) | units.km earth.velocity = (0.0, 29800, 0.0) | (units.m / units.s) return stars def simulate_system_until(particles, end_time): convert_nbody = nbody_system.nbody_to_si( 1.0 | units.MSun, 149.5e6 | units.km) instance = Hermite(convert_nbody) instance.parameters.epsilon_squared = 0.0 | units.AU**2 instance.particles.add_particles(particles) t0 = 0 | units.day dt = 10 | units.day t = t0 earth = instance.particles[1] x_values = quantities.AdaptingVectorQuantity() y_values = quantities.AdaptingVectorQuantity() while t < end_time: instance.evolve_model(t) x_values.append(earth.x) y_values.append(earth.y) t += dt instance.stop() return x_values, y_values def plot_track(x, y): figure = pyplot.figure(figsize=(5, 5)) plot = figure.add_subplot(1, 1, 1) x_values_in_AU = x.value_in(units.AU) y_values_in_AU = y.value_in(units.AU) plot.plot(x_values_in_AU, y_values_in_AU, color="b") plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) plot.set_xlabel('x (AU)') plot.set_ylabel('y (AU)') pyplot.show() if __name__ in ('__main__', '__plot__'): distributed_amuse = start_distributed_amuse() particles = new_system_of_sun_and_earth() x, y = simulate_system_until(particles, 20 | units.yr) plot_track(x, y) distributed_amuse.stop()
3,754
24.371622
78
py
amuse
amuse-main/examples/applications/linear_wave_boundaries.py
""" In this script we simulate a 1d linear wave in a 2d field, the periodic boundaries are not handled in the code but by amuse (much slower at time of writing) """ import numpy # from amuse.support.core import late # from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, speed, mass, density ) from amuse.community.capreole.interface import Capreole from amuse import io # from amuse.io import text from amuse.datamodel import Grid # from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation # from amuse.datamodel.grids import SamplePointOnCellCenter try: # from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False USE_BOUNDARIES = True class EvolveHydrodynamicsCodeWithAmusePeriodicBoundaries(object): def __init__(self, code, number_of_grid_points, nghost): self.code = code self.number_of_grid_points = number_of_grid_points self.nghost = nghost def set_parameters(self): self.code.parameters.x_boundary_conditions = ("interface", "interface") self.code.parameters.y_boundary_conditions = ("interface", "interface") self.code.stopping_conditions.number_of_steps_detection.enable() def init_channels(self): instance = self.code self.xbound1 = instance.get_boundary_grid('xbound1') self.xbound2 = instance.get_boundary_grid('xbound2') self.ybound1 = instance.get_boundary_grid('ybound1') self.ybound2 = instance.get_boundary_grid('ybound2') self.xbound1_channel = instance.grid[ self.number_of_grid_points - self.nghost:, ..., ... ].new_channel_to(self.xbound1) self.xbound2_channel = instance.grid[ 0: self.nghost, ..., ... ].new_channel_to( self.xbound2) self.ybound1_channel = instance.grid[ ..., self.number_of_grid_points-self.nghost:, ... ].new_channel_to( self.ybound1[ self.nghost:self.number_of_grid_points+self.nghost, ..., ... ]) self.ybound2_channel = instance.grid[ ..., 0:self.nghost, ... ].new_channel_to( self.ybound2[ self.nghost:self.number_of_grid_points+self.nghost, ..., ...] ) xbound1_bottom = self.xbound1[0:self.nghost, 0:self.nghost, ...] xbound1_top = self.xbound1[ 0:self.nghost, self.number_of_grid_points - self.nghost:, ...] ybound1_left = self.ybound1[0:self.nghost, 0:self.nghost, ...] ybound2_left = self.ybound2[0:self.nghost, 0:self.nghost, ...] self.xbound1_ybound1_channel = xbound1_top.new_channel_to(ybound1_left) self.xbound1_ybound2_channel = xbound1_bottom.new_channel_to( ybound2_left) xbound2_bottom = self.xbound2[0:self.nghost, 0:self.nghost, ...] xbound2_top = self.xbound2[ 0:self.nghost, self.number_of_grid_points - self.nghost:, ...] ybound1_right = self.ybound1[self.number_of_grid_points + self.nghost:, 0:self.nghost, ...] ybound2_right = self.ybound2[self.number_of_grid_points + self.nghost:, 0:self.nghost, ...] self.xbound2_ybound1_channel = xbound2_top.new_channel_to( ybound1_right) self.xbound2_ybound2_channel = xbound2_bottom.new_channel_to( ybound2_right) self.copy_to_boundary_cells() def copy_to_boundary_cells(self): self.xbound1_channel.copy() self.xbound2_channel.copy() self.ybound1_channel.copy() self.ybound2_channel.copy() self.xbound1_ybound1_channel.copy() self.xbound1_ybound2_channel.copy() self.xbound2_ybound1_channel.copy() self.xbound2_ybound2_channel.copy() def evolve_model(self, time, endtime): while self.code.model_time < time: if ( self.code.get_timestep() + self.code.model_time ) >= time and time == endtime: self.code.parameters.must_evolve_to_exact_time = True self.code.evolve_model(time) self.copy_to_boundary_cells() class EvolveHydrodynamicsCodeWithPeriodicBoundaries(object): def __init__(self, code): self.code = code def set_parameters(self): self.code.parameters.x_boundary_conditions = ("periodic", "periodic") self.code.parameters.y_boundary_conditions = ("periodic", "periodic") self.code.stopping_conditions.number_of_steps_detection.enable() def init_channels(self): pass def evolve_model(self, time, endtime): while self.code.model_time < time: if ( self.code.get_timestep() + self.code.model_time ) >= time and time == endtime: self.code.parameters.must_evolve_to_exact_time = True self.code.evolve_model(time) class CalculateLinearWave1D(object): gamma = 5.0/3.0 wave_flag = 0 def __init__(self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="athena", amplitude=1e-4 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=10, use_boundaries=True ): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.amplitude = amplitude self.vflow_factor = vflow_factor self.grid_length = 1.0 | length self.number_of_steps = number_of_steps self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 1 ) self.nghost = 4 self.use_boundaries = use_boundaries def new_instance_of_code(self): attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 3 ) self.nghost = 2 return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena(number_of_workers=self.number_of_workers) result.parameters.gamma = self.gamma result.parameters.courant_number = 0.8 self.nghost = 4 return result def new_instance_of_mpiamrvac_code(self): raise Exception( "MPIAMRVAC does not yet have support for detailed boundaries in amuse") from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac( mode="2d", number_of_workers=self.number_of_workers, debugger="xterm") result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def set_parameters(self, instance, evolve): instance.parameters.mesh_size = self.dimensions_of_mesh instance.parameters.length_x = self.grid_length instance.parameters.length_y = self.grid_length instance.parameters.length_z = self.grid_length instance.parameters.z_boundary_conditions = ("periodic", "periodic") evolve.set_parameters() result = instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def new_rhoe_right_eigenmatrix(self, velocity, amplitude, enthalpy): right_eigenmatrix = numpy.zeros((5, 5)) | speed right_eigenmatrix[0][0] = 1.0 | speed right_eigenmatrix[1][0] = velocity[0] - amplitude right_eigenmatrix[2][0] = velocity[1] right_eigenmatrix[3][0] = velocity[2] right_eigenmatrix[4][0] = ( 1.0 | time/length) * (enthalpy - velocity[0]*amplitude) # right_eigenmatrix[0][1] = 0.0; # right_eigenmatrix[1][1] = 0.0; right_eigenmatrix[2][1] = 1.0 | speed # right_eigenmatrix[3][1] = 0.0; right_eigenmatrix[4][1] = velocity[1] # right_eigenmatrix[0][2] = 0.0; */ # right_eigenmatrix[1][2] = 0.0; */ # right_eigenmatrix[2][2] = 0.0; */ right_eigenmatrix[3][2] = 1.0 | speed right_eigenmatrix[4][2] = velocity[2] right_eigenmatrix[0][3] = 1.0 | speed right_eigenmatrix[1][3] = velocity[0] right_eigenmatrix[2][3] = velocity[1] right_eigenmatrix[3][3] = velocity[2] right_eigenmatrix[4][3] = 0.5*velocity.length() right_eigenmatrix[0][4] = 1.0 | speed right_eigenmatrix[1][4] = velocity[0] + amplitude right_eigenmatrix[2][4] = velocity[1] right_eigenmatrix[3][4] = velocity[2] right_eigenmatrix[4][4] = ( 1.0 | time/length) * (enthalpy + velocity[0]*amplitude) return right_eigenmatrix def initialize_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) rho = 1.0 | density pressure = (1.0/self.gamma) | (mass / (length * time**2)) vx = (self.gamma * pressure / rho).sqrt() velocity = self.vflow_factor * vx * [1.0, 0.0, 0.0] velocity_squared = velocity.length() energy = (pressure/(self.gamma - 1.0) + (0.5 | length / time)*rho*velocity_squared) enthalpy = (energy + pressure)/rho amplitude_squared = (self.gamma - 1.0) * max( enthalpy - (0.5 | length/time) * velocity_squared, 1e-100 | enthalpy.unit) amplitude = amplitude_squared.sqrt() nwave = 5 eigenvalues = ([0] * nwave) | speed eigenvalues[0] = velocity[0] - amplitude eigenvalues[1] = velocity[0] eigenvalues[2] = velocity[0] eigenvalues[3] = velocity[0] eigenvalues[4] = velocity[0] + amplitude right_eigenmatrix = self.new_rhoe_right_eigenmatrix( velocity, amplitude, enthalpy) grid.rho = rho grid.energy = energy grid.rhovy = rho*self.vflow_factor*(1.0 | speed) wave = self.amplitude*numpy.sin(grid.y * (2.0 | length**-1)*numpy.pi) grid.rho += ( wave * right_eigenmatrix[0][self.wave_flag] * (1.0 | mass * time**2 / length**5) ) grid.rhovx += ( wave * right_eigenmatrix[3][self.wave_flag] * (1.0 | mass * time / length**4) ) grid.rhovy += ( wave * right_eigenmatrix[1][self.wave_flag] * (1.0 | mass * time / length**4) ) grid.rhovz += ( wave * right_eigenmatrix[2][self.wave_flag] * (1.0 | mass * time / length**4) ) grid.energy += ( wave * right_eigenmatrix[4][self.wave_flag] * (1.0 | mass / length**3) ) def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "linear_wave_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def new_evolve_object(self, instance): """Returns a special object to evolve to code in time""" if self.use_boundaries: return EvolveHydrodynamicsCodeWithAmusePeriodicBoundaries( instance, self.number_of_grid_points, self.nghost) else: return EvolveHydrodynamicsCodeWithPeriodicBoundaries(instance) def get_solution_at_time(self, time): instance = self.new_instance_of_code() evolve = self.new_evolve_object(instance) self.set_parameters(instance, evolve) self.start_grids = [] for x in instance.itergrids(): inmem = x.copy() self.clear_grid(inmem) self.initialize_grid(inmem) self.start_grids.append(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() evolve.init_channels() print("start evolve") dt = time / self.number_of_steps t = dt step = 1 while t <= time: instance.parameters.must_evolve_to_exact_time = False evolve.evolve_model(t, time) print("time : ", t, instance.model_time) # , instance.parameters.must_evolve_to_exact_time t += dt step += 1 print("copying results") result = [] for x in instance.itergrids(): result.append(x.copy()) print("terminating code") instance.stop() return result def main(): number_of_grid_points = 64 name_of_the_code = 'athena' model1 = CalculateLinearWave1D( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code, amplitude=1e-1 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=5, use_boundaries=True ) model2 = CalculateLinearWave1D( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code, amplitude=1e-1 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=5, use_boundaries=False ) if not IS_PLOT_AVAILABLE: return print("Evolve model with amuse implementing the periodic boundaries") grids1 = model1.get_solution_at_time(1.0 | time) print("Evolve model with the code implementing the periodic boundaries") grids2 = model2.get_solution_at_time(1.0 | time) rho1 = grids1[0].rho[..., ..., 0].value_in(density) rho2 = grids2[0].rho[..., ..., 0].value_in(density) drho = rho2 - rho1 print(drho.sum(), rho1[0][0], rho2[0][0], drho[0][0]) x = grids1[0].x[..., ..., 0].value_in(length) y = grids1[0].y[..., ..., 0].value_in(length) figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 2, 1, projection='3d') plot.plot_surface(x, y, drho) plot = figure.add_subplot(1, 2, 2, projection='3d') plot.plot_surface(x, y, rho1, color='r') figure.savefig('kelvin_helmholtz_{0}_{1}.png'.format( name_of_the_code, number_of_grid_points)) pyplot.show() if __name__ == "__main__": main()
15,714
33.922222
104
py
amuse
amuse-main/examples/applications/vader_selfsim.py
import numpy as np import matplotlib.pyplot as plt import scipy.constants as physcons from amuse.units import units from amuse.community.vader.interface import Vader kB = physcons.k*1e7 | units.erg/units.K mH = 1e3*physcons.physical_constants['atomic mass constant'][0]*1.00794 | units.g mu = 2.33 def setup_vader (R0, nu0, Mdot0, init_temp): viscous = Vader(mode='selfsim', redirection='none') viscous.parameters.alpha_function = True viscous.parameters.inner_pressure_boundary_type = 3 viscous.parameters.inner_boundary_function = True viscous.parameters.outer_pressure_boundary_type = 3 viscous.parameters.outer_boundary_function = True viscous.parameters.gamma = 1.000001 viscous.parameters.number_of_user_parameters = 4 viscous.parameters.begin_time = R0**2/(3.*nu0) viscous.parameters.verbosity = 1 viscous.initialize_keplerian_grid(512, False, 1.5e12|units.cm, 3.e14|units.cm, 1.99e33|units.g) viscous.set_parameter(0, nu0.value_in(units.cm**2/units.s)) viscous.set_parameter(1, R0.value_in(units.cm)) viscous.set_parameter(2, Mdot0.value_in(units.g/units.s)) viscous.set_parameter(3, (init_temp*kB/(mu*mH)).value_in((units.cm/units.s)**2)) return viscous def setup_initial_conditions (viscous, R0, nu0, Mdot0, init_temp): x = viscous.grid.r/R0 col1 = Mdot0/(3.*np.pi*nu0) col = col1 * np.exp(-x)/x pres = col * init_temp * kB/(mu*mH) viscous.grid.column_density = col viscous.grid.pressure = pres def plot_results (viscous, col, R0, nu0, Mdot0, init_temp): t0 = R0**2/(3.*nu0) col1 = Mdot0/(3.*np.pi*nu0) fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) colors = ['r', 'g', 'b'] x = viscous.grid.r/R0 T = 1. col_ana = np.exp(-x/T)/(x*T**(3./2.)) ax1.scatter(x[::16], col[0,::16]/col1, c='k') ax1.plot(x, col_ana, label='$t/t_s=$1', c='k') for i in range(3): T = i+2. col_ana = np.exp(-x/T)/(x*T**(3./2.)) ax1.scatter(x[::16], col[i+1,::16]/col1, c=colors[i]) ax1.plot(x, col_ana, label='$t/t_s=$'+str(i+2), c=colors[i]) ax2.plot(x, np.abs((col[i+1]/col1 - col_ana)/col_ana), label='$t/t_s=$'+str(i+2), c=colors[i]) ax1.set_xlim(1e-1, 2e1) ax1.set_ylim(1e-10, 1e2) ax2.set_xlim(1e-1, 2e1) ax2.set_ylim(1e-7, 1e0) ax1.set_xlabel('$r/R_0$') ax1.set_ylabel('$\\Sigma/\\Sigma_0$') ax2.set_ylabel('|Error|') ax1.set_yscale('log') ax2.set_yscale('log') ax1.set_xscale('log') ax2.set_xscale('log') ax1.axes.get_xaxis().set_visible(False) ax1.legend() ax2.legend() plt.subplots_adjust(hspace=0) plt.savefig('KrumholzForbes2015_Fig1.pdf') def run_selfsim (R0, nu0, Mdot0, init_temp): viscous = setup_vader(R0, nu0, Mdot0, init_temp) setup_initial_conditions(viscous, R0, nu0, Mdot0, init_temp) grid_copy = viscous.grid.copy() ch_from_code = viscous.grid.new_channel_to(grid_copy) col = np.zeros((4,len(grid_copy))) | units.g/units.cm**2 col[0] = grid_copy.column_density t0 = R0**2/(3.*nu0) for i in range(3): viscous.evolve_model( (i+2)*t0 ) ch_from_code.copy() col[i+1] = grid_copy.column_density plot_results(viscous, col, R0, nu0, Mdot0, init_temp) if __name__ == '__main__': R0 = 1.5e13 | units.cm nu0 = 2.37e13 | units.cm**2/units.s Mdot0 = 6.3e19 | units.g/units.s init_temp = 1e2 | units.K print ("(Partial) reproduction of Figure 1 in Krumholz & Forbes 2015") print ("Slight numerical differences can arise due to differences in timestepping. The interface restarts every iteration with the initial timestep; VADER writes data during the run, slowing down if necessary, but not necessarily to the initial timestep.") run_selfsim(R0, nu0, Mdot0, init_temp)
3,889
26.202797
260
py
amuse
amuse-main/examples/applications/linear_wave_parts_live.py
""" In this script we simulate a 1d linear wave in a 2d field, the periodic boundaries are not handled in the code but by amuse (much slower at time of writing) """ import sys import numpy # import math # from amuse.support.core import late # from amuse.units.quantities import VectorQuantity from amuse.units.generic_unit_system import ( time, length, speed, mass, density ) from amuse.community.capreole.interface import Capreole from amuse import io # from amuse.io import text from amuse.datamodel import Grid # from amuse.datamodel.grids import SamplePointsOnMultipleGrids # from amuse.datamodel.grids import SamplePointWithIntepolation # from amuse.datamodel.grids import SamplePointOnCellCenter try: # from amuse import plot from matplotlib import pyplot from matplotlib import animation IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False USE_BOUNDARIES = True class EvolveHydrodynamicsCodeWithAmusePeriodicBoundaries(object): def __init__(self, code, number_of_grid_points, nghost): self.code = code self.number_of_grid_points = number_of_grid_points self.nghost = nghost def set_parameters(self): self.code.parameters.x_boundary_conditions = ("interface", "interface") self.code.parameters.y_boundary_conditions = ("interface", "interface") self.code.stopping_conditions.number_of_steps_detection.enable() def init_channels(self): instance = self.code self.xbound1 = instance.get_boundary_grid('xbound1') self.xbound2 = instance.get_boundary_grid('xbound2') self.ybound1 = instance.get_boundary_grid('ybound1') self.ybound2 = instance.get_boundary_grid('ybound2') self.xbound1_channel = instance.grid[ self.number_of_grid_points - self.nghost:, ..., ... ].new_channel_to(self.xbound1) self.xbound2_channel = instance.grid[ 0: self.nghost, ..., ...].new_channel_to(self.xbound2) self.ybound1_channel = instance.grid[ ..., self.number_of_grid_points-self.nghost:, ... ].new_channel_to( self.ybound1[ self.nghost:self.number_of_grid_points+self.nghost, ..., ...] ) self.ybound2_channel = instance.grid[ ..., 0:self.nghost, ... ].new_channel_to( self.ybound2[ self.nghost:self.number_of_grid_points+self.nghost, ..., ...] ) xbound1_bottom = self.xbound1[0:self.nghost, 0:self.nghost, ...] xbound1_top = self.xbound1[ 0:self.nghost, self.number_of_grid_points - self.nghost:, ...] ybound1_left = self.ybound1[0:self.nghost, 0:self.nghost, ...] ybound2_left = self.ybound2[0:self.nghost, 0:self.nghost, ...] self.xbound1_ybound1_channel = xbound1_top.new_channel_to(ybound1_left) self.xbound1_ybound2_channel = xbound1_bottom.new_channel_to( ybound2_left) xbound2_bottom = self.xbound2[0:self.nghost, 0:self.nghost, ...] xbound2_top = self.xbound2[ 0:self.nghost, self.number_of_grid_points - self.nghost:, ...] ybound1_right = self.ybound1[self.number_of_grid_points + self.nghost:, 0:self.nghost, ...] ybound2_right = self.ybound2[self.number_of_grid_points + self.nghost:, 0:self.nghost, ...] self.xbound2_ybound1_channel = xbound2_top.new_channel_to( ybound1_right) self.xbound2_ybound2_channel = xbound2_bottom.new_channel_to( ybound2_right) self.copy_to_boundary_cells() def copy_to_boundary_cells(self): self.xbound1_channel.copy() self.xbound2_channel.copy() self.ybound1_channel.copy() self.ybound2_channel.copy() self.xbound1_ybound1_channel.copy() self.xbound1_ybound2_channel.copy() self.xbound2_ybound1_channel.copy() self.xbound2_ybound2_channel.copy() def evolve_model(self, time, endtime): while self.code.model_time < time: if ( self.code.get_timestep() + self.code.model_time ) >= time and time == endtime: self.code.parameters.must_evolve_to_exact_time = True self.code.evolve_model(time) self.copy_to_boundary_cells() class EvolveHydrodynamicsCodeWithAmusePeriodicBoundariesAndNCodes(object): def __init__( self, codes, number_of_grid_points, number_of_grid_points_per_code, nghost): self.codes = codes self.number_of_grid_points = number_of_grid_points self.number_of_grid_points_per_code = number_of_grid_points_per_code self.nghost = nghost self.min_timestep = None def set_parameters(self): for code in self.codes: code.parameters.x_boundary_conditions = ("interface", "interface") code.parameters.y_boundary_conditions = ("interface", "interface") code.stopping_conditions.number_of_steps_detection.enable() def init_channels(self): channels = [] after_channels = [] for index in range(0, len(self.codes)): instance = self.codes[index] nx, ny, nz = instance.grid.shape print(nx,ny,nz) xbound1 = instance.get_boundary_grid('xbound1') xbound2 = instance.get_boundary_grid('xbound2') xbound1_nghost_x, _, ybound1_nghost_z = xbound1.shape xbound2_nghost_x, _, ybound2_nghost_z = xbound2.shape print(xbound1_nghost_x,xbound2_nghost_x) ybound1 = instance.get_boundary_grid('ybound1') ybound2 = instance.get_boundary_grid('ybound2') ybound1_nghost_x, ybound1_nghost_y, ybound1_nghost_z = ybound1.shape ybound2_nghost_x, ybound2_nghost_y, ybound2_nghost_z = ybound2.shape ybound1_nghost_x = (ybound1_nghost_x - nx) / 2 ybound2_nghost_x = (ybound2_nghost_x - nx) / 2 xbound1_channel = instance.grid[ nx - xbound1_nghost_x:, ..., ...].new_channel_to(xbound1) xbound2_channel = instance.grid[ 0:xbound2_nghost_x, ..., ...].new_channel_to(xbound2) if index == 0: instance11 = self.codes[-1] else: instance11 = self.codes[index-1] print(ybound1[ybound1_nghost_x:nx+ybound1_nghost_x, ..., ...].shape) print(instance11.grid[..., ny-ybound1_nghost_y:, ...].shape) ybound1_channel = instance11.grid[ ..., ny-ybound1_nghost_y:, ...].new_channel_to( ybound1[ ybound1_nghost_x:nx+ybound1_nghost_x, ..., ... ] ) nx11, ny11, nz11 = instance11.grid.shape ybound1_left_channel = instance11.grid[ 0:ybound1_nghost_x, ny11 - ybound1_nghost_y:, ... ].new_channel_to(ybound1[0:ybound1_nghost_x, ..., ...]) ybound1_right_channel = instance11.grid[ nx11-ybound1_nghost_x:, ny11 - ybound1_nghost_y:, ... ].new_channel_to(ybound1[nx+ybound1_nghost_x:, ..., ...]) if index == len(self.codes)-1: instance12 = self.codes[0] else: instance12 = self.codes[index+1] ybound2_channel = instance12.grid[ ..., 0:ybound2_nghost_y, ...].new_channel_to( ybound2[ ybound2_nghost_x:nx+ybound2_nghost_x, ..., ...] ) nx12, ny12, nz12 = instance12.grid.shape ybound2_left_channel = instance12.grid[ 0:ybound2_nghost_x, 0:ybound2_nghost_y, ... ].new_channel_to( ybound2[0:ybound2_nghost_x, ..., ...]) ybound2_right_channel = instance12.grid[ nx12-ybound2_nghost_x:, 0:ybound2_nghost_y, ... ].new_channel_to(ybound2[nx+ybound2_nghost_x:, ..., ...]) channels.append(xbound1_channel) channels.append(xbound2_channel) channels.append(ybound1_channel) channels.append(ybound2_channel) after_channels.append(ybound1_left_channel) after_channels.append(ybound1_right_channel) after_channels.append(ybound2_left_channel) after_channels.append(ybound2_right_channel) self.channels = channels self.channels.extend(after_channels) self.copy_to_boundary_cells() def copy_to_boundary_cells(self): for channel in self.channels: channel.copy() def evolve_model(self, time, endtime): code = self.codes[0] t_unit = code.get_timestep().unit while code.model_time < time: timesteps = [] | t_unit for x in self.codes: timesteps.append(x.get_timestep()) min_timestep = timesteps.min() if code.model_time == 0.0 | t_unit: min_timestep = time if (min_timestep + code.model_time) >= time and time == endtime: for x in self.codes: x.parameters.must_evolve_to_exact_time = True print(min_timestep) for x in self.codes: x.set_timestep(min_timestep) for x in self.codes: x.evolve_model(x.model_time + (min_timestep * 2)) print("MODEL_TIME:", x.model_time) self.copy_to_boundary_cells() class EvolveHydrodynamicsCodeWithAmusePeriodicBoundariesAndNCodesWithDifferentGridsSizes(object): """ first version, grids connect on the y axis, whole system is periodic """ def __init__( self, codes, number_of_grid_points, number_of_grid_points_per_code, nghost): self.codes = codes self.number_of_grid_points = number_of_grid_points self.number_of_grid_points_per_code = number_of_grid_points_per_code self.nghost = nghost self.min_timestep = None def set_parameters(self): for code in self.codes: code.parameters.x_boundary_conditions = ("interface", "interface") code.parameters.y_boundary_conditions = ("interface", "interface") code.stopping_conditions.number_of_steps_detection.enable() def init_channels(self): channels = [] after_channels = [] for index in range(0, len(self.codes)): instance = self.codes[index] xbound1 = instance.get_boundary_grid('xbound1') xbound2 = instance.get_boundary_grid('xbound2') ybound1 = instance.get_boundary_grid('ybound1') ybound2 = instance.get_boundary_grid('ybound2') xbound1_bottom = xbound1[0:self.nghost, 0:self.nghost, ...] xbound1_top = xbound1[0:self.nghost, self.number_of_grid_points - self.nghost:, ...] xbound1_channel = instance.grid[ self.number_of_grid_points - self.nghost:, ..., ... ].new_channel_to(xbound1) xbound2_channel = instance.grid[ 0: self.nghost, ..., ...].new_channel_to(xbound2) if index == 0: instance11 = self.codes[-1] else: instance11 = self.codes[index-1] ybound1_channel = instance11.grid[ ..., self.number_of_grid_points_per_code-self.nghost:, ... ].new_channel_to( ybound1[ self.nghost:self.number_of_grid_points+self.nghost, ..., ... ] ) ybound1_left_channel = instance11.grid[ 0:self.nghost, self.number_of_grid_points_per_code - self.nghost:, ...].new_channel_to(ybound1[0:self.nghost, ..., ...]) ybound1_right_channel = instance11.grid[ -self.nghost:, self.number_of_grid_points_per_code - self.nghost:, ...].new_channel_to( ybound1[ self.number_of_grid_points+self.nghost:, ..., ...] ) if index == len(self.codes)-1: instance12 = self.codes[0] else: instance12 = self.codes[index+1] ybound2_channel = instance12.grid[ ..., 0:self.nghost, ... ].new_channel_to( ybound2[ self.nghost:self.number_of_grid_points+self.nghost, ..., ... ] ) xbound1next = instance12.get_boundary_grid('xbound1') xbound2next = instance12.get_boundary_grid('xbound2') ybound2_left_channel = xbound1next[ ..., 0:self.nghost, ... ].new_channel_to( ybound2[0:self.nghost, ..., ...]) ybound2_right_channel = xbound2next[ ..., 0:self.nghost, ... ].new_channel_to( ybound2[ self.number_of_grid_points+self.nghost:, ..., ... ] ) channels.append(xbound1_channel) channels.append(xbound2_channel) channels.append(ybound1_channel) channels.append(ybound2_channel) after_channels.append(ybound1_left_channel) after_channels.append(ybound1_right_channel) after_channels.append(ybound2_left_channel) after_channels.append(ybound2_right_channel) self.channels = channels self.channels.extend(after_channels) self.copy_to_boundary_cells() def copy_to_boundary_cells(self): for channel in self.channels: channel.copy() def evolve_model(self, time, endtime): code = self.codes[0] t_unit = code.get_timestep().unit while code.model_time < time: timesteps = [] | t_unit for x in self.codes: timesteps.append(x.get_timestep()) min_timestep = timesteps.min() if code.model_time == 0.0 | t_unit: min_timestep = time if (min_timestep + code.model_time) >= time and time == endtime: for x in self.codes: x.parameters.must_evolve_to_exact_time = True for x in self.codes: x.set_timestep(min_timestep) for x in self.codes: x.evolve_model(time) self.copy_to_boundary_cells() class EvolveHydrodynamicsCodeWithPeriodicBoundaries(object): def __init__(self, code): self.code = code def set_parameters(self): self.code.parameters.x_boundary_conditions = ("periodic", "periodic") self.code.parameters.y_boundary_conditions = ("periodic", "periodic") self.code.stopping_conditions.number_of_steps_detection.disable() def init_channels(self): pass def evolve_model(self, time, endtime): while self.code.model_time < time: if ( self.code.get_timestep() + self.code.model_time ) >= time and time == endtime: self.code.parameters.must_evolve_to_exact_time = True self.code.evolve_model(time) class CalculateLinearWave1D(object): gamma = 5.0/3.0 wave_flag = 0 def __init__(self, number_of_grid_points=10, number_of_workers=1, name_of_the_code="athena", amplitude=1e-6 | speed, vflow_factor=1.0, grid_length=1.0 | length, number_of_steps=10, use_boundaries=True, number_of_codes=2 ): self.number_of_grid_points = number_of_grid_points self.number_of_workers = number_of_workers self.name_of_the_code = name_of_the_code self.amplitude = amplitude self.vflow_factor = vflow_factor self.grid_length = 1.0 | length self.number_of_steps = number_of_steps self.number_of_codes = number_of_codes self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 4 ) self.nghost = 4 self.use_boundaries = use_boundaries def new_instance_of_code(self): if 1: if self.name_of_the_code == 'athena': self.name_of_the_code = 'capreole' else: self.name_of_the_code = 'athena' attribute = "new_instance_of_{0}_code".format( self.name_of_the_code.lower()) return getattr(self, attribute)() def new_instance_of_capreole_code(self): result = Capreole(number_of_workers=self.number_of_workers) self.dimensions_of_mesh = ( self.number_of_grid_points, self.number_of_grid_points, 4 ) self.nghost = 2 return result def new_instance_of_athena_code(self): from amuse.community.athena.interface import Athena result = Athena(number_of_workers=self.number_of_workers) result.parameters.gamma = self.gamma result.parameters.courant_number = 0.4 self.nghost = 4 return result def new_instance_of_mpiamrvac_code(self): raise Exception( "MPIAMRVAC does not yet have support for detailed boundaries in amuse") from amuse.community.mpiamrvac.interface import MpiAmrVac result = MpiAmrVac( mode="2d", number_of_workers=self.number_of_workers, debugger="xterm", ) result.set_parameters_filename(result.default_parameters_filename) result.initialize_code() return result def set_parameters(self, codes, evolve): mesh_for_code = list(self.dimensions_of_mesh) mesh_for_code[1] /= self.number_of_codes for instance in codes: instance.parameters.mesh_size = list(mesh_for_code) instance.parameters.length_x = self.grid_length instance.parameters.length_y = ( self.grid_length / self.number_of_codes) instance.parameters.length_z = self.grid_length instance.parameters.z_boundary_conditions = ( "periodic", "periodic") evolve.set_parameters() for instance in codes: instance.commit_parameters() def new_grid(self): grid = Grid.create(self.dimensions_of_mesh, [1, 1, 1] | length) self.clear_grid(grid) return grid def clear_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) grid.rho = 0.0 | density grid.rhovx = 0.0 | momentum grid.rhovy = 0.0 | momentum grid.rhovz = 0.0 | momentum grid.energy = 0.0 | energy return grid def new_rhoe_right_eigenmatrix(self, velocity, amplitude, enthalpy): right_eigenmatrix = numpy.zeros((5, 5)) | speed right_eigenmatrix[0][0] = 1.0 | speed right_eigenmatrix[1][0] = velocity[0] - amplitude right_eigenmatrix[2][0] = velocity[1] right_eigenmatrix[3][0] = velocity[2] right_eigenmatrix[4][0] = ( 1.0 | time/length) * (enthalpy - velocity[0]*amplitude) # right_eigenmatrix[0][1] = 0.0; # right_eigenmatrix[1][1] = 0.0; right_eigenmatrix[2][1] = 1.0 | speed # right_eigenmatrix[3][1] = 0.0; right_eigenmatrix[4][1] = velocity[1] # right_eigenmatrix[0][2] = 0.0; */ # right_eigenmatrix[1][2] = 0.0; */ # right_eigenmatrix[2][2] = 0.0; */ right_eigenmatrix[3][2] = 1.0 | speed right_eigenmatrix[4][2] = velocity[2] right_eigenmatrix[0][3] = 1.0 | speed right_eigenmatrix[1][3] = velocity[0] right_eigenmatrix[2][3] = velocity[1] right_eigenmatrix[3][3] = velocity[2] right_eigenmatrix[4][3] = 0.5*velocity.length() right_eigenmatrix[0][4] = 1.0 | speed right_eigenmatrix[1][4] = velocity[0] + amplitude right_eigenmatrix[2][4] = velocity[1] right_eigenmatrix[3][4] = velocity[2] right_eigenmatrix[4][4] = ( 1.0 | time/length) * (enthalpy + velocity[0]*amplitude) return right_eigenmatrix def initialize_grid(self, grid): density = mass / length**3 momentum = speed * density energy = mass / (time**2 * length) rho = 1.0 | density pressure = (1.0/self.gamma) | (mass / (length * time**2)) vx = (self.gamma * pressure / rho).sqrt() velocity = self.vflow_factor * vx * [1.0, 0.0, 0.0] velocity_squared = velocity.length() energy = (pressure/(self.gamma - 1.0) + (0.5 | length / time)*rho*velocity_squared) enthalpy = (energy + pressure)/rho amplitude_squared = (self.gamma - 1.0) * max( enthalpy - (0.5 | length/time) * velocity_squared, 1e-100 | enthalpy.unit) amplitude = amplitude_squared.sqrt() nwave = 5 eigenvalues = ([0] * nwave) | speed eigenvalues[0] = velocity[0] - amplitude eigenvalues[1] = velocity[0] eigenvalues[2] = velocity[0] eigenvalues[3] = velocity[0] eigenvalues[4] = velocity[0] + amplitude right_eigenmatrix = self.new_rhoe_right_eigenmatrix( velocity, amplitude, enthalpy) grid.rho = rho grid.energy = energy grid.rhovy = rho*self.vflow_factor*(1.0 | speed) wave = self.amplitude*numpy.sin(grid.y * (2.0 | length**-1)*numpy.pi) grid.rho += wave * \ right_eigenmatrix[0][self.wave_flag] * \ (1.0 | mass * time**2 / length**5) grid.rhovx += wave * \ right_eigenmatrix[3][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.rhovy += wave * \ right_eigenmatrix[1][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.rhovz += wave * \ right_eigenmatrix[2][self.wave_flag] * \ (1.0 | mass * time / length**4) grid.energy += wave * \ right_eigenmatrix[4][self.wave_flag] * (1.0 | mass / length**3) def store_grids(self, grids, step): if __name__ == '__plot__': return grids_in_memory = [x.copy() for x in grids] io.write_set_to_file( grids_in_memory, "linear_wave_{2}_{0}_{1}.vtu".format( self.number_of_grid_points, step, self.name_of_the_code), "vtu", is_multiple=True ) def new_evolve_object(self, instance): """Returns a special object to evolve to code in time""" if self.use_boundaries: # return EvolveHydrodynamicsCodeWithAmusePeriodicBoundaries(instance[0], self.number_of_grid_points, self.nghost) return EvolveHydrodynamicsCodeWithAmusePeriodicBoundariesAndNCodes( instance, self.number_of_grid_points, self.number_of_grid_points / self.number_of_codes, self.nghost) else: return EvolveHydrodynamicsCodeWithPeriodicBoundaries(instance[0]) def initialize(self): self.codes = [] for i in range(self.number_of_codes): self.codes.append(self.new_instance_of_code()) self.evolve = self.new_evolve_object(self.codes) self.set_parameters(self.codes, self.evolve) self.start_grids = [] offset = 0.0 * self.grid_length for code in self.codes: for x in code.itergrids(): inmem = x.copy() self.clear_grid(inmem) inmem.y += offset self.initialize_grid(inmem) self.start_grids.append(inmem) from_model_to_code = inmem.new_channel_to(x) from_model_to_code.copy() offset += self.grid_length / self.number_of_codes for x in self.codes: x.initialize_grid() self.evolve.init_channels() def evolve_model(self, time, endtime): for code in self.codes: code.parameters.must_evolve_to_exact_time = False self.evolve.evolve_model(time, endtime) def get_grids(self): result = [] offset = 0.0 * self.grid_length for code in self.codes: for x in code.itergrids(): inmem = x.copy() inmem.y += offset result.append(inmem) offset += self.grid_length / self.number_of_codes return result def stop(self): print("terminating code") for code in self.codes: code.stop() def main(): number_of_grid_points = 60 name_of_the_code = 'athena' number_of_steps = 2000 vflow_factor = -1.0 pertubation_amplitude = 1e-4 | speed grid_length = 1.0 | length number_of_codes = int(sys.argv[1]) if number_of_grid_points % number_of_codes != 0: raise Exception( "grid points should be dividable by the number of codes") model1 = CalculateLinearWave1D( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code, amplitude=pertubation_amplitude, vflow_factor=vflow_factor, grid_length=grid_length, number_of_steps=number_of_steps, use_boundaries=True, number_of_codes=number_of_codes ) if 0: model2 = CalculateLinearWave1D( number_of_grid_points=number_of_grid_points, number_of_workers=1, name_of_the_code=name_of_the_code, amplitude=pertubation_amplitude, vflow_factor=vflow_factor, grid_length=grid_length, number_of_steps=number_of_steps, use_boundaries=False, number_of_codes=number_of_codes ) if not IS_PLOT_AVAILABLE: print("Plot is not available. stop now") return model1.initialize() # model2.initialize() grids1 = model1.get_grids() # grids2 = model2.get_grids() figure = pyplot.figure(figsize=(10, 5)) plot1 = figure.add_subplot(1, 1, 1) lines = [] ys = [] for grid in grids1: y = grid.y[0, ..., 0].value_in(length) ys.append(y) rho = grid.rho[0, ..., 0].value_in(density) line = plot1.plot(y, rho)[0] lines.append(line) end_time = 10.0 | time dt = end_time / number_of_steps t = dt step = 1 title = figure.suptitle('{0:.3f}'.format(0.0)) variables = [t, step] def update(xx): t, step = variables title.set_text('{0:.3f}'.format(t.value_in(time))) model1.evolve_model(t, end_time) # model2.evolve_model(t, end_time) t += dt grids1 = model1.get_grids() # grids2 = model2.get_grids() for line, grid in zip(lines, grids1): y = grid.y[0, ..., 0].value_in(length) rho = grid.rho[0, ..., 0].value_in(density) line.set_data(y,rho) #line = plot1.plot(y,rho)[0] #lines.append(line) print(t) step += 1 variables[0] = t variables[1] = step return lines if 1: process = animation.FuncAnimation( figure, update, numpy.arange(1, 200), interval=25, blit=False ) else: update(0) update(0) pass pyplot.show() model1.stop() # model2.stop() if __name__ == "__main__": main()
29,043
35.350438
125
py
amuse
amuse-main/examples/applications/galaxy_merger.py
""" Simple Galaxy Merger example simulating a merger of two Milky Way-type galaxies, collisionless particles (i.e. no gas) """ import os import os.path import numpy from amuse.units import nbody_system, units from amuse.datamodel import Particles from amuse.io import read_set_from_file, write_set_to_file from amuse.plot import ( plot, native_plot, pynbody_column_density_plot, HAS_PYNBODY ) from amuse.community.gadget2.interface import Gadget2 from amuse.ext.galactics_model import new_galactics_model NHALO = 10000 NDISK = 5000 def make_plots(all_particles, disk_only, i=0): for j, particles in enumerate([all_particles, disk_only]): if HAS_PYNBODY: temp_particles = particles.copy() temp_particles.u = 1 | units.ms**2 temp = Gadget2() temp.gas_particles.add_particles(temp_particles) temp.commit_particles() pynbody_column_density_plot( temp.gas_particles, width=300 | units.kpc, units='m_p cm^-2', vmin=17, vmax=23) temp.stop() else: native_plot.gca().set_aspect("equal") native_plot.xlim(-150, 150) native_plot.ylim(-150, 150) plot(particles.x.as_quantity_in(units.kpc), particles.y.as_quantity_in(units.kpc), 'r.') native_plot.savefig( os.path.join( "plots", "plot_galaxy_merger_{0}_{1:=04}.png".format( "disk" if j else "total", i) ) ) native_plot.close() def make_galaxies(): if os.path.exists('disk_galactICs.amuse'): galaxy1 = read_set_from_file('disk_galactICs.amuse', 'amuse') else: halo_number_of_particles = NHALO converter = nbody_system.nbody_to_si( 1.0e9 | units.MSun, 1. | units.kpc) galaxy1 = new_galactics_model( halo_number_of_particles, disk_number_of_particles=NDISK, generate_bulge_flag=False, unit_system_converter=converter, disk_random_seed=12345) write_set_to_file(galaxy1, 'disk_galactICs.amuse', 'amuse') galaxy2 = Particles(len(galaxy1)) galaxy2.mass = galaxy1.mass galaxy2.position = galaxy1.position galaxy2.velocity = galaxy1.velocity galaxy1.rotate(0.0, numpy.pi/4, 0.0) galaxy2.rotate(numpy.pi/6, 0.0, 0.0) galaxy1.position += [100.0, 0, 0] | units.kpc galaxy2.position -= [100.0, 0, 0] | units.kpc galaxy1.velocity += [0.0, 50.0, 0] | units.km/units.s galaxy2.velocity -= [0.0, 50.0, 0] | units.km/units.s return galaxy1, galaxy2 def simulate_merger(galaxy1, galaxy2, dt=25. | units.Myr, tend=3. | units.Gyr): converter = nbody_system.nbody_to_si(1.0e9 | units.MSun, 1. | units.kpc) dynamics = Gadget2(converter, number_of_workers=2) dynamics.parameters.epsilon_squared = (1. | units.kpc)**2 # max internal timestep for Gadget dynamics.parameters.max_size_timestep = dt # max possible evolve time for Gadget, 2**k *dt should be > tend dynamics.parameters.time_max = 2**9*dt set1 = dynamics.particles.add_particles(galaxy1) set2 = dynamics.particles.add_particles(galaxy2) galaxies_without_halo = set1[:NDISK] + set2[:NDISK] make_plots(dynamics.particles, galaxies_without_halo) print("starting simulation..") i = 0 while dynamics.model_time < tend: i = i+1 dynamics.evolve_model(i * dt) print( "evolved to:", dynamics.model_time.as_quantity_in(units.Myr), "/", tend ) make_plots(dynamics.particles, galaxies_without_halo, i) dynamics.stop() if __name__ == '__main__': galaxy1, galaxy2 = make_galaxies() if not os.path.exists("plots"): os.mkdir("plots") simulate_merger(galaxy1, galaxy2)
3,960
31.735537
79
py
amuse
amuse-main/examples/applications/__init__.py
0
0
0
py
amuse
amuse-main/examples/applications/test_jeans_instability.py
from amuse.community.athena.interface import Athena from amuse.units import generic_unit_converter # from amuse.units import generic_unit_system from amuse.units import units from amuse.units import constants from amuse.test import amusetest import numpy try: from amuse import plot from matplotlib import pyplot IS_PLOT_AVAILABLE = True except ImportError: IS_PLOT_AVAILABLE = False dyn = units.g * units.cm / units.s**2 RUN_WITH_SELF_GRAVITY = True class JeansInstability(object): def __init__( self, rho0, p0, wavenumber_factor=4.0, pertubation_amplitude=1e-3, gamma=5.0/3.0, ncells=100): self.rho0 = rho0 self.p0 = p0 self.pertubation_amplitude = pertubation_amplitude self.gamma = gamma self.ncells = ncells self.dimensions_of_mesh = (ncells, ncells, 1) self.sound_speed = (self.gamma * self.p0 / self.rho0).sqrt() self.jeans_wavenumber = ( 4 * numpy.pi * constants.G * self.rho0).sqrt() / self.sound_speed self.wavenumber = wavenumber_factor * self.jeans_wavenumber self.length_scale = ( 0.5 * ( numpy.pi * self.gamma * self.p0 / ( constants.G * self.rho0**2 ) ).sqrt() ) self.unit_converter = \ generic_unit_converter.ConvertBetweenGenericAndSiUnits( self.length_scale, 1 | units.s, 1 | units.g ) def new_code(self): if RUN_WITH_SELF_GRAVITY: result = Athena(self.unit_converter, mode='self-gravity') result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 result.parameters.four_pi_G = numpy.pi * 4 * constants.G result.parameters.gravity_mean_rho = self.rho0 else: result = Athena(self.unit_converter) result.parameters.gamma = self.gamma result.parameters.courant_number = 0.3 return result def set_parameters(self): self.code.parameters.mesh_size = self.dimensions_of_mesh self.code.parameters.length_x = self.length_scale self.code.parameters.length_y = self.length_scale self.code.parameters.length_z = self.length_scale self.code.parameters.x_boundary_conditions = ("periodic", "periodic") self.code.parameters.y_boundary_conditions = ("periodic", "periodic") self.code.parameters.z_boundary_conditions = ("periodic", "periodic") result = self.code.commit_parameters() def initialize_grid(self, grid): grid.momentum = [0.0, 0.0, 0.0] | units.g / (units.s * units.cm**2) k_dot_x = self.wavenumber * grid.x grid.rho = self.rho0 * \ (1 + self.pertubation_amplitude * numpy.cos(k_dot_x)) pressure = self.p0 * \ (1 + self.pertubation_amplitude * self.gamma * numpy.cos(k_dot_x)) grid.energy = pressure / (self.gamma - 1) def setup(self): self.code = self.new_code() self.set_parameters() self.initialize_grid(self.code.grid) # self.update_potential_grid() def update_potential_grid(self): potential_grid = self.code.potential_grid potential_grid_inmem = potential_grid.copy() self.calculate_potential_for_grid(potential_grid_inmem, self.code.grid) channel = potential_grid_inmem.new_channel_to(potential_grid) channel.copy() def evolve_model(self, time): self.code.stopping_conditions.number_of_steps_detection.disable() self.code.stopping_conditions.number_of_steps_detection.enable() epsilon = 1e-12 | units.s while self.code.model_time + epsilon < time: self.code.evolve_model(time) if 0: # plot for debugging phi = self.code.grid.gravitational_potential[:, :, 0] figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 1, 1) plot.imshow(phi.value_in(units.m**2 / units.s**2)) pyplot.show() print(phi[:, 1][0:10]) self.P0 = phi # self.update_potential_grid() def stop(self): self.code.stop() def get_gravity_for_grid(self, grid): """Calculates the gravitational force at each grid point, we do not use a code here (altoug possible)""" x = grid.x y = grid.y z = grid.z cell_size = (self.length_scale / self.ncells) cell_volume = cell_size * cell_size * (1 | units.cm) epsilon_squared = cell_size ** 2 for cell in grid: dx = x - cell.x dy = x - cell.y dz = x - cell.z r_squared = (dx**2 + dy**2 + dz**2 + epsilon_squared) r = r_squared.sqrt() r_3 = r * r_squared force = grid.rho * volume / r_3 ax = (force * dx).sum() ay = (force * dy).sum() az = (force * dz).sum() def calculate_potential_for_grid(self, grid, field): x = field.x.flatten() x = field.x[:, 0, 0] y = field.y[0, :, 0] # we assume constant grid spacing so # we just create a sample space using # the number of points in x and y nx = len(x) ny = len(y) dx = x[1] - x[0] dy = y[1] - y[0] # # wavenumbers from online examples # kx = (2 * numpy.pi) * numpy.fft.fftfreq(nx, d = dx ) * (1 | units.m) # ky = (2 * numpy.pi) * numpy.fft.fftfreq(ny, d = dy ) * (1 | units.m) # # wavenumbers as calculated in athena dkx = 2.0*numpy.pi/nx dky = 2.0*numpy.pi/ny kx = ((((2.0*numpy.cos(numpy.arange(nx) * dkx))-2.0)/(dx**2)) ).value_in(units.m**-2) ky = ((((2.0*numpy.cos(numpy.arange(ny) * dky))-2.0)/(dy**2)) ).value_in(units.m**-2) kx_grid, ky_grid = numpy.meshgrid(kx, ky) # convert rho to 2d field rho = field.rho[:, :, 0] # use rho0 as mean, should be equal to rho.mean() # but we are comparing with athena and # want the most accurate solution rho_mean = self.rho0 # field.rho.mean() # to remove division by zero kx_grid[0][0] = 1 ky_grid[0][0] = 1 # for poisson solver the source term (gravity) # has to sum to zero over the field # we can ensure this by subtracting the mean from rho rho -= rho_mean gravity_function = 4 * numpy.pi * constants.G * rho gravity_function = gravity_function.value_in(units.s ** -2) gravity_function_fourier_space = numpy.fft.fftn(gravity_function) phi_fourier_space = gravity_function_fourier_space / \ (kx_grid + ky_grid) # 0,0 was divided by zero, should just be zero phi_fourier_space[0, 0] = 0 phi = numpy.fft.ifftn(phi_fourier_space).real # we removed the units for fft, replace these phi = phi | units.m**2 / units.s**2 if 0: # plot for debugging phi_delta = phi # - self.P0 figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 2, 1) plot.imshow(phi_delta.value_in(units.m**2 / units.s**2)[1:, 1:]) plot = figure.add_subplot(1, 2, 2) plot.imshow( (phi - self.P0).value_in(units.m**2 / units.s**2)[1:, 1:]) pyplot.show() print(phi[:, 1][0:10]) print( (phi[:, 1][0:10] - self.P0[:, 1][0:10]) / phi[:, 1][0:10] ) def gravity_for_code(self, field, grid): x = field.x.flatten() y = field.y.flatten() z = field.z.flatten() rho = field.rho.flatten() cell_size = (self.length_scale / self.ncells) cell_volume = cell_size * cell_size * (1 | units.cm) epsilon_squared = cell_size ** 2 cell_mass = rho * cell_volume for cell in grid.iter_cells(): dx = x - cell.x dy = y - cell.y dz = z - cell.z r_squared = (dx**2 + dy**2 + dz**2 + epsilon_squared) r = r_squared.sqrt() cell.potential = constants.G * (cell_mass / r).sum() phi = grid.potential[:, :, 0] figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 1, 1) plot.imshow(phi.value_in(units.m**2 / units.s**2)) pyplot.show() class TestJeansInstability(amusetest.TestCase): def test1(self): ncells = 5 x = JeansInstability( 1.5e7 | units.g / units.cm**3, 1.5e7 | dyn / units.cm**2, ncells=ncells ) self.assertAlmostRelativeEquals( x.jeans_wavenumber, 2.747 | units.cm**-1, 3) x.setup() self.assertAlmostRelativeEquals( (x.code.grid.rho[:, 0, 0].sum()).as_quantity_in( units.g / units.cm**3 ) / ncells, 1.5e7 | units.g / units.cm**3 ) x.stop() if __name__ == '__main__': ncells = 1000 run = JeansInstability( 1.5e7 | units.g / units.cm**3, 1.5e7 | dyn / units.cm**2, ncells=ncells ) run.setup() t = 0 | units.s x = [] | units.s y = [] | units.g / units.cm**3 x.append(t) y.append(run.code.grid[2, 2, 0].rho) while t < 10 | units.s: t += 0.01 | units.s run.evolve_model(t) x.append(t) y.append(run.code.grid[2, 2, 0].rho) print("evolved to", t, run.code.grid[2, 2, 0].rho) if IS_PLOT_AVAILABLE: figure = pyplot.figure(figsize=(10, 5)) plot = figure.add_subplot(1, 1, 1) plot.plot(x.value_in(units.s), y.value_in(units.g / units.cm**3)) if RUN_WITH_SELF_GRAVITY: figure.savefig('jeans_instability_grav.png') else: figure.savefig('jeans_instability_nograv.png') pyplot.show()
10,206
31.403175
79
py
amuse
amuse-main/examples/applications/mercury_solarsystem.py
# import numpy from amuse.community.mercury.interface import MercuryInterface try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False solarsystem = [ [ 'MERCURY', 1.66013679527193009E-07, 20., 5.43, -3.83966017419175965E-01, -1.76865300855700736E-01, 2.07959213998758705E-02, 5.96286238644834141E-03, -2.43281292146216750E-02, -2.53463209848734695E-03, 0., 0., 0.], [ 'VENUS', 2.44783833966454430E-06, 20., 5.24, 6.33469157915745540E-01, 3.49855234102151691E-01, -3.17853172088953667E-02, -9.84258038001823571E-03, 1.76183746921837227E-02, 8.08822351013463794E-04, 0., 0., 0.], [ 'EARTHMOO', 3.04043264264672381E-06, 20., 5.52, 2.42093942183383037E-01, -9.87467766698604366E-01, -4.54276292555233496E-06, 1.64294055023289365E-02, 4.03200725816140870E-03, 1.13609607260006795E-08, 0., 0., 0.], [ 'MARS', 3.22715144505386530E-07, 20., 3.94, 2.51831018120174499E-01, 1.52598983115984788E+00, 2.57781137811807781E-02, -1.32744166042475433E-02, 3.46582959610421387E-03, 3.98930013246952611E-04, 0., 0., 0.], [ 'JUPITER', 9.54791938424326609E-04, 3., 1.33, 4.84143144246472090E+00, -1.16032004402742839E+00, -1.03622044471123109E-01, 1.66007664274403694E-03, 7.69901118419740425E-03, -6.90460016972063023E-05, 0., 0., 0.], [ 'SATURN', 2.85885980666130812E-04, 3., 0.70, 8.34336671824457987E+00, 4.12479856412430479E+00, -4.03523417114321381E-01, -2.76742510726862411E-03, 4.99852801234917238E-03, 2.30417297573763929E-05, 0., 0., 0.], [ 'URANUS', 4.36624404335156298E-05, 3., 1.30, 1.28943695621391310E+01, -1.51111514016986312E+01, -2.23307578892655734E-01, 2.96460137564761618E-03, 2.37847173959480950E-03, -2.96589568540237556E-05, 0., 0., 0.], [ 'NEPTUNE', 5.15138902046611451E-05, 3., 1.76, 1.53796971148509165E+01, -2.59193146099879641E+01, 1.79258772950371181E-01, 2.68067772490389322E-03, 1.62824170038242295E-03, -9.51592254519715870E-05, 0., 0., 0.], [ 'PLUTO', 7.39644970414201173E-09, 3., 1.1, -1.15095623952731607E+01, -2.70779438829451422E+01, 6.22871533567077229E+00, 2.97220056963797431E-03, -1.69820233395912967E-03, -6.76798264809371094E-04, 0., 0., 0.] ] def planetplot(): instance = MercuryInterface() instance.initialize_code() ids = dict() xpos = dict() ypos = dict() for x in solarsystem: pid, err = instance.new_orbiter( x[1], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[2] ) ids[x[0]] = pid xpos[x[0]] = [] ypos[x[0]] = [] xpos[x[0]].append(x[4]) ypos[x[0]].append(x[5]) instance.commit_particles() t_end = 365.25*20 time = 0 while time < t_end: time = time+8 err = instance.evolve_model(time) for p in solarsystem: mass, dens, x, y, z, vx, vy, vz, sx, sy, sz, celimit, err = \ instance.get_orbiter_state(ids[p[0]]) xpos[p[0]].append(x) ypos[p[0]].append(y) instance.stop() pyplot.plot(xpos['MERCURY'], ypos['MERCURY']) pyplot.plot(xpos['VENUS'], ypos['VENUS']) pyplot.plot(xpos['EARTHMOO'], ypos['EARTHMOO']) pyplot.plot(xpos['MARS'], ypos['MARS']) pyplot.plot(xpos['JUPITER'], ypos['JUPITER']) pyplot.xlim(-6.0, 6.0) pyplot.ylim(-6.0, 6.0) pyplot.savefig('solarsytem.png') def energyplot(): instance = MercuryInterface() instance.initialize_code() for x in solarsystem: pid, err = instance.new_orbiter( x[1], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], x[2]) instance.commit_particles() t_end = 365.25*1000000 time = 0 e0, err = instance.get_total_energy() energy = [0.] times = [0.] while time < t_end: time = time+8*10000. err = instance.evolve_model(time) if(err != 0): print("err:", err) e, err = instance.get_total_energy() t, err = instance.get_time() energy.append((e0-e)/e0) times.append(t/365.25) instance.stop() pyplot.plot(times, energy) pyplot.xlim(0, t_end/365.25) pyplot.ylim(-1.e-6, 1.e-6) pyplot.savefig('solarsytem_energy.png') if __name__ == "__main__": print("this may take a while..") planetplot() # energyplot()
5,147
34.020408
77
py
amuse
amuse-main/examples/applications/test_blender.py
# 1BPY """ Name: 'sun-earth' Blender: 249 Group:'Add' Tooltip: 'Amuse example' """ from amuse.community.hermite.interface import Hermite from amuse.units import nbody_system from amuse.units import units from amuse.ext.blender import blender # get blender API import numpy as np from amuse import datamodel class SunEarth(object): def new_system_of_sun_and_earth(self): stars = datamodel.Stars(2) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(np.array((0.0, 0.0, 0.0))) sun.velocity = units.ms(np.array((0.0, 0.0, 0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(np.array((149.5e6, 0.0, 0.0))) earth.velocity = units.ms(np.array((0.0, 29800, 0.0))) return stars def evolve_model(self): convert_nbody = nbody_system.nbody_to_si( 1.0 | units.MSun, 149.5e6 | units.km) hermite = Hermite(convert_nbody) hermite.initialize_code() hermite.parameters.epsilon_squared = 0.0 | units.AU**2 stars = self.new_system_of_sun_and_earth() earth = stars[1] sun = stars[0] Earth = blender.Primitives.sphere(10, 10, 0.1) # Make the earth avatar Sun = blender.Primitives.sphere(32, 32, 1) # Make the sun avatar hermite.particles.add_particles(stars) for i in range(1*365): hermite.evolve_model(i | units.day) hermite.particles.copy_values_of_all_attributes_to(stars) # update avatar positions: Earth.loc = ( 1*earth.position.value_in(units.AU)[0], 1*earth.position.value_in(units.AU)[1], earth.position.value_in(units.AU)[2]) Sun.loc = ( 1*sun.position.value_in(units.AU)[0], 1*sun.position.value_in(units.AU)[1], sun.position.value_in(units.AU)[2]) blender.Redraw() hermite.print_refs() hermite.stop() if __name__ == '__main__': system = SunEarth() system.evolve_model()
2,202
29.597222
79
py
amuse
amuse-main/examples/applications/test_evrard.py
import os # import sys import numpy try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False from amuse.community.fi import interface as interface from amuse.ext.evrard_test import MakeEvrardTest # from amuse.ext.evrard_test import regular_grid_unit_cube # from amuse.ext.evrard_test import body_centered_grid_unit_cube from amuse.test.amusetest import get_path_to_results # import logging # logging.basicConfig(level=logging.DEBUG) from amuse.rfi.core import is_mpd_running def energy_plot(time, ek, ep, eth): if not HAS_MATPLOTLIB: return pyplot.figure(figsize=(5, 5)) pyplot.xlabel(r'time') pyplot.ylabel(r'energy') pyplot.plot(time, ek) pyplot.plot(time, ep) pyplot.plot(time, eth) pyplot.plot(time, ek+ep+eth) test_results_path = get_path_to_results() pyplot.savefig(os.path.join(test_results_path, "evrard_test.png")) def run_evrard(x): evrard = MakeEvrardTest(x) mass, x, y, z, vx, vy, vz, u = evrard.new_model() smooth = numpy.zeros_like(mass) nb = interface.FiInterface(redirection="none") nb.initialize_code() # nb.set_stepout(99999) # nb.set_steplog(99999) nb.set_use_hydro(1) nb.set_radiate(0) nb.set_dtime(0.05) # nb.set_gdgop(1) nb.set_uentropy(0) # nb.set_verbosity(0) ids,error = nb.new_sph_particle(mass,smooth,x,y,z,vx,vy,vz,u) if [x for x in error if x != 0] != []: raise Exception nb.commit_particles() if hasattr(nb, "viewer"): nb.viewer() dt = 0.05 tnow = 0. nb.synchronize_model() time, Ek, Ep, Eth = [], [], [], [] time.append(tnow) e, ret = nb.get_kinetic_energy() Ek.append(e) e, ret = nb.get_potential_energy() Ep.append(e) e, ret = nb.get_thermal_energy() Eth.append(e) while tnow < 3.0: tnow = tnow+dt nb.evolve_model(tnow) nb.synchronize_model() tnow, err = nb.get_time() time.append(tnow) e, ret = nb.get_kinetic_energy() Ek.append(e) e, ret = nb.get_potential_energy() Ep.append(e) e, ret = nb.get_thermal_energy() Eth.append(e) nb.cleanup_code() nb.stop() nb.stop() time = numpy.array(time) Ek = numpy.array(Ek) Ep = numpy.array(Ep) Eth = numpy.array(Eth) energy_plot(time, Ek, Ep, Eth) def test_evrard(): if not is_mpd_running(): return run_evrard(64) if __name__ in ("__main__", "__plot__"): run_evrard(1000)
2,538
22.95283
70
py
amuse
amuse-main/examples/applications/imperial.py
from amuse.units.units import ( kg, m, s, N, named ) pound = named('avoirdupois pound', 'lbm', 0.45359237 * kg) g = 9.80665 * m / s**2 poundforce = named('poundforce', 'lbf', pound*g) print(poundforce.as_quantity_in(N)) feet = named('feet', 'feet', 1/3.2808399 * m) print(g.value_in(feet/s**2)) print(poundforce.as_quantity_in(pound*feet/s**2)) print((1| N).as_quantity_in(poundforce))
404
27.928571
58
py
amuse
amuse-main/examples/applications/test_triple_statistics.py
""" In this script we simulate triple evolution. See papers: http://arxiv.org/abs/1004.2506 and http://arxiv.org/abs/1101.0399 """ import numpy import sys # import time from amuse.units import nbody_system, units from amuse.units.quantities import AdaptingVectorQuantity from amuse.datamodel import Particles from amuse.community.hermite.interface import Hermite from amuse.rfi import channel # from multiprocessing import Process, Queue try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False from mpi4py import MPI from amuse.io import text class SimulateTripleSystemUntilDecay(object): gravitational_constant = nbody_system.G distance_relative_to_inner_binary_axis = 50 t0 = 0 | nbody_system.time tmax = 7000 | nbody_system.time dt = 10 | nbody_system.time def __init__(self, gravity_code, particles, rank=0, index=0): self.particles = particles self.gravity_code = gravity_code self.gravity_code.particles.add_particles(self.particles) self.from_code_to_model_channel = \ self.gravity_code.particles.new_channel_to(self.particles) self.rank = rank self.index = index def is_hyperbolic(self, inner_binary, outer_particle): mass_inner = inner_binary.mass.sum() velocity_cm = inner_binary.center_of_mass_velocity() position_cm = inner_binary.center_of_mass() distance_to_cm = (outer_particle.position - position_cm).length() energy = ( ((mass_inner * (velocity_cm.length_squared())) / 2.0) + ( ( outer_particle.mass * ( outer_particle.velocity.length_squared() ) ) / 2.0 ) - ( self.gravitational_constant * mass_inner * outer_particle.mass / distance_to_cm ) ) # formula (3) in Orlov(2010) return energy > 0 | nbody_system.energy def is_outside_escape_distance(self, inner_binary, outer_particle): position_cm = inner_binary.center_of_mass() distance_to_cm = (outer_particle.position - position_cm).length() distance_between_inner_particles = ( inner_binary[0].position - inner_binary[1].position).length() return ( distance_to_cm / distance_between_inner_particles ) > self.distance_relative_to_inner_binary_axis def has_triple_an_escaper(self, particles): breakup_of_indices = ( ((0, 1), 2), ((0, 2), 1), ((1, 2), 0) ) for binary_indices, outer_particle_index in breakup_of_indices: binary = particles.get_all_particles_at(*binary_indices) outer = particles[outer_particle_index] is_possible_escape = self.is_outside_escape_distance( binary, outer ) if is_possible_escape: is_on_hyperbolic_trajectory = self.is_hyperbolic( binary, outer ) if is_on_hyperbolic_trajectory: return True return False def evolve_model_until_escape(self): self.time = self.t0 has_escaper = False self.setup_point_positions() while self.time < self.tmax and not has_escaper: self.gravity_code.evolve_model(self.time) self.time += self.dt self.from_code_to_model_channel.copy() has_escaper = self.has_triple_an_escaper(self.particles) self.store_point_positions() self.make_plot() return self.time def setup_point_positions(self): self.x_positions = [AdaptingVectorQuantity() for x in range(len(self.particles))] self.y_positions = [AdaptingVectorQuantity() for x in range(len(self.particles))] def store_point_positions(self): for index in range(len(self.particles)): self.x_positions[index].append(self.particles[index].x) self.y_positions[index].append(self.particles[index].y) def make_plot(self): figure = pyplot.figure() plot = figure.add_subplot(1, 1, 1) for index in range(len(self.particles)): plot.plot( self.x_positions[index].value_in(nbody_system.length), self.y_positions[index].value_in(nbody_system.length) ) figure.savefig("triple_{0:03}_{1:03}.png".format( self.rank, self.index)) def stop(self): self.gravity_code.stop() def new_initial_system(): n = 10.0 xi = 0.001 result = Particles(3) mass = numpy.random.rand(3) mass = mass / mass.sum() result.mass = mass * (1.0 | nbody_system.mass) a = (numpy.random.rand() * n) + (n+xi) b = numpy.random.rand() * 2*n c = (numpy.random.rand() * 2*n) + xi result[0].position = [0, 0, 0] | nbody_system.length result[1].position = [a, 0, 0] | nbody_system.length result[2].position = [b, c, 0] | nbody_system.length result.radius = 0 | nbody_system.length result.velocity = [0, 0, 0] | nbody_system.speed return result 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 if __name__ == '__main__': result = AdaptingVectorQuantity() channel.MpiChannel.ensure_mpi_initialized() rank = MPI.COMM_WORLD.Get_rank() total_number_of_systems = int(sys.argv[1]) data = calculate_escape_time(rank, total_number_of_systems) output = text.CsvFileText(filename="triple_data_{0:03}.csv".format(rank)) output.quantities = data output.attribute_names = ("x0", "y0", "x1", "y1", "x2", "y2", "m0", "m1", "m2", "tend") output.store() times = AdaptingVectorQuantity() counts = AdaptingVectorQuantity() 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 """
8,115
29.977099
79
py
amuse
amuse-main/examples/applications/test_smallcluster_async.py
import sys # import unittest import numpy # import random # import collections import os import threading import time try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False from amuse.units import nbody_system from amuse.units import units from amuse.io import store # from amuse.community.hermite.interface import Hermite from amuse.community.bhtree.interface import BHTree from amuse.community.sse.interface import SSE # from amuse.community.phigrape.interface import PhiGRAPE from amuse.test.amusetest import get_path_to_results # from amuse.datamodel import particle_attributes from amuse.rfi.core import is_mpd_running from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution def plot_particles(particles, name_of_the_figure): return 1 if HAS_MATPLOTLIB: print("plotting the data") figure = pyplot.figure(figsize=(40, 40)) plots = [figure.add_subplot(4,4, x+1) for x in range(4*4)] index = 0 for data in particles.history: if index > 15: break x_values = data.x.value_in(units.parsec) y_values = data.y.value_in(units.parsec) mass_values = data.mass.value_in(units.MSun) sizes = mass_values * 10.0 plots[index].scatter(x_values, y_values, marker='o', s=sizes) index += 1 for plot in plots: plot.set_xlim(-2.0, 2.0) plot.set_ylim(-2.0, 2.0) figure.savefig(name_of_the_figure) if False: from matplotlib import axes3d figure = pyplot.figure() axes_3d = axes3d.Axes3D(figure) positions = particles.get_values_of_attribute('position') xs = numpy.array([position.x.value_in(units.lightyear) for position in positions]) ys = numpy.array([position.y.value_in(units.lightyear) for position in positions]) zs = numpy.array([position.z.value_in(units.lightyear) for position in positions]) # print xs, yz, zs plot = axes_3d.scatter(xs, ys, zs) axes_3d.set_xlim(-10.0, 10.0) axes_3d.set_ylim(-10.0, 10.0) axes_3d.set_zlim(-10.0, 10.0) figure.savefig("3d_"+name_of_the_figure) def print_log(time, gravity, particles, total_energy_at_t0, total_energy_at_this_time): print("Evolved model to t = " + str(time)) print(total_energy_at_t0.as_quantity_in(units.J), \ total_energy_at_this_time.as_quantity_in(units.J), \ (total_energy_at_this_time - total_energy_at_t0) / total_energy_at_t0) # print "KE:" , particles.kinetic_energy().as_quantity_in(units.J) # print "PE:" , particles.potential_energy(gravity.parameters.epsilon_squared) print("center of mass:", particles.center_of_mass()) print("center of mass velocity:", particles.center_of_mass_velocity()) total_mass = 0|units.kg for m in particles.mass: total_mass += m print("total mass =", total_mass) class AmuseEvolveThread(threading.Thread): def __init__(self, amuse_module, t_end, sync=False): threading.Thread.__init__(self) self.amuse_module = amuse_module self.t_end = t_end self.sync = sync self.run_time = 0.0 def run(self): start_time = time.clock() self.amuse_module.evolve_model(self.t_end) if self.sync: self.amuse_module.synchronize_model() end_time = time.clock() self.run_time = end_time - start_time def simulate_small_cluster(number_of_stars, end_time=40 | units.Myr, name_of_the_figure="test-2.svg"): # numpy.random.seed(1) salpeter_masses = new_salpeter_mass_distribution(number_of_stars) total_mass = salpeter_masses.sum() convert_nbody = nbody_system.nbody_to_si(total_mass, 1.0 | units.parsec) particles = new_plummer_model(number_of_stars, convert_nbody) gravity = BHTree(convert_nbody) gravity.initialize_code() # gravity.parameters.set_defaults() # print gravity.parameters.timestep.as_quantity_in(units.Myr) gravity.parameters.timestep = 0.0001 | units.Myr # tiny! gravity.parameters.epsilon_squared \ = (float(number_of_stars)**(-0.333333) | units.parsec) ** 2 stellar_evolution = SSE() stellar_evolution.initialize_module_with_default_parameters() print("setting masses of the stars") particles.radius = 0.0 | units.RSun particles.mass = salpeter_masses print("initializing the particles") stellar_evolution.particles.add_particles(particles) from_stellar_evolution_to_model \ = stellar_evolution.particles.new_channel_to(particles) from_stellar_evolution_to_model.copy_attributes(["mass"]) print("centering the particles") particles.move_to_center() print("scaling particles to viridial equilibrium") particles.scale_to_standard(convert_nbody) gravity.particles.add_particles(particles) from_model_to_gravity = particles.new_channel_to(gravity.particles) from_gravity_to_model = gravity.particles.new_channel_to(particles) gravity.commit_particles() time = 0.0 | units.Myr particles.savepoint(time) total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy print("evolving the model until t = " + str(end_time)) while time < end_time: time += 0.25 | units.Myr print("Gravity evolve step starting") gravity_evolve = gravity.evolve_model.async(time) print("Stellar evolution step starting") stellar_evolution_evolve = stellar_evolution.evolve_model(time) print("Stellar evolution step done.") gravity_evolve.result() print("Gravity evolve step done.") from_gravity_to_model.copy() from_stellar_evolution_to_model.copy_attributes(["mass", "radius"]) particles.savepoint(time) from_model_to_gravity.copy_attributes(["mass"]) total_energy_at_this_time \ = gravity.kinetic_energy + gravity.potential_energy print_log(time, gravity, particles, total_energy_at_t0, total_energy_at_this_time) test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "small.hdf5") if os.path.exists(output_file): os.remove(output_file) storage = store.StoreHDF(output_file) storage.store(particles) gravity.stop() stellar_evolution.stop() plot_particles(particles, name_of_the_figure) def test_simulate_small_cluster(): """test_simulate_small_cluster This method is found by the testing framework and automatically run with all other tests. This method simulates a too small cluster, this is done to limit the testing time. """ assert is_mpd_running() test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "test-2.svg") simulate_small_cluster(4, 4 | units.Myr, name_of_the_figure=output_file) if __name__ == '__main__': N = 50 t_end = 10 output_file = 'test' if len(sys.argv) > 1: N = int(sys.argv[1]) if len(sys.argv) > 2: t_end = float(sys.argv[2]) if len(sys.argv) > 3: output_file = sys.argv[3] simulate_small_cluster(N, t_end | units.Myr, output_file)
7,593
32.307018
82
py
amuse
amuse-main/examples/applications/test_smallcluster.py
import sys # import unittest import numpy # import random # import collections import os try: from matplotlib import pyplot HAS_MATPLOTLIB = True except ImportError: HAS_MATPLOTLIB = False from amuse.units import nbody_system from amuse.units import units # from amuse.community.hermite.interface import Hermite from amuse.community.bhtree.interface import BHTree from amuse.community.sse.interface import SSE # from amuse.community.phigrape.interface import PhiGRAPE from amuse.test.amusetest import get_path_to_results from amuse.io import store # from amuse.datamodel import particle_attributes from amuse.rfi.core import is_mpd_running from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution def plot_particles(particles, name_of_the_figure): if HAS_MATPLOTLIB: print("plotting the data") figure = pyplot.figure(figsize=(40, 40)) plots = [figure.add_subplot(4,4, x+1) for x in range(4*4)] index = 0 for data in particles.history: if index > 15: break x_values = data.x.value_in(units.parsec) y_values = data.y.value_in(units.parsec) mass_values = data.mass.value_in(units.MSun) sizes = mass_values * 10.0 plots[index].scatter(x_values, y_values, marker='o', s=sizes) index += 1 for plot in plots: plot.set_xlim(-2.0, 2.0) plot.set_ylim(-2.0, 2.0) figure.savefig(name_of_the_figure) if False: from matplotlib import axes3d figure = pyplot.figure() axes_3d = axes3d.Axes3D(figure) positions = particles.get_values_of_attribute('position') xs = numpy.array([position.x.value_in(units.lightyear) for position in positions]) ys = numpy.array([position.y.value_in(units.lightyear) for position in positions]) zs = numpy.array([position.z.value_in(units.lightyear) for position in positions]) # print xs, yz, zs plot = axes_3d.scatter(xs, ys, zs) axes_3d.set_xlim(-10.0, 10.0) axes_3d.set_ylim(-10.0, 10.0) axes_3d.set_zlim(-10.0, 10.0) figure.savefig("3d_"+name_of_the_figure) def print_log(time, gravity, particles, total_energy_at_t0, total_energy_at_this_time): print("Evolved model to t = " + str(time)) print(total_energy_at_t0.as_quantity_in(units.J), \ total_energy_at_this_time.as_quantity_in(units.J), \ (total_energy_at_this_time - total_energy_at_t0) / total_energy_at_t0) # print "KE:" , particles.kinetic_energy().as_quantity_in(units.J) # print "PE:" , particles.potential_energy(gravity.parameters.epsilon_squared) print("center of mass:", particles.center_of_mass()) print("center of mass velocity:", particles.center_of_mass_velocity()) total_mass = 0|units.kg for m in particles.mass: total_mass += m print("total mass =", total_mass) def simulate_small_cluster(number_of_stars, end_time = 40 | units.Myr, name_of_the_figure = "test-2.svg"): #numpy.random.seed(1) salpeter_masses = new_salpeter_mass_distribution(number_of_stars) total_mass = salpeter_masses.sum() convert_nbody = nbody_system.nbody_to_si(total_mass, 1.0 | units.parsec) particles = new_plummer_model(number_of_stars, convert_nbody) gravity = BHTree(convert_nbody) # print gravity.parameters.timestep.as_quantity_in(units.Myr) gravity.parameters.timestep = 0.0001 | units.Myr # tiny! gravity.parameters.epsilon_squared \ = (float(number_of_stars)**(-0.333333) | units.parsec) ** 2 stellar_evolution = SSE() print("setting masses of the stars") particles.radius = 0.0 | units.RSun particles.mass = salpeter_masses print("initializing the particles") stellar_evolution.particles.add_particles(particles) from_stellar_evolution_to_model \ = stellar_evolution.particles.new_channel_to(particles) from_stellar_evolution_to_model.copy_attributes(["mass"]) print("centering the particles") particles.move_to_center() print("scaling particles to viridial equilibrium") particles.scale_to_standard(convert_nbody) gravity.particles.add_particles(particles) from_model_to_gravity = particles.new_channel_to(gravity.particles) from_gravity_to_model = gravity.particles.new_channel_to(particles) time = 0.0 | units.Myr particles.savepoint(time) total_energy_at_t0 = gravity.kinetic_energy + gravity.potential_energy print("evolving the model until t = " + str(end_time)) while time < end_time: time += 0.25 | units.Myr print("gravity evolve step starting") gravity.evolve_model(time) print("gravity evolve step done") print("stellar evolution step starting") stellar_evolution.evolve_model(time) print("stellar evolution step done") from_gravity_to_model.copy() from_stellar_evolution_to_model.copy_attributes(["mass", "radius"]) particles.savepoint(time) from_model_to_gravity.copy_attributes(["mass"]) total_energy_at_this_time \ = gravity.kinetic_energy + gravity.potential_energy print_log(time, gravity, particles, total_energy_at_t0, total_energy_at_this_time) test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "small.hdf5") if os.path.exists(output_file): os.remove(output_file) storage = store.StoreHDF(output_file) storage.store(particles) gravity.stop() stellar_evolution.stop() plot_particles(particles, name_of_the_figure) def test_simulate_small_cluster(): """test_simulate_small_cluster This method is found by the testing framework and automatically run with all other tests. This method simulates a too small cluster, this is done to limit the testing time. """ assert is_mpd_running() test_results_path = get_path_to_results() output_file = os.path.join(test_results_path, "test-2.svg") simulate_small_cluster(4, 4 | units.Myr, name_of_the_figure=output_file) if __name__ == '__main__': N = 50 t_end = 10 output_file = 'test' if len(sys.argv) > 1: N = int(sys.argv[1]) if len(sys.argv) > 2: t_end = float(sys.argv[2]) if len(sys.argv) > 3: output_file = sys.argv[3] simulate_small_cluster(N, t_end | units.Myr, output_file)
6,750
32.755
82
py
amuse
amuse-main/examples/applications/distributed_nosetests.py
#!/usr/bin/python import nose from amuse.units import units from amuse.community.distributed.interface import ( # DistributedAmuseInterface, DistributedAmuse, ) from amuse.community.distributed.interface import ( # Resource, # Resources, Pilot, # Pilots, ) # Simple script to run nosetests using the distributed code. Should work for # any existing amuse test. # This example only runs the tests on the local machine. print("Setting up distributed code") instance = DistributedAmuse(redirection='none') # instance.parameters.debug = True # instance.parameters.webinterface_port = 4556 instance.commit_parameters() # Add some resources # resource = Resource() # resource.name='DAS4-VU' # resource.location="user@fs0.das4.cs.vu.nl" # resource.scheduler_type="sge" # resource.amuse_dir="/home/user/amuse" # instance.resources.add_resource(resource) print("Resources:") print(instance.resources) # Claim nodes on the resources. In this example simply the "local" machine pilot = Pilot() pilot.resource_name = 'local' pilot.node_count = 1 pilot.time = 2 | units.hour pilot.slots_per_node = 32 pilot.label = 'local' instance.pilots.add_pilot(pilot) print("Pilots:") print(instance.pilots) print("Waiting for pilots") instance.wait_for_pilots() print("setting distributed as default channel") instance.use_for_all_workers() print("Running tests") nose.run() print("all tests done, stopping distributed code") instance.stop()
1,495
23.129032
76
py
amuse
amuse-main/examples/syllabus/hydro_sink_particles.py
from amuse.lab import * def hydro_sink_particles(sinks, bodies): all_lost_particles = Particles() for s in sinks: xs,ys,zs=s.x,s.y,s.z radius_squared = s.radius**2 insink=bodies.select_array(lambda x,y,z: (x-xs)**2+(y-ys)**2+(z-zs)**2 < radius_squared,['x','y','z']) if len(insink)==0: return insink cm=s.position*s.mass p=s.velocity*s.mass s.mass+=insink.total_mass() s.position=(cm+insink.center_of_mass()*insink.total_mass())/s.mass s.velocity=(p+insink.total_momentum())/s.mass all_lost_particles.add_particles(insink) return all_lost_particles def main(N, Mtot, Rvir, rsink): converter=nbody_system.nbody_to_si(Mtot, Rvir) bodies = new_plummer_gas_model(N, convert_nbody=converter) sink = Particles(1) sink.mass = 0 | units.MSun sink.radius = rsink sink.position = (0, 0, 0) | units.AU sink.velocity = (0, 0, 0) | units.kms accreted = hydro_sink_particles(sink, bodies) print("Particles in sink: N=", len(accreted), " M=", sink.mass) print("sink position=", sink.position.as_quantity_in(units.AU)) print("sink velocity=", sink.velocity.as_quantity_in(units.kms)) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of sph particles [100]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1|units.MSun, help="Mass of molcular cloud [%default]") result.add_option("-R", unit=units.AU, dest="Rvir", type="float", default = 100|units.AU, help="Radius of cloud [%default]") result.add_option("-r", unit=units.AU, dest="rsink", type="float", default = 100|units.AU, help="Radius of the sink [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,124
37.636364
112
py
amuse
amuse-main/examples/syllabus/add_function_to_particleset.py
from amuse.lab import * def function(body): return 0.2*body[0].mass bodies = Particles(1) bodies.mass = 1|units.MSun bodies.add_global_function_attribute("new_function", function) print(bodies.new_function().in_(units.MSun))
231
22.2
62
py
amuse
amuse-main/examples/syllabus/plot_salpeter.py
""" Example AMUSE sciprt for plotting the Salpeter mass function """ import numpy from matplotlib import pyplot from amuse.lab import new_salpeter_mass_distribution, units def main(N, m, M, ximf): masses = new_salpeter_mass_distribution(N, m, M, ximf) lm = numpy.log10(m.value_in(units.MSun)) lM = numpy.log10(M.value_in(units.MSun)) bins = 10**numpy.linspace(lm, lM, 50) Nbin, bin_edges= numpy.histogram(masses.value_in(units.MSun), bins=bins) bin_sizes = bin_edges[1:] - bin_edges[:-1] y = Nbin / bin_sizes x = (bin_edges[1:] + bin_edges[:-1]) / 2.0 for i in range(len(y)): y[i] = max(y[i], 1.e-10) pyplot.scatter(x, y) c = ((M.value_in(units.MSun)**(ximf+1)) - (m.value_in(units.MSun)**(ximf+1))) / (ximf+1) pyplot.plot(x, N/ c * (x**ximf)) pyplot.loglog() pyplot.xlabel('$M [M_\odot]$') pyplot.ylabel('N') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [10]") result.add_option("-m", unit=units.MSun, dest="m", type="float",default = 1|units.MSun, help="minimum mass of the mass function [0.1] %unit") result.add_option("-M", unit=units.MSun, dest="M", type="float",default = 100|units.MSun, help="maximum mass of the mass function [100] %unit") result.add_option("-x", dest="ximf", type="float",default = -2.35, help="mass function slope [-2.35]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,803
36.583333
92
py
amuse
amuse-main/examples/syllabus/gravity_stellar_collision.py
""" Nbody integration of N particles with a Salpeter initial mass function between Mmin and Mmax and with stellar evolution with metalicity z. """ from __future__ import print_function from amuse.lab import * from amuse.io import store from amuse.community.seba.interface import SeBa def merge_two_stars(bodies, particles_in_encounter): com_pos = particles_in_encounter.center_of_mass() com_vel = particles_in_encounter.center_of_mass_velocity() new_particle=Particles(1) new_particle.mass = particles_in_encounter.total_mass() new_particle.age = min(particles_in_encounter.age) * max(particles_in_encounter.mass)/new_particle.mass new_particle.position = com_pos new_particle.velocity = com_vel new_particle.radius = 0 | units.RSun bodies.add_particles(new_particle) bodies.remove_particles(particles_in_encounter) def main(N, W0, t_end, dt, filename, Rvir, Mmin, Mmax, z): masses = new_salpeter_mass_distribution(N, Mmin, Mmax) Mtot_init = masses.sum() converter=nbody_system.nbody_to_si(Mtot_init,Rvir) bodies = new_king_model(N, W0,convert_nbody=converter) bodies.mass = masses bodies.scale_to_standard(convert_nbody=converter) gravity = ph4(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() stellar = SeBa() stellar.parameters.metallicity = z stellar.particles.add_particle(bodies) channel_from_se_to_framework = stellar.particles.new_channel_to(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se_to_framework.copy_attributes(["mass","radius", "age"]) write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') E_init = gravity.kinetic_energy + gravity.potential_energy Nenc = 0 #dE_enc = dE_dyn = dE_stellar = zero dE_coll = zero time = zero while time < t_end: time += dt bodies.radius *= 1.e+5 channel_from_framework_to_gd.copy_attributes(["mass", "radius"]) E_dyn = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(time) dE_dyn = E_dyn - (gravity.kinetic_energy + gravity.potential_energy) if stopping_condition.is_set(): E_coll = gravity.kinetic_energy + gravity.potential_energy print("At time=", gravity.model_time.in_(units.Myr), "number of encounters=", len(stopping_condition.particles(0))) for ci in range(len(stopping_condition.particles(0))): particles_in_encounter = Particles(particles=[stopping_condition.particles(0)[ci], stopping_condition.particles(1)[ci]]) particles_in_encounter = particles_in_encounter.get_intersecting_subset_in(bodies) merge_two_stars(bodies, particles_in_encounter) bodies.synchronize_to(gravity.particles) bodies.synchronize_to(stellar.particles) Nenc+=1 print("Resolve encounter Number:", Nenc) gravity.evolve_model(time) dE_coll = E_coll - (gravity.kinetic_energy + gravity.potential_energy) E_stellar = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) dE_stellar = E_stellar - (gravity.kinetic_energy + gravity.potential_energy) channel_from_gd_to_framework.copy() channel_from_se_to_framework.copy_attributes(["age", "mass", "radius"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') print_diagnostics(time, bodies.mass.sum(), E_dyn, dE_dyn, dE_coll, dE_stellar) gravity.stop() stellar.stop() def print_diagnostics(time, Mtot, Etot, dE_dyn, dE_coll, dE_stellar): print("T=", time, end=' ') print("M=", Mtot, end=' ') print("E= ", Etot, end=' ') print("dE(dyn)=", dE_dyn/Etot, end=' ') print("dE(coll)=", dE_coll/Etot, end=' ') print("dE(se)=", dE_stellar/Etot) def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "gravity_stellar.hdf5", help="output filename [%default]") result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [%default]") result.add_option("--dt", unit=units.Myr, dest="dt", type="float",default = 1|units.Myr, help="output timesteps [%default]") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float",default = 100, help="maximal stellar mass [%default.value_in(units.MSun))]") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float",default = 0.1, help="minimal stellar mass [%default.value_in(units.MSun)]") result.add_option("-R", unit=units.parsec, dest="Rvir", type="float",default = 1.0, help="cluser virial radius [%default.value_in(units.parsec)]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 10.0, help="end time of the simulation [%default.value_in(units.Myr]") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimension-less depth of the King potential (W0) [%default]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,904
43.067164
136
py
amuse
amuse-main/examples/syllabus/three_body_bridge.py
from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge def new_system_of_sun_and_earth(): stars = Particles(3) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) moon = stars[2] moon.mass = units.kg(7.3477e22 ) moon.radius = units.km(1737.10) moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity return stars def main(): filename = "SunAndEarthAndMoon.hdf" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] moon = ss[2] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) moon_gravity = ph4(converter) moon_gravity.particles.add_particle(moon) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss) write_set_to_file(ss, filename, 'hdf5') gravity = bridge.Bridge(use_threading=False) gravity.add_system(star_gravity, (planet_gravity,moon_gravity) ) gravity.add_system(planet_gravity, (star_gravity,moon_gravity) ) gravity.add_system(moon_gravity, (star_gravity,planet_gravity) ) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.timestep = 1|units.day time = zero dt = 3|units.day t_end = 1 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() channel_from_moon_to_framework.copy() write_set_to_file(ss, filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
2,759
31.857143
82
py
amuse
amuse-main/examples/syllabus/core_temperature_density.py
from amuse.lab import * Second_Asymptotic_Giant_Branch = 6 | units.stellar_type HeWhiteDwarf = 10 | units.stellar_type def stellar_remnant(stellar): remnant = True if stellar.particles[0].stellar_type<HeWhiteDwarf or stellar.particles[0].stellar_type>11|units.stellar_type: remnant = False return remnant def stellar_core_temperature_and_density(M, z): stellar = MESA() stellar.parameters.metallicity = z star = stellar.particles.add_particle(Particle(mass=M)) while not stellar_remnant(stellar): stellar.evolve_model() T_core = star.get_temperature_profile(star.get_number_of_zones())[0] density_core = star.get_density_profile(star.get_number_of_zones())[0] T_surface = star.get_temperature_profile(star.get_number_of_zones())[-1] density_surface = star.get_density_profile(star.get_number_of_zones())[-1] print(star.age, T_surface, density_surface, T_core, density_core) stellar.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.0 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() stellar_core_temperature_and_density(**o.__dict__)
1,554
36.02381
113
py
amuse
amuse-main/examples/syllabus/sun_venus_earth.py
""" Example AMUSE script for evolving Venus and Earth around the Sun. Syllabus List. 2.1 and 2.2 """ from amuse.lab import Particles, units def sun_venus_and_earth(): particles = Particles(3) sun = particles[0] sun.mass = 1.0 | units.MSun sun.position = (0.0,0.0,0.0) | units.m sun.velocity = (0.0,0.0,0.0) | (units.m/units.s) sun.radius = 1.0 | units.RSun venus = particles[1] venus.mass = 0.0025642 | units.MJupiter venus.radius = 3026.0 | units.km venus.position = (0.6335, 0.3499, -0.03179) | units.AU venus.velocity = (-17.0420, 30.5055, 1.4004) | units.kms earth = particles[2] earth.mass = 5.9736e24 | units.kg earth.radius = 6371.0 | units.km earth.position = (0.2421, -0.9875, -0.00004) | units.AU earth.velocity = (28.4468, 6.98125, 0.0002) | units.kms particles.move_to_center() return particles def integrate_solar_system(particles, end_time): from amuse.lab import Huayno, nbody_system from amuse.units import quantities convert_nbody = nbody_system.nbody_to_si(particles.mass.sum(), particles[1].position.length()) gravity = Huayno(convert_nbody) gravity.particles.add_particles(particles) venus = gravity.particles[1] earth = gravity.particles[2] x_earth = quantities.AdaptingVectorQuantity() y_earth = quantities.AdaptingVectorQuantity() x_venus = quantities.AdaptingVectorQuantity() y_venus = quantities.AdaptingVectorQuantity() while gravity.model_time < end_time: gravity.evolve_model(gravity.model_time + (10 | units.day)) x_earth.append(earth.x) y_earth.append(earth.y) x_venus.append(venus.x) y_venus.append(venus.y) gravity.stop() return x_earth, y_earth, x_venus, y_venus def plot_track(xe,ye,xv,yv): from matplotlib import pyplot, rc figure = pyplot.figure(figsize=(10,10)) font = {'size' : 20} rc('font', **font) plot = figure.add_subplot(1,1,1) plot.scatter([0.0], [0.0], color='y') plot.plot(xe.value_in(units.AU), ye.value_in(units.AU), color = "b") plot.plot(xv.value_in(units.AU), yv.value_in(units.AU), color = "r") plot.set_xlim(-1.5, 1.5) plot.set_ylim(-1.5, 1.5) plot.set_xlabel('x (AU)') plot.set_ylabel('y (AU)') pyplot.show() if __name__ in ('__main__','__plot__'): particles = sun_venus_and_earth() xe,ye, xv,yv = integrate_solar_system(particles, 2 | units.yr) plot_track(xe,ye,xv,yv)
2,493
31.815789
98
py
amuse
amuse-main/examples/syllabus/two_body_bridge.py
from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge def new_system_of_sun_and_earth(): stars = Particles(2) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) return stars def main(): filename = "SunAndEarth.hdf" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) star_gravity = ph4(converter) star_gravity.particles.add_particle(star) ###BOOKLISTSTART### planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) gravity = bridge.Bridge(use_threading=False) gravity.add_system(star_gravity, (planet_gravity,)) gravity.add_system(planet_gravity, (star_gravity,)) ###BOOKLISTSTOP### write_set_to_file(ss, filename, 'hdf5') Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init gravity.timestep = 1|units.day time = zero dt = 10|units.day t_end = 10 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() write_set_to_file(ss, filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
2,232
29.175676
82
py
amuse
amuse-main/examples/syllabus/binary_evolution_example.py
""" Generates a grid of binaries with different, primary mass, mass ratio and separation and evolves these over time. """ from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.community.seba.interface import SeBa from matplotlib import pyplot import numpy import time def create_double_star(Mprim, Msec, a, e): primary_stars = datamodel.Particles(mass=Mprim) secondary_stars = datamodel.Particles(mass=Msec) stars = datamodel.Particles() primary_stars = stars.add_particles(primary_stars) secondary_stars = stars.add_particles(secondary_stars) double_star = datamodel.Particles(semi_major_axis = a, eccentricity = e) double_star.child1 = list(primary_stars) double_star.child2 = list(secondary_stars) return double_star, stars def evolve_double_star(Mprim, Msec, a, e, end_time, n_steps): q = Msec/Mprim double_star, stars = create_double_star(Mprim, Msec, a, e) time = 0|units.Myr time_step = end_time/n_steps code = SeBa() code.particles.add_particles(stars) code.binaries.add_particles(double_star) channel_from_code_to_model_for_binaries = code.binaries.new_channel_to(double_star) channel_from_code_to_model_for_stars = code.particles.new_channel_to(stars) t = [] a = [] e = [] while time < end_time: time += time_step code.evolve_model(time) channel_from_code_to_model_for_stars.copy() channel_from_code_to_model_for_binaries.copy() t.append(time.value_in(units.Myr)) a.append(double_star[0].semi_major_axis.value_in(units.RSun)) e.append(double_star[0].eccentricity) code.stop() fig = pyplot.figure(figsize = (8,8)) fta = fig.add_subplot(2,1,1) # fte = fig.add_subplot(2,2,1) pyplot.title('Binary evolution', fontsize=12) fta.plot(t, a) pyplot.xlabel('time [Myr]') pyplot.ylabel('semi major axis (AU)') # fta.plot(t, e) #pyplot.ylabel('eccentricity') pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mprim", type="float",default = 12|units.MSun, help="primar mass [%defailt]") result.add_option("-m", unit=units.MSun, dest="Msec", type="float",default = 10|units.MSun, help="secondary mass [%defailt]") result.add_option("-T", unit=units.Myr, dest="end_time", type="float", default = 25.0 |units.Myr, help="end time of the simulation [%defailt]") result.add_option("-a", unit=units.RSun, dest="a", type="float",default = 205|units.RSun, help="orbital separation [%defailt]") result.add_option("-e", dest="e", type="float", default = 0.0, help="orbital eccentricity [%defailt]") result.add_option("-n", dest="n_steps", type="float", default = 100, help="number of output steps [%defailt]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() evolve_double_star(**o.__dict__)
3,283
35.488889
87
py
amuse
amuse-main/examples/syllabus/hydro_outflow_particles.py
import numpy from amuse.lab import * from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere set_printing_strategy("custom", #nbody_converter = converter, preferred_units = [units.MSun, units.AU, units.Myr], precision = 5, prefix = "", separator = " [", suffix = "]" ) def new_sph_particles_from_stellar_wind(stars, mgas): new_sph=datamodel.Particles(0) for si in stars: Ngas = int(-si.Mwind/mgas) if Ngas==0: continue Mgas = mgas*Ngas si.Mwind += Mgas add=datamodel.Particles(Ngas) add.mass = mgas add.h_smooth=0. | units.parsec dx,dy,dz=uniform_unit_sphere(Ngas).make_xyz() add.x=si.x+(dx * si.radius) add.y=si.y+(dy * si.radius) add.z=si.z+(dz * si.radius) for ri in range(len(add)): r = add[ri].position-si.position r = r/r.length() v_wind = (constants.G*si.mass/(add[ri].position-si.position).length()).sqrt() add.u= 0.5 * (v_wind)**2 add.vx=si.vx + r[0]*si.terminal_wind_velocity add.vy=si.vy + r[1]*si.terminal_wind_velocity add.vz=si.vz + r[2]*si.terminal_wind_velocity new_sph.add_particles(add) return new_sph def v_terminal_teff(star): t4=(numpy.log10(star.temperature.value_in(units.K))-4.).clip(0.,1.) return (30 | units.km/units.s) + ((4000 | units.km/units.s)*t4) def main(): stars = Particles(2) stars.mass = (9.5, 10) | units.MSun stars[0].position = (1, 0, 0) | units.AU stars[0].velocity = (0, 0, 0) | units.kms stars[1].position = (0, 0, 0) | units.AU stars[1].velocity = (0, 0, 0) | units.kms stars.move_to_center() a = stars.position.length().amax() vc = constants.G*stars.mass.sum()/a stellar = SeBa() stellar.particles.add_particles(stars) stellar_to_framework = stellar.particles.new_channel_to(stars) stellar.evolve_model(26|units.Myr) stellar_to_framework.copy_attributes(["mass","radius","temperature"]) dt = 0.1|units.Myr stellar.evolve_model((26|units.Myr)+dt) stars.dmdt = (stellar.particles.mass-stars.mass)/dt stars.Mwind = 0 | units.MSun stars.terminal_wind_velocity=v_terminal_teff(stars) stellar.stop() dt = 0.1|units.day mgas = 0.1*abs(stars.dmdt.sum()*dt) converter=nbody_system.nbody_to_si(1|units.MSun, a) bodies = Particles(0) bodies.mass = mgas bodies.position = (0,0,0)|units.AU bodies.velocity = (0,0,0)|units.kms bodies.u = 0 | units.m**2 * units.s**-2 bodies.h_smooth= 0.01*a hydro = Fi(converter, redirection="none") if len(bodies)>0: hydro.gas_particles.add_particles(bodies) hydro.parameters.use_hydro_flag=True hydro.parameters.timestep=dt hydro.parameters.periodic_box_size = 1000*a hydro_to_framework = hydro.gas_particles.new_channel_to(bodies) moving_bodies = ParticlesSuperset([stars, bodies]) filename = "hydro_outflow.hdf5" istep = 0 while hydro.model_time < 10|units.yr: stars.Mwind += stars.dmdt*dt new_sph = new_sph_particles_from_stellar_wind(stars, mgas) if len(new_sph)>0: bodies.add_particles(new_sph) bodies.synchronize_to(hydro.gas_particles) print("time=", hydro.model_time, "Ngas=", len(bodies), mgas*len(bodies)) if len(bodies)>100: hydro.evolve_model(hydro.model_time+dt) hydro_to_framework.copy() if istep%10 == 0: write_set_to_file(moving_bodies, filename, 'hdf5') istep += 1 hydro.stop() if __name__ in ('__main__', '__plot__'): main()
3,715
34.390476
89
py
amuse
amuse-main/examples/syllabus/plot_plummer.py
""" Example AMUSE sciprt for generating a Plummer shere and plot the results. """ from matplotlib.pyplot import show, xlim, ylim, figure from amuse.plot import scatter, xlabel, ylabel from amuse.lab import new_plummer_model def main(N=10): figure(figsize=(5,5)) bodies = new_plummer_model(N) scatter(bodies.x, bodies.y) xlim(-1, 1) ylim(-1, 1) xlabel("X") ylabel("Y") show() def new_option_parser(): from optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [1000]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
741
26.481481
95
py
amuse
amuse-main/examples/syllabus/gravity_kepler_disks.py
from __future__ import print_function from amuse.lab import * #from amuse.io import store #from amuse.community.seba.interface import SeBa from amuse.community.fractalcluster.interface import new_fractal_cluster_model def resolve_close_encounter(time, bodies, Johannes): Johannes.initialize_from_particles(bodies) rcom = bodies.center_of_mass() vcom = bodies.center_of_mass_velocity() a, e = Johannes.get_elements() p = Johannes.get_periastron() print("Close encounter at t=", time.in_(units.Myr), "a=", a.in_(units.AU), "e=", e, "p=", p.in_(units.AU), "M=", bodies.mass.max().in_(units.MSun), bodies.mass.min().in_(units.MSun), "at d=", rcom.in_(units.parsec), "with v=", vcom.in_(units.kms)) truncate_disks_due_to_encounter(bodies, p) def truncate_disks_due_to_encounter(bodies, p): q = bodies[1].mass/bodies[0].mass rtr_prim = 0.28*p / q**(0.32) rtr_sec = 0.28*p * q**(0.32) dm0 = truncate_disk_due_to_encounter(bodies[0], rtr_prim) dm1 = truncate_disk_due_to_encounter(bodies[1], rtr_sec) mtot = bodies.mass.sum() bodies[0].accreted_mass += dm1 * bodies[0].mass/mtot bodies[1].accreted_mass += dm0 * bodies[1].mass/mtot bodies[0].radius = min(bodies[0].radius, 0.5*p) bodies[1].radius = min(bodies[1].radius, 0.5*p) bodies[0].mass = bodies[0].stellar_mass + bodies[0].disk_mass + bodies[0].accreted_mass bodies[1].mass = bodies[1].stellar_mass + bodies[1].disk_mass + bodies[1].accreted_mass def stripped_disk_mass(body, dr): rold = body.disk_radius rnew = rold - dr dm = body.disk_mass * (rold**0.5-rnew**0.5)/rold**0.5 return max(0|units.MSun, dm) def truncate_disk_due_to_encounter(body, r_tr): dr = max(0|units.AU, body.disk_radius-r_tr) dm = stripped_disk_mass(body, dr) body.disk_radius -= dr body.disk_mass -= dm return dm def main(N, Rvir, Qvir, Fd): filename= 'Cl_N%g_R%gpc_Q%g_F%g.h5'%(N, Rvir.value_in(units.parsec), Qvir, Fd) t_end = 1.0 | units.Myr dt = 0.1 | units.Myr Mmax = 100 | units.MSun masses = new_kroupa_mass_distribution(N, Mmax) Mtot_init = masses.sum() converter=nbody_system.nbody_to_si(Mtot_init,Rvir) bodies = new_fractal_cluster_model(N=N, fractal_dimension=Fd, convert_nbody=converter) bodies.scale_to_standard(converter, virial_ratio=Qvir) bodies.stellar_mass = masses bodies.disk_mass = 0.1*bodies.stellar_mass bodies.mass = bodies.stellar_mass + bodies.disk_mass bodies.accreted_mass = 0 | units.MSun bodies.disk_radius = 400 | units.AU bodies.radius = 10 * bodies.disk_radius gravity = ph4(converter) gravity.parameters.epsilon_squared = (100|units.AU)**2 gravity.particles.add_particles(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() Johannes = Kepler(converter) Johannes.initialize_code() write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5', append_to_file=False) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init Nenc = 0 dEk_enc = zero dEp_enc = zero time = 0.0 | t_end.unit while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy while stopping_condition.is_set(): channel_from_gd_to_framework.copy() Ek_enc = gravity.kinetic_energy Ep_enc = gravity.potential_energy for ci in range(len(stopping_condition.particles(0))): particles_in_encounter = Particles(particles=[stopping_condition.particles(0)[ci], stopping_condition.particles(1)[ci]]) local_particles_in_encounter = particles_in_encounter.get_intersecting_subset_in(bodies) resolve_close_encounter(gravity.model_time, local_particles_in_encounter, Johannes) Nenc+=1 print("At time=", gravity.model_time.value_in(units.Myr), "Nenc=", Nenc, "Rdisk=", local_particles_in_encounter.disk_radius.in_(units.AU)) channel_from_framework_to_gd.copy_attributes(["radius"]) dEk_enc += Ek_enc - gravity.kinetic_energy dEp_enc += Ep_enc - gravity.potential_energy gravity.evolve_model(time) channel_from_framework_to_gd.copy_attributes(["mass"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_prev-Etot dE_se = Etot_prev_se-Etot Mtot = bodies.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtot_init, ")", end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, end=' ') print("(dE[SE]=", dE_se/Etot, ")") print("dE(enc)=", dEk_enc, dEp_enc) Etot_init -= dE Etot_prev = Etot gravity.stop() Johannes.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 2000, help="number of stars [%default]") result.add_option("-R", dest="Rvir", type="float", unit=units.parsec, default = 0.5|units.parsec, help="cluser virial radius [%default]") result.add_option("-Q", dest="Qvir", type="float",default = 0.5, help="virial ratio [%default]") result.add_option("-F", dest="Fd", type="float",default = 1.6, help="fractal dimension [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
6,086
39.046053
252
py
amuse
amuse-main/examples/syllabus/star_to_hydro.py
""" Convert a 1D Henhey stellar model into a spherical particle distribution """ from amuse.units import units from amuse.community.evtwin.interface import EVtwin from amuse.ext.star_to_sph import convert_stellar_model_to_SPH from amuse.plot import sph_particles_plot, native_plot from amuse.datamodel import Particle def convert_star_to_hydro_model(M, t_end): star = Particle(mass=M) stellar_evolution = EVtwin() se_star = stellar_evolution.particles.add_particle(star) stellar_evolution.evolve_model(t_end) sph_particles = convert_stellar_model_to_SPH(se_star, 10000).gas_particles stellar_evolution.stop() return sph_particles if __name__ in ("__main__", "__plot__"): sph_particles = convert_star_to_hydro_model(2.0|units.MSun, 110|units.Myr) native_plot.figure(figsize = (10, 10), dpi = 50) sph_particles_plot(sph_particles) native_plot.show()
901
33.692308
78
py
amuse
amuse-main/examples/syllabus/rad_minimal.py
""" Minimalistic routine for running a radiative transfer code. """ from __future__ import print_function from amuse.lab import * def main(N=1000, Lstar=100|units.LSun, boxsize=10|units.parsec, rho=1.0 | (units.amu/units.cm**3), t_end=0.1 |units.Myr): internal_energy = (9. |units.kms)**2 source=Particle() source.position = (0, 0, 0) |units.parsec source.flux = Lstar/(20. | units.eV) source.rho = rho source.xion = 0.0 source.u = internal_energy from amuse.ext.molecular_cloud import ism_cube ism = ism_cube(N, boxsize/2., rho, internal_energy).result ism.rho = rho ism.flux = 0. | units.s**-1 ism.xion = source.xion radiative = SimpleX() radiative.parameters.box_size=1.001*boxsize radiative.parameters.timestep=0.001 | units.Myr radiative.particles.add_particle(source) radiative.particles.add_particles(ism) radiative.evolve_model(t_end) print("min ionization:", radiative.particles.xion.min()) print("average Xion:", radiative.particles.xion.mean()) print("max ionization:", radiative.particles.xion.max()) radiative.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int", default = 1000, help="number of stars [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", default = 0.1|units.Myr, help="radiation time [%default]") result.add_option("-L", unit=units.LSun, dest="Lstar", default = 100|units.LSun, help="luminosity of ionizing source [%default]") result.add_option("-p", unit=units.amu/units.cm**3, dest="rho", default = 1|units.amu/units.cm**3, help="interstellar density [%default] amu/cm^3") result.add_option("-d", unit=units.parsec, dest="boxsize", default = 100|units.parsec, help="size of the density box [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,224
35.47541
70
py
amuse
amuse-main/examples/syllabus/rad_simple.py
from __future__ import print_function from amuse.lab import * from amuse.ext.molecular_cloud import ism_cube from amuse.ext.protodisk import ProtoPlanetaryDisk from amuse.community.simplex.interface import SimpleXInterface, SimpleX,SimpleXSplitSet def new_disk_with_bump(Mstar = 1|units.MSun, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU): converter=nbody_system.nbody_to_si(Mdisk, Rmin) bodies = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1.0, Rmax=Rmax/Rmin, q_out=1.0, discfraction=1.0).result Mdisk = bodies.mass.sum() bodies.move_to_center() com = bodies.center_of_mass() mm = Mdisk/float(Ndisk) Nbump = Mbump/mm print("Nbump=", Mbump, Rbump, Nbump) print("Mass =", Mstar, Mdisk, bodies.mass.sum().in_(units.MSun), bodies.mass.sum()/Mstar) bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump r_bump = abump inner_particles = bodies.select(lambda r: (com-r).length()<abump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./abump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms bodies.add_particles(bump) return bodies def main(N=1000, Lstar=100| units.LSun, boxsize=10| units.parsec, rho=1.0| (units.amu/units.cm**3), t_end=0.1|units.Myr, n_steps=10): ionization_fraction = 0.0 internal_energy = (9. |units.kms)**2 source=Particles(1) source.position = (0, 0, 0) |units.parsec source.flux = Lstar/(20. | units.eV) source.luminosity = Lstar/(20. | units.eV) source.rho = rho source.xion = ionization_fraction source.u = internal_energy converter=nbody_system.nbody_to_si(1|units.MSun, boxsize) ism = ProtoPlanetaryDisk(N, convert_nbody=converter, densitypower=1.5, Rmin=0.1, Rmax=1, q_out=1.0, discfraction=1.0).result ism = ism.select(lambda r: r.length()<0.5*boxsize,["position"]) gamma=5./3. mu=1.| units.amu Tinit = 10000|units.K ism.u = 1/(gamma-1)*constants.kB * Tinit/mu ism.rho = rho ism.flux = 0. | units.s**-1 ism.xion = ionization_fraction ism.h_smooth = 0 | units.AU rad = SimpleXSplitSet(redirect="none") # rad = SimpleX() # rad = SPHRay() rad.parameters.box_size=1.001*boxsize rad.parameters.timestep=0.001 | units.Myr rad.src_particles.add_particle(source) rad.gas_particles.add_particles(ism) channel_to_local_gas = rad.gas_particles.new_channel_to(ism) write_set_to_file(ism, "rad.hdf5", 'hdf5') time = 0.0 | t_end.unit dt = t_end/float(n_steps) while time<t_end: time += dt rad.evolve_model(time) channel_to_local_gas.copy_attributes(["xion",]) write_set_to_file(ism, "rad.hdf5", 'hdf5') print("Time=", time) print("min ionization:", rad.gas_particles.xion.min()) print("average Xion:", rad.gas_particles.xion.mean()) print("max ionization:", rad.gas_particles.xion.max()) rad.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 1000, help="number of stars [10]") result.add_option("-t", unit=units.Myr, dest="t_end", default = 0.1|units.Myr, help="radiation time [%default]") result.add_option("-L", unit=units.LSun, dest="Lstar", default = 100|units.LSun, help="luminosity of ionizing source [%default]") result.add_option("-p", unit=units.amu/units.cm**3, dest="rho", default = 1|units.amu/units.cm**3, help="interstellar density [%default] amu/cm^3") result.add_option("-d", unit=units.parsec, dest="boxsize", default = 100|units.parsec, help="size of the density box [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
4,649
38.07563
93
py
amuse
amuse-main/examples/syllabus/three_body_bridge_hierarchical.py
from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge def new_system_of_sun_and_earth(): stars = Particles(3) sun = stars[0] sun.mass = units.MSun(1.0) sun.position = units.m(numpy.array((0.0,0.0,0.0))) sun.velocity = units.ms(numpy.array((0.0,0.0,0.0))) sun.radius = units.RSun(1.0) earth = stars[1] earth.mass = units.kg(5.9736e24) earth.radius = units.km(6371) earth.position = units.km(numpy.array((149.5e6,0.0,0.0))) earth.velocity = units.ms(numpy.array((0.0,29800,0.0))) moon = stars[2] moon.mass = units.kg(7.3477e22 ) moon.radius = units.km(1737.10) moon.position = units.km(numpy.array((149.5e6 + 384399.0 ,0.0,0.0))) moon.velocity = ([0.0,1.022,0] | units.km/units.s) + earth.velocity return stars def main(): filename = "SunAndEarthAndMoon.hdf" ss = new_system_of_sun_and_earth() star = ss[0] planet = ss[1] moon = ss[2] converter=nbody_system.nbody_to_si(star.mass,planet.position.length()) star_gravity = ph4(converter) star_gravity.particles.add_particle(star) planet_gravity = ph4(converter) planet_gravity.particles.add_particle(planet) moon_gravity = ph4(converter) moon_gravity.particles.add_particle(moon) channel_from_star_to_framework = star_gravity.particles.new_channel_to(ss) channel_from_planet_to_framework = planet_gravity.particles.new_channel_to(ss) channel_from_moon_to_framework = moon_gravity.particles.new_channel_to(ss) write_set_to_file(ss, filename, 'hdf5') sp_gravity = bridge.Bridge(use_threading=False) sp_gravity.add_system(moon_gravity, (planet_gravity,) ) sp_gravity.add_system(planet_gravity, (moon_gravity,) ) gravity = bridge.Bridge(use_threading=False) gravity.add_system(sp_gravity, (star_gravity,) ) gravity.add_system(star_gravity, (sp_gravity,) ) Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init sp_gravity.timestep = 1|units.day gravity.timestep = 10|units.day time = zero dt = 3|units.day t_end = 1 | units.yr while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy channel_from_star_to_framework.copy() channel_from_planet_to_framework.copy() channel_from_moon_to_framework.copy() write_set_to_file(ss, filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() if __name__ in ('__main__', '__plot__'): main()
2,870
31.625
82
py
amuse
amuse-main/examples/syllabus/hydro_minimal.py
""" Minimalistic routine for running a hydrodynamics solver """ from __future__ import print_function from amuse.lab import * def main(N=100, Mtot=1|units.MSun, Rvir=1|units.RSun, t_end=1|units.hour): converter=nbody_system.nbody_to_si(Mtot, Rvir) gas = new_plummer_gas_model(N, convert_nbody=converter) hydro = Gadget2(converter) hydro.gas_particles.add_particles(gas) Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy hydro.evolve_model(t_end) Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot) print("pos=", hydro.gas_particles.center_of_mass().in_(units.RSun)) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of gas particles [%default]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 6|units.hour, help="end time of the simulation [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1|units.MSun, help="Mass of the cloud [%default]") result.add_option("-R", unit=units.RSun, dest="Rvir", type="float", default = 1|units.RSun, help="Radius of the cloud [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,799
38.130435
84
py
amuse
amuse-main/examples/syllabus/stellar_minimal.py
""" Minimalistic routine for running a stellar evolution code """ from amuse.lab import * def main(M, z, model_time): # stellar = MESA() stellar = SSE() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=M)) stellar.commit_particles() initial_luminosity = stellar.particles.luminosity dt = 0.1 | units.Myr time = 0 | units.Myr while stellar.particles[0].age<model_time: time+=dt stellar.evolve_model(time) final_luminosity = stellar.particles.luminosity print("L(t=0)=", initial_luminosity, \ ", L (t=", stellar.particles.age, ")=", \ final_luminosity, stellar.particles.radius, stellar.particles.mass.in_(units.MSun)) stellar.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.0 | units.MSun, help="stellar mass [%default]") result.add_option("-t", unit = units.Myr, dest="model_time", type="float", default = 4700.0|units.Myr, help="end time of the simulation [%default]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,519
33.545455
91
py
amuse
amuse-main/examples/syllabus/merge_two_stars.py
""" Initialize two stars to a ertain age and merge them using MMAMS """ import sys import numpy from amuse.lab import * from amuse.plot import plot, xlabel, ylabel from matplotlib import pyplot def merge_two_stars(Mprim, Msec, t_coll): bodies = Particles(mass=[Mprim, Msec] |units.MSun) stellar = MESA() primary = stellar.particles.add_particles(bodies[0].as_set()) secondary = stellar.particles.add_particles(bodies[1].as_set()) stellar.evolve_model(t_coll) n_zones = code.particles.get_number_of_zones() stellar.merge_colliding(primary.copy(), secondary.copy(), MMAMS, dict(), dict(target_n_shells_mixing = n_zones), return_merge_products=["se"]) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho def plot_density_profile(radius, rho): plot(radius.in_(units.RSun), rho) pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") pyplot.semilogy() pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", dest="Mprim", type="float",default = 5, help="Mass of the primary star [%default] MSun") result.add_option("-m", dest="Msec", type="float",default = 3, help="Mass of the secondary star [%default] MSun") result.add_option("-t", unit=units.Myr, dest="t_coll", type="float", default = 1.0|units.Myr, help="end time of the simulation [%default] Myr") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() radius, rho = merge_two_stars(**o.__dict__) plot_density_profile(radius, rho)
1,822
34.057692
97
py
amuse
amuse-main/examples/syllabus/plot_gravity.py
""" Simple visualization for N-body integration. Reads particle set from file (nbody.hdf5) and prints frames. """ from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.lab import * from amuse.io import store def main(filename, lim): pyplot.ion() particles = read_set_from_file(filename, "hdf5") if lim<=zero: lim = max(particles.x).value_in(lim.unit) time = 0 for si in particles.history: pyplot.title("Cluster at t="+str(time)) scatter(si.x.as_quantity_in(lim.unit), si.y.as_quantity_in(lim.unit)) xlabel("X") ylabel("Y") if lim>zero: pyplot.xlim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.ylim(-lim.value_in(lim.unit), lim.value_in(lim.unit)) pyplot.draw() pyplot.cla() pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "gravity.hdf5", help="output filename [gravty.hdf5]") result.add_option("-l", unit=units.kpc, dest="lim", type="float", default = -1|units.kpc, help="axis length [1000] %unit") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,354
32.04878
108
py
amuse
amuse-main/examples/syllabus/stellar_simple.py
""" Evolve a population of N stars. initial mass function between Mmin and Mmax and with stellar evolution with metalicity z. """ from __future__ import print_function import sys import numpy from amuse.lab import * from amuse.units.optparse import OptionParser from matplotlib import pyplot from amuse.plot import scatter, xlabel, ylabel from amuse.community.seba.interface import SeBa def main(N=10, t_end=10|units.Myr, dt=1|units.Myr, filename="stellar.hdf5", Mmin=1.0|units.MSun, Mmax= 100|units.MSun, z=0.02, C="SeBa"): if C.find("SeBa")>=0: print("SeBa") stellar = SeBa() elif C.find("SSE")>=0: print("SSE") stellar = SSE() elif C.find("MESA")>=0: stellar = MESA() elif C.find("EVtwin")>=0: stellar = EVtwin() else: print("No stellar model specified.") return stellar.parameters.metallicity = z mZAMS = new_salpeter_mass_distribution(N, Mmin, Mmax) mZAMS = mZAMS.sorted() bodies = Particles(mass=mZAMS) stellar.particles.add_particles(bodies) stellar.commit_particles() write_set_to_file(stellar.particles, filename, 'hdf5') Mtot_init = stellar.particles.mass.sum() time = 0.0 | t_end.unit while time < t_end: time += dt stellar.evolve_model(time) write_set_to_file(stellar.particles, filename, 'hdf5') Mtot = stellar.particles.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "dM[SE]=", Mtot/Mtot_init) #, stellar.particles[0].stellar_type T = [] L = [] r = [] import math for si in stellar.particles: T.append(math.log10(si.temperature.value_in(units.K))) L.append(math.log10(si.luminosity.value_in(units.LSun))) r.append(1.0+10*si.radius.value_in(units.RSun)) stellar.stop() pyplot.xlim(4.5, 3.3) pyplot.ylim(-4.0, 3.0) scatter(T, L, s=r) pyplot.xlabel("$log_{10}(T/K)$") pyplot.ylabel("$log_{10}(L/L_\odot)$") pyplot.show() def new_option_parser(): result = OptionParser() result.add_option("-C", dest="C", default = "SeBa", help="stellar evolution code [SeBa]") result.add_option("-d", unit=units.Myr, dest="dt", type="float", default = 100.0 |units.Myr, help="diagnostics time step [%defailt]") result.add_option("-f", dest="filename", default = "stellar.hdf5", help="output filename [stellar.hdf5]") result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [%defailt]") result.add_option("-M", unit=units.MSun, dest="Mmax", type="float",default = 100|units.MSun, help="maximal stellar mass [%defailt]") result.add_option("-m", unit=units.MSun, dest="Mmin", type="float",default = 1.0 |units.MSun, help="minimal stellar mass [%defailt]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 100.0 |units.Myr, help="end time of the simulation [%defailt]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%defailt]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
3,440
33.757576
89
py
amuse
amuse-main/examples/syllabus/gravity_minimal.py
""" Minimalistic routine for running a gravity code """ from __future__ import print_function from amuse.lab import * def main(N=10, W0=7.0, t_end=10): t_end = t_end | nbody_system.time bodies = new_king_model(N, W0) bodies.scale_to_standard() gravity = Hermite() gravity.particles.add_particles(bodies) Etot_init = gravity.kinetic_energy + gravity.potential_energy gravity.evolve_model(t_end) Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", gravity.get_time(), "M=", bodies.mass.sum(), end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, "dE=", (Etot_init-Etot)/Etot) gravity.stop() def new_option_parser(): from optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [%default]") result.add_option("-t", dest="t_end", type="float", default = 1, help="end time of the simulation [%default] N-body units") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimension-less depth of the potential (W0) [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,274
33.459459
129
py
amuse
amuse-main/examples/syllabus/initialize_singe_star.py
""" Script for initializing a star and printing its structure """ from amuse.lab import * from matplotlib import pyplot from amuse.plot import plot, xlabel, ylabel def get_density_profile(code=MESA, M=1.0|units.MSun, z=0.02): stellar = code() stellar.parameters.metallicity = z stellar.particles.add_particle(Particle(mass=M)) print("Nzones=", stellar.particles.get_number_of_zones()) radius = stellar.particles[0].get_radius_profile() rho = stellar.particles[0].get_density_profile() stellar.stop() return radius, rho def main(M, z): r, rho = get_density_profile(EVtwin, M, z) plot(r.in_(units.RSun), rho, label="EVtwin") r, rho = get_density_profile(MESA, M, z) plot(r.in_(units.RSun), rho, label="MESA") pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") pyplot.semilogy() pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit= units.MSun, dest="M", type="float",default = 1.0 | units.MSun, help="stellar mass [1.0] %unit") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [0.02]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
1,414
33.512195
72
py
amuse
amuse-main/examples/syllabus/stellar_gravity_hydro.py
""" example code for bridging a gravity solver with a hydrodynamics solver """ from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge from amuse import datamodel from amuse.ext.evrard_test import uniform_unit_sphere def new_sph_particles_from_stellar_wind(stars, mgas): new_sph=datamodel.Particles(0) for si in stars: p = si.position v = si.velocity Ngas = int(-si.Mwind/mgas) print("new Ngas=", si.mass, Ngas, end=' ') if Ngas==0: continue Mgas = mgas*Ngas si.Mwind += Mgas # Ngas = 10 # mgas = Mgas/10. print("new Ngas=", Ngas, mgas) add=datamodel.Particles(Ngas) add.mass = mgas add.h_smooth=0. | units.parsec dx,dy,dz=uniform_unit_sphere(Ngas).make_xyz() add.x=si.x+(dx * si.radius) add.y=si.y+(dy * si.radius) add.z=si.z+(dz * si.radius) for ri in range(len(add)): r = add[ri].position-p r = r/r.length() v_wind = (constants.G*si.mass/(add[ri].position-p).length()).sqrt() add.u= 0.5 * (v_wind)**2 v_wind = si.terminal_wind_velocity add.vx=v.x + r[0]*v_wind add.vy=v.y + r[1]*v_wind add.vz=v.z + r[2]*v_wind new_sph.add_particles(add) return new_sph def v_terminal_teff(star): t4=numpy.log10(star.temperature.value_in(units.K))-4. t4=t4.clip(0.,1.) return (30 | units.km/units.s) + ((4000 | units.km/units.s)*t4) def get_kepler_elements(model_time, bh, star, converter): kep = Kepler(converter) kep.initialize_code() pos = bh.position - star.position vel = bh.velocity - star.velocity print("Kep:", bh.mass + star.mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) kep.initialize_from_dyn(bh.mass + star.mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a,e = kep.get_elements() kep.stop() return a, e def gravity_hydro_bridge(a, ecc, t_end, n_steps, Rgas, Mgas, Ngas): stars = Particles(3) stars.mass = [5.0, 9.9, 10.0] | units.MSun stellar = SeBa() stellar.particles.add_particles(stars) stellar_to_framework = stellar.particles.new_channel_to(stars) stellar.evolve_model(26|units.Myr) stellar_to_framework.copy_attributes(["mass","radius","temperature"]) print("stars=", stars) stellar.evolve_model(26.1|units.Myr) stars.dmdt = (stellar.particles.mass-stars.mass)/(0.1|units.Myr) stars.Mwind = 0 | units.MSun stars.terminal_wind_velocity=v_terminal_teff(stars) stellar.stop() print("dmdt=", stars.dmdt) dt = 0.1|units.day mgas = 0.1*abs(stars.dmdt.sum()*dt) print("mgas=", mgas.value_in(units.MJupiter), stars.dmdt/mgas) vc = constants.G*stars.mass.sum()/a Porb = 2*numpy.pi*(a**3/(constants.G*stars.mass.sum())).sqrt() stars[0].position = (0,0,0) | units.AU stars[0].velocity = (0,0,0) | units.kms vc = (constants.G*stars[:2].mass.sum()/(a*(1+ecc))).sqrt() vc *= numpy.sqrt((1-ecc)/(1+ecc)) stars[1].position = (a.value_in(units.AU),0,0) | units.AU stars[1].velocity = (0,vc.value_in(units.kms),0) | units.kms stars[:2].move_to_center() ecc = 0.2 vc = (constants.G*stars.mass.sum()/(10*a*(1+ecc))).sqrt() vc *= numpy.sqrt((1-ecc)/(1+ecc)) stars[2].position = (10*a.value_in(units.AU),0,0) | units.AU stars[2].velocity = (0,vc.value_in(units.kms),0) | units.kms stars.move_to_center() stars.radius = 0.2*a #define for printing # stars.h_smooth= 0.0*a # stars.u = 0 | units.kms**2 converter=nbody_system.nbody_to_si(stars.mass.sum(), a) gravity = ph4(converter, redirection="none") gravity.particles.add_particles(stars) gravity.parameters.epsilon_squared = (10|units.RSun)**2 Ed0_tot = gravity.kinetic_energy + gravity.potential_energy channel_from_gravity = gravity.particles.new_channel_to(stars) channel_from_to_gravity = stars.new_channel_to(gravity.particles) dt = t_end/float(n_steps) converter=nbody_system.nbody_to_si(1.0|units.MSun, a) ism = Particles(0) ism.mass = mgas ism.position = (0,0,0)|units.AU ism.velocity = (0,0,0)|units.kms ism.u = 0 | units.m**2 * units.s**-2 ism.h_smooth= 0.01*a hydro = Fi(converter, redirection="none") hydro.parameters.timestep = dt/8. hydro.parameters.use_hydro_flag=True hydro.parameters.radiation_flag=False hydro.parameters.self_gravity_flag=True hydro.parameters.integrate_entropy_flag=False hydro.parameters.gamma=1. hydro.parameters.isothermal_flag=True hydro.parameters.epsilon_squared = (10|units.RSun)**2 if len(ism)>0: hydro.gas_particles.add_particles(ism) Eh0_tot = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy hydro.parameters.periodic_box_size = 10000*a channel_from_hydro = hydro.gas_particles.new_channel_to(ism) channel_from_to_hydro = ism.new_channel_to(hydro.gas_particles) moving_bodies = ParticlesSuperset([stars, ism]) model_time = 0 | units.Myr filename = "stellargravhydro.hdf5" if len(ism)>0: write_set_to_file(moving_bodies, filename, 'hdf5') gravhydro = bridge.Bridge(use_threading=False) gravhydro.add_system(gravity, (hydro,) ) gravhydro.add_system(hydro, (gravity,) ) gravhydro.timestep = min(dt, 2*hydro.parameters.timestep) istep = 0 while model_time < t_end: model_time += dt a, e = get_kepler_elements(gravity.model_time, stars[0], stars[1], converter) print("AB: time=", model_time, a, e) com_star = Particles(1) com_star.mass = stars[:2].mass.sum() com_star.position = stars[:2].center_of_mass() com_star.velocity = stars[:2].center_of_mass_velocity() a, e = get_kepler_elements(gravity.model_time, com_star[0], stars[2], converter) print("(AB)C: time=", model_time, a, e) stars.Mwind += stars.dmdt*dt print("Mw=", stars.Mwind, stars.Mwind/mgas) new_sph = new_sph_particles_from_stellar_wind(stars, mgas) print("Ngas=", len(new_sph), len(ism), len(hydro.gas_particles)) if len(new_sph)>0: # and len(bodies)<4000: ism.add_particles(new_sph) ism.synchronize_to(hydro.gas_particles) if len(ism)>100: print("t=", hydro.model_time, dt) gravhydro.evolve_model(model_time) channel_from_gravity.copy() channel_from_hydro.copy() channel_from_hydro.copy_attributes(["u"]) print("N=", len(hydro.particles)) Ed_tot = gravity.kinetic_energy + gravity.potential_energy Eh_tot = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy print("Energies:", Ed_tot/Ed0_tot, Eh_tot/Eh0_tot) if istep%10==0: write_set_to_file(moving_bodies, filename, 'hdf5') istep+=1 gravity.stop() hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="n_steps", type="int", default = 1000, help="number of diagnostics time steps [%default]") result.add_option("-N", dest="Ngas", type="int", default = 1024, help="number of gas particles [%default]") result.add_option("-M", unit=units.MSun, dest="Mgas", type="float", default = 1|units.MSun, help="Mass of the gas [%default]") result.add_option("-R", unit=units.AU, dest="Rgas", type="float", default = 1|units.AU, help="Size of the gas distribution [%default]") result.add_option("-a", unit=units.AU, dest="a", type="float", default = 0.2|units.AU, help="initial orbital separation [%default]") result.add_option("-e", dest="ecc", type="float", default = 0.0, help="initial orbital eccentricity [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 10|units.yr, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() gravity_hydro_bridge(**o.__dict__)
8,412
37.949074
96
py
amuse
amuse-main/examples/syllabus/hydro_experiment.py
""" Simulate the hydrodynamial evolve a disk with a single bump around a star """ from __future__ import print_function from amuse.lab import * from amuse.io import store def main(Mstar = 1|units.MSun, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU, t_end=1, n_steps=10): converter=nbody_system.nbody_to_si(Mdisk, Rmin) from amuse.ext.protodisk import ProtoPlanetaryDisk bodies = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1.0, Rmax=Rmax/Rmin, q_out=1.0, discfraction=1.0).result Mdisk = bodies.mass.sum() bodies.move_to_center() com = bodies.center_of_mass() mm = Mdisk/float(Ndisk) Nbump = Mbump/mm bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump r_bump = abump inner_particles = bodies.select(lambda r: (com-r).length()<abump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./abump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms bodies.add_particles(bump) star=Particles(1) star.mass=Mstar star.radius= Rmin star.position = [0, 0, 0] | units.AU star.velocity = [0, 0, 0] | units.kms import math P_bump = (abump**3*4*math.pi**2/(constants.G*(Mbump+Mstar))).sqrt() t_end *= P_bump hydro = Gadget2(converter) hydro.gas_particles.add_particles(bodies) hydro.dm_particles.add_particles(star) Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy particles = ParticlesSuperset([star, bodies]) particles.move_to_center() particles.new_channel_to(hydro.particles).copy() bodies.h_smooth = Rmin # for the plotting routine channel_to_star = hydro.dm_particles.new_channel_to(star) channel_to_bodies = hydro.gas_particles.new_channel_to(bodies) write_set_to_file(star, "stars.hdf5","hdf5") write_set_to_file(bodies, "hydro.hdf5","hdf5") time = 0.0 | t_end.unit dt = t_end/float(n_steps) while time < t_end: time += dt hydro.evolve_model(time) channel_to_star.copy() channel_to_bodies.copy() write_set_to_file(star, "stars.hdf5","hdf5") write_set_to_file(bodies, "hydro.hdf5","hdf5") star.radius = Rmin from hydro_sink_particles import hydro_sink_particles lost = hydro_sink_particles(star, bodies) if len(lost)>0: hydro.particles.remove_particles(lost) hydro.particles.synchronize_to(particles) print("Disk=", hydro.model_time, len(bodies), len(lost), lost.mass.sum(), star.mass) Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot) print("Star=", hydro.model_time, star[0].mass, star[0].position) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ndisk", type="int",default = 100, help="number of stars [10]") result.add_option("-n", dest="n_steps", type="int",default = 10, help="number of steps [10]") result.add_option("-t", dest="t_end", type="float", default = 1, help="end time of the simulation in bump orbits") result.add_option("-M", dest="Mstar", type="float", default = 1|units.MSun, help="Mass of the central star [%default]") result.add_option("--Mdisk", dest="Mdisk", type="float", default = 0.9|units.MSun, help="Mass of the disk [%default]") result.add_option("-r", unit=units.AU, dest="Rmin", type="float", default = 10 |units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, dest="Rmax", type="float", default = 100 | units.AU, help="outer disk radius [%default]") result.add_option("--Mbump", unit=units.MSun, dest="Mbump", type="float", default = 0.1 | units.MSun, help="bump mass [%default]") result.add_option("--Rbump", unit=units.AU, dest="Rbump", type="float", default = 10 | units.AU, help="bump radius [%default]") result.add_option("-a", unit=units.AU, dest="abump", type="float", default = 20 | units.AU, help="distance of bump from star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,136
39.769841
96
py
amuse
amuse-main/examples/syllabus/sun_and_M67.py
from __future__ import print_function import numpy from amuse.lab import * from amuse.couple import bridge from matplotlib import pyplot class MilkyWay_galaxy(object): def get_gravity_at_point(self, eps, x,y,z): phi_0 = self.get_potential_at_point(eps, x,y,z) grav = AdaptingVectorQuantity() dpos = 0.001*(x**2+y**2+z**2).sqrt() phi_dx = self.get_potential_at_point(0,x+dpos,y,z) - phi_0 phi_dy = self.get_potential_at_point(0,x,y+dpos,z) - phi_0 phi_dz = self.get_potential_at_point(0,x,y, z+dpos) - phi_0 return phi_dx/dpos, phi_dy/dpos, phi_dz/dpos def disk_and_bulge_potentials(self, x,y,z, a, b, mass): r = (x**2+y**2).sqrt() return constants.G * mass /\ (r**2 + (a + (z**2 + b**2).sqrt())**2).sqrt() def halo_potential(self, x,y,z, Mc=5.0E+10|units.MSun, Rc=1.0|units.kpc**2): r=(x**2+y**2+z**2).sqrt() rr = (r/Rc) return -constants.G * (Mc/Rc)*(0.5*numpy.log(1 +rr**2) + numpy.arctan(rr)/rr) def get_potential_at_point(self, eps, x, y, z): pot_disk = self.disk_and_bulge_potentials(x,y,z, 0.0|units.kpc, 0.277|units.kpc, 1.12E+10|units.MSun) pot_bulge = self.disk_and_bulge_potentials(x,y,z, 3.7|units.kpc, 0.20|units.kpc, 8.07E+10|units.MSun) pot_halo = self.halo_potential(x,y,z, Mc=5.0E+10|units.MSun, Rc=6.0|units.kpc) return pot_disk + pot_bulge + pot_halo def movie(time, sun_and_planets): R = [] | units.kpc for sp in sun_and_planets: R.append(sp.position.length()) # - sun_and_planets.z print(R) pyplot.subplot(2,2,1) pyplot.scatter(sun_and_planets.x.value_in(units.kpc), sun_and_planets.y.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.subplot(2,2,2) pyplot.scatter(R.value_in(units.kpc), sun_and_planets.z.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.xlabel("R [kpc]") pyplot.ylabel("Z [kpc]") R = [] | units.kpc R.append((sun_and_planets[1].position-sun_and_planets[0].position).length()) pyplot.subplot(2,2,3) pyplot.scatter(-time.value_in(units.Gyr), R.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.xlabel("t [Myr]") pyplot.ylabel("r [kpc]") pyplot.draw() def main(t_end, filename): bodies = Particles(2) Sun = bodies[0] Sun.mass = 1|units.MSun Sun.position = (8.4, 0.0, 0.0) | units.kpc Sun.velocity = (-10.1, 235.5, 7.5) | units.kms # SPZ2009 M67 = bodies[1] M67.mass = 50000 | units.MSun M67.position = Sun.position + ((0.766, 0.0, 0.49) |units.kpc) M67.velocity = Sun.velocity + ((31.92, -21.66, -8.71) |units.kms) converter = nbody_system.nbody_to_si(bodies.mass.sum(), Sun.x) sunandm67 = Huayno(converter) sunandm67.particles.add_particle(bodies) channel_from_sunandm67 = sunandm67.particles.new_channel_to(bodies) gravity = bridge.Bridge() gravity.add_system(sunandm67, (MilkyWay_galaxy(),) ) dt = 1|units.Myr gravity.timestep = dt Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init t_end = 4.5|units.Gyr time = 0 * t_end if filename: write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5", append_to_file=False) pyplot.draw() else: R = [] | units.kpc for bi in bodies: R.append(bi.position.length()) pyplot.ion() pyplot.scatter(R.value_in(units.kpc), bodies.z.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.xlabel("R [kpc]") pyplot.ylabel("Z [kpc]") while time < t_end: time += dt gravity.evolve_model(time) channel_from_sunandm67.copy() Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, "M=", bodies.mass.sum(), end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot if filename: write_set_to_file(bodies.savepoint(time), filename, "hdf5") else: R = [] | units.kpc for bi in bodies: R.append(bi.position.length()) pyplot.scatter(R.value_in(units.kpc), bodies.z.value_in(units.kpc), c=['k', 'r'], s=10, lw=0) pyplot.draw() gravity.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-t", unit=units.Gyr, dest="t_end", type="float", default = 4.5|units.Gyr, help="end time of the simulation [%default]") result.add_option("-f", dest="filename", default = "", help="output filename") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
5,242
34.187919
85
py
amuse
amuse-main/examples/syllabus/rad_experiment.py
""" Simulate the radiative and hydrodynamial evolution of a disk with a single bump around a single star """ from __future__ import print_function from time import time, localtime from amuse.lab import * from amuse.ext.molecular_cloud import ism_cube from amuse.community.simplex.interface import SimpleXInterface, SimpleX,SimpleXSplitSet set_printing_strategy("custom", preferred_units = [units.MSun, units.AU, units.Myr], precision = 5, prefix = "", separator = " [", suffix = "]" ) def new_disk_with_bump(Mstar = 1|units.MSun, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU): converter=nbody_system.nbody_to_si(Mdisk, Rmin) from amuse.ext.protodisk import ProtoPlanetaryDisk bodies = ProtoPlanetaryDisk(Ndisk, convert_nbody=converter, densitypower=1.5, Rmin=1, Rmax=Rmax/Rmin, q_out=1.0, discfraction=1.0).result Mdisk = bodies.mass.sum() bodies.move_to_center() com = bodies.center_of_mass() mm = Mdisk/float(Ndisk) Nbump = Mbump/mm bump = new_plummer_gas_model(Nbump, convert_nbody=nbody_system.nbody_to_si(Mbump, Rbump)) bump.x += abump r_bump = abump inner_particles = bodies.select(lambda r: (com-r).length()<abump,["position"]) M_inner = inner_particles.mass.sum() + Mstar v_circ = (constants.G*M_inner*(2./r_bump - 1./abump)).sqrt().value_in(units.kms) bump.velocity += [0, v_circ, 0] | units.kms bodies.add_particles(bump) bodies = bodies.select(lambda r: (com-r).length()>Rmin,["position"]) bodies = bodies.select(lambda r: (com-r).length()<Rmax,["position"]) print("Nbump=", Ndisk, Mbump, Rbump, Nbump) print("Mass =", Mstar, Mdisk, bodies.mass.sum().in_(units.MSun), bodies.mass.sum()/Mstar) print("X-min/max:", min(bodies.x), max(bodies.x)) bodies = bodies.select(lambda r: r.length()<1.0*Rmax,["position"]) print("X-min/max:", min(bodies.x), max(bodies.x)) return bodies def read_disk_with_bump(image_id=1, filename="hydro.hdf5"): star = read_set_from_file(filename, "hdf5") ism = read_set_from_file(filename, "hdf5") snapshot_id = 0 for si in ism.history: snapshot_id += 1 print("reading snapshot_id=", snapshot_id) if image_id<0 or image_id == snapshot_id: com = si.center_of_mass() return si def irradiate_disk_with_bump(Mstar = 10|units.MSun, tstar = 20|units.Myr, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU, t_end=10|units.yr, n_steps=10): dt = t_end/float(n_steps) stellar = SeBa() stellar.particles.add_particle(Particle(mass=Mstar)) stellar.evolve_model(tstar) source=Particles(1) source.mass = stellar.particles[0].mass source.position = (0, 0, 0) |units.AU source.velocity = (0, 0, 0) |units.kms source.luminosity = stellar.particles[0].luminosity/(20. | units.eV) source.temperature = stellar.particles[0].temperature Teff = stellar.particles[0].temperature source.flux = source.luminosity source.rho = 1.0|(units.g/units.cm**3) source.xion = 0.0 #ionization_fraction source.u = (9. |units.kms)**2 #internal_energy stellar.stop() ism = new_disk_with_bump(source[0].mass, Ndisk, Mdisk, Rmin, Rmax, Mbump, Rbump, abump) ism.flux = 0 | units.s**-1 ism.xion = 0.0 #ionization_fraction hydro = Gadget2(nbody_system.nbody_to_si(Mdisk, Rmax)) hydro.gas_particles.add_particles(ism) hydro.dm_particles.add_particles(source) hydro.evolve_model(1|units.day) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() rad = SimpleXSplitSet(redirect="none",numer_of_workers=4) rad.parameters.box_size=2.01*Rmax rad.parameters.timestep=0.1*dt rad.set_source_Teff(Teff) rad.src_particles.add_particle(source) rad.gas_particles.add_particles(ism) rad_to_framework = rad.gas_particles.new_channel_to(ism) particles = ParticlesSuperset([source, ism]) write_set_to_file(particles, "rad.hdf5", 'hdf5') while rad.model_time<t_end: rad.evolve_model(rad.model_time + dt) rad_to_framework.copy_attributes(["x","y", "z", "xion"]) write_set_to_file(particles, "rad.hdf5", 'hdf5') print("Time=", rad.model_time, "Ionization (min, mean, max):", ism.xion.min(), ism.xion.mean(), ism.xion.max()) rad.stop() def _irradiate_disk_with_pump(Mstar = 10|units.MSun, tstar = 20|units.Myr, Ndisk=100, Mdisk=0.9|units.MSun, Rmin=1.0|units.AU, Rmax=100.0|units.AU, Mbump=0.1|units.MSun,Rbump=10.0|units.AU, abump=10|units.AU, t_end=10|units.yr, n_steps=10, filename = None, image_id=1): model_time = 0.0 | t_end.unit dt = t_end/float(n_steps) ionization_fraction = 0.0 internal_energy = (9. |units.kms)**2 stellar = SeBa() stellar.particles.add_particle(Particle(mass=Mstar)) stellar.evolve_model(tstar) print("L=", stellar.particles[0].luminosity.in_(units.LSun), stellar.particles[0].temperature) source=Particles(1) source.mass = stellar.particles[0].mass source.position = (0, 0, 0) |units.AU source.velocity = (0, 0, 0) |units.kms source.luminosity = stellar.particles[0].luminosity/(20. | units.eV) source.temperature = stellar.particles[0].temperature Teff = stellar.particles[0].temperature source.flux = source.luminosity source.rho = 1.0|(units.g/units.cm**3) source.xion = ionization_fraction source.u = internal_energy stellar.stop() Mstar = source[0].mass if filename ==None: ism = new_disk_with_bump(Mstar = Mstar, Ndisk=Ndisk, Mdisk=Mdisk, Rmin=Rmin, Rmax=Rmax, Mbump=Mbump, Rbump=Rbump, abump=abump) else: ism = read_disk_with_bump(image_id=image_id, filename=filename)#, Rmax=Rmax) ism = ism.select(lambda r: r.length()<1.0*Rmax,["position"]) ism.flux = 0 | units.s**-1 ism.xion = ionization_fraction if filename ==None: converter=nbody_system.nbody_to_si(Mdisk, Rmax) hydro = Gadget2(converter) hydro.gas_particles.add_particles(ism) hydro.dm_particles.add_particles(source) hydro.evolve_model(1|units.day) hydro.gas_particles.new_channel_to(ism).copy() hydro.stop() rad = SimpleXSplitSet(redirect="none",numer_of_workers=4) rad.parameters.number_of_freq_bins=5 rad.parameters.thermal_evolution_flag=1 rad.parameters.blackbody_spectrum_flag=1 rad.parameters.metal_cooling_flag=0 rad.parameters.box_size=2.01*Rmax if isinstance(rad, SPHRay): ism.h_smooth = 0.1 | (units.RSun) else: rad.parameters.timestep=0.1*dt rad.set_source_Teff(Teff) rad.src_particles.add_particle(source) rad.gas_particles.add_particles(ism) channel_from_rad_to_framework = rad.gas_particles.new_channel_to(ism) particles = ParticlesSuperset([source, ism]) write_set_to_file(particles, "rad.hdf5", 'hdf5') tCPU = time() while model_time<t_end: model_time += dt rad.evolve_model(model_time) channel_from_rad_to_framework.copy_attributes(["x","y", "z", "xion"]) write_set_to_file(particles, "rad.hdf5", 'hdf5') print("Date:"+str(localtime()[2])+"."+str(localtime()[1])+"."+str(localtime()[1]), "at", str(localtime()[3])+"h", str(localtime()[4])+"m") print("Time=", model_time, "dt_CPU=", time()-tCPU) print("min ionization:", ism.xion.min()) print("average Xion:", ism.xion.mean()) print("max ionization:", ism.xion.max()) tCPU = time() rad.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="Ndisk", type="int",default = 1000, help="number of stars [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 1|units.yr, help="radiation time [%default]") result.add_option("-f", dest="filename", default = None, help="input filename [%default]") result.add_option("--tstar", unit=units.Myr, dest="tstar", type="float", default = 20|units.Myr, help="age of the star [%default]") result.add_option("-n", dest="n_steps", type="int",default = 36500, help="number of steps [%default]") result.add_option("-i", dest="image_id", type="int",default = 1, help="id of the input (filename) snapshot [%default]") result.add_option("--Mstar", unit=units.MSun, dest="Mstar", type="float", default = 10|units.MSun, help="Mass of the central star [%default]") result.add_option("--Mdisk", unit=units.MSun, dest="Mdisk", type="float", default = 0.0002|units.MSun, help="Mass of the disk [%default]") result.add_option("-r", unit=units.AU, dest="Rmin", type="float", default = 10 |units.AU, help="inner disk radius [%default]") result.add_option("-R", unit=units.AU, dest="Rmax", type="float", default = 100 | units.AU, help="outer disk radius [%default]") result.add_option("--Mbump", unit=units.MSun, dest="Mbump", type="float", default = 0.0001 | units.MSun, help="bump mass [%default]") result.add_option("--Rbump", unit=units.AU, dest="Rbump", type="float", default = 5 | units.AU, help="bump radius [%default]") result.add_option("-a", unit=units.AU, dest="abump", type="float", default = 10 | units.AU, help="distance of bump from star [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() irradiate_disk_with_bump(**o.__dict__)
10,552
40.222656
241
py
amuse
amuse-main/examples/syllabus/plot_molecular_cloud.py
""" example of molecular cloud evolution with explictly split SPH and grav evolution Initial condition is a smooth spherical cloud with random velocities as in Bonnell et al. (2003) """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.lab import * from amuse.ext.molecular_cloud import molecular_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from amuse.plot import sph_particles_plot, native_plot def create_molecular_cloud(N, Mcloud, Rcloud, t_end): converter = nbody_system.nbody_to_si(Mcloud,Rcloud) parts=molecular_cloud(targetN=N,convert_nbody=converter, base_grid=body_centered_grid_unit_cube, seed=100).result # parts = new_plummer_gas_model(N, convert_nbody=converter) sph=Fi(converter) sph.gas_particles.add_particle(parts) sph.evolve_model(t_end) ch = sph.gas_particles.new_channel_to(parts) ch.copy() sph.stop() return parts if __name__ in ("__main__","__plot__"): sph_particles = create_molecular_cloud(10000, Mcloud=10000. | units.MSun, Rcloud=10. | units.parsec, t_end=1|units.day) native_plot.figure(figsize = (10, 10), dpi = 50) sph_particles_plot(sph_particles) native_plot.show()
1,261
29.780488
123
py
amuse
amuse-main/examples/syllabus/gravity_potential.py
import numpy from amuse.units import units from amuse.units import constants from amuse.units import nbody_system from amuse.ext.bridge import bridge from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.fi.interface import Fi from amuse.community.gadget2.interface import Gadget2 from matplotlib import pyplot from amuse.ic.kingmodel import new_king_model """ Implements a code simulating the galactic center. As the center itself does not evolve we only need to define the 'get_gravity_at_point' and 'get_potential_at_point'. Note that both functions get arrays of points. """ class GalacticCenterGravityCode(object): def __init__(self,R=1000.| units.parsec, M=1.6e10 | units.MSun, alpha=1.2): self.R=R self.M=M self.alpha=alpha def get_gravity_at_point(self,eps,x,y,z): r2=x**2+y**2+z**2 r=r2**0.5 m=self.M*(r/self.R)**self.alpha fr=constants.G*m/r2 ax=-fr*x/r ay=-fr*y/r az=-fr*z/r return ax,ay,az def get_potential_at_point(self,eps,x,y,z): r2=x**2+y**2+z**2 r=r2**0.5 c=constant.G*self.M/self.R**self.alpha phi=c/(alpha-1)*(r**(self.alpha-1)-R**(self.alpha-1)) return phi def vcirc(self,r): m=self.M*(r/self.R)**self.alpha vc=(constants.G*m/r)**0.5 return vc """ helper function to setup an nbody king model cluster (returns code with particles) """ def king_model_cluster(interface,N=1024,W0=3, Mcluster=4.e4 | units.MSun, Rcluster= .7 | units.parsec,parameters=[]): converter=nbody_system.nbody_to_si(Mcluster,Rcluster) parts=new_king_model(N,W0,convert_nbody=converter) parts.radius=0.0| units.parsec nb=interface(converter) for name,value in parameters: setattr(nb.parameters, name, value) nb.particles.add_particles(parts) return nb def shift_sys(system,dx,dy,dz,dvx,dvy,dvz): """ helper function to shift system """ parts=system.particles.copy() parts.x=parts.x+dx parts.y=parts.y+dy parts.z=parts.z+dz parts.vx=parts.vx+dvx parts.vy=parts.vy+dvy parts.vz=parts.vz+dvz channel=parts.new_channel_to(system.particles) channel.copy_attributes(["x","y","z","vx","vy","vz"]) # parts.copy_values_of_state_attributes_to(system.particles) if __name__ == "__main__": N=1024 W0=3 Rinit=50. | units.parsec timestep=0.01 | units.Myr Mcluster=4.e4 | units.MSun Rcluster=0.7 | units.parsec cluster=king_model_cluster(Fi,N,W0, Mcluster,Rcluster, parameters=[ ("epsilon_squared", (0.01 | units.parsec)**2), ("periodic_box_size",200 | units.parsec), ("timestep",timestep/4)] ) center=GalacticCenterGravityCode() vcirc=center.vcirc(Rinit) shift_sys(cluster,Rinit,0| units.parsec,0.|units.parsec, 0| units.kms,0.8*vcirc,0| units.kms) sys=bridge(verbose=False) sys.add_system(cluster, (center,), False) times=units.Myr([0.,0.2,0.4,0.6,0.8,1.0,1.2,1.4]) f=pyplot.figure(figsize=(8,16)) for i,t in enumerate(times): sys.evolve_model(t,timestep=timestep) x=sys.particles.x.value_in(units.parsec) y=sys.particles.y.value_in(units.parsec) subplot=f.add_subplot(4,2,i+1) subplot.plot(x,y,'r .') subplot.plot([0.],[0.],'b +') subplot.set_xlim(-60,60) subplot.set_ylim(-60,60) subplot.set_title(t) if i==7: subplot.set_xlabel('parsec') cluster.stop() pyplot.show()
3,681
28.934959
86
py
amuse
amuse-main/examples/syllabus/stellar_massloss_response.py
""" Calculate the response of a star as a result of mass loss. """ from amuse.lab import * Second_Asymptotic_Giant_Branch = 6 | units.stellar_type set_printing_strategy("custom", preferred_units = [units.MSun, units.RSun, units.Myr], precision = 6, prefix = "", separator = " [", suffix = "]") def calculate_zeta(star, z, dmdt): stellar = MESA() stellar.parameters.metallicity = z stellar.particles.add_particles(star) stellar.commit_particles() rold = star.radius star.mass_change = dmdt dm = 0.01*star.mass star.time_step = dm/dmdt stellar.particles.evolve_one_step() rnew = stellar.particles[0].radius dlnr = (rnew-rold)/rold dlnm = (stellar.particles[0].mass-star.mass)/star.mass zeta = dlnr/dlnm stellar.stop() return zeta def main(Mstar, z, dmdt): stellar = MESA() stellar.parameters.metallicity = z bodies = Particles(mass=Mstar) stellar.particles.add_particles(bodies) channel_to_framework = stellar.particles.new_channel_to(bodies) copy_argument = ["age", "mass", "radius", "stellar_type"] while stellar.particles[0].stellar_type<Second_Asymptotic_Giant_Branch: stellar.particles.evolve_one_step() channel_to_framework.copy_attributes(copy_argument) star = stellar.particles.copy() zeta = calculate_zeta(star, z, dmdt) print("Zeta=", zeta[0], bodies[0].age, bodies[0].mass, bodies[0].radius, dmdt, bodies[0].stellar_type) stellar.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mstar", type="float",default = 1.|units.MSun, help="stellar mass [%default]") result.add_option("--dmdt", unit=units.MSun/units.yr, dest="dmdt", type="float", default = -0.01|(units.MSun/units.yr), help="dmdt [%default]") result.add_option("-z", dest="z", type="float", default = 0.02, help="metalicity [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,176
36.534483
147
py
amuse
amuse-main/examples/syllabus/hydro_simple.py
""" Simple routine for running a hydrodynamics solver """ from __future__ import print_function from amuse.lab import * def main(N=100, Mtot=1|units.MSun, Rvir=1|units.RSun, t_end=1|units.day, n_steps=6): converter=nbody_system.nbody_to_si(Mtot, Rvir) bodies = new_plummer_gas_model(N, convert_nbody=converter) hydro = Gadget2(converter) hydro.gas_particles.add_particles(bodies) Etot_init = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy hydro_to_framework = hydro.gas_particles.new_channel_to(bodies) write_set_to_file(bodies.savepoint(0.0 | t_end.unit), "hydro.hdf5", "hdf5",append_to_file=False) time = 0.0*t_end dt = t_end/float(n_steps) while time < t_end-dt/2: time += dt hydro.evolve_model(time) hydro_to_framework.copy() write_set_to_file(bodies.savepoint(time), "hydro.hdf5", "hdf5") Ekin = hydro.kinetic_energy Epot = hydro.potential_energy Eth = hydro.thermal_energy Etot = Ekin + Epot + Eth print("T=", hydro.get_time(), "M=", hydro.gas_particles.mass.sum(), end=' ') print("E= ", Etot, "Q= ", (Ekin+Eth)/Epot, "dE=", (Etot_init-Etot)/Etot) hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [%default]") result.add_option("-n", dest="n_steps", type="int",default = 6, help="number of steps [10]") result.add_option("-t", unit=units.Myr, dest="t_end", type="float", default = 1|units.day, help="end time of the simulation [%default]") result.add_option("-M", unit=units.MSun, dest="Mtot", type="float", default = 1|units.MSun, help="Mass of molcular cloud [%default]") result.add_option("-R", unit=units.RSun, dest="Rvir", type="float", default = 1|units.RSun, help="Radius of cloud [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,260
38.666667
100
py
amuse
amuse-main/examples/syllabus/merge_two_stars_sph.py
""" Initialize two stars to a ertain age and merge them using MMAMS """ import sys import numpy from amuse.lab import * from amuse.plot import plot, xlabel, ylabel from matplotlib import pyplot from orbital_elements_to_Cartesian import Orbital_elements_to_pos_vel from amuse.ext.sph_to_star import convert_SPH_to_stellar_model def convert_star_to_hydro_model(M, t_end): return sph_particles def plot_density_profile(radius, rho): plot(radius.in_(units.RSun), rho) pyplot.xlabel("$R$ [$R_\odot$]") pyplot.ylabel("density [$g/cm^3$]") # pyplot.semilogy() # pyplot.show() def merge_two_stars_sph(Mprim, Msec, t_coll): star = Particle(mass=Mprim) stellar_evolution = EVtwin() EVTwin_star = stellar_evolution.particles.add_particle(star) stellar_evolution.evolve_model(t_coll) print("star=", EVTwin_star) EVTwin_radius = EVTwin_star.get_radius_profile() EVTwin_rho = EVTwin_star.get_density_profile() N_sph = 100*Mprim.value_in(units.MSun) primary_star = convert_stellar_model_to_SPH(EVTwin_star, N_sph).gas_particles stellar_evolution.stop() converter=nbody_system.nbody_to_si(Mprim, 1.0|units.AU) hydro = Gadget2(converter) hydro.gas_particles.add_particles(primary_star) channel = hydro.gas_particles.new_channel_to(primary_star) hydro.evolve_model(1.0|units.s) channel.copy() hydro.stop() pyplot.scatter(primary_star.x.value_in(units.AU), primary_star.y.value_in(units.AU)) pyplot.show() new_stellar_model = convert_SPH_to_stellar_model(primary_star) stellar_evolution = MESA(redirection="none") stellar_evolution.commit_parameters() stellar_evolution.new_particle_from_model(new_stellar_model, t_coll) MESA_star = stellar_evolution.particles[0] print("star=", MESA_star) MESA_radius = MESA_star.get_radius_profile() MESA_rho = MESA_star.get_density_profile() stellar_evolution.stop() plot_density_profile(MESA_radius, MESA_rho) plot_density_profile(EVTwin_radius, EVTwin_rho) pyplot.semilogy() pyplot.show() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-M", unit=units.MSun, dest="Mprim", type="float",default = 10|units.MSun, help="Mass of the primary star [%default] MSun") result.add_option("-m", unit=units.MSun, dest="Msec", type="float",default = 1|units.MSun, help="Mass of the secondary star [%default] MSun") result.add_option("-t", unit=units.Myr, dest="t_coll", type="float", default = 0.01|units.Myr, help="end time of the simulation [%default] Myr") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() merge_two_stars_sph(**o.__dict__)
2,923
34.658537
88
py
amuse
amuse-main/examples/syllabus/gravity_hydro.py
""" example code for bridging a gravity solver with a hydrodynamics solver """ import numpy from amuse.lab import * from amuse.couple import bridge def get_kepler_elements(model_time, bh, star, converter): kep = Kepler(converter) kep.initialize_code() pos = bh.position - star.position vel = bh.velocity - star.velocity kep.initialize_from_dyn(bh.mass + star.mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a,e = kep.get_elements() kep.stop() return a, e def gravity_hydro_bridge(a, ecc, t_end, n_steps, Rgas, Mgas, Ngas): stars = Particles(2) stars.mass = [3.2, 3.1] | units.MSun Porb = 2*numpy.pi*(a**3/(constants.G*stars.mass.sum())).sqrt() stars[0].position = (0,0,0) | units.AU stars[0].velocity = (0,0,0) | units.kms vc = (constants.G*stars.mass.sum()/(a*(1+ecc))).sqrt() vc *= numpy.sqrt((1-ecc)/(1+ecc)) stars[1].position = (a.value_in(units.AU),0,0) | units.AU stars[1].velocity = (0,vc.value_in(units.kms),0) | units.kms stars.move_to_center() converter=nbody_system.nbody_to_si(stars.mass.sum(), a) gravity = ph4(converter, redirection="none") gravity.particles.add_particles(stars) gravity.parameters.epsilon_squared = (10|units.RSun)**2 Ed0_tot = gravity.kinetic_energy + gravity.potential_energy channel_from_gravity = gravity.particles.new_channel_to(stars) channel_from_to_gravity = stars.new_channel_to(gravity.particles) dt = t_end/float(n_steps) converter=nbody_system.nbody_to_si(1.0|units.MSun, Rgas) ism = new_plummer_gas_model(Ngas, convert_nbody=converter) ism.move_to_center() ism = ism.select(lambda r: r.length()<2*a,["position"]) hydro = Fi(converter, redirection="none") hydro.parameters.timestep = dt/8. hydro.parameters.epsilon_squared = (10|units.RSun)**2 hydro.gas_particles.add_particles(ism) Eh0_tot = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy hydro.parameters.periodic_box_size = 10*Rgas channel_from_hydro = hydro.gas_particles.new_channel_to(ism) channel_from_to_hydro = ism.new_channel_to(hydro.gas_particles) model_time = 0 | units.Myr filename = "gravhydro.hdf5" write_set_to_file(stars.savepoint(model_time), filename, 'hdf5') write_set_to_file(ism, filename, 'hdf5') gravhydro = bridge.Bridge(use_threading=False) gravhydro.add_system(gravity, (hydro,) ) gravhydro.add_system(hydro, (gravity,) ) gravhydro.timestep = min(dt, 2*hydro.parameters.timestep) while model_time < t_end: model_time += dt a, e = get_kepler_elements(gravity.model_time, stars[0], stars[1], converter) print("time=", model_time, a, e) gravhydro.evolve_model(model_time) Ed_tot = gravity.kinetic_energy + gravity.potential_energy Eh_tot = hydro.kinetic_energy + hydro.potential_energy + hydro.thermal_energy print("Energies:", Ed_tot/Ed0_tot, Eh_tot/Eh0_tot) channel_from_gravity.copy() channel_from_hydro.copy() write_set_to_file(stars.savepoint(model_time), filename, 'hdf5') write_set_to_file(ism, filename, 'hdf5') gravity.stop() hydro.stop() def new_option_parser(): from amuse.units.optparse import OptionParser result = OptionParser() result.add_option("-n", dest="n_steps", type="int", default = 1000, help="number of diagnostics time steps [%default]") result.add_option("-N", dest="Ngas", type="int", default = 1024, help="number of gas particles [%default]") result.add_option("-M", unit=units.MSun, dest="Mgas", type="float", default = 1|units.MSun, help="Mass of the gas [%default]") result.add_option("-R", unit=units.AU, dest="Rgas", type="float", default = 1|units.AU, help="Size of the gas distribution [%default]") result.add_option("-a", unit=units.AU, dest="a", type="float", default = 0.1|units.AU, help="initial orbital separation [%default]") result.add_option("-e", dest="ecc", type="float", default = 0.0, help="initial orbital eccentricity [%default]") result.add_option("-t", unit=units.yr, dest="t_end", type="float", default = 10|units.yr, help="end time of the simulation [%default]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() gravity_hydro_bridge(**o.__dict__)
4,597
41.183486
96
py
amuse
amuse-main/examples/syllabus/molecular_cloud_to_star_cluster.py
""" example of molecular cloud evolution with explictly split SPH and grav evolution Initial condition is a smooth spherical cloud with random velocities as in Bonnell et al. (2003) """ from __future__ import print_function import numpy from matplotlib import pyplot from amuse.lab import * from amuse.units import nbody_system from amuse.units import units from amuse.units import constants from amuse.community.fi.interface import Fi from amuse.ext.molecular_cloud import molecular_cloud from amuse.ext.evrard_test import body_centered_grid_unit_cube from amuse.ext.derived_grav_systems import copycat from amuse.ext.bridge import bridge from amuse.io import write_set_to_file from amuse.datamodel import ParticlesWithUnitsConverted from amuse.datamodel import Particles def make_map(sph,N=100,L=1): x,y=numpy.indices( ( N+1,N+1 )) x=L*(x.flatten()-N/2.)/N y=L*(y.flatten()-N/2.)/N z=x*0. vx=0.*x vy=0.*x vz=0.*x x=units.parsec(x) y=units.parsec(y) z=units.parsec(z) vx=units.kms(vx) vy=units.kms(vy) vz=units.kms(vz) rho,rhovx,rhovy,rhovz,rhoe=sph.get_hydro_state_at_point(x,y,z,vx,vy,vz) rho=rho.reshape((N+1,N+1)) return rho ''' def write_output(filename, parts, conv): output= file(filename, 'w') for i in range (0,len(parts)): #print i rho = conv.to_nbody(parts.rho[i]) mass= conv.to_nbody(parts.mass[i]) x= conv.to_nbody(parts.x[i]) y= conv.to_nbody(parts.y[i]) z= conv.to_nbody(parts.z[i]) vx= conv.to_nbody(parts.vx[i]) vy= conv.to_nbody(parts.vy[i]) vz= conv.to_nbody(parts.vz[i]) print>> output, rho.value_in(nbody_system.mass/nbody_system.length**3), mass.value_in(nbody_system.mass), x.value_in(nbody_system.length), y.value_in(nbody_system.length), z.value_in(nbody_system.length), vx.value_in(nbody_system.length/nbody_system.time), vy.value_in(nbody_system.length/nbody_system.time),vz.value_in(nbody_system.length/nbody_system.time) output.close() return 0 ''' def write_output(filename, parts, conv): particles_nbody = ParticlesWithUnitsConverted(parts, conv.as_converter_from_nbody_to_si()) #print particles_nbody write_set_to_file(particles_nbody, filename, "txt", attribute_names= ('rho', 'mass', 'x', 'y', 'z','vx', 'vy', 'vz')) return 0 def plot_stars(time, stars, i, L=6.): fig=pyplot.figure(figsize=(12,12)) m = 100.0*stars.mass/max(stars.mass) x = -stars.x.value_in(units.parsec) y = stars.y.value_in(units.parsec) pyplot.scatter(x, y, s=m) pyplot.title("Star cluster at"+time.as_string_in(units.Myr)) pyplot.xlim(-L/2., L/2.) pyplot.ylim(-L/2., L/2.) pyplot.xlabel("x [pc]") pyplot.ylabel("y [pc]") pyplot.savefig("SC_"+str(i)+".png") def plot_hydro(time, sph, i, L=10): fig=pyplot.figure(figsize=(12,12)) rho=make_map(sph,N=200,L=L) pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5) # subplot.set_title("GMC at zero age") pyplot.title("Molecular cloud at time="+time.as_string_in(units.Myr)) pyplot.xlabel("x [pc]") pyplot.ylabel("x [pc]") pyplot.title("GMC at time="+time.as_string_in(units.Myr)) pyplot.savefig("GMC_"+str(i)+".png") def plot_hydro_and_stars(time, sph, L=10): fig=pyplot.figure(figsize=(12,12)) rho=make_map(sph,N=200,L=L) pyplot.imshow(numpy.log10(1.e-5+rho.value_in(units.amu/units.cm**3)), extent=[-L/2,L/2,-L/2,L/2],vmin=1,vmax=5) # subplot.set_title("GMC at zero age") stars = get_stars_from_molecular_clous(sph.gas_particles) m = 100.0*stars.mass/max(stars.mass) x = -stars.x.value_in(units.parsec) y = stars.y.value_in(units.parsec) pyplot.scatter(x, y, s=m) pyplot.xlim(-L/2., L/2.) pyplot.ylim(-L/2., L/2.) pyplot.title("Molecular cloud at time="+time.as_string_in(units.Myr)) pyplot.xlabel("x [pc]") pyplot.ylabel("x [pc]") pyplot.title("GMC at time="+time.as_string_in(units.Myr)) pyplot.savefig("GMC_SC.png") def run_molecular_cloud(N=100, Mcloud=100. | units.MSun, Rcloud=1. | units.parsec): conv = nbody_system.nbody_to_si(Mcloud,Rcloud) rho_cloud = 3.*Mcloud/(4.*numpy.pi*Rcloud**3) print(rho_cloud) tff = 0.5427/numpy.sqrt(constants.G*rho_cloud) print("t_ff=", tff.value_in(units.Myr), 'Myr') dt = 5.e-2 | units.Myr tend=1.0 | units.Myr # tend=2.0 | units.Myr parts=molecular_cloud(targetN=N,convert_nbody=conv, base_grid=body_centered_grid_unit_cube, seed=100).result sph=Fi(conv, number_of_workers=3) sph.parameters.use_hydro_flag=True sph.parameters.radiation_flag=False sph.parameters.gamma=1 sph.parameters.isothermal_flag=True sph.parameters.integrate_entropy_flag=False sph.parameters.timestep=dt sph.parameters.verbosity = 0 sph.parameters.eps_is_h_flag = False# h_smooth is constant eps = 0.1 | units.parsec sph.parameters.gas_epsilon = eps sph.parameters.sph_h_const = eps parts.h_smooth= eps print('eps-h flag', sph.get_eps_is_h(), sph.get_consthsm()) expected_dt = 0.2*numpy.pi*numpy.power(eps, 1.5)/numpy.sqrt(constants.G*Mcloud/N) print("dt_exp=", expected_dt.value_in(units.Myr)) print("dt=", dt) print("eps=", sph.parameters.gas_epsilon.in_(units.parsec)) sph.gas_particles.add_particles(parts) #grav=copycat(Fi, sph, conv) #sys=bridge(verbose=False) #sys.add_system(sph,(grav,),False) channel_from_sph_to_parts= sph.gas_particles.new_channel_to(parts) channel_from_parts_to_sph= parts.new_channel_to(sph.gas_particles) i=0 L=6 E0 = 0.0 ttarget = 0.0 | units.Myr plot_hydro(ttarget, sph, i, L) while ttarget < tend: ttarget=float(i)*dt print(ttarget) sph.evolve_model(ttarget, timestep=dt) E = sph.gas_particles.kinetic_energy()+sph.gas_particles.potential_energy() + sph.gas_particles.thermal_energy() E_th = sph.gas_particles.thermal_energy() if i==0: E0 = E Eerr = (E-E0)/E0 print('energy=', E, 'energy_error=', Eerr, 'e_th=', E_th) channel_from_sph_to_parts.copy() """ filename = 'm400k_r10pc_e01_'+ str(i).zfill(2) + '.dat' print filename parts_sorted = parts.sorted_by_attribute('rho') write_output(filename, parts_sorted, conv) """ plot_hydro(ttarget, sph, i, L) i=i+1 plot_hydro_and_stars(ttarget, sph, L) sph.stop() return parts def make_stars(cluster_particle): sfe = 0.3 mmean = 1.0|units.MSun N = int(sfe*cluster_particle.mass/mmean) stars = Particles(0) print("N_cluster=", N) if N>0: masses = new_salpeter_mass_distribution(N, 0.3|units.MSun, min(100|units.MSun, cluster_particle.mass)) r = cluster_particle.h_smooth converter=nbody_system.nbody_to_si(masses.sum(),r) stars = new_plummer_model(N, convert_nbody=converter) stars.mass = masses stars.position += cluster_particle.position stars.velocity += cluster_particle.velocity return stars def get_stars_from_molecular_clous(parts): cutoff_density = 10000 | units.amu/units.cm**3 stars = Particles(0) for ip in parts: if ip.rho>cutoff_density: local_stars = make_stars(ip) stars.add_particles(local_stars) return stars def run_dynamics(bodies, t_end, nsteps): Mtot_init = bodies.mass.sum() stellar = SeBa() stellar.parameters.metallicity = 0.02 stellar.particles.add_particle(bodies) Rvir = 1|units.parsec converter=nbody_system.nbody_to_si(stars.mass.sum(),Rvir) gravity = ph4(converter) # gravity = bhtree(converter) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) channel_from_se_to_framework = stellar.particles.new_channel_to(bodies) channel_from_gd_to_framework = gravity.particles.new_channel_to(bodies) channel_from_framework_to_gd = bodies.new_channel_to(gravity.particles) channel_from_se_to_framework.copy_attributes(["mass","radius","luminosity"]) bodies.scale_to_standard(convert_nbody=converter) filename = "GMC_stars.hdf5" write_set_to_file(bodies.savepoint(0|units.Myr), filename, 'hdf5') Etot_init = gravity.kinetic_energy + gravity.potential_energy Etot_prev = Etot_init time = 0.0 | t_end.unit dt = t_end/nsteps i = 0 plot_stars(time, bodies, i) while time < t_end: time += dt gravity.evolve_model(time) Etot_prev_se = gravity.kinetic_energy + gravity.potential_energy stellar.evolve_model(time) channel_from_gd_to_framework.copy() channel_from_se_to_framework.copy_attributes(["mass","radius","luminosity", "temperature"]) channel_from_framework_to_gd.copy_attributes(["mass"]) write_set_to_file(bodies.savepoint(time), filename, 'hdf5') Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot dE = Etot_prev-Etot dE_se = Etot_prev_se-Etot Mtot = bodies.mass.sum() print("T=", time, end=' ') print("M=", Mtot, "(dM[SE]=", Mtot/Mtot_init, ")", end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot, end=' ') print("(dE[SE]=", dE_se/Etot, ")") Etot_init -= dE Etot_prev = Etot plot_stars(time, bodies, i) i+=1 gravity.stop() stellar.stop() plot_stars(time, bodies, i, L=20) if __name__ in ("__main__","__plot__"): # parts = run_molecular_cloud(4000, Mcloud=400000. | units.MSun, Rcloud=10. | units.parsec) parts = run_molecular_cloud(1000, Mcloud=10000. | units.MSun, Rcloud=3. | units.parsec) stars = get_stars_from_molecular_clous(parts) # write_set_to_file(stars, "stars.hdf5", 'hdf5') run_dynamics(stars, 10.0|units.Myr, 10)
10,096
32.104918
367
py
amuse
amuse-main/examples/syllabus/gravity_simple.py
""" Simple routine for running a gravity code """ from __future__ import print_function from amuse.lab import * def main(N=10, W0=7.0, t_end=10, dt=1, filename="nbody.hdf5"): t_end = t_end | nbody_system.time dt = dt | t_end.unit bodies = new_king_model(N, W0) bodies.scale_to_standard() bodies.radius = 0 | nbody_system.length gravity = ph4(number_of_workers=4) gravity.parameters.timestep_parameter = 0.01 gravity.particles.add_particles(bodies) channel_from_gravity_to_framework = gravity.particles.new_channel_to(bodies) write_set_to_file(bodies.savepoint(0.0 | t_end.unit), filename, "hdf5") Etot_prev = Etot_init = gravity.kinetic_energy + gravity.potential_energy time = 0.0 | t_end.unit while time < t_end: time += dt gravity.evolve_model(time) channel_from_gravity_to_framework.copy() write_set_to_file(bodies.savepoint(time), filename, "hdf5") Ekin = gravity.kinetic_energy Epot = gravity.potential_energy Etot = Ekin + Epot print("T=", time, "M=", bodies.mass.sum(), end=' ') print("E= ", Etot, "Q= ", Ekin/Epot, end=' ') print("dE=", (Etot_init-Etot)/Etot, "ddE=", (Etot_prev-Etot)/Etot) Etot_prev = Etot gravity.stop() def new_option_parser(): from optparse import OptionParser result = OptionParser() result.add_option("-f", dest="filename", default = "nbody.hdf5", help="output filename [nbody.hdf5]") result.add_option("-N", dest="N", type="int",default = 100, help="number of stars [10]") result.add_option("-t", dest="t_end", type="float", default = 1, help="end time of the simulation [1] N-body units") result.add_option("-d", dest="dt", type="float", default = 0.1, help="diagnostics time step [0.1] N-body units") result.add_option("-W", dest="W0", type="float", default = 7.0, help="Dimension-less depth of the potential (W0) [7.0]") return result if __name__ in ('__main__', '__plot__'): o, arguments = new_option_parser().parse_args() main(**o.__dict__)
2,192
38.160714
80
py
amuse
amuse-main/examples/validation/particles_and_gas_in_cluster.py
from amuse.couple import bridge from amuse.community.bhtree.interface import BHTree from amuse.community.hermite.interface import Hermite from amuse.community.fi.interface import Fi from amuse.community.octgrav.interface import Octgrav from amuse.community.gadget2.interface import Gadget2 from amuse.community.phigrape.interface import PhiGRAPE from amuse.ic import plummer from amuse.ic import gasplummer from amuse.units import units from amuse.units import constants from amuse.units import quantities from amuse.units import nbody_system from optparse import OptionParser import numpy # import time try: import pylab except ImportError: pylab = None class GasPlummerModelExternalField(object): """ skeleton grav code for use in bridge. must have get_gravity_at_point and get_potential_at_point """ def __init__( self, position=[0, 0, 0] | units.parsec, radius=1000. | units.parsec, total_mass=1.6e10 | units.MSun): self.radius = radius self.total_mass = total_mass self.gravity_constant = constants.G self.position = position self.radius_squared = (self.radius**2) def get_gravity_at_point(self, eps, x, y, z): dx = x - self.position.x dy = y - self.position.y dz = z - self.position.z radii_squared = dx**2 + dy**2 + dz**2 # radii = radii_squared**0.5 plummer_radii_squared = radii_squared + self.radius_squared plummer_radii_15 = plummer_radii_squared ** 1.5 fr = -self.gravity_constant*self.total_mass/plummer_radii_15 ax = fr*dx ay = fr*dy az = fr*dz return ax, ay, az def get_potential_at_point(self, eps, x, y, z): dx = x - self.position.x dy = y - self.position.y dz = z - self.position.z radii_squared = dx**2 + dy**2 + dz**2 # radii = radii_squared**0.5 plummer_radii = (radii_squared + self.radius_squared)**0.5 phi = self.gravity_constant*self.total_mass/plummer_radii return -phi * 2 def stop(self): pass @property def kinetic_energy(self): return quantities.zero @property def potential_energy(self): return quantities.zero @property def thermal_energy(self): return quantities.zero class AbstractStarAndGasPlummerCode(object): def __init__(self, nstars=10, ngas=-1, endtime=10, total_mass=1000, gas_fraction=0.9, rscale=1.0, star_smoothing_fraction=0.001, gas_smoothing_fraction=0.05, seed=-1, ntimesteps=10, must_do_plot=True ): if seed >= 0: numpy.random.seed(seed) if ngas < 0: ngas = nstars * 10 self.must_do_plot = must_do_plot self.line = None self.line2 = None self.ntimesteps = ntimesteps self.ngas = ngas self.nstars = nstars self.total_mass = total_mass | units.MSun self.gas_fraction = gas_fraction self.star_fraction = 1.0 - self.gas_fraction self.rscale = rscale | units.parsec self.star_epsilon = star_smoothing_fraction * self.rscale self.gas_epsilon = gas_smoothing_fraction * self.rscale self.star_mass = self.star_fraction * self.total_mass self.gas_mass = self.gas_fraction * self.total_mass self.converter = nbody_system.nbody_to_si(self.total_mass, self.rscale) self.endtime = self.converter.to_si(endtime | nbody_system.time) self.delta_t = self.endtime / self.ntimesteps def update_plot(self, time, code): time = self.converter.to_nbody(time).value_in(nbody_system.time), sum_energy = ( code.kinetic_energy + code.potential_energy + code.thermal_energy ) energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = ( self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) ) # kicke = self.converter.to_nbody(code.kick_energy).value_in(nbody_system.energy) if self.line is None: pylab.ion() pylab.subplot(1, 2, 1) self.line = pylab.plot([time], [energy])[0] pylab.xlim(0, self.converter.to_nbody( self.endtime).value_in(nbody_system.time)) pylab.ylim(energy * 0.8, energy * 1.2) pylab.subplot(1, 2, 2) self.line2 = pylab.plot([time], [coreradius])[0] # self.line2 = pylab.plot([time], [kicke])[0] pylab.xlim(0, self.converter.to_nbody( self.endtime).value_in(nbody_system.time)) pylab.ylim(0, 3) # pylab.ylim(-0.1, 0.1) else: xdata = self.line.get_xdata() ydata = self.line.get_ydata() xdata = numpy.concatenate((xdata, time)) ydata = numpy.concatenate((ydata, [energy])) self.line.set_xdata(xdata) self.line.set_ydata(ydata) xdata = self.line2.get_xdata() ydata = self.line2.get_ydata() xdata = numpy.concatenate((xdata, time)) # ydata = numpy.concatenate( (ydata, [kicke]) ) ydata = numpy.concatenate((ydata, [coreradius])) self.line2.set_xdata(xdata) self.line2.set_ydata(ydata) pylab.draw() def new_particles_cluster(self): particles = plummer.new_plummer_model( self.nstars, convert_nbody=self.converter) particles.radius = self.star_epsilon particles.mass = (1.0/self.nstars) * self.star_mass return particles def new_gas_cluster(self): particles = gasplummer.new_plummer_gas_model( self.ngas, convert_nbody=self.converter) particles.h_smooth = self.gas_epsilon particles.mass = (1.0/self.ngas) * self.gas_mass return particles def new_particles_cluster_as_gas(self): particles = plummer.new_plummer_model( self.ngas, convert_nbody=self.converter) particles.radius = self.gas_epsilon particles.mass = (1.0/self.ngas) * self.gas_mass return particles def stop(self): pass def evolve_model(self): if self.must_do_plot: self.update_plot(time=0 * self.delta_t, code=self.code) for time in self.delta_t * range(1, self.ntimesteps+1): self.code.evolve_model(time) print self.converter.to_nbody(self.code.time) if self.must_do_plot: self.update_plot(time=self.code.time, code=self.code) class BridgeStarAndGasPlummerCode(AbstractStarAndGasPlummerCode): def __init__(self, nstars=10, ngas=-1, endtime=10, total_mass=1000, gas_fraction=0.9, rscale=1.0, star_code='hermite', gas_code='field', star_smoothing_fraction=0.001, gas_smoothing_fraction=0.05, seed=-1, ntimesteps=10, interaction_timestep=0.01, must_do_plot=True, gas_to_star_interaction_code='none', star_to_gas_interaction_code='none', **ignored_options ): AbstractStarAndGasPlummerCode.__init__( self, nstars, ngas, endtime, total_mass, gas_fraction, rscale, star_smoothing_fraction, gas_smoothing_fraction, seed, ntimesteps, must_do_plot ) self.interaction_timestep = self.converter.to_si( interaction_timestep | nbody_system.time) self.create_codes( gas_code, star_code, gas_to_star_interaction_code, star_to_gas_interaction_code, ) self.create_bridge() self.code = self.bridge_system time = 0 sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) print "Time :", time print "Energy :", energy print "Virial radius :", coreradius self.evolve_model() if must_do_plot: pylab.show() pylab.savefig( "{0}-{1}-{2}-{3}.png".format( star_code, gas_code, nstars, ngas ) ) time = self.converter.to_nbody( self.code.time).value_in(nbody_system.time) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) print "Time :", time print "Energy :", energy print "Virial radius :", coreradius self.stop() if must_do_plot: raw_input('Press enter...') def create_codes( self, gas_code, star_code, gas_to_star_interaction_code, star_to_gas_interaction_code): self.star_code = getattr(self, 'new_star_code_'+star_code)() self.gas_code = getattr(self, 'new_gas_code_'+gas_code)() self.gas_to_star_codes = getattr( self, 'new_gas_to_star_interaction_codes_'+gas_to_star_interaction_code )(self.gas_code) self.star_to_gas_codes = getattr( self, 'new_star_to_gas_interaction_codes_'+star_to_gas_interaction_code )(self.star_code) def create_bridge(self): bridge_code1 = bridge.GravityCodeInField( self.gas_code, self.star_to_gas_codes ) bridge_code2 = bridge.GravityCodeInField( self.star_code, self.gas_to_star_codes ) self.bridge_system = bridge.Bridge( timestep=self.interaction_timestep, use_threading=False ) self.bridge_system.add_code(bridge_code2) self.bridge_system.add_code(bridge_code1) def stop(self): self.star_code.stop() self.gas_code.stop() def new_gas_to_star_interaction_codes_self(self, gas_code): return [gas_code] def new_star_to_gas_interaction_codes_self(self, star_code): return [star_code] def new_gas_to_star_interaction_codes_none(self, gas_code): return [] def new_star_to_gas_interaction_codes_none(self, gas_code): return [] def new_gas_to_star_interaction_codes_octgrav(self, gas_code): def new_octgrav(): result = Octgrav(self.converter) result.parameters.epsilon_squared = self.gas_epsilon ** 2 return result return [bridge.CalculateFieldForCodes(new_octgrav, [gas_code])] def new_gas_to_star_interaction_codes_bhtree(self, gas_code): def new_bhtree(): result = BHTree(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 return result return [bridge.CalculateFieldForCodes(new_bhtree, [gas_code])]\ def new_gas_code_fi(self): result = Fi(self.converter) result.parameters.self_gravity_flag = True result.parameters.use_hydro_flag = True result.parameters.radiation_flag = False result.parameters.periodic_box_size = 500 | units.parsec result.parameters.timestep = 0.125 * self.interaction_timestep # result.parameters.adaptive_smoothing_flag = True # result.parameters.epsilon_squared = self.gas_epsilon ** 2 # result.parameters.eps_is_h_flag = False result.parameters.integrate_entropy_flag = False # result.parameters.self_gravity_flag = False result.gas_particles.add_particles(self.new_gas_cluster()) result.commit_particles() return result def new_star_code_fi(self): result = Fi(self.converter) result.parameters.self_gravity_flag = True result.parameters.use_hydro_flag = False result.parameters.radiation_flag = False result.parameters.periodic_box_size = 500 | units.parsec result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_gas_code_gadget(self): result = Gadget2(self.converter) result.gas_particles.add_particles(self.new_gas_cluster()) result.commit_particles() return result def new_gas_code_field(self): result = GasPlummerModelExternalField( radius=self.rscale, total_mass=self.gas_mass ) return result def new_gas_code_hermite(self): result = Hermite(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster_as_gas()) result.commit_particles() return result def new_star_code_hermite(self): result = Hermite(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_phigrape(self): result = PhiGRAPE(self.converter, mode="gpu") result.parameters.initialize_gpu_once = 1 result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_bhtree(self): result = BHTree(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_octgrav(self): result = Octgrav(self.converter) result.parameters.epsilon_squared = self.star_epsilon ** 2 result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_gas_code_bhtree(self): result = BHTree(self.converter) result.parameters.epsilon_squared = self.gas_epsilon ** 2 result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster_as_gas()) result.commit_particles() return result class AllInOneStarAndGasPlummerCode(AbstractStarAndGasPlummerCode): def __init__(self, nstars=10, ngas=-1, endtime=10, total_mass=1000, gas_fraction=0.9, rscale=1.0, sph_code='fi', star_smoothing_fraction=0.001, gas_smoothing_fraction=0.05, seed=-1, ntimesteps=10, must_do_plot=True, interaction_timestep=0.01, **ignored_options ): AbstractStarAndGasPlummerCode.__init__( self, nstars, ngas, endtime, total_mass, gas_fraction, rscale, star_smoothing_fraction, gas_smoothing_fraction, seed, ntimesteps, must_do_plot ) self.interaction_timestep = self.converter.to_si( interaction_timestep | nbody_system.time) self.create_code(sph_code) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = self.code.dm_particles.virial_radius().value_in( self.rscale.to_unit()) print "Time:", 0 print "Energy:", energy print "Virial radius:", coreradius self.evolve_model() if must_do_plot: pylab.show() pylab.savefig( "{0}-{1}-{2}.png".format( sph_code, nstars, ngas ) ) time = self.converter.to_nbody( self.code.model_time).value_in(nbody_system.time) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy + self.code.thermal_energy energy = self.converter.to_nbody( sum_energy).value_in(nbody_system.energy) coreradius = self.code.dm_particles.virial_radius().value_in( self.rscale.to_unit()) print "Time:", time print "Energy:", energy print "Virial radius:", coreradius self.stop() if must_do_plot: raw_input('Press enter...') def evolve_model(self): if self.must_do_plot: self.update_plot(time=0 * self.delta_t, code=self.code) for time in self.delta_t * range(1, self.ntimesteps+1): self.code.evolve_model(time) print self.converter.to_nbody(self.code.model_time) if self.must_do_plot: self.update_plot(time=self.code.time, code=self.code) def create_code(self, name): self.code = getattr(self, 'new_sph_code_'+name)() def stop(self): self.code.stop() def new_sph_code_fi(self): result = Fi(self.converter) result.parameters.self_gravity_flag = True result.parameters.use_hydro_flag = True result.parameters.radiation_flag = False result.parameters.periodic_box_size = 500 | units.parsec result.parameters.timestep = 0.125 * self.interaction_timestep # result.parameters.adaptive_smoothing_flag = True # result.parameters.epsilon_squared = self.gas_epsilon ** 2 # result.parameters.eps_is_h_flag = False result.parameters.integrate_entropy_flag = False result.dm_particles.add_particles(self.new_particles_cluster()) result.gas_particles.add_particles(self.new_gas_cluster()) result.commit_particles() return result def new_sph_code_gadget(self): result = Gadget2(self.converter) result.dm_particles.add_particles(self.new_particles_cluster()) result.gas_particles.add_particles(self.new_gas_cluster()) result.commit_particles() return result def new_option_parser(): result = OptionParser() result.add_option( "-n", "--nstar", default=10, dest="nstars", help="number of star particles", type="int" ) result.add_option( "-g", "--ngas", default=-1, dest="ngas", help="number of gas particles (if -1, 10 times the number of stars)", type="int" ) result.add_option( "--gas-code", default="field", dest="gas_code", help="the code modelling the gas ('fi', 'gadget', 'field')", type="string" ) result.add_option( "--star-code", default="hermite", dest="star_code", help="the code modelling the particles ('hermite', 'bhtree', 'octgrav', 'phigrape')", type="string" ) result.add_option( "--sph-code", default="fi", dest="sph_code", help="the code modelling the particles and the gas simultaniously", type="string" ) result.add_option( "--gas-star-code", default="self", dest="gas_to_star_interaction_code", help="the code calculating the gravity field of the gas code for the star code (default is self, gas code will calculate field for star code)", type="string" ) result.add_option( "--star-gas-code", default="self", dest="star_to_gas_interaction_code", help="the code calculating the gravity field of the star code for the gas code (default is self, star code will calculate field for gas code)", type="string" ) result.add_option( "-m", "--total-mass", default=1000.0, dest="total_mass", help="the total mass in solar masses", type="float" ) result.add_option( "--gas-fraction", default=0.9, dest="gas_fraction", help="the gas fraction between 0.0 and 1.0 (default 0.9)", type="float" ) result.add_option( "-r", "--rscale", default=1.0, dest="rscale", help="length scale of the problem in parsec (default 1) ", type="float" ) result.add_option( "--star_smoothing_fraction", default=0.001, dest="star_smoothing_fraction", help="smoothing length of the stars as a fraction of the length scale", type="float" ) result.add_option( "--gas_smoothing_fraction", default=0.05, dest="gas_smoothing_fraction", help="smoothing length of the gas particles as a fraction of the length scale", type="float" ) result.add_option( "-s", "--seed", default=0, dest="seed", help="random number seed (-1, no seed)", type="int" ) result.add_option( "--interaction-timestep", default=0.01, dest="interaction_timestep", help="time between bridge interactions (0.01 nbody time)", type="float" ) result.add_option( "-t", "--end-time", default=1, dest="endtime", help="end time of the simulation (in nbody time, default 1)", type="float" ) result.add_option( "--ntimesteps", default=10, dest="ntimesteps", help="number of times to do reporting", type="int" ) result.add_option( "--noplot", dest="must_do_plot", default=True, help="do not show a plot and end as soon as possible", action="store_false" ) result.add_option( "--allinoone", dest="must_do_bridge", default=True, help="simulate the stars and gas with one sph code", action="store_false" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() if options.must_do_bridge: options = options.__dict__ BridgeStarAndGasPlummerCode(**options) else: options = options.__dict__ AllInOneStarAndGasPlummerCode(**options)
23,500
31.149111
151
py
amuse
amuse-main/examples/validation/particles_and_multiples.py
# from amuse.couple import bridge from amuse.community.bhtree.interface import BHTree from amuse.community.hermite.interface import Hermite from amuse.community.fi.interface import Fi from amuse.community.octgrav.interface import Octgrav # from amuse.community.gadget2.interface import Gadget2 from amuse.community.phigrape.interface import PhiGRAPE from amuse.community.ph4.interface import ph4 from amuse.community.smalln.interface import SmallN from amuse.ic import plummer # from amuse.ic import gasplummer from amuse.couple import multiples from amuse.units import ( units, nbody_system ) from optparse import OptionParser import numpy # import time try: import pylab except ImportError: pylab = None class MultiplesClusterCode(object): def __init__(self, nstars=10, endtime=10, total_mass=1000, rscale=1.0, interaction_radius=-1.0, star_code='hermite', star_smoothing_fraction=0.0, seed=-1, ntimesteps=10, must_do_plot=True, **ignored_options ): if seed >= 0: numpy.random.seed(seed) if interaction_radius < 0.0: self.interaction_radius = 0.01 | nbody_system.length else: self.interaction_radius = interaction_radius | nbody_system.length self.must_do_plot = must_do_plot self.line = None self.line2 = None self.ntimesteps = ntimesteps self.nstars = nstars self.total_mass = total_mass | nbody_system.mass self.rscale = rscale | nbody_system.length self.star_epsilon = star_smoothing_fraction * self.rscale self.star_mass = self.total_mass self.endtime = endtime | nbody_system.time self.delta_t = self.endtime / self.ntimesteps self.create_code(star_code) self.code = multiples.Multiples(self.star_code, self.new_smalln) time = 0 sum_energy = self.code.kinetic_energy + self.code.potential_energy energy0 = sum_energy.value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) print "Time :", time print "Energy :", energy0 print "Virial radius :", coreradius self.evolve_model() if must_do_plot: pylab.show() pylab.savefig( "multiples-{0}-{1}.png".format( star_code, nstars ) ) time = self.code.model_time.value_in(nbody_system.time) sum_energy = self.code.kinetic_energy + \ self.code.potential_energy - self.code.multiples_energy_correction energy = sum_energy.value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) print "Time :", time print "Energy :", energy print "Delta E :", (energy-energy0)/energy0 print "Virial radius :", coreradius self.stop() if must_do_plot: raw_input('Press enter...') def update_plot(self, time, code): time = time.value_in(nbody_system.time), sum_energy = code.kinetic_energy + code.potential_energy - \ self.code.multiples_energy_correction energy = sum_energy.value_in(nbody_system.energy) coreradius = self.star_code.particles.virial_radius().value_in( self.rscale.to_unit()) if self.line is None: pylab.ion() pylab.subplot(1, 2, 1) self.line = pylab.plot([time], [energy])[0] pylab.xlim(0, self.endtime.value_in(nbody_system.time)) pylab.ylim(energy * 0.8, energy * 1.2) pylab.subplot(1, 2, 2) self.line2 = pylab.plot([time], [coreradius])[0] # self.line2 = pylab.plot([time], [kicke])[0] pylab.xlim(0, self.endtime.value_in(nbody_system.time)) pylab.ylim(0, 3) # pylab.ylim(-0.1, 0.1) else: xdata = self.line.get_xdata() ydata = self.line.get_ydata() xdata = numpy.concatenate((xdata, time)) ydata = numpy.concatenate((ydata, [energy])) self.line.set_xdata(xdata) self.line.set_ydata(ydata) xdata = self.line2.get_xdata() ydata = self.line2.get_ydata() xdata = numpy.concatenate((xdata, time)) # ydata = numpy.concatenate( (ydata, [kicke]) ) ydata = numpy.concatenate((ydata, [coreradius])) self.line2.set_xdata(xdata) self.line2.set_ydata(ydata) pylab.draw() def new_particles_cluster(self): particles = plummer.new_plummer_model(self.nstars) particles.scale_to_standard() particles.radius = self.interaction_radius return particles def evolve_model(self): if self.must_do_plot: self.update_plot(time=0 * self.delta_t, code=self.code) for time in self.delta_t * range(1, self.ntimesteps+1): self.code.evolve_model(time) print self.code.model_time if self.must_do_plot: self.update_plot(time=self.code.model_time, code=self.code) self.code.print_trees_summary() def create_code(self, star_code): self.star_code = getattr(self, 'new_star_code_'+star_code)() def stop(self): self.star_code.stop() def new_smalln(self): result = SmallN() result.parameters.timestep_parameter = 0.1 result.parameters.cm_index = 50000 return result def new_star_code_fi(self): result = Fi() result.parameters.self_gravity_flag = True result.parameters.use_hydro_flag = False result.parameters.radiation_flag = False result.parameters.periodic_box_size = 500 | units.parsec result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_hermite(self): result = Hermite() result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_phigrape(self): result = PhiGRAPE(mode="gpu") result.parameters.initialize_gpu_once = 1 result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_ph4(self): result = ph4(mode="gpu") result.parameters.epsilon_squared = self.star_epsilon ** 2 result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_bhtree(self): result = BHTree() result.parameters.epsilon_squared = self.star_epsilon ** 2 result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_star_code_octgrav(self): result = Octgrav() result.parameters.epsilon_squared = self.star_epsilon ** 2 result.parameters.timestep = 0.125 * self.interaction_timestep result.particles.add_particles(self.new_particles_cluster()) result.commit_particles() return result def new_option_parser(): result = OptionParser() result.add_option( "-n", "--nstar", default=10, dest="nstars", help="number of star particles", type="int" ) result.add_option( "--star-code", default="hermite", dest="star_code", help="the code modelling the particles ('hermite', 'bhtree', 'octgrav', 'phigrape', 'ph4')", type="string" ) result.add_option( "-m", "--total-mass", default=1, dest="total_mass", help="the total mass in nbody units", type="float" ) result.add_option( "-r", "--rscale", default=1.0, dest="rscale", help="length scale of the problem in nbody units (default 1) ", type="float" ) result.add_option( "--star_smoothing_fraction", default=0.0, dest="star_smoothing_fraction", help="smoothing length of the stars as a fraction of the length scale (default 0)", type="float" ) result.add_option( "-s", "--seed", default=0, dest="seed", help="random number seed (-1, no seed)", type="int" ) result.add_option( "--interaction-radius", default=0.01, dest="interaction_radius", help="radius of all stars, collision detection will depend on this", type="float" ) result.add_option( "-t", "--end-time", default=1, dest="endtime", help="end time of the simulation (in nbody time, default 1)", type="float" ) result.add_option( "--ntimesteps", default=10, dest="ntimesteps", help="number of times to do reporting", type="int" ) result.add_option( "--noplot", dest="must_do_plot", default=True, help="do not show a plot and end as soon as possible", action="store_false" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() options = options.__dict__ MultiplesClusterCode(**options)
9,951
31
100
py
amuse
amuse-main/examples/validation/__init__.py
0
0
0
py
amuse
amuse-main/src/amuse/config.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ configuration from config.mk """ import os import warnings def parse_configmk(filename): configfile = open(filename, "r") lines = configfile.readlines() configfile.close() cfgvars = dict() if "amuse configuration" not in lines[0]: raise Exception( "file: {0} is not an amuse configuration file".format(filename) ) for line in lines: if "=" in line: var, value = line.split("=", 1) if value.startswith("@") and value.endswith("@"): warnings.warn( "possible configuration error/ unconfigured variable in" " {0}".format(filename) ) cfgvars[var] = value.strip() return cfgvars try: configmk = parse_configmk("config.mk") except IOError: from .support import get_amuse_root_dir configmk = parse_configmk( os.path.join(get_amuse_root_dir(), "config.mk") ) class interpreters(): python = configmk["PYTHON"] class compilers(): cxx = configmk["CXX"] cc = configmk["CC"] fc = configmk["FC"] cxx_flags = configmk["CXXFLAGS"] cc_flags = configmk["CFLAGS"] fc_flags = configmk["FCFLAGS"] ld_flags = configmk["LDFLAGS"] found_fftw = configmk["FOUND_FFTW"] fftw_flags = configmk["FFTW_FLAGS"] fftw_libs = configmk["FFTW_LIBS"] found_gsl = configmk["FOUND_GSL"] gsl_flags = configmk["GSL_FLAGS"] gsl_libs = configmk["GSL_LIBS"] gfortran_version = configmk["GFORTRAN_VERSION"] ifort_version = configmk["IFORT_VERSION"] fc_iso_c_bindings = configmk["FC_ISO_C_AVAILABLE"] == 'yes' cython = configmk["CYTHON"] pythondev_cflags = configmk["PYTHONDEV_CFLAGS"] pythondev_ldflags = configmk["PYTHONDEV_LDFLAGS"] class mpi(): is_enabled = configmk["MPI_ENABLED"] == 'yes' mpicxx = configmk["MPICXX"] mpicc = configmk["MPICC"] mpif95 = configmk["MPIFC"] mpifc = configmk["MPIFC"] mpif90 = configmk["MPIFC"] mpiexec = configmk["MPIEXEC"] mpi_cflags = configmk["MPI_CFLAGS"] mpi_cxxflags = configmk["MPI_CXXFLAGS"] mpi_fcflags = configmk["MPI_FCFLAGS"] mpi_clibs = configmk["MPI_CLIBS"] mpi_cxxlibs = configmk["MPI_CXXLIBS"] mpi_fclibs = configmk["MPI_FCLIBS"] class java(): is_enabled = configmk["JAVA_ENABLED"] == 'yes' java = configmk["JAVA"] javac = configmk["JAVAC"] jar = configmk["JAR"] version = configmk["JAVA_VERSION"] class cuda(): is_enabled = configmk["CUDA_ENABLED"] == 'yes' compiler = configmk["NVCC"] compiler_flags = configmk["NVCC_FLAGS"] toolkit_path = configmk["CUDA_TK"] sdk_path = "/TOBEFIXED" cuda_libs = configmk["CUDA_LIBS"] sapporo_version = configmk["SAPPORO_VERSION"] class openmp(): is_enabled = configmk["OPENMP_ENABLED"] == 'yes' fcflags = configmk["OPENMP_FCFLAGS"] cflags = configmk["OPENMP_CFLAGS"]
2,968
25.747748
76
py
amuse
amuse-main/src/amuse/__init__.py
""" The Astrophysical Multipurpose Software Environment The aim of AMUSE is to provide a software framework, in which existing codes for dynamics, stellar evolution, hydrodynamics and radiative transfer can easily be coupled, in order to perform state-of-the-art simulations of a wide range of different astrophysical phenomena. It contains several packages, most notably: units - AMUSE uses quantities, i.e. a number (or array) with a unit attached, instead of just numbers (vital when coupling different codes!) datamodel - defines particles and grids, on which data (quantities) can be stored ic - a collection of routines to generate initial conditions io - how to read and write data in several file formats community - a variety of existing codes of different physical domains, each with a uniform interface to enable coupling Help is available for each of these packages, e.g.: > python >>> import amuse.ic >>> help(amuse.ic) # doctest: +ELLIPSIS Help on package amuse.ic in amuse: ... or (directly from the terminal): > pydoc amuse.ic """ import sys import os import numpy _AMUSE_ROOT = os.path.abspath(os.path.dirname(__file__)) def numpy_fix(): try: numpy.set_printoptions(legacy='1.13') except TypeError: pass numpy_fix() class NoConfig(object): def __init__(self, message): self._message=message def __getattr__(self, attr): raise AttributeError(self._message) try: from . import config except Exception as ex: message="Configuration not read in - or configuration invalid, exception:\n"+str(ex) config=NoConfig(message) # always report AMUSE reference information try: from amuse.support.literature import TrackLiteratureReferences TrackLiteratureReferences.default() except: pass def get_data(path): return os.path.join(_AMUSE_ROOT, 'data', path)
1,903
28.292308
88
py
amuse
amuse-main/src/amuse/lab.py
""" This is the public interface to the AMUSE *Astrophysical Multipurpose Software Environment* framework. """ from amuse.support.core import late from amuse.datamodel import ( particle_attributes, Particle, Particles, ParticlesSuperset, Grid, ) from amuse.io import ( write_set_to_file, read_set_from_file, get_options_for_format, ReportTable, ) from amuse.units import ( units, core, si, constants, nbody_system, generic_unit_system, generic_unit_converter, ) from amuse.units import generic_unit_system as generic from amuse.units import nbody_system as nbody from amuse.units.quantities import ( zero, ScalarQuantity, VectorQuantity, AdaptingVectorQuantity, new_quantity, ) from amuse.support.console import ( set_printing_strategy, get_current_printing_strategy, ) from amuse.ic.plummer import new_plummer_model, new_plummer_sphere from amuse.ic.salpeter import ( new_salpeter_mass_distribution, new_salpeter_mass_distribution_nbody, new_powerlaw_mass_distribution, new_powerlaw_mass_distribution_nbody, ) from amuse.ic.brokenimf import ( new_broken_power_law_mass_distribution, new_scalo_mass_distribution, new_miller_scalo_mass_distribution, new_kroupa_mass_distribution, ) from amuse.ic.flatimf import ( new_flat_mass_distribution, new_flat_mass_distribution_nbody, ) from amuse.ic.kingmodel import new_king_model from amuse.ic.gasplummer import new_plummer_gas_model from amuse.ext.molecular_cloud import new_ism_cube from amuse.ext.solarsystem import ( new_solar_system_for_mercury, new_solar_system, ) from amuse.ext.spherical_model import ( new_uniform_spherical_particle_distribution, new_spherical_particle_distribution ) try: from amuse.ext.halogen_model import new_halogen_model except ImportError: def new_halogen_model(): print( "Error - Halogen not installed. Install it with 'pip install " "amuse-halogen'." ) return -1 try: from amuse.ext.galactics_model import new_galactics_model except ImportError: def new_galactics_model(): print( "Error - Galactics not installed. Install it with 'pip install " "amuse-galactics'." ) return -1 try: from amuse.ext.star_to_sph import ( convert_stellar_model_to_SPH, pickle_stellar_model, ) except ImportError: def convert_stellar_model_to_SPH(): print( "Error - Gadget2 not installed. Install it with 'pip install " "amuse-gadget2'." ) return -1 def pickle_stellar_model(): print( "Error - Gadget2 not installed. Install it with 'pip install " "amuse-gadget2'." ) return -1 _community_codes = [ "BHTree", "Hermite", "PhiGRAPE", "Octgrav", "TwoBody", "Huayno", "ph4", "Bonsai", "Pikachu", "AarsethZare", "Adaptb", "Hacs64", "HiGPUs", "Kepler", "Mercury", "MI6", "Mikkola", "SmallN", "Rebound", "Brutus", "Fi", "Gadget2", "Athena", "Capreole", "MpiAmrVac", "SimpleX", "Mocassin", "SPHRay", "SSE", "BSE", "MOSSE", "MOBSE", "SeBa", "EVtwin", "MESA", "MMAMS", "Hop", ] def _placeholder(name): class _placeholder(object): def __init__(self, *arg, **kwargs): raise Exception( "failed import, code {0} not available, maybe it needs to be " "(pip) installed?".format(name)) return _placeholder for _name in _community_codes: _interfacename = _name+"Interface" _packagename = _name.lower() _standardisedname = _name.title() try: _interface = __import__( "amuse.community."+_packagename+".interface", fromlist=[_name, _interfacename, _standardisedname], ) locals()[_name] = getattr(_interface, _name) locals()[_interfacename] = getattr(_interface, _interfacename) locals()[_standardisedname] = getattr(_interface, _standardisedname) except ImportError: locals()[_name] = _placeholder(_packagename) locals()[_interfacename] = _placeholder(_packagename) locals()[_standardisedname] = _placeholder(_packagename) def vector(value=[], unit=None): if unit is None: if isinstance(value, core.unit): return VectorQuantity([], unit=value) elif isinstance(value, ScalarQuantity): return value.as_vector_with_length(1) else: result = AdaptingVectorQuantity() result.extend(value) return result else: if isinstance(value, ScalarQuantity): return value.as_vector_with_length(1) else: return VectorQuantity(value, unit)
4,808
26.959302
79
py
amuse
amuse-main/src/amuse/codes.py
import sys _CODES = [ 'athena', 'capreole', 'cachedse', 'gadget2', 'mesa', 'octgrav', 'twobody', 'capreole', 'hermite0', 'mocassin', 'phiGRAPE', 'athena', 'evtwin', 'hop', 'seba', 'bhtree', 'evtwin2sse', 'interface', 'smallN', 'bse', 'fi', 'mercury', 'sse', ] __all__ = [] def _import_modules(): for x in _CODES: modulename = 'amuse.legacy.' + x + '.interface' try: __import__(modulename) globals()[x] = sys.modules[modulename] __all__.append(x) except ImportError as ex: modulename = 'amuse.legacy.' + x + '.' + x try: __import__(modulename) globals()[x] = sys.modules[modulename] __all__.append(x) except ImportError as ex: pass _import_modules()
915
26.757576
96
py
amuse
amuse-main/src/amuse/community/__init__.py
from amuse.community.interface.stopping_conditions import StoppingConditionInterface from amuse.community.interface.stopping_conditions import StoppingConditions from amuse.support.options import option from amuse.support.options import OptionalAttributes from amuse.units import units from amuse.units import nbody_system from amuse.units import generic_unit_system from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits from amuse.support import exceptions from amuse.support.interface import * from amuse.datamodel import parameters from amuse.datamodel import attributes from amuse.support.literature import LiteratureReferencesMixIn from amuse.rfi.core import CodeInterface from amuse.rfi.core import CodeWithDataDirectories from amuse.rfi.core import legacy_function,remote_function from amuse.rfi.core import LegacyFunctionSpecification from amuse.rfi.core import is_mpd_running import os from amuse.support import get_amuse_root_dir ERROR_CODE = MethodWithUnitsDefinition.ERROR_CODE NO_UNIT = MethodWithUnitsDefinition.NO_UNIT INDEX = MethodWithUnitsDefinition.INDEX LINK = MethodWithUnitsDefinition.LINK """ Existing, production codes Contains the source code of production codes and software to embed these codes into AMUSE """
1,277
30.95
89
py
amuse
amuse-main/src/amuse/community/octgrav/__init__.py
# -*- mode: python; coding: utf-8 -*- __author__ = 'Evghenii Gaburov (code), Derek Groen (interface)' __author_email__ = '<egaburov@science.uva.nl>,<djgroen@science.uva.nl>' __date__ = '2008-04-14 15:42:00 CEST' # Dummy file to indicate that this directory is a package. from .interface import Octgrav
318
34.444444
71
py
amuse
amuse-main/src/amuse/community/octgrav/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode class OctgravInterface( CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, GravityFieldInterface): """ .. [#] ADS:2010ProCS...1.1119G (Gaburov E., Bedorf J., Portegies Zwart S., 2010, Proc. C. Sc., 1, 1119: .. [#] ... "A gravitational tree code on graphics processing units: Implementation in CUDA" """ include_headers = ['interface.h', 'parameters.h', 'worker_code.h', 'local.h', 'stopcond.h'] def __init__(self, convert_nbody = None, **options): CodeInterface.__init__(self, name_of_the_worker="octgrav_worker", **options) """ self.parameters = parameters.Parameters(self.parameter_definitions, self) if convert_nbody is None: convert_nbody = nbody_system.nbody_to_si.get_default() self.convert_nbody = convert_nbody """ LiteratureReferencesMixIn.__init__(self) @legacy_function def get_theta_for_tree(): """ """ function = LegacyFunctionSpecification() function.addParameter('opening_angle', dtype='float64', direction=function.OUT, description = "opening_angle") function.result_type = 'int32' function.result_doc = """ 0 - OK xx -1 - ERROR xx """ return function @legacy_function def set_theta_for_tree(): """ """ function = LegacyFunctionSpecification() function.addParameter('opening_angle', dtype='float64', direction=function.IN, description = "opening_angle") function.result_type = 'int32' function.result_doc = """ 0 - OK xx -1 - ERROR xx """ return function @legacy_function def set_time_step(): """ Update timestep. """ function = LegacyFunctionSpecification() function.addParameter('time_step', dtype='float64', direction=function.IN, description = "timestep") function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found in the model and the information was set -1 - ERROR particle could not be found """ return function class Octgrav(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody = None, **options): legacy_interface = OctgravInterface(**options) self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def define_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.01 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "constant timestep for iteration", default_value = 0.01 | nbody_system.time ) handler.add_method_parameter( "get_theta_for_tree", "set_theta_for_tree", "opening_angle", "opening angle for building the tree between 0 and 1", default_value = 0.8 ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time to start the simulation at", default_value = 0.0 | nbody_system.time ) self.stopping_conditions.define_parameters(handler) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_step", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_theta_for_tree", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_theta_for_tree", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) # this should be checked! handler.add_method('EDIT', 'get_gravity_at_point') handler.add_method('EDIT', 'get_potential_at_point') self.stopping_conditions.define_state(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler)
5,783
28.814433
111
py
amuse
amuse-main/src/amuse/community/pikachu/__init__.py
from .interface import Pikachu
31
15
30
py
amuse
amuse-main/src/amuse/community/pikachu/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode class PikachuInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, GravityFieldInterface, CodeWithDataDirectories): """ Pikachu - a.k.a. P^3 Tree Hybrid N-body module, combining a tree (Barnes & Hut) to approximate long-range forces, with direct summation of the forces from neighbour particles. .. [#] ADS:2015ComAC...2....6I (Iwasawa, M., Portegies Zwart, S., Makino, J., *Computational Astrophysics and Cosmology*, **2**, 6 (2015): .. [#] ... "GPU-enabled particle-particle particle-tree scheme for simulating dense stellar cluster system") """ include_headers = ['worker_code.h', 'stopcond.h', 'interface.h'] MODE_NORMAL = 'normal' MODE_LARGE_N = 'large_n' def __init__(self, mode=MODE_NORMAL, **options): CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL: return 'pikachu_worker' elif mode == self.MODE_LARGE_N: return 'pikachu_worker_large_n' else: print("Warning: unknown mode: '{0}' - using default ('{1}').".format(mode, self.MODE_NORMAL)) return 'pikachu_worker' @option(type="string", sections=('data',)) def default_kernel_directory(self): """ The default directory containing the Sequoia kernels """ return os.path.join(self.amuse_root_directory, 'src', 'amuse', 'community', 'pikachu') @legacy_function def get_kernel_directory(): function = LegacyFunctionSpecification() function.addParameter('kernel_directory', dtype='string', direction=function.OUT, description = "Name of the Sequoia kernel directory") function.result_type = 'int32' return function @legacy_function def set_kernel_directory(): function = LegacyFunctionSpecification() function.addParameter('kernel_directory', dtype='string', direction=function.IN, description = "Name of the Sequoia kernel directory") function.result_type = 'int32' return function @legacy_function def get_eps2_fs_fs(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_fs_fs', dtype='float64', direction=function.OUT, description = "The current value of the smooting parameter, squared, for star-star interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_eps2_fs_fs(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_fs_fs', dtype='float64', direction=function.IN, description = "The new value of the smooting parameter, squared, for star-star interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_eps2_fs_bh(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_fs_bh', dtype='float64', direction=function.OUT, description = "The current value of the smooting parameter, squared, for star-blackhole interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_eps2_fs_bh(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_fs_bh', dtype='float64', direction=function.IN, description = "The new value of the smooting parameter, squared, for star-blackhole interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_eps2_bh_bh(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_bh_bh', dtype='float64', direction=function.OUT, description = "The current value of the smooting parameter, squared, for blackhole-blackhole interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_eps2_bh_bh(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared_bh_bh', dtype='float64', direction=function.IN, description = "The new value of the smooting parameter, squared, for blackhole-blackhole interactions.", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_eta_s(): function = LegacyFunctionSpecification() function.addParameter('eta_start', dtype='float64', direction=function.OUT, description = "The current value of the initial timestep parameter.") function.result_type = 'int32' return function @legacy_function def set_eta_s(): function = LegacyFunctionSpecification() function.addParameter('eta_start', dtype='float64', direction=function.IN, description = "The new value of the initial timestep parameter.") function.result_type = 'int32' return function @legacy_function def get_eta_fs(): function = LegacyFunctionSpecification() function.addParameter('eta_field_star', dtype='float64', direction=function.OUT, description = "The current value of the timestep parameter for field stars.") function.result_type = 'int32' return function @legacy_function def set_eta_fs(): function = LegacyFunctionSpecification() function.addParameter('eta_field_star', dtype='float64', direction=function.IN, description = "The new value of the timestep parameter for field stars.") function.result_type = 'int32' return function @legacy_function def get_eta_smbh(): function = LegacyFunctionSpecification() function.addParameter('eta_supermassive_black_hole', dtype='float64', direction=function.OUT, description = "The current value of the timestep parameter for black holes.") function.result_type = 'int32' return function @legacy_function def set_eta_smbh(): function = LegacyFunctionSpecification() function.addParameter('eta_supermassive_black_hole', dtype='float64', direction=function.IN, description = "The new value of the timestep parameter for black holes.") function.result_type = 'int32' return function @legacy_function def get_theta_for_tree(): function = LegacyFunctionSpecification() function.addParameter('opening_angle', dtype='float64', direction=function.OUT, description = "The opening angle, theta, for building the tree: between 0 and 1.") function.result_type = 'int32' return function @legacy_function def set_theta_for_tree(): function = LegacyFunctionSpecification() function.addParameter('opening_angle', dtype='float64', direction=function.IN, description = "The opening angle, theta, for building the tree: between 0 and 1.") function.result_type = 'int32' return function @legacy_function def get_calculate_quadrupole_moments(): function = LegacyFunctionSpecification() function.addParameter('calculate_quadrupole_moments', dtype='int32', direction=function.OUT, description = "Flag that specifies whether quadrupole moments are calculated for the tree") function.result_type = 'int32' return function @legacy_function def set_calculate_quadrupole_moments(): function = LegacyFunctionSpecification() function.addParameter('calculate_quadrupole_moments', dtype='int32', direction=function.IN, description = "Flag that specifies whether quadrupole moments are calculated for the tree") function.result_type = 'int32' return function @legacy_function def set_time_step(): function = LegacyFunctionSpecification() function.addParameter('time_step', dtype='float64', direction=function.IN, description = "The new value of the global timestep.", unit = nbody_system.time) function.result_type = 'int32' return function @legacy_function def get_search_factor(): function = LegacyFunctionSpecification() function.addParameter('search_factor', dtype='float64', direction=function.OUT, description = "The search factor, if positive, determines rsearch = rcut_out + search_factor * velocity_dispersion * timestep") function.result_type = 'int32' return function @legacy_function def set_search_factor(): function = LegacyFunctionSpecification() function.addParameter('opening_angle', dtype='float64', direction=function.IN, description = "The search factor, if positive, determines rsearch = rcut_out + search_factor * velocity_dispersion * timestep") function.result_type = 'int32' return function @legacy_function def get_vel_disp(): function = LegacyFunctionSpecification() function.addParameter('vel_disp', dtype='float64', direction=function.OUT, description = "The velocity dispersion assumed when calculating rsearch", unit = nbody_system.speed) function.result_type = 'int32' return function @legacy_function def set_vel_disp(): function = LegacyFunctionSpecification() function.addParameter('vel_disp', dtype='float64', direction=function.IN, description = "The velocity dispersion assumed when calculating rsearch", unit = nbody_system.speed) function.result_type = 'int32' return function @legacy_function def get_rcut_out_FS_FS(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_FS_FS', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rcut_out_FS_FS(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_FS_FS', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_rcut_out_FS_BH(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_FS_BH', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rcut_out_FS_BH(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_FS_BH', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_rcut_out_BH_BH(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_BH_BH', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rcut_out_BH_BH(): function = LegacyFunctionSpecification() function.addParameter('rcut_out_BH_BH', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_rsearch_FS_FS(): function = LegacyFunctionSpecification() function.addParameter('rsearch_FS_FS', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rsearch_FS_FS(): function = LegacyFunctionSpecification() function.addParameter('rsearch_FS_FS', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_rsearch_FS_BH(): function = LegacyFunctionSpecification() function.addParameter('rsearch_FS_BH', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rsearch_FS_BH(): function = LegacyFunctionSpecification() function.addParameter('rsearch_FS_BH', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_rsearch_BH_BH(): function = LegacyFunctionSpecification() function.addParameter('rsearch_BH_BH', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_rsearch_BH_BH(): function = LegacyFunctionSpecification() function.addParameter('rsearch_BH_BH', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function class Pikachu(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = PikachuInterface(**options) self.legacy_doc = legacy_interface.__doc__ GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) self.stopping_conditions.define_state(handler) def define_parameters(self, handler): GravitationalDynamics.define_parameters(self, handler) self.stopping_conditions.define_parameters(handler) handler.add_method_parameter( "get_kernel_directory", "set_kernel_directory", "kernel_directory", "Name of the Sequoia kernel directory", default_value = self.default_kernel_directory ) handler.add_alias_parameter( "epsilon_squared", "epsilon_squared_star_star", "smoothing parameter for gravity calculations - star-star interactions only (alias for epsilon_squared_star_star)" ) handler.add_method_parameter( "get_eps2_fs_fs", "set_eps2_fs_fs", "epsilon_squared_star_star", "smoothing parameter for gravity calculations - star-star interactions only", default_value = 1.0e-8 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_eps2_fs_bh", "set_eps2_fs_bh", "epsilon_squared_star_blackhole", "smoothing parameter for gravity calculations - star-blackhole interactions only", default_value = 1.0e-8 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_eps2_bh_bh", "set_eps2_bh_bh", "epsilon_squared_blackhole_blackhole", "smoothing parameter for gravity calculations - blackhole-blackhole interactions only", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_eta_s", "set_eta_s", "initial_timestep_parameter", "initial timestep parameter (eta)", default_value = 0.005 ) handler.add_alias_parameter( "timestep_parameter", "timestep_parameter_stars", "timestep parameter (eta) for field stars (alias for timestep_parameter_stars)" ) handler.add_method_parameter( "get_eta_fs", "set_eta_fs", "timestep_parameter_stars", "timestep parameter (eta) for field stars", default_value = 0.025 ) handler.add_method_parameter( "get_eta_smbh", "set_eta_smbh", "timestep_parameter_black_holes", "timestep parameter (eta) for black holes", default_value = 0.025 ) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "global timestep for iteration", default_value = 1.0 / 2048.0 | nbody_system.time ) handler.add_method_parameter( "get_theta_for_tree", "set_theta_for_tree", "opening_angle", "opening angle, theta, for building the tree: between 0 and 1", default_value = 0.4 ) handler.add_method_parameter( "get_search_factor", "set_search_factor", "search_factor", "search factor, if positive, determines rsearch = rcut_out + search_factor * velocity_dispersion * timestep", default_value = 3.0 ) handler.add_method_parameter( "get_vel_disp", "set_vel_disp", "velocity_dispersion", "velocity dispersion assumed when calculating rsearch", default_value = 0.707106781 | nbody_system.speed ) handler.add_method_parameter( "get_rcut_out_FS_FS", "set_rcut_out_FS_FS", "rcut_out_star_star", "cut-off radius beyond which direct force calculations smoothly transition into tree approximations", default_value = 2.0e-3 | nbody_system.length ) handler.add_method_parameter( "get_rcut_out_FS_BH", "set_rcut_out_FS_BH", "rcut_out_star_blackhole", "cut-off radius beyond which direct force calculations smoothly transition into tree approximations", default_value = 2.0e-2 | nbody_system.length ) handler.add_method_parameter( "get_rcut_out_BH_BH", "set_rcut_out_BH_BH", "rcut_out_blackhole_blackhole", "cut-off radius beyond which direct force calculations smoothly transition into tree approximations", default_value = 1.0e5 | nbody_system.length ) handler.add_method_parameter( "get_rsearch_FS_FS", "set_rsearch_FS_FS", "rsearch_star_star", "maximum radius for neighbour search, must be larger than rcut_out to " "provide a buffer for particles moving into rcut_out during a time step, " "only effective if search_factor <= 0", default_value = 0.0 | nbody_system.length ) handler.add_method_parameter( "get_rsearch_FS_BH", "set_rsearch_FS_BH", "rsearch_star_blackhole", "maximum radius for neighbour search, must be larger than rcut_out to " "provide a buffer for particles moving into rcut_out during a time step, " "only effective if search_factor <= 0", default_value = 0.0 | nbody_system.length ) handler.add_method_parameter( "get_rsearch_BH_BH", "set_rsearch_BH_BH", "rsearch_blackhole_blackhole", "maximum radius for neighbour search, must be larger than rcut_out to " "provide a buffer for particles moving into rcut_out during a time step, " "only effective if search_factor <= 0", default_value = 0.0 | nbody_system.length ) handler.add_boolean_parameter( "get_calculate_quadrupole_moments", "set_calculate_quadrupole_moments", "calculate_quadrupole_moments", "Flag that specifies whether quadrupole moments are calculated for the tree", False ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler)
21,295
41.935484
142
py
amuse
amuse-main/src/amuse/community/fastkick/__init__.py
from .interface import Fastkick
32
15.5
31
py
amuse
amuse-main/src/amuse/community/fastkick/interface.py
from amuse.community import * #~from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravityFieldCode, GravityFieldInterface from amuse.community.interface.common import CommonCodeInterface, CommonCode class FastKickInterface(CodeInterface, CommonCodeInterface, GravityFieldInterface): """ """ include_headers = ['worker_code.h'] MODE_CPU = 'cpu' MODE_GPU = 'gpu' def __init__(self, mode=MODE_CPU, **options): CodeInterface.__init__(self, name_of_the_worker=self.get_name_of_the_worker(mode), **options) def get_name_of_the_worker(self, mode): if mode == self.MODE_CPU: return "fastkick_worker" if mode == self.MODE_GPU: return "fastkick_worker_gpu" else: return "fastkick_worker" @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) function.addParameter('mass', dtype='float64', direction=function.IN, description = "The mass of the particle") function.addParameter('x', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def recommit_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def get_eps2(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eps2(): function = LegacyFunctionSpecification() function.addParameter('epsilon_squared', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_potential_energy(): function = LegacyFunctionSpecification() function.addParameter('potential_energy', dtype='float64', direction=function.OUT, unit=nbody_system.energy) function.result_type = 'int32' return function @legacy_function def get_mass(): """ Retrieve the mass of a particle. Mass is a scalar property of a particle, this function has one OUT argument. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the state from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('mass', dtype='float64', direction=function.OUT, description = "The current mass of the particle") function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True function.result_doc = """ 0 - OK particle was removed from the model -1 - ERROR particle could not be found """ return function @legacy_function def set_mass(): """ Update the mass of a particle. Mass is a scalar property of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle for which the state is to be updated. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('mass', dtype='float64', direction=function.IN, description = "The new mass of the particle") function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True function.result_doc = """ 0 - OK particle was found in the model and the information was set -1 - ERROR particle could not be found -2 - ERROR code does not support updating of a particle """ return function class FastKickDoc(object): def __get__(self, instance, owner): return instance.legacy_doc+"\n\n"+instance.parameters.__doc__ class FastKick(CommonCode, GravityFieldCode): __doc__ = FastKickDoc() def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter legacy_interface = FastKickInterface(**options) self.legacy_doc = legacy_interface.__doc__ CommonCode.__init__(self, legacy_interface, **options) def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method("new_particle", [nbody_system.mass] + [nbody_system.length]*3, (handler.INDEX, handler.ERROR_CODE)) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "set_mass", ( handler.NO_UNIT, nbody_system.mass, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_mass", ( handler.NO_UNIT, ), ( nbody_system.mass, handler.ERROR_CODE ) ) def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('END', 'INITIALIZED', 'initialize_code', False) handler.add_transition('INITIALIZED', 'EDIT', 'commit_parameters') handler.add_transition('RUN', 'CHANGE_PARAMETERS_RUN', 'before_set_parameter', False) handler.add_transition('EDIT', 'CHANGE_PARAMETERS_EDIT', 'before_set_parameter', False) handler.add_transition('UPDATE', 'CHANGE_PARAMETERS_UPDATE', 'before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN', 'RUN', 'recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT', 'EDIT', 'recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE', 'UPDATE', 'recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE', 'before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_method('EDIT', 'new_particle') handler.add_method('EDIT', 'delete_particle') handler.add_method('UPDATE', 'new_particle') handler.add_method('UPDATE', 'delete_particle') handler.add_transition('EDIT', 'RUN', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_particle', False) handler.add_transition('RUN', 'UPDATE', 'delete_particle', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') GravityFieldCode.define_state(self, handler) handler.add_method('RUN', 'get_potential_energy') def define_converter(self, handler): if not self.unit_converter is None: handler.set_converter(self.unit_converter.as_converter_from_si_to_generic()) def commit_parameters(self): self.parameters.send_not_set_parameters_to_code() self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def cleanup_code(self): self.overridden().cleanup_code() handler = self.get_handler('PARTICLES') handler._cleanup_instances() def reset(self): parameters = self.parameters.copy() self.cleanup_code() self.initialize_code() self.parameters.reset_from_memento(parameters) def define_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_particle') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_mass') handler.add_getter('particles', 'get_mass', names = ('mass',)) def define_properties(self, handler): handler.add_property("get_potential_energy") Fastkick = FastKick
10,311
39.598425
166
py
amuse
amuse-main/src/amuse/community/halogen/__init__.py
# generated file from .interface import Halogen
48
15.333333
30
py
amuse
amuse-main/src/amuse/community/halogen/interface.py
import os.path from amuse.community import * from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.support.options import option class HalogenInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ This is a stripped-down version of Halogen, developed during the Modest 7a workshop in Split, Croatia, in August 2007. This version can be used for generating single-mass initial conditions. Halogen allows to generate spherical structures from the alpha-beta-gamma-model family with an isotropic velocity tensor. Particles are sampled self-consistently from the distribution function of the models. Relevant references: .. [#] ADS:2008MNRAS.386.1543Z (Zemp M., Moore B., Stadel J., Carollo C.M. & Madau P. 2008, MNRAS, 386, 1543) """ include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="halogen_worker", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def generate_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function new_particle = None def delete_particle(self, index_of_the_particle): return 0 def invoke_state_change2(self): pass def invoke_state_change_updated(self): pass @legacy_function def get_number_of_particles_updated(): """ Return the number of particles added during the last generate_particles. """ function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='float64', direction=function.OUT, description = "The current mass of the particle") function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def get_position(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('x', dtype='float64', direction=function.OUT, description = "The current x component of the position vector of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current y component of the position vector of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current z component of the position vector of the particle") function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def get_velocity(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The current x component of the velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current y component of the velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current z component of the velocity vector of the particle") function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def get_model_alpha(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_model_alpha(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_model_beta(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_model_beta(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_model_gamma(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_model_gamma(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_total_mass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_total_mass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_scale_radius(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_scale_radius(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_cutoff_radius(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_cutoff_radius(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_target_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_target_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_black_hole_mass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_black_hole_mass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_random_seed(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_random_seed(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_do_exact_virial_radius_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_do_exact_virial_radius_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outputgridr_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outputgridr_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outputgriddf_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outputgriddf_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_write_output_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_write_output_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_output_path(): function = LegacyFunctionSpecification() function.addParameter('output_directory', dtype='string', direction=function.OUT, description = "The path to the output directory.") function.result_type = 'int32' return function @legacy_function def set_output_path(): function = LegacyFunctionSpecification() function.addParameter('output_directory', dtype='string', direction=function.IN, description = "The path to the output directory.") function.result_type = 'int32' return function @legacy_function def get_output_basename(): function = LegacyFunctionSpecification() function.addParameter('output_basename', dtype='string', direction=function.OUT, description = "The basename of output files.") function.result_type = 'int32' return function @legacy_function def set_output_basename(): function = LegacyFunctionSpecification() function.addParameter('output_basename', dtype='string', direction=function.IN, description = "The basename of output files.") function.result_type = 'int32' return function class Halogen(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, HalogenInterface(**options), **options) def initialize_code(self): result = self.overridden().initialize_code() self.parameters.set_defaults() self.parameters.output_directory = self.get_output_directory() def define_parameters(self, handler): handler.add_method_parameter( "get_model_alpha", "set_model_alpha", "alpha", "alpha parameter in density profile (see amuse/community/halogen/src/doc for details)", default_value = -1.0 ) handler.add_method_parameter( "get_model_beta", "set_model_beta", "beta", "beta parameter in density profile (see amuse/community/halogen/src/doc for details)", default_value = -1.0 ) handler.add_method_parameter( "get_model_gamma", "set_model_gamma", "gamma", "gamma parameter in density profile (see amuse/community/halogen/src/doc for details)", default_value = -1.0 ) handler.add_method_parameter( "get_total_mass", "set_total_mass", "total_mass", "the total mass of the model", default_value = 1.0 | nbody_system.mass ) handler.add_method_parameter( "get_scale_radius", "set_scale_radius", "scale_radius", "the scale radius of the density profile (see amuse/community/halogen/src/doc for details)", default_value = 1.0 | nbody_system.length ) handler.add_method_parameter( "get_cutoff_radius", "set_cutoff_radius", "cutoff_radius", "the cutoff radius of the density profile (see amuse/community/halogen/src/doc for details)", default_value = -1.0 | nbody_system.length ) handler.add_method_parameter( "get_target_number_of_particles", "set_target_number_of_particles", "number_of_particles", "the number of particles to be generated in the model", default_value = -1 ) handler.add_method_parameter( "get_black_hole_mass", "set_black_hole_mass", "black_hole_mass", "the mass of the central black hole", default_value = 0.0 | nbody_system.mass ) handler.add_method_parameter( "get_random_seed", "set_random_seed", "random_seed", "the initial seed to be used by the random number generator", default_value = 42 ) handler.add_boolean_parameter( "get_do_exact_virial_radius_flag", "set_do_exact_virial_radius_flag", "do_exact_virial_radius_flag", "Flag specifying whether to calculate the virial radius exactly via N^2 sum - Warning: time consuming for large N!", False ) handler.add_boolean_parameter( "get_outputgridr_flag", "set_outputgridr_flag", "outputgridr_flag", "Flag specifying whether to write a file outputting grid in r", False ) handler.add_boolean_parameter( "get_outputgriddf_flag", "set_outputgriddf_flag", "outputgriddf_flag", "Flag specifying whether to write a file outputting grid for distribution function", False ) handler.add_boolean_parameter( "get_write_output_flag", "set_write_output_flag", "write_output_flag", "Flag specifying whether to write the model and a log to file", False ) handler.add_method_parameter( "get_output_path", "set_output_path", "output_directory", "The path to the output directory", default_value = "./" ) handler.add_method_parameter( "get_output_basename", "set_output_basename", "output_basename", "The basename of output files", default_value = "halogen" ) def define_errorcodes(self, handler): handler.add_errorcode(-1, 'Unspecified, other error.') handler.add_errorcode(-2, 'Missing or bad parameter for halo (see amuse/community/halogen/src/doc for details on required parameters).') def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method("generate_particles", (), (handler.ERROR_CODE,)) handler.add_method("get_number_of_particles_updated", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("get_mass", (handler.INDEX,), (nbody_system.mass, handler.ERROR_CODE) ) handler.add_method("get_position", (handler.INDEX,), (nbody_system.length, nbody_system.length, nbody_system.length, handler.ERROR_CODE) ) handler.add_method("get_velocity", (handler.INDEX,), (nbody_system.speed, nbody_system.speed, nbody_system.speed, handler.ERROR_CODE) ) handler.add_method("get_model_alpha", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_model_alpha", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_model_beta", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_model_beta", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_model_gamma", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_model_gamma", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_total_mass", (), (nbody_system.mass, handler.ERROR_CODE,)) handler.add_method("set_total_mass", (nbody_system.mass, ), (handler.ERROR_CODE,)) handler.add_method("get_scale_radius", (), (nbody_system.length, handler.ERROR_CODE,)) handler.add_method("set_scale_radius", (nbody_system.length, ), (handler.ERROR_CODE,)) handler.add_method("get_cutoff_radius", (), (nbody_system.length, handler.ERROR_CODE,)) handler.add_method("set_cutoff_radius", (nbody_system.length, ), (handler.ERROR_CODE,)) handler.add_method("get_target_number_of_particles", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_target_number_of_particles", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_black_hole_mass", (), (nbody_system.mass, handler.ERROR_CODE,)) handler.add_method("set_black_hole_mass", (nbody_system.mass, ), (handler.ERROR_CODE,)) handler.add_method("get_random_seed", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_random_seed", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_output_path", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_output_path", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_output_basename", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_output_basename", (handler.NO_UNIT,), (handler.ERROR_CODE,)) def define_converter(self, handler): if not self.unit_converter is None: handler.set_converter(self.unit_converter.as_converter_from_si_to_generic()) def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_particle') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_getter('particles', 'get_mass') handler.add_getter('particles', 'get_position') handler.add_getter('particles', 'get_velocity') def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False) handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False) handler.add_transition('UPDATE','CHANGE_PARAMETERS_UPDATE','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE','UPDATE','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_transition('EDIT', 'UPDATE', 'generate_particles', False) handler.add_transition('UPDATE', 'RUN', 'update_particle_set') handler.add_transition('RUN', 'EDIT', 'clear_particle_set') handler.add_method('RUN', 'invoke_state_change_updated') handler.add_method('EDIT', 'get_number_of_particles_updated') handler.add_method('UPDATE', 'get_number_of_particles_updated') handler.add_method('RUN', 'get_number_of_particles_updated') handler.add_method('RUN', 'get_mass') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_velocity') def generate_particles(self): result = self.overridden().generate_particles() self.invoke_state_change_updated() def update_particle_set(self): """ update the particle set after changes in the code this implementation needs to move to the amuse.datamodel.incode_storage module, as it uses a lot of internal methods and info! """ number_of_updated_particles = self.get_number_of_particles_updated() if number_of_updated_particles: self.particles._private.attribute_storage._add_indices( list(range(number_of_updated_particles)) ) def clear_particle_set(self): if len(self.particles): self.particles.remove_particles(self.particles)
22,661
39.832432
156
py
amuse
amuse-main/src/amuse/community/secularmultiple/__init__.py
from .interface import Secularmultiple
39
19
38
py
amuse
amuse-main/src/amuse/community/secularmultiple/interface.py
import numpy as np from amuse.community import ( InCodeComponentImplementation, CodeInterface, legacy_function, LegacyFunctionSpecification, INDEX, NO_UNIT, LINK, ) from amuse.units import units, constants # units used in the legacy code # numerical values are defined in src/types.h UNIT_LENGTH = units.au UNIT_MASS = units.MSun UNIT_TIME = 1.0e6 * units.yr UNIT_ANGULAR_MOMENTUM = UNIT_MASS * UNIT_LENGTH**2 / UNIT_TIME # specific angular momentum UNIT_ENERGY = UNIT_MASS * UNIT_LENGTH**2 / (UNIT_TIME**2) # energy UNIT_LUMINOSITY = UNIT_ENERGY / UNIT_TIME PRINT_NAME = 'SecularMultipleVar' class SecularMultipleInterface(CodeInterface): """ SecularMultiple -- by Adrian Hamers, based on 2016MNRAS.459.2827H A code to compute the secular (orbit-averaged) gravitational dynamics of hierarchical multiple systems composed of nested binary orbits (simplex-type systems). with any configuration and any number of bodies. A particle can repesent a binary (`is_binary = True') or a body (`is_binary = False'). The structure of the system is determined by linking to other particles with the attributes child1 and child2. Tidal interactions and relativistic corrections are included in an ad hoc fashion (tides: treating the companion as a single body, even if it is not; relativistic terms: only including binary-binary interactions). November 2017: Updates for external perturbations (flybys & supernovae), detailed in Hamers (2018, in prep) .. [#] ADS:2016MNRAS.459.2827H .. [#] ADS:2018MNRAS.476.4139H """ include_headers = [ 'interface.h', 'src/types.h', 'src/evolve.h', 'src/ODE_system.h' ] def __init__(self, **options): # CodeInterface.__init__(self, name_of_the_worker="secularmultiple_worker", **options) CodeInterface.__init__(self, **options) ####################### # basic interface ####################### # particles @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, unit=INDEX) function.addParameter( 'is_binary', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.result_type = 'int32' return function @legacy_function def set_children(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('child1', dtype='int32', direction=function.IN, unit=LINK('particles')) function.addParameter('child2', dtype='int32', direction=function.IN, unit=LINK('particles')) function.result_type = 'int32' return function @legacy_function def get_children(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('child1', dtype='int32', direction=function.OUT, unit=LINK('particles')) function.addParameter('child2', dtype='int32', direction=function.OUT, unit=LINK('particles')) function.result_type = 'int32' return function @legacy_function def set_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass', dtype='float64', direction=function.IN, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass', dtype='float64', direction=function.OUT, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def set_mass_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass_dot_external', dtype='float64', direction=function.IN, unit=UNIT_MASS / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_mass_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass_dot_external', dtype='float64', direction=function.OUT, unit=UNIT_MASS / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_radius_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius_dot_external', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_radius_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius_dot_external', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_radius_ddot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius_ddot_external', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / (UNIT_TIME**2)) function.result_type = 'int32' return function @legacy_function def get_radius_ddot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('radius_ddot_external', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / (UNIT_TIME**2)) function.result_type = 'int32' return function @legacy_function def get_level(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('level', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_stellar_type(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('stellar_type', dtype='int32', direction=function.IN, unit=units.stellar_type) function.result_type = 'int32' return function @legacy_function def get_stellar_type(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('stellar_type', dtype='int32', direction=function.OUT, unit=units.stellar_type) function.result_type = 'int32' return function @legacy_function def set_true_anomaly(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('true_anomaly', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_true_anomaly(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('true_anomaly', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_sample_orbital_phases_randomly(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('sample_orbital_phases_randomly', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_sample_orbital_phases_randomly(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('sample_orbital_phases_randomly', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function ################################################# ### user-specified instantaneous perturbation ### ################################################# @legacy_function def set_instantaneous_perturbation_delta_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_mass', dtype='float64', direction=function.IN, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def get_instantaneous_perturbation_delta_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_mass', dtype='float64', direction=function.OUT, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def set_instantaneous_perturbation_delta_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_position_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('instantaneous_perturbation_delta_position_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('instantaneous_perturbation_delta_position_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_instantaneous_perturbation_delta_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_position_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('instantaneous_perturbation_delta_position_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('instantaneous_perturbation_delta_position_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_instantaneous_perturbation_delta_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_velocity_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('instantaneous_perturbation_delta_velocity_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('instantaneous_perturbation_delta_velocity_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_instantaneous_perturbation_delta_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('instantaneous_perturbation_delta_velocity_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('instantaneous_perturbation_delta_velocity_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('instantaneous_perturbation_delta_velocity_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function ########################## # external particles ########################## @legacy_function def new_external_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.OUT, unit=INDEX) function.addParameter('mass', dtype='float64', direction=function.IN, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def delete_external_particle(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.result_type = 'int32' return function @legacy_function def set_external_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass', dtype='float64', direction=function.IN, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def get_external_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mass', dtype='float64', direction=function.OUT, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def set_external_path(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('path', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_path(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('path', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_external_mode(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mode', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_mode(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('mode', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_external_t_ref(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('t_ref', dtype='float64', direction=function.IN, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_external_t_ref(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('t_ref', dtype='float64', direction=function.OUT, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_external_t_passed(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('t_passed', dtype='float64', direction=function.IN, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_external_t_passed(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('t_passed', dtype='float64', direction=function.OUT, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_external_r0_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('r0_vec_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('r0_vec_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('r0_vec_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_external_r0_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('r0_vec_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('r0_vec_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('r0_vec_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_external_rdot_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('rdot_vec_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('rdot_vec_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('rdot_vec_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_external_rdot_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('rdot_vec_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('rdot_vec_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('rdot_vec_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_external_periapse_distance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('periapse_distance', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_external_periapse_distance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('periapse_distance', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_external_eccentricity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('eccentricity', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_eccentricity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('eccentricity', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_external_e_hat_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_hat_vec_x', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('e_hat_vec_y', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('e_hat_vec_z', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_e_hat_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_hat_vec_x', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('e_hat_vec_y', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('e_hat_vec_z', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_external_h_hat_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('h_hat_vec_x', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('h_hat_vec_y', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('h_hat_vec_z', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_h_hat_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('h_hat_vec_x', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('h_hat_vec_y', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('h_hat_vec_z', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_external_r_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_external_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('r_vec_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('r_vec_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('r_vec_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function #################### ### spin vectors ### #################### @legacy_function def set_spin_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('spin_vec_x', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.addParameter('spin_vec_y', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.addParameter('spin_vec_z', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_spin_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('spin_vec_x', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.addParameter('spin_vec_y', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.addParameter('spin_vec_z', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_spin_vector_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('spin_vec_x_dot_external', dtype='float64', direction=function.IN, unit=1.0 / (UNIT_TIME**2)) function.addParameter('spin_vec_y_dot_external', dtype='float64', direction=function.IN, unit=1.0 / (UNIT_TIME**2)) function.addParameter('spin_vec_z_dot_external', dtype='float64', direction=function.IN, unit=1.0 / (UNIT_TIME**2)) function.result_type = 'int32' return function @legacy_function def get_spin_vector_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('spin_vec_x_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / (UNIT_TIME**2)) function.addParameter('spin_vec_y_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / (UNIT_TIME**2)) function.addParameter('spin_vec_z_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / (UNIT_TIME**2)) function.result_type = 'int32' return function ################################ ### orbital vectors/elements ### ################################ @legacy_function def set_orbital_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_vec_x', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('e_vec_y', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('e_vec_z', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('h_vec_x', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM) function.addParameter('h_vec_y', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM) function.addParameter('h_vec_z', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM) function.result_type = 'int32' return function @legacy_function def get_orbital_vectors(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_vec_x', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('e_vec_y', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('e_vec_z', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('h_vec_x', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM) function.addParameter('h_vec_y', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM) function.addParameter('h_vec_z', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM) function.result_type = 'int32' return function @legacy_function def set_orbital_vectors_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_vec_x_dot_external', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.addParameter('e_vec_y_dot_external', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.addParameter('e_vec_z_dot_external', dtype='float64', direction=function.IN, unit=1.0 / UNIT_TIME) function.addParameter('h_vec_x_dot_external', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.addParameter('h_vec_y_dot_external', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.addParameter('h_vec_z_dot_external', dtype='float64', direction=function.IN, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_orbital_vectors_dot_external(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('e_vec_x_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.addParameter('e_vec_y_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.addParameter('e_vec_z_dot_external', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.addParameter('h_vec_x_dot_external', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.addParameter('h_vec_y_dot_external', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.addParameter('h_vec_z_dot_external', dtype='float64', direction=function.OUT, unit=UNIT_ANGULAR_MOMENTUM / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_orbital_elements(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('semimajor_axis', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('eccentricity', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('inclination', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('argument_of_pericenter', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('longitude_of_ascending_node', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_orbital_elements(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('semimajor_axis', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('eccentricity', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('inclination', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('argument_of_pericenter', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.addParameter('longitude_of_ascending_node', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_inclination_relative_to_parent(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('inclination_relative_to_parent', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_de_dt(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('de_dt', dtype='float64', direction=function.OUT, unit=1.0 / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_position_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('position_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('position_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.addParameter('position_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_position_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('position_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('position_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.addParameter('position_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_velocity_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('velocity_x', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('velocity_y', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('velocity_z', dtype='float64', direction=function.IN, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_velocity_vector(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=INDEX) function.addParameter('velocity_x', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('velocity_y', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.addParameter('velocity_z', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH / UNIT_TIME) function.result_type = 'int32' return function ################ ### PN terms ### ################ @legacy_function def set_include_pairwise_1PN_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_pairwise_1PN_terms', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_pairwise_1PN_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_pairwise_1PN_terms', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_pairwise_25PN_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_pairwise_25PN_terms', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_pairwise_25PN_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_pairwise_25PN_terms', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function ############# ### tides ### ############# @legacy_function def set_tides_method(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_method', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_tides_method(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_method', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_tidal_friction_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_tidal_friction_terms', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_tidal_friction_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_tidal_friction_terms', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_tidal_bulges_precession_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_tidal_bulges_precession_terms', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_tidal_bulges_precession_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_tidal_bulges_precession_terms', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_rotation_precession_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_rotation_precession_terms', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_rotation_precession_terms(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('include_rotation_precession_terms', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_minimum_eccentricity_for_tidal_precession(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('minimum_eccentricity_for_tidal_precession', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_minimum_eccentricity_for_tidal_precession(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('minimum_eccentricity_for_tidal_precession', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function # physical parameters @legacy_function def set_tides_apsidal_motion_constant(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_apsidal_motion_constant', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_tides_apsidal_motion_constant(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_apsidal_motion_constant', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_tides_gyration_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_gyration_radius', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_tides_gyration_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_gyration_radius', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_tides_viscous_time_scale(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_viscous_time_scale', dtype='float64', direction=function.IN, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def get_tides_viscous_time_scale(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_viscous_time_scale', dtype='float64', direction=function.OUT, unit=UNIT_TIME) function.result_type = 'int32' return function @legacy_function def set_tides_viscous_time_scale_prescription(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_viscous_time_scale_prescription', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_tides_viscous_time_scale_prescription(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('tides_viscous_time_scale_prescription', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_convective_envelope_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('convective_envelope_mass', dtype='float64', direction=function.IN, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def get_convective_envelope_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('convective_envelope_mass', dtype='float64', direction=function.OUT, unit=UNIT_MASS) function.result_type = 'int32' return function @legacy_function def set_convective_envelope_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('convective_envelope_radius', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_convective_envelope_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('convective_envelope_radius', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def set_luminosity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('luminosity', dtype='float64', direction=function.IN, unit=UNIT_LUMINOSITY) function.result_type = 'int32' return function @legacy_function def get_luminosity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('luminosity', dtype='float64', direction=function.OUT, unit=UNIT_LUMINOSITY) function.result_type = 'int32' return function #################### ### root finding ### #################### # secular breakdown @legacy_function def set_check_for_secular_breakdown(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_secular_breakdown', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_secular_breakdown(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_secular_breakdown', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function # dynamical instablity @legacy_function def set_check_for_dynamical_instability(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_dynamical_instability', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_dynamical_instability(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_dynamical_instability', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_dynamical_instability_criterion(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_criterion', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_dynamical_instability_criterion(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_criterion', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_dynamical_instability_central_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_central_particle', dtype='int32', direction=function.IN, unit=LINK('particles')) function.result_type = 'int32' return function @legacy_function def get_dynamical_instability_central_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_central_particle', dtype='int32', direction=function.OUT, unit=LINK('particles')) function.result_type = 'int32' return function @legacy_function def set_dynamical_instability_K_parameter(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_K_parameter', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_dynamical_instability_K_parameter(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='float64', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_K_parameter', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function # physical collision / orbit crossing @legacy_function def set_check_for_physical_collision_or_orbit_crossing(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_physical_collision_or_orbit_crossing', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_physical_collision_or_orbit_crossing(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_physical_collision_or_orbit_crossing', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function # minimum periapse distance reached @legacy_function def set_check_for_minimum_periapse_distance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_minimum_periapse_distance', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_minimum_periapse_distance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_minimum_periapse_distance', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_check_for_minimum_periapse_distance_value(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_minimum_periapse_distance_value', dtype='float64', direction=function.IN, unit=UNIT_LENGTH) function.result_type = 'int32' return function @legacy_function def get_check_for_minimum_periapse_distance_value(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_minimum_periapse_distance_value', dtype='float64', direction=function.OUT, unit=UNIT_LENGTH) function.result_type = 'int32' return function # RLOF at pericentre @legacy_function def set_check_for_RLOF_at_pericentre(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_RLOF_at_pericentre', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_RLOF_at_pericentre(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_RLOF_at_pericentre', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_check_for_RLOF_at_pericentre_use_sepinsky_fit(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_RLOF_at_pericentre_use_sepinsky_fit', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_check_for_RLOF_at_pericentre_use_sepinsky_fit(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('check_for_RLOF_at_pericentre_use_sepinsky_fit', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function # retrieve root finding state @legacy_function def set_root_finding_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('secular_breakdown_has_occurred', dtype='bool', direction=function.IN, unit=NO_UNIT) function.addParameter('dynamical_instability_has_occurred', dtype='bool', direction=function.IN, unit=NO_UNIT) function.addParameter('physical_collision_or_orbit_crossing_has_occurred', dtype='bool', direction=function.IN, unit=NO_UNIT) function.addParameter('minimum_periapse_distance_has_occurred', dtype='bool', direction=function.IN, unit=NO_UNIT) function.addParameter('RLOF_at_pericentre_has_occurred', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_root_finding_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('secular_breakdown_has_occurred', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.addParameter('dynamical_instability_has_occurred', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.addParameter('physical_collision_or_orbit_crossing_has_occurred', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.addParameter('minimum_periapse_distance_has_occurred', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.addParameter('RLOF_at_pericentre_has_occurred', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function ######################## ### evolve interface ### ######################## @legacy_function def evolve_interface(): function = LegacyFunctionSpecification() function.addParameter('start_time', dtype='float64', direction=function.IN, unit=UNIT_TIME) function.addParameter('time_step', dtype='float64', direction=function.IN, unit=UNIT_TIME) function.addParameter('output_time', dtype='float64', direction=function.OUT, unit=UNIT_TIME) function.addParameter('hamiltonian', dtype='float64', direction=function.OUT, unit=UNIT_ENERGY) function.addParameter('flag', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.addParameter('error_code', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def determine_binary_parents_levels_and_masses_interface(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def apply_external_perturbation_assuming_integrated_orbits_interface(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def apply_user_specified_instantaneous_perturbation_interface(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def set_positions_and_velocities_interface(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function ####################### ### code parameters ### ####################### @legacy_function def get_orbital_phases_random_seed(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_orbital_phases_random_seed(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function ################## ### tolerances ### ################## @legacy_function def get_relative_tolerance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_relative_tolerance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_absolute_tolerance_eccentricity_vectors(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_absolute_tolerance_eccentricity_vectors(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function ############# ### terms ### ############# @legacy_function def get_include_quadrupole_order_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_quadrupole_order_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_octupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_octupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_octupole_order_binary_triplet_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_octupole_order_binary_triplet_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_hexadecupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_hexadecupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_include_dotriacontupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT, unit=NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_include_dotriacontupole_order_binary_pair_terms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN, unit=NO_UNIT) function.result_type = 'int32' return function class SecularMultiple(InCodeComponentImplementation): def __init__(self, **options): InCodeComponentImplementation.__init__(self, SecularMultipleInterface(**options), **options) self.model_time = 0.0 | units.Myr self.particles_committed = False self.initial_hamiltonian = 0.0 | UNIT_ENERGY self.hamiltonian = 0.0 | UNIT_ENERGY self.flag = 0 self.error_code = 0 # self.verbose = True # self.debug = True def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_particle') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_children', names=('child1', 'child2')) handler.add_getter('particles', 'get_children', names=('child1', 'child2')) handler.add_setter('particles', 'set_mass') handler.add_getter('particles', 'get_mass') handler.add_setter('particles', 'set_mass_dot_external') handler.add_getter('particles', 'get_mass_dot_external') handler.add_setter('particles', 'set_radius') handler.add_getter('particles', 'get_radius') handler.add_setter('particles', 'set_radius_dot_external') handler.add_getter('particles', 'get_radius_dot_external') handler.add_setter('particles', 'set_radius_ddot_external') handler.add_getter('particles', 'get_radius_ddot_external') handler.add_getter('particles', 'get_level') handler.add_setter('particles', 'set_stellar_type') handler.add_getter('particles', 'get_stellar_type') handler.add_setter('particles', 'set_true_anomaly') handler.add_getter('particles', 'get_true_anomaly') handler.add_setter('particles', 'set_sample_orbital_phases_randomly') handler.add_getter('particles', 'get_sample_orbital_phases_randomly') handler.add_setter('particles', 'set_instantaneous_perturbation_delta_mass') handler.add_getter('particles', 'get_instantaneous_perturbation_delta_mass') handler.add_setter('particles', 'set_instantaneous_perturbation_delta_position') handler.add_getter('particles', 'get_instantaneous_perturbation_delta_position') handler.add_setter('particles', 'set_instantaneous_perturbation_delta_velocity') handler.add_getter('particles', 'get_instantaneous_perturbation_delta_velocity') handler.add_setter('particles', 'set_spin_vector') handler.add_getter('particles', 'get_spin_vector') handler.add_setter('particles', 'set_spin_vector_dot_external') handler.add_getter('particles', 'get_spin_vector_dot_external') handler.add_setter('particles', 'set_orbital_vectors') handler.add_getter('particles', 'get_orbital_vectors') handler.add_setter('particles', 'set_orbital_vectors_dot_external') handler.add_getter('particles', 'get_orbital_vectors_dot_external') handler.add_setter('particles', 'set_orbital_elements', names=('semimajor_axis', 'eccentricity', 'inclination', 'argument_of_pericenter', 'longitude_of_ascending_node')) handler.add_getter('particles', 'get_orbital_elements', names=('semimajor_axis', 'eccentricity', 'inclination', 'argument_of_pericenter', 'longitude_of_ascending_node')) handler.add_getter('particles', 'get_inclination_relative_to_parent') handler.add_getter('particles', 'get_de_dt') handler.add_setter('particles', 'set_position_vector') handler.add_getter('particles', 'get_position_vector') handler.add_setter('particles', 'set_velocity_vector') handler.add_getter('particles', 'get_velocity_vector') handler.add_setter('particles', 'set_include_pairwise_1PN_terms') handler.add_getter('particles', 'get_include_pairwise_1PN_terms') handler.add_setter('particles', 'set_include_pairwise_25PN_terms') handler.add_getter('particles', 'get_include_pairwise_25PN_terms') handler.add_setter('particles', 'set_tides_method') handler.add_getter('particles', 'get_tides_method') handler.add_setter('particles', 'set_include_tidal_friction_terms') handler.add_getter('particles', 'get_include_tidal_friction_terms') handler.add_setter('particles', 'set_include_tidal_bulges_precession_terms') handler.add_getter('particles', 'get_include_tidal_bulges_precession_terms') handler.add_setter('particles', 'set_include_rotation_precession_terms') handler.add_getter('particles', 'get_include_rotation_precession_terms') handler.add_setter('particles', 'set_minimum_eccentricity_for_tidal_precession') handler.add_getter('particles', 'get_minimum_eccentricity_for_tidal_precession') handler.add_setter('particles', 'set_tides_apsidal_motion_constant') handler.add_getter('particles', 'get_tides_apsidal_motion_constant') handler.add_setter('particles', 'set_tides_gyration_radius') handler.add_getter('particles', 'get_tides_gyration_radius') handler.add_setter('particles', 'set_tides_viscous_time_scale') handler.add_getter('particles', 'get_tides_viscous_time_scale') handler.add_setter('particles', 'set_tides_viscous_time_scale_prescription') handler.add_getter('particles', 'get_tides_viscous_time_scale_prescription') handler.add_setter('particles', 'set_convective_envelope_mass') handler.add_getter('particles', 'get_convective_envelope_mass') handler.add_setter('particles', 'set_convective_envelope_radius') handler.add_getter('particles', 'get_convective_envelope_radius') handler.add_setter('particles', 'set_luminosity') handler.add_getter('particles', 'get_luminosity') handler.add_setter('particles', 'set_check_for_secular_breakdown') handler.add_getter('particles', 'get_check_for_secular_breakdown') handler.add_setter('particles', 'set_check_for_dynamical_instability') handler.add_getter('particles', 'get_check_for_dynamical_instability') handler.add_setter('particles', 'set_dynamical_instability_criterion') handler.add_getter('particles', 'get_dynamical_instability_criterion') handler.add_setter('particles', 'set_dynamical_instability_central_particle') handler.add_getter('particles', 'get_dynamical_instability_central_particle') handler.add_setter('particles', 'set_dynamical_instability_K_parameter') handler.add_getter('particles', 'get_dynamical_instability_K_parameter') handler.add_setter('particles', 'set_check_for_physical_collision_or_orbit_crossing') handler.add_getter('particles', 'get_check_for_physical_collision_or_orbit_crossing') handler.add_setter('particles', 'set_check_for_minimum_periapse_distance') handler.add_getter('particles', 'get_check_for_minimum_periapse_distance') handler.add_setter('particles', 'set_check_for_minimum_periapse_distance_value') handler.add_getter('particles', 'get_check_for_minimum_periapse_distance_value') handler.add_setter('particles', 'set_check_for_RLOF_at_pericentre') handler.add_getter('particles', 'get_check_for_RLOF_at_pericentre') handler.add_setter('particles', 'set_check_for_RLOF_at_pericentre_use_sepinsky_fit') handler.add_getter('particles', 'get_check_for_RLOF_at_pericentre_use_sepinsky_fit') handler.add_setter('particles', 'set_root_finding_state') handler.add_getter('particles', 'get_root_finding_state') handler.define_set('external_particles', 'index_of_the_external_particle') handler.set_new('external_particles', 'new_external_particle') handler.set_delete('external_particles', 'delete_external_particle') handler.add_setter('external_particles', 'set_external_mass') handler.add_getter('external_particles', 'get_external_mass') handler.add_setter('external_particles', 'set_external_path') handler.add_getter('external_particles', 'get_external_path') handler.add_setter('external_particles', 'set_external_mode') handler.add_getter('external_particles', 'get_external_mode') handler.add_setter('external_particles', 'set_external_t_ref') handler.add_getter('external_particles', 'get_external_t_ref') handler.add_setter('external_particles', 'set_external_t_passed') handler.add_getter('external_particles', 'get_external_t_passed') handler.add_setter('external_particles', 'set_external_r0_vectors') handler.add_getter('external_particles', 'get_external_r0_vectors') handler.add_setter('external_particles', 'set_external_rdot_vectors', names=('rdot_vec_x', 'rdot_vec_y', 'rdot_vec_z')) handler.add_getter('external_particles', 'get_external_rdot_vectors', names=('rdot_vec_x', 'rdot_vec_y', 'rdot_vec_z')) handler.add_setter('external_particles', 'set_external_eccentricity') handler.add_getter('external_particles', 'get_external_eccentricity') handler.add_setter('external_particles', 'set_external_periapse_distance') handler.add_getter('external_particles', 'get_external_periapse_distance') handler.add_setter('external_particles', 'set_external_e_hat_vectors') handler.add_getter('external_particles', 'get_external_e_hat_vectors') handler.add_setter('external_particles', 'set_external_h_hat_vectors') handler.add_getter('external_particles', 'get_external_h_hat_vectors') handler.add_getter('external_particles', 'get_external_r_vectors') def define_parameters(self, handler): handler.add_method_parameter( "get_relative_tolerance", "set_relative_tolerance", "relative_tolerance", "relative_tolerance", default_value=1.0e-16 ) handler.add_method_parameter( "get_absolute_tolerance_eccentricity_vectors", "set_absolute_tolerance_eccentricity_vectors", "absolute_tolerance_eccentricity_vectors", "absolute_tolerance_eccentricity_vectors", default_value=1.0e-14 ) handler.add_method_parameter( "get_include_quadrupole_order_terms", "set_include_quadrupole_order_terms", "include_quadrupole_order_terms", "include_quadrupole_order_terms", default_value=True ) handler.add_method_parameter( "get_include_octupole_order_binary_pair_terms", "set_include_octupole_order_binary_pair_terms", "include_octupole_order_binary_pair_terms", "include_octupole_order_binary_pair_terms", default_value=True ) handler.add_method_parameter( "get_include_octupole_order_binary_triplet_terms", "set_include_octupole_order_binary_triplet_terms", "include_octupole_order_binary_triplet_terms", "include_octupole_order_binary_triplet_terms", default_value=False ) handler.add_method_parameter( "get_include_hexadecupole_order_binary_pair_terms", "set_include_hexadecupole_order_binary_pair_terms", "include_hexadecupole_order_binary_pair_terms", "include_hexadecupole_order_binary_pair_terms", default_value=False ) handler.add_method_parameter( "get_include_dotriacontupole_order_binary_pair_terms", "set_include_dotriacontupole_order_binary_pair_terms", "include_dotriacontupole_order_binary_pair_terms", "include_dotriacontupole_order_binary_pair_terms", default_value=False ) handler.add_method_parameter( "get_orbital_phases_random_seed", "set_orbital_phases_random_seed", "orbital_phases_random_seed", "orbital_phases_random_seed", default_value=0 ) def define_methods(self, handler): pass def before_get_parameter(self): """ Called everytime just before a parameter is retrieved in using:: instance.parameter.name """ pass def before_set_parameter(self): """ Called everytime just before a parameter is updated in using:: instance.parameter.name = newvalue """ pass def commit_particles(self): print(f"{PRINT_NAME} -- committing particles") particles = self.particles if len(particles) == 0: print(f"{PRINT_NAME} -- no particles have been added -- exiting") return -2 # sys.exit(-1) # SR: exiting causes an AMUSE crash... particles.add_vector_attribute("spin_vec", ["spin_vec_x", "spin_vec_y", "spin_vec_z"]) particles.add_vector_attribute("e_vec", ["e_vec_x", "e_vec_y", "e_vec_z"]) particles.add_vector_attribute("h_vec", ["h_vec_x", "h_vec_y", "h_vec_z"]) self.external_particles.add_vector_attribute("r_vec", ["r_vec_x", "r_vec_y", "r_vec_z"]) # evaluate the initial hamiltonian time_step = 0.0 | units.Myr end_time, self.initial_hamiltonian, flag, error_code = self.evolve_interface(self.model_time, time_step) self.particles_committed = True def evolve_model(self, end_time): if end_time is None: print(f"{PRINT_NAME} -- end time not specified in evolve_model! exiting") return -2 # don't exit, just return an error if self.particles_committed == False: self.commit_particles() # integrate system of ODEs start_time = self.model_time time_step = end_time - start_time end_time, self.hamiltonian, flag, error_code = self.evolve_interface(start_time, time_step) # compute energy error self.relative_energy_error = np.fabs((self.initial_hamiltonian - self.hamiltonian) / self.initial_hamiltonian) # update model time self.model_time = end_time if (flag == 99): print(f"{PRINT_NAME} -- error occurred during ODE integration") print(f"{PRINT_NAME} -- error code is {error_code}") self.flag = flag self.error_code = error_code def determine_binary_parents_levels_and_masses(self): self.determine_binary_parents_levels_and_masses_interface() def apply_external_perturbation_assuming_integrated_orbits(self): self.apply_external_perturbation_assuming_integrated_orbits_interface() def apply_user_specified_instantaneous_perturbation(self): self.apply_user_specified_instantaneous_perturbation_interface() def set_positions_and_velocities(self): self.set_positions_and_velocities_interface() Secularmultiple = SecularMultiple
84,722
49.400357
177
py
amuse
amuse-main/src/amuse/community/huayno/__init__.py
from .interface import Huayno
30
14.5
29
py
amuse
amuse-main/src/amuse/community/huayno/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface,GravityFieldInterface from amuse.community.interface.gd import GravitationalDynamics,GravityFieldCode class HuaynoInterface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, GravityFieldInterface): """ HUAYNO is a code to solve the astrophysical N-body problem. It uses recursive Hamiltonian splitting to generate multiple-timestep integrators which conserve momentum to machine precision. A number of different integrators are available. The code has been developed within the AMUSE environment. It can make use of GPUs - for this an OpenCL version can be compiled. .. [#] ADS:2012NewA...17..711P (Pelupessy, Federico I.; J\"anes, J\"urgen; Portegies Zwart, Simon, New Astronomy, Volume 17, Issue 8, p. 711-719) .. [#] ADS:2014A&A...570A..20J (J\"anes, J\"urgen; Pelupessy, Federico I.; Portegies Zwart, Simon, A&A, Volume 570, October 2014 (for CC, OK methods)) """ include_headers = ['worker_code.h'] MODE_OPENCL='opencl' MODE_OPENMP='openmp' def name_of_worker(self,mode): if mode==self.MODE_OPENCL: return 'huayno_worker_cl' if mode==self.MODE_OPENMP: return 'huayno_worker_mp' return 'huayno_worker' def __init__(self, mode=None, **options): CodeInterface.__init__(self, name_of_the_worker = self.name_of_worker(mode), **options) LiteratureReferencesMixIn.__init__(self) @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def get_kinetic_energy(): function = LegacyFunctionSpecification() function.addParameter('kinetic_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_potential_energy(): function = LegacyFunctionSpecification() function.addParameter('potential_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def initialize_code(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('time_end', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_timestep_parameter(): function = LegacyFunctionSpecification() function.addParameter('time_param', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_timestep_parameter(): function = LegacyFunctionSpecification() function.addParameter('time_param', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_timestep(): function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_verbosity_parameter(): function = LegacyFunctionSpecification() function.addParameter('verbosity', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_verbosity_parameter(): function = LegacyFunctionSpecification() function.addParameter('verbosity', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('number_of_particles', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_inttype_parameter(): function = LegacyFunctionSpecification() function.addParameter('inttype', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_inttype_parameter(): function = LegacyFunctionSpecification() function.addParameter('inttype', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_eps2_parameter(): function = LegacyFunctionSpecification() function.addParameter('eps2', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_eps2_parameter(): function = LegacyFunctionSpecification() function.addParameter('eps2', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_accel_zero_mass_parameter(): function = LegacyFunctionSpecification() function.addParameter('accelerate_zero_mass', dtype='b', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_accel_zero_mass_parameter(): function = LegacyFunctionSpecification() function.addParameter('accelerate_zero_mass', dtype='b', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_opencl_device_type(): function = LegacyFunctionSpecification() function.addParameter('opencl_device_type', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_opencl_device_type(): function = LegacyFunctionSpecification() function.addParameter('opencl_device_type', dtype='i', direction=function.IN) function.result_type = 'i' return function def set_eps2(self, e): return self.set_eps2_parameter(e) def get_eps2(self): return self.get_eps2_parameter() @legacy_function def get_evolve_statistics(): function = LegacyFunctionSpecification() function.addParameter('ttot', dtype='int64', direction=function.OUT) function.addParameter('ktot', dtype='int64', direction=function.OUT) function.addParameter('dtot', dtype='int64', direction=function.OUT) function.addParameter('tstot', dtype='int64', direction=function.OUT) function.addParameter('kstot', dtype='int64', direction=function.OUT) function.addParameter('dstot', dtype='int64', direction=function.OUT) function.result_type = 'i' return function class Huayno(GravitationalDynamics,GravityFieldCode): __interface__ = HuaynoInterface class inttypes(object): """ CONSTANT# = constant global timestep, of different order SHARED# = shared, but varying global timestep, of different order SHARED#_COLLISION = shared, but varying global timestep, of different order with collision detection CC_.. = various variant of connected component (termination with KEPLER or Bulirsch-stoer, see paper Janes CCC_... = with centering of subsys OK = Optimal Kick (see paper Janes) PASS, HOLD, BRIDGE and variants= momentum conserving individual timestepping see paper Pelupessy NAIVE = naive implementation of individual timestepping others are experimental, testing, development """ @classmethod def _list(cls): return set([x for x in cls.__dict__.keys() if not x.startswith('_')]) all_inttypes=dict(CONSTANT = 0, SHARED2 = 1, PASS_KDK = 2, HOLD_KDK = 3, BRIDGE_KDK = 4, EXTRAPOLATE = 5, PASS_DKD = 7, HOLD_DKD = 8, PPASS_DKD = 9, BRIDGE_DKD = 10, CC = 11, CC_KEPLER = 12, OK = 13, KEPLER = 14, SHARED4 = 15, FOURTH_M4 = 16, FOURTH_M5 = 17, SHARED6 = 18, SHARED8 = 19, SHARED10 = 20, SHAREDBS = 21, CCC = 22, CCC_KEPLER = 23, CC_BS = 24, CCC_BS = 25, BS_CC_KEPLER = 26, CC_BSA = 27, CCC_BSA = 28, SHARED2_COLLISIONS = 29, SHARED4_COLLISIONS = 30, SHARED6_COLLISIONS = 31, SHARED8_COLLISIONS = 32, SHARED10_COLLISIONS = 33, CONSTANT2 = 34, CONSTANT4 = 35, CONSTANT6 = 36, CONSTANT8 = 37, CONSTANT10 = 38, ERROR_CONTROL=39, CC_SHARED10=40, CCC_SHARED10=41) for key, val in all_inttypes.items(): setattr(inttypes, key, val) def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = self.__interface__(**options) # self.legacy_doc = legacy_interface.__doc__ GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def set_integrator(self, name): return self.set_inttype_parameter(self.all_inttypes[name]) def get_integrator(self): value= self.get_inttype_parameter() for key, index in self.all_inttypes.items(): if value == index: return key return "unknown" def define_parameters(self, handler): self.stopping_conditions.define_parameters(handler) handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_timestep_parameter", "set_timestep_parameter", "timestep_parameter", "timestep parameter for gravity calculations", default_value = 0.03 ) handler.add_method_parameter( "get_timestep", "set_timestep", "timestep", "timestep for evolve calls", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_verbosity_parameter", "set_verbosity_parameter", "verbosity_parameter", "verbosity parameter (0 mean silent)", default_value = 0 ) handler.add_boolean_parameter( "get_accel_zero_mass_parameter", "set_accel_zero_mass_parameter", "accelerate_zero_mass", "accelerate zero mass particle interactions (should always be true, except for testing)", default_value = True ) inttypes=sorted([(getattr(self.inttypes,t),t ) for i,t in enumerate(sorted(self.inttypes._list()))]) handler.add_method_parameter( "get_inttype_parameter", "set_inttype_parameter", "inttype_parameter", "integrator method to use, this can be one of: "+ ",".join( ["{0}={1}".format(i, t) for i,t in inttypes]), #~ default_value = 8 ) handler.add_method_parameter( "get_integrator", "set_integrator", "integrator", "integrator method to use, this can be one of: "+ ",".join( ["{0}".format(t) for i,t in inttypes]), #~ default_value="HOLD_DKD" ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time to start the simulation at", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_opencl_device_type", "set_opencl_device_type", "opencl_device_type", "set preferred OpenCL device type (0=default, 1=cpu, 2=gpu)", default_value = 0 ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_timestep_parameter", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_timestep_parameter", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_timestep", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_timestep", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_inttype_parameter", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_inttype_parameter", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) handler.add_method('RUN', 'get_kinetic_energy') handler.add_method('RUN', 'get_potential_energy') self.stopping_conditions.define_state(handler)
14,167
34.331671
154
py
amuse
amuse-main/src/amuse/community/simplex/__init__.py
from .interface import Simplex
31
15
30
py
amuse
amuse-main/src/amuse/community/simplex/interface.py
import os.path from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community import * from amuse.support.options import option from amuse.datamodel import Particles class SimpleXInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ SimpleX(2.5) is a method for radiative transfer on an unstructured Delaunay grid. The grid samples the medium through which photons are transported in an optimal way for fast radiative transfer calculations. The relevant references are: .. [#] ADS:2011PhDT........13K (Kruip, C.J.H., Ph. D. thesis, University of Leiden (2011)) .. [#] ADS:2010PhDT........63P (Paardekooper, J.-P., Ph. D. thesis, University of Leiden (2010)) .. [#] ADS:2010A&A...515A..79P (Paardekooper, J.-P., Kruip, C.J.H., Icke, V. 2010, A&A, 515, A79 (SimpleX2)) .. [#] ADS:2006PhRvE..74b6704R (Ritzerveld, J., & Icke, V. 2006, Phys. Rev. E, 74, 26704 (SimpleX)) """ include_headers=['worker_code.h'] def __init__(self, **kwargs): CodeInterface.__init__(self, name_of_the_worker = "simplex_worker", **kwargs) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def set_simplex_output_directory(): function = LegacyFunctionSpecification() function.addParameter('output_path', dtype='string', direction=function.IN, description = "Name of the output directory") function.result_type = 'int32' return function @legacy_function def set_simplex_data_directory(): """ Update the path to the SimpleX database. """ function = LegacyFunctionSpecification() function.addParameter('data_directory', dtype='string', direction=function.IN, description = "Name of the SimpleX data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_simplex_data_directory(): """ Retrieve the path to the SimpleX database currently used. """ function = LegacyFunctionSpecification() function.addParameter('data_directory', dtype='string', direction=function.OUT, description = "Name of the SimpleX data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Value was retrieved -1 - ERROR Could not retrieve value """ return function @legacy_function def commit_particles(): """ Let the code perform initialization actions after all particles have been loaded in the model. Should be called before the first evolve call and after the last new_particle call. """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK Model is initialized and evolution can start -1 - ERROR Error happened during initialization, this error needs to be further specified by every code implemention """ return function @legacy_function def recommit_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) for x in ['x','y','z','rho','flux','xion','u']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter('metallicity', dtype='float64',direction=function.IN, default=0.0 ) function.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for x in ['x','y','z','rho','flux','xion','u']: function.addParameter(x, dtype='float64', direction=function.OUT) function.addParameter('metallicity', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the position from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('x', dtype='float64', direction=function.OUT, description = "The current x position of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current y position of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_flux(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the flux from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('flux', dtype='float64', direction=function.OUT, description = "The current flux of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_mean_intensity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the mean intensity from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('Js', dtype='float64', direction=function.OUT, description = "The current mean intensity of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_diffuse_intensity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the diffuse intensity from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('Jd', dtype='float64', direction=function.OUT, description = "The current diffuse intensity of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the density from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('rho', dtype='float64', direction=function.OUT, description = "The current density of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the internal energy from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('u', dtype='float64', direction=function.OUT, description = "The current internal energy of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_dinternal_energy_dt(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the d/dt internal energy from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('du_dt', dtype='float64', direction=function.OUT, description = "The current d/dt internal energy of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_ionisation(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the ionisation from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('xion', dtype='float64', direction=function.OUT, description = "The current ionisation of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_metallicity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the metallicity from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('metallicity', dtype='float64', direction=function.OUT, description = "The current metallicity of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def set_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for x in ['x','y','z','rho','flux','xion','u']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter('metallicity',dtype='float64',direction=function.IN,default=0.0) function.result_type = 'int32' return function @legacy_function def set_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the position for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('x', dtype='float64', direction=function.IN, description = "The new x position of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new y position of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_flux(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the flux for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('flux', dtype='float64', direction=function.IN, description = "The new flux of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the density for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('rho', dtype='float64', direction=function.IN, description = "The new density of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the internal energy for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('u', dtype='float64', direction=function.IN, description = "The new internal energy of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_dinternal_energy_dt(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the d/dt internal energy for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('du_dt', dtype='float64', direction=function.IN, description = "The new d/dt internal energy of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_ionisation(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the ionisation for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('xion', dtype='float64', direction=function.IN, description = "The new ionisation of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def set_metallicity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to set the metallicity for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('metallicity', dtype='float64', direction=function.IN, description = "The new metallicity of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN) # function.addParameter('synchronize', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_box_size(): function = LegacyFunctionSpecification() function.addParameter('box_size', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_box_size(): function = LegacyFunctionSpecification() function.addParameter('box_size', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_hilbert_order(): function = LegacyFunctionSpecification() function.addParameter('hilbert_order', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_hilbert_order(): function = LegacyFunctionSpecification() function.addParameter('hilbert_order', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_timestep(): function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_source_Teff(): function = LegacyFunctionSpecification() function.addParameter('sourceTeff', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_source_Teff(): function = LegacyFunctionSpecification() function.addParameter('sourceTeff', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_number_frequency_bins(): function = LegacyFunctionSpecification() function.addParameter('number_of_freq_bins', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_number_frequency_bins(): function = LegacyFunctionSpecification() function.addParameter('number_of_freq_bins', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_number_of_border_sites(): function = LegacyFunctionSpecification() function.addParameter('number_of_border_sites', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_number_of_border_sites(): function = LegacyFunctionSpecification() function.addParameter('number_of_border_sites', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_thermal_evolution(): function = LegacyFunctionSpecification() function.addParameter('thermal_evolution_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_thermal_evolution(): function = LegacyFunctionSpecification() function.addParameter('thermal_evolution_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_blackbody_spectrum(): function = LegacyFunctionSpecification() function.addParameter('blackbody_spectrum_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_blackbody_spectrum(): function = LegacyFunctionSpecification() function.addParameter('blackbody_spectrum_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_metal_cooling(): function = LegacyFunctionSpecification() function.addParameter('metal_cooling_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_metal_cooling(): function = LegacyFunctionSpecification() function.addParameter('metal_cooling_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_recombination_radiation(): function = LegacyFunctionSpecification() function.addParameter('recombination_radiation_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_recombination_radiation(): function = LegacyFunctionSpecification() function.addParameter('recombination_radiation_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_collisional_ionization(): function = LegacyFunctionSpecification() function.addParameter('collisional_ionisation_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_collisional_ionization(): function = LegacyFunctionSpecification() function.addParameter('collisional_ionisation_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function def synchronize_model(self): pass def auto_go_to_run(self): pass class GlSimpleXInterface(SimpleXInterface): include_headers=['worker_gl.h'] def __init__(self, **kwargs): CodeInterface.__init__(self,debug_with_gdb=False, name_of_the_worker = 'simplex_worker_gl', **kwargs) @legacy_function def start_viewer(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def stop_viewer(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function class SimpleXDoc(object): def __get__(self, instance, owner): return instance.legacy_interface.__doc__+"\n\n"+instance.parameters.__doc__ class SimpleX(CommonCode): __doc__ = SimpleXDoc() def __init__(self, **options): InCodeComponentImplementation.__init__(self, SimpleXInterface(**options)) self.set_simplex_output_directory(self.output_directory) self.set_simplex_data_directory(self.data_directory) def define_properties(self, handler): handler.add_property('get_time', public_name = "model_time") def define_parameters(self, handler): handler.add_method_parameter( "get_timestep", "set_timestep", "timestep", "timestep for radiative transfer sweeps", default_value = 0.05 | units.Myr ) handler.add_method_parameter( "get_source_Teff", "set_source_Teff", "source_effective_T", "effective temperature for sources", default_value = 1.e5 | units.K ) handler.add_method_parameter( "get_hilbert_order", "set_hilbert_order", "hilbert_order", "hilbert_order for domain decomposition", default_value = 1 ) handler.add_method_parameter( "get_number_frequency_bins", "set_number_frequency_bins", "number_of_freq_bins", "the number of bins of frequency", default_value = 1 ) handler.add_method_parameter( "get_thermal_evolution", "set_thermal_evolution", "thermal_evolution_flag", "solve full thermal evolution if 1", default_value = 0 ) handler.add_method_parameter( "get_metal_cooling", "set_metal_cooling", "metal_cooling_flag", "include cooling from metals if 1, not if zero", default_value = 0 ) handler.add_method_parameter( "get_recombination_radiation", "set_recombination_radiation", "recombination_radiation_flag", "include recombination radiation if 1, not if zero", default_value = 0 ) handler.add_method_parameter( "get_blackbody_spectrum", "set_blackbody_spectrum", "blackbody_spectrum_flag", "monochromatic if 0, blackbody_spectrum if 1", default_value = 0 ) handler.add_method_parameter( "get_collisional_ionization", "set_collisional_ionization", "collisional_ionization_flag", "not use collisional ionization if 0, do if 1", default_value = 0 ) handler.add_method_parameter( "get_box_size", "set_box_size", "box_size", "boxsize for radiative transfer particle distribution", default_value = 13200. | units.parsec ) handler.add_method_parameter( "get_simplex_data_directory", "set_simplex_data_directory", "simplex_data_directory", "Name of the SimpleX data directory", default_value = "." ) handler.add_method_parameter( "get_number_of_border_sites", "set_number_of_border_sites", "number_of_border_sites", "Number of border sites to generate on the boundary, needs to be a large number. These sites will be placed randomly outside the problem domain and will culled to create a closed boundary", default_value = 25000 ) def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method('evolve_model', (units.Myr,), ( handler.ERROR_CODE, )) handler.add_method( "new_particle", ( units.parsec, units.parsec, units.parsec, units.amu / units.cm**3, 1.0e48 / units.s, handler.NO_UNIT, units.cm**2 / units.s**2, handler.NO_UNIT ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "delete_particle", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state", ( handler.NO_UNIT, ), ( units.parsec, units.parsec, units.parsec, units.amu / units.cm**3, 1.0e48 / units.s, handler.NO_UNIT, units.cm**2 / units.s**2, handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_state", ( handler.NO_UNIT, units.parsec, units.parsec, units.parsec, units.amu / units.cm**3, 1.0e48 / units.s, handler.NO_UNIT, units.cm**2 / units.s**2, handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_internal_energy", ( handler.NO_UNIT, ), ( units.cm**2 / units.s**2, handler.ERROR_CODE ) ) handler.add_method( "set_internal_energy", ( handler.NO_UNIT, units.cm**2 / units.s**2, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_dinternal_energy_dt", ( handler.NO_UNIT, ), ( units.cm**2 / units.s**3, handler.ERROR_CODE ) ) handler.add_method( "set_dinternal_energy_dt", ( handler.NO_UNIT, units.cm**2 / units.s**3, ), ( handler.ERROR_CODE ) ) handler.add_method( "set_position", ( handler.NO_UNIT, units.parsec, units.parsec, units.parsec, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_position", ( handler.NO_UNIT, ), ( units.parsec, units.parsec, units.parsec, handler.ERROR_CODE ) ) handler.add_method( "set_density", ( handler.NO_UNIT, units.amu / units.cm**3, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_density", ( handler.NO_UNIT, ), ( units.amu / units.cm**3, handler.ERROR_CODE ) ) handler.add_method( "set_flux", ( handler.NO_UNIT, 1.0e48 / units.s, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_flux", ( handler.NO_UNIT, ), ( 1.0e48 / units.s, handler.ERROR_CODE ) ) handler.add_method( "get_mean_intensity", ( handler.NO_UNIT, ), ( 1.0e48 / units.s, handler.ERROR_CODE ) ) handler.add_method( "get_diffuse_intensity", ( handler.NO_UNIT, ), ( 1.0e48 / units.s, handler.ERROR_CODE ) ) handler.add_method( "set_ionisation", ( handler.NO_UNIT, handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_ionisation", ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_metallicity", ( handler.NO_UNIT, handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_metallicity", ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( 'commit_particles', (), (handler.ERROR_CODE) ) handler.add_method( 'recommit_particles', (), (handler.ERROR_CODE) ) handler.add_method( "get_timestep", (), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "set_timestep", (units.Myr, ), (handler.ERROR_CODE,) ) handler.add_method( "get_source_Teff", (), (units.K, handler.ERROR_CODE,) ) handler.add_method( "set_source_Teff", (units.K, ), (handler.ERROR_CODE,) ) handler.add_method( "get_hilbert_order", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_hilbert_order", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "set_blackbody_spectrum", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_blackbody_spectrum", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_thermal_evolution", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_thermal_evolution", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_collisional_ionization", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_collisional_ionization", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_number_frequency_bins", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_number_frequency_bins", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_metal_cooling", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_metal_cooling", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_recombination_radiation", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_recombination_radiation", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_box_size", (), (units.parsec, handler.ERROR_CODE,) ) handler.add_method( "set_box_size", (units.parsec, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (units.s,handler.ERROR_CODE,) ) handler.add_method( 'set_time', (units.s,), (handler.ERROR_CODE,) ) handler.add_method( "get_simplex_data_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_simplex_data_directory", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_particle') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_particle') handler.add_setter('particles', 'set_state') handler.add_getter('particles', 'get_state') handler.add_setter('particles', 'set_position') handler.add_getter('particles', 'get_position') handler.add_setter('particles', 'set_density') handler.add_getter('particles', 'get_density') handler.add_setter('particles', 'set_flux') handler.add_getter('particles', 'get_flux') handler.add_getter('particles', 'get_mean_intensity') handler.add_getter('particles', 'get_diffuse_intensity') handler.add_setter('particles', 'set_ionisation') handler.add_getter('particles', 'get_ionisation') handler.add_setter('particles', 'set_metallicity') handler.add_getter('particles', 'get_metallicity') handler.add_setter('particles', 'set_internal_energy') handler.add_getter('particles', 'get_internal_energy') handler.add_setter('particles', 'set_dinternal_energy_dt') handler.add_getter('particles', 'get_dinternal_energy_dt') def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter') handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter') handler.add_transition('UPDATE','CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE','UPDATE','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_method('EVOLVED','before_get_parameter') handler.add_method('EDIT', 'new_particle') handler.add_method('EDIT', 'delete_particle') handler.add_transition('EDIT', 'RUN', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_particle', False) handler.add_transition('RUN', 'UPDATE', 'delete_particle', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') handler.add_transition('RUN', 'EVOLVED', 'evolve_model', False) handler.add_method('EVOLVED', 'evolve_model') handler.add_transition('EVOLVED','RUN', 'synchronize_model') handler.add_method('RUN', 'synchronize_model') handler.add_method('RUN', 'get_state') handler.add_method('RUN', 'get_density') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_flux') handler.add_method('RUN', 'get_mean_intensity') handler.add_method('RUN', 'get_diffuse_intensity') handler.add_method('RUN', 'get_ionisation') handler.add_method('RUN', 'get_internal_energy') handler.add_method('RUN', 'set_dinternal_energy_dt') handler.add_method('RUN', 'get_dinternal_energy_dt') handler.add_method('UPDATE', 'set_dinternal_energy_dt') handler.add_method('UPDATE', 'get_dinternal_energy_dt') handler.add_method('INITIALIZED', 'set_hilbert_order') handler.add_method('INITIALIZED', 'set_box_size') handler.add_method('INITIALIZED', 'set_timestep') handler.add_method('INITIALIZED', 'set_source_Teff') handler.add_method('INITIALIZED', 'set_number_frequency_bins') handler.add_method('INITIALIZED', 'set_thermal_evolution') handler.add_method('INITIALIZED', 'set_blackbody_spectrum') handler.add_method('INITIALIZED', 'set_metal_cooling') handler.add_method('INITIALIZED', 'set_recombination_radiation') handler.add_method('INITIALIZED', 'set_collisional_ionization') class SimpleXSplitSet(SimpleX): def __init__(self,**options): SimpleX.__init__(self,**options) self.gas_particles=Particles() self.src_particles=Particles() def commit_particles(self): sites=self.gas_particles.copy() sites.flux=0. | units.s**-1 for p in self.src_particles: nearest=sites.find_closest_particle_to(p.x,p.y,p.z) nearest.flux+=p.luminosity self.particles.add_particles(sites) self.simplex_to_gas_channel=self.particles.new_channel_to(self.gas_particles) self.overridden().commit_particles() if hasattr(sites,"du_dt"): attributes=["du_dt"] channel=sites.new_channel_to(self.particles) channel.copy_attributes(attributes) del sites def recommit_particles(self): sites=self.gas_particles.copy() sites.flux=0. | units.s**-1 for p in self.src_particles: nearest=sites.find_closest_particle_to(p.x,p.y,p.z) nearest.flux+=p.luminosity # sites.synchronize_to(self.particles) add_set=sites.difference(self.particles) remove_set=self.particles.difference(sites) if len(remove_set)>0: self.particles.remove_particles(remove_set) if len(add_set)>0: self.particles.add_particles(add_set) self.overridden().recommit_particles() channel=sites.new_channel_to(self.particles) attributes=["x","y","z","rho","xion","u","flux"] if hasattr(sites,"metallicity"): attributes.append("metallicity") if hasattr(sites,"du_dt"): attributes.append("du_dt") channel.copy_attributes(attributes) del sites self.overridden().recommit_particles() def evolve_model(self,tend): self.overridden().evolve_model(tend) self.simplex_to_gas_channel.copy_attributes(["xion","u","metallicity"]) def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False) handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False) handler.add_transition('UPDATE','CHANGE_PARAMETERS_UPDATE','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE','UPDATE','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_method('EVOLVED','before_get_parameter') handler.add_method('RUNCOMMIT','before_get_parameter') handler.add_method('EDIT', 'new_particle') handler.add_method('EDIT', 'delete_particle') handler.add_transition('EDIT', 'RUNCOMMIT', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_particle', False) handler.add_transition('RUN', 'UPDATE', 'delete_particle', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') handler.add_transition('RUN','RUNCOMMIT', 'recommit_particles') handler.add_transition('RUNCOMMIT','RUN', 'auto_go_to_run') handler.add_transition('RUNCOMMIT', 'EVOLVED', 'evolve_model', False) # handler.add_method('EVOLVED', 'evolve_model') handler.define_state('RUNCOMMIT') handler.add_transition('EVOLVED','RUN', 'synchronize_model') handler.add_method('RUN', 'synchronize_model') handler.add_method('RUN', 'get_state') handler.add_method('RUN', 'get_density') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_flux') handler.add_method('RUN', 'get_ionisation') handler.add_method('RUN', 'get_internal_energy') handler.add_method('RUN', 'set_dinternal_energy_dt') handler.add_method('RUN', 'get_dinternal_energy_dt') handler.add_method('UPDATE', 'set_dinternal_energy_dt') handler.add_method('UPDATE', 'get_dinternal_energy_dt') handler.add_method('INITIALIZED', 'set_hilbert_order') handler.add_method('INITIALIZED', 'set_box_size') handler.add_method('INITIALIZED', 'set_timestep') handler.add_method('INITIALIZED', 'set_source_Teff') handler.add_method('INITIALIZED', 'set_number_frequency_bins') handler.add_method('INITIALIZED', 'set_thermal_evolution') handler.add_method('INITIALIZED', 'set_blackbody_spectrum') handler.add_method('INITIALIZED', 'set_metal_cooling') handler.add_method('INITIALIZED', 'set_recombination_radiation') handler.add_method('INITIALIZED', 'set_collisional_ionization') Simplex = SimpleX
48,398
35.555136
202
py
amuse
amuse-main/src/amuse/community/mmams/__init__.py
from .interface import Mmams
29
14
28
py
amuse
amuse-main/src/amuse/community/mmams/interface.py
import numpy from amuse.community import * from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.support.options import option from amuse.units import units from amuse.datamodel import Particle import os.path class MMAMSInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ MakeMeAMassiveStar is a computationally inexpensive method in which the merger process is approximated, including shock heating, hydrodynamic mixing and mass loss, with a simple algorithm based on conservation laws and a basic qualitative understanding of the hydrodynamics of stellar mergers. The algorithm relies on Archimedes' principle to dictate the distribution of the fluid in the stable equilibrium situation. Without the effects of microscopic mixing, the temperature and chemical composition profiles in a collision product can become double-valued functions of enclosed mass. Such an unphysical situation is mended by simulating microscopic mixing as a post-collision effect. Relevant references: .. [#] ADS:2008MNRAS.383L...5G (Gaburov E., Lombardi J. C. & Portegies Zwart S., 2008, MNRAS, 383, L5) """ include_headers = ['worker_code.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker = "mmams_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def new_particle(): """ Define a new particle in the stellar collision code. The particle is initialized as an empty model (with zero shells). The model has to be constructed shell by shell using `add_shell'. An index is returned that can be used to refer to this particle. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) function.addParameter('mass', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK new empty particle was created -1 - ERROR particle could not be created""" return function @legacy_function def delete_particle(): """ Remove a particle from the stellar collision code. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def add_shell(): """ Add a new shell to an existing particle in the stellar collision code. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('d_mass', dtype='float64', direction=function.IN, description = "The mass of the current shell of this particle") function.addParameter('cumul_mass', dtype='float64', direction=function.IN, description = "The cumulative mass from the center to the current shell of this particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of this shell") function.addParameter('density', dtype='float64', direction=function.IN, description = "The density of this shell") function.addParameter('pressure', dtype='float64', direction=function.IN, description = "The pressure of this shell") function.addParameter('temperature', dtype='float64', direction=function.IN, description = "The temperature of this shell") function.addParameter('luminosity', dtype='float64', direction=function.IN, description = "The luminosity of this shell") function.addParameter('molecular_weight', dtype='float64', direction=function.IN, description = "The molecular_weight of this shell") function.addParameter('H1', dtype='float64', direction=function.IN, description = "The H1 fraction of this shell") function.addParameter('He4', dtype='float64', direction=function.IN, description = "The He4 fraction of this shell") function.addParameter('C12', dtype='float64', direction=function.IN, description = "The C12 fraction of this shell") function.addParameter('N14', dtype='float64', direction=function.IN, description = "The N14 fraction of this shell") function.addParameter('O16', dtype='float64', direction=function.IN, description = "The O16 fraction of this shell") function.addParameter('Ne20', dtype='float64', direction=function.IN, description = "The Ne20 fraction of this shell") function.addParameter('Mg24', dtype='float64', direction=function.IN, description = "The Mg24 fraction of this shell") function.addParameter('Si28', dtype='float64', direction=function.IN, description = "The Si28 fraction of this shell") function.addParameter('Fe56', dtype='float64', direction=function.IN, description = "The Fe56 fraction of this shell") function.result_type = 'int32' function.result_doc = """ 0 - OK new shell was added to the specified particle -1 - ERROR specified particle was not found""" return function @legacy_function def get_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('number_of_particles', dtype='int32', direction=function.OUT, description = "The number of currently defined particles") function.result_type = 'int32' return function @legacy_function def get_number_of_zones(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('number_of_zones', dtype='int32', direction=function.OUT, description = "The number of currently defined shells of this particle") function.result_type = 'int32' return function @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='float64', unit=units.MSun, direction=function.OUT, description = "The total mass of this particle") function.result_type = 'int32' return function @legacy_function def get_stellar_model_element(): """ Return properties of the stellar model at a specific zone. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_zone', dtype='int32', direction=function.IN) function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('d_mass', dtype='float64', direction=function.OUT, description = "The mass of the current shell of this particle") function.addParameter('cumul_mass', dtype='float64', direction=function.OUT, description = "The cumulative mass from the center to the current shell of this particle") function.addParameter('radius', dtype='float64', direction=function.OUT, description = "The radius of this shell") function.addParameter('density', dtype='float64', direction=function.OUT, description = "The density of this shell") function.addParameter('pressure', dtype='float64', direction=function.OUT, description = "The pressure of this shell") function.addParameter('entropy', dtype='float64', direction=function.OUT, description = "The entropy of this shell") function.addParameter('temperature', dtype='float64', direction=function.OUT, description = "The temperature of this shell") function.addParameter('luminosity', dtype='float64', direction=function.OUT, description = "The luminosity of this shell") function.addParameter('molecular_weight', dtype='float64', direction=function.OUT, description = "The molecular_weight of this shell") function.addParameter('H1', dtype='float64', direction=function.OUT, description = "The H1 fraction of this shell") function.addParameter('He4', dtype='float64', direction=function.OUT, description = "The He4 fraction of this shell") function.addParameter('C12', dtype='float64', direction=function.OUT, description = "The C12 fraction of this shell") function.addParameter('N14', dtype='float64', direction=function.OUT, description = "The N14 fraction of this shell") function.addParameter('O16', dtype='float64', direction=function.OUT, description = "The O16 fraction of this shell") function.addParameter('Ne20', dtype='float64', direction=function.OUT, description = "The Ne20 fraction of this shell") function.addParameter('Mg24', dtype='float64', direction=function.OUT, description = "The Mg24 fraction of this shell") function.addParameter('Si28', dtype='float64', direction=function.OUT, description = "The Si28 fraction of this shell") function.addParameter('Fe56', dtype='float64', direction=function.OUT, description = "The Fe56 fraction of this shell") function.result_type = 'int32' return function @legacy_function def read_usm(): """ Define a new particle in the stellar collision code. Read the stellar model from a usm file. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) function.addParameter('usm_file', dtype='string', direction=function.IN, description = "The path to the usm file.") function.result_type = 'int32' return function @legacy_function def merge_two_stars(): """ Merge two previously defined particles. Returns an index to the new stellar model. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_product', dtype='int32', direction=function.OUT) function.addParameter('index_of_the_primary', dtype='int32', direction=function.IN) function.addParameter('index_of_the_secondary', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_dump_mixed_flag(): """Set the dump_mixed flag: specifies whether the returned products must be mixed first.""" function = LegacyFunctionSpecification() function.addParameter('dump_mixed_flag', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_dump_mixed_flag(): """Get the dump_mixed flag: specifies whether the returned products must be mixed first.""" function = LegacyFunctionSpecification() function.addParameter('dump_mixed_flag', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_mass_loss_do_const_flag(): """Set the dump_mixed flag: specifies whether the returned products must be mixed first.""" function = LegacyFunctionSpecification() function.addParameter('mass_loss_do_const_flag', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_mass_loss_do_const_flag(): """Get the dump_mixed flag: specifies whether the returned products must be mixed first.""" function = LegacyFunctionSpecification() function.addParameter('mass_loss_do_const_flag', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_const_mass_loss(): """Get the const_mass_loss""" function = LegacyFunctionSpecification() function.addParameter('const_mass_loss', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_const_mass_loss(): """Set the const_mass_loss""" function = LegacyFunctionSpecification() function.addParameter('const_mass_loss', dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_target_n_shells_mixing(): """Set the target number of shells for mixed models.""" function = LegacyFunctionSpecification() function.addParameter('target_n_shells_mixing', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_target_n_shells_mixing(): """Get the target number of shells for mixed models.""" function = LegacyFunctionSpecification() function.addParameter('target_n_shells_mixing', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_target_n_shells(): """Set the target number of shells for unmixed models.""" function = LegacyFunctionSpecification() function.addParameter('target_n_shells', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_target_n_shells(): """Get the target number of shells for unmixed models.""" function = LegacyFunctionSpecification() function.addParameter('target_n_shells', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_do_shock_heating_flag(): """Set the flag that specifies whether to solve for shock-heating.""" function = LegacyFunctionSpecification() function.addParameter('do_shock_heating_flag', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_do_shock_heating_flag(): """Get the flag that specifies whether to solve for shock-heating.""" function = LegacyFunctionSpecification() function.addParameter('do_shock_heating_flag', dtype='int32', direction=function.OUT) function.result_type = 'i' return function class MMAMS(CommonCode): stellar_evolution_code_required = True gravity_code_required = False def __init__(self, **options): InCodeComponentImplementation.__init__(self, MakeMeAMassiveStarInterface(**options), **options) self.create_new_key = True def get_create_new_key(self): return self.create_new_key def set_create_new_key(self, value): self.create_new_key = value def define_properties(self, handler): handler.add_property("get_number_of_particles") def define_parameters(self, handler): handler.add_method_parameter( "get_target_n_shells_mixing", "set_target_n_shells_mixing", "target_n_shells_mixing", "target number of shells for mixed models", default_value = 200 ) handler.add_method_parameter( "get_target_n_shells", "set_target_n_shells", "target_n_shells", "target number of shells for unmixed models", default_value = 10000 ) handler.add_boolean_parameter( "get_dump_mixed_flag", "set_dump_mixed_flag", "dump_mixed_flag", "dump_mixed flag: specifies whether the returned products must be mixed first", True ) handler.add_boolean_parameter( "get_mass_loss_do_const_flag", "set_mass_loss_do_const_flag", "mass_loss_do_const", "mass_loss_do_const flag: whether to use const mass loss fraction (True) or the original Gaburov 2008 fromulation", False ) handler.add_method_parameter( "get_const_mass_loss", "set_const_mass_loss", "constant_mass_loss", "if do_const=True, specify what the constant mass loss fraction used is", 0.1 ) handler.add_boolean_parameter( "get_do_shock_heating_flag", "set_do_shock_heating_flag", "do_shock_heating_flag", "do_shock_heating flag: specifies whether to solve for shock-heating", True ) handler.add_method_parameter( "get_create_new_key", "set_create_new_key", "create_new_key", "Flag to specify whether the merge product gets a new key, or the key of the most massive collider.", True ) def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method( "new_particle", (units.MSun,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "delete_particle", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "read_usm", (handler.NO_UNIT,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "add_shell", (handler.INDEX, units.MSun, units.MSun, units.RSun, units.g / units.cm**3, units.barye, units.K, units.LSun, units.amu, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_stellar_model_element", (handler.INDEX, handler.INDEX,), (units.MSun, units.MSun, units.RSun, units.g / units.cm**3, units.barye, handler.NO_UNIT, units.K, units.LSun, units.amu, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_number_of_zones", (handler.INDEX, ), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_number_of_particles", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "merge_two_stars", (handler.INDEX, handler.INDEX,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method("get_target_n_shells_mixing", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_target_n_shells_mixing", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_target_n_shells", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_target_n_shells", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_number_of_particles", (), (handler.NO_UNIT, handler.ERROR_CODE,)) def define_errorcodes(self, handler): handler.add_errorcode(-1, 'Unspecified, other error.') handler.add_errorcode(-2, 'Specified zone is undefined for this particle.') handler.add_errorcode(-3, 'A particle with the given index was not found.') def define_particle_sets(self, handler): handler.define_super_set('particles', ['native_stars', 'imported_stars', 'merge_products'], index_to_default_set = 0) handler.define_set('native_stars', 'index_of_the_particle') handler.set_new('native_stars', 'new_particle') handler.define_set('imported_stars', 'index_of_the_particle') handler.set_new('imported_stars', 'read_usm') handler.define_set('merge_products', 'index_of_the_particle') handler.set_new('merge_products', 'merge_stars') for particle_set_name in ['native_stars', 'imported_stars', 'merge_products']: handler.set_delete(particle_set_name, 'delete_particle') handler.add_getter(particle_set_name, 'get_number_of_zones') handler.add_getter(particle_set_name, 'get_mass') handler.add_method(particle_set_name, 'add_shell') handler.add_method(particle_set_name, 'get_stellar_model', 'get_internal_structure') def get_stellar_model(self, index_of_the_particle): if hasattr(index_of_the_particle, '__iter__'): return [self._create_new_grid(self._specify_stellar_model, index_of_the_particle = x) for x in index_of_the_particle] else: return self._create_new_grid(self._specify_stellar_model, index_of_the_particle = index_of_the_particle) def get_range_in_zones(self, index_of_the_particle): """ Returns the inclusive range of defined zones/mesh-cells of the star. """ return (0, self.get_number_of_zones(index_of_the_particle)-1) def _specify_stellar_model(self, definition, index_of_the_particle = 0): definition.set_grid_range('get_range_in_zones') definition.add_getter('get_stellar_model_element', names=('d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe')) definition.define_extra_keywords({'index_of_the_particle':index_of_the_particle}) def _key_to_index_in_code(self, key): if self.native_stars.has_key_in_store(key): return self.native_stars._subset([key]).index_in_code[0] elif self.imported_stars.has_key_in_store(key): return self.imported_stars._subset([key]).index_in_code[0] else: return self.merge_products._subset([key]).index_in_code[0] def merge_stars(self, primary, secondary): indices_of_primaries = [self._key_to_index_in_code(particle.key) for particle in primary] indices_of_secondaries = [self._key_to_index_in_code(particle.key) for particle in secondary] result = self.merge_two_stars( indices_of_primaries, indices_of_secondaries ) return result def match_composition_to_mass_profile(self, stellar_model, mass_profile): new_composition = numpy.array([[0.0]*len(mass_profile)]*8) current_index = 0 previous_mass = 0.0 | units.MSun for i, mass_i in enumerate(mass_profile): previous_index = current_index mass_fractions = [] | units.MSun while stellar_model.mass[current_index] < mass_i: mass_fractions.append(stellar_model.mass[current_index]-previous_mass) previous_mass = stellar_model.mass[current_index] current_index += 1 if stellar_model.mass[current_index] > mass_i: mass_fractions.append(mass_i-previous_mass) previous_mass = mass_i weights = mass_fractions / mass_fractions.sum() next_index = previous_index+len(weights) new_composition[0, i] = (stellar_model.X_H[previous_index:next_index]*weights).sum() new_composition[2, i] = (stellar_model.X_He[previous_index:next_index]*weights).sum() new_composition[3, i] = (stellar_model.X_C[previous_index:next_index]*weights).sum() new_composition[4, i] = (stellar_model.X_N[previous_index:next_index]*weights).sum() new_composition[5, i] = (stellar_model.X_O[previous_index:next_index]*weights).sum() new_composition[6, i] = (stellar_model.X_Ne[previous_index:next_index]*weights).sum() new_composition[7, i] = ((stellar_model.X_Mg[previous_index:next_index] + stellar_model.X_Si[previous_index:next_index] + stellar_model.X_Fe[previous_index:next_index])*weights).sum() return new_composition def key_for_merge_product(self, primary, secondary): if self.create_new_key: return None else: return primary.key if primary.mass > secondary.mass else secondary.key def handle_collision(self, primary, secondary, stellar_evolution_code=None, gravity_code=None): primary = self.add_particle_with_internal_structure(primary, stellar_evolution_code=stellar_evolution_code) secondary = self.add_particle_with_internal_structure(secondary, stellar_evolution_code=stellar_evolution_code) merge_product = Particle( key = self.key_for_merge_product(primary, secondary), primary = primary, secondary = secondary ) return self.merge_products.add_particles(merge_product.as_set()) def add_particle_with_internal_structure(self, particle, stellar_evolution_code=None): new = self.native_stars.add_particle(particle) if not stellar_evolution_code is None: particle = particle.as_set().get_intersecting_subset_in(stellar_evolution_code.particles)[0] number_of_zones = particle.get_number_of_zones() density_profile = particle.get_density_profile(number_of_zones = number_of_zones) radius_profile = particle.get_radius_profile(number_of_zones = number_of_zones) if hasattr(particle, "get_mass_profile"): mass_profile = particle.get_mass_profile(number_of_zones = number_of_zones)* particle.mass else: print("mass profile from density and radius") radii_cubed = radius_profile**3 radii_cubed.prepend(0|units.m**3) mass_profile = (4.0/3.0 * numpy.pi) * density_profile * (radii_cubed[1:] - radii_cubed[:-1]) if hasattr(particle, "get_cumulative_mass_profile"): cumul_mass_profile = particle.get_cumulative_mass_profile(number_of_zones = number_of_zones) * particle.mass else: print("cumulative mass profile from mass profile") cumul_mass_profile = mass_profile.accumulate() temperature_profile = particle.get_temperature_profile(number_of_zones = number_of_zones) #lum = particle.get_luminosity_profile(number_of_zones = number_of_zones) lum = numpy.zeros_like(temperature_profile) | units.LSun pressure_profile = particle.get_pressure_profile(number_of_zones = number_of_zones) mu_profile = particle.get_mu_profile(number_of_zones = number_of_zones) composition_profile = particle.get_chemical_abundance_profiles(number_of_zones = number_of_zones) new.add_shell(mass_profile, cumul_mass_profile, radius_profile, density_profile, pressure_profile, temperature_profile, lum, mu_profile, composition_profile[0], composition_profile[1]+composition_profile[2], composition_profile[3], composition_profile[4], composition_profile[5], composition_profile[6], composition_profile[7], composition_profile[7]*0.0, composition_profile[7]*0.0) return new MakeMeAMassiveStarInterface = MMAMSInterface MakeMeAMassiveStar = MMAMS Mmams = MMAMS
27,837
49.431159
175
py
amuse
amuse-main/src/amuse/community/mercury/__init__.py
from .interface import Mercury
31
15
30
py
amuse
amuse-main/src/amuse/community/mercury/interface.py
import os import numpy from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community import * from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.datamodel import Particles class MercuryInterface(CodeInterface, CommonCodeInterface, CodeWithDataDirectories, LiteratureReferencesMixIn, StoppingConditionInterface): """ Mercury N-body integrator package, version 6.2. Mercury is a general-purpose N-body integration package for problems in celestial mechanics. The standard symplectic (MVS) algorithm is described in Wisdom & Holman (1991). The hybrid symplectic algorithm is described in Chambers (1999). Relevant references: .. [#] ADS:1999MNRAS.304..793C (Chambers J. E., 1999, MNRAS, 304, 793) .. [#] ADS:1991AJ....102.1528W (Wisdom J. & Holman M., 1991, AJ, 102, 1528) """ use_modules = ['StoppingConditions', 'AmuseInterface'] def __init__(self, **args): CodeInterface.__init__(self, name_of_the_worker = 'mercury_worker',**args) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def recommit_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def synchronize_model(): """ After an evolve the particles may be at different simulation times. Synchronize the particles to a consistent stat at the current simulation time """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK """ return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_initial_timestep(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.IN, unit = units.day) function.result_type = 'i' return function @legacy_function def get_initial_timestep(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.OUT, unit = units.day) function.result_type = 'i' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def new_orbiter(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.OUT) for x in ['mass','density','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='float64', direction=function.IN) for x,default in zip(['lx','ly','lz','celimit'], [0,0,0,3]): function.addParameter(x, dtype='float64', direction=function.IN, default = default) function.result_type = 'int32' return function @legacy_function def new_central_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.OUT) for x in ['mass']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['radius','j2','j4','j6','lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def get_orbiter_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','density','x','y','z','vx','vy','vz','lx','ly','lz','celimit']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_orbiter_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','density','x','y','z','vx','vy','vz','lx','ly','lz','celimit']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_central_particle_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','radius','j2','j4','j6','lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_central_particle_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','radius','j2','j4','j6','lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN, description = "Index of the particle to get the position from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('x', dtype='float64', direction=function.OUT, description = "The current x position of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current y position of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def set_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN, description = "Index of the particle to set the position for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('x', dtype='float64', direction=function.IN, description = "The new x position of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new y position of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def get_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN, description = "Index of the particle to get the position from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The current x position of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current y position of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def set_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN, description = "Index of the particle to set the position for. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('vx', dtype='float64', direction=function.IN, description = "The new x position of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The new y position of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The new z position of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK new value was set -1 - ERROR particle could not be found """ return function @legacy_function def get_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('density', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('density', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_central_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_central_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_central_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_central_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_celimit(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('celimit', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_celimit(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('celimit', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_central_oblateness(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['j2','j4','j6']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_central_oblateness(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['j2','j4','j6']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_central_spin(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_central_spin(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_angularmomentum(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_angularmomentum(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['lx','ly','lz']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_number_of_orbiters(): function = LegacyFunctionSpecification() function.addParameter('norbiters', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_energy_deviation(): function = LegacyFunctionSpecification() function.addParameter('delta_e', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_kinetic_energy(): function = LegacyFunctionSpecification() function.addParameter('ek', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_potential_energy(): function = LegacyFunctionSpecification() function.addParameter('ep', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_total_energy(): function = LegacyFunctionSpecification() function.addParameter('e_tot', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_total_angular_momentum(): function = LegacyFunctionSpecification() function.addParameter('am_tot', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_begin_time(): """ Retrieve the model time to start the evolution at. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT, description = "The begin time", unit = units.day) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time was retrieved -2 - ERROR The code does not have support for querying the begin time """ return function @legacy_function def set_begin_time(): """ Set the model time to start the evolution at. This is an offset for all further calculations in the code. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN, description = "The model time to start at", unit = units.day) function.result_type = 'int32' function.result_doc = """ 0 - OK Time value was changed -2 - ERROR The code does not support setting the begin time """ return function @legacy_function def get_integrator(): """ Retrieve the integrator (algor parameter) """ function = LegacyFunctionSpecification() function.addParameter('integrator', dtype='i', direction=function.OUT, description = "integrator to use") function.result_type = 'int32' return function @legacy_function def set_integrator(): """ Set the model integrator (algor parameter) """ function = LegacyFunctionSpecification() function.addParameter('integrator', dtype='i', direction=function.IN, description = "integrator to use") function.result_type = 'int32' function.result_doc = """ 0 - OK integrator was changed -1 - ERROR integrator not supported (wrong input) """ return function @legacy_function def get_rmax(): """ Retrieve the maximal radius (rmax) -- heliocentric distance at which objects are considered ejected. """ function = LegacyFunctionSpecification() function.addParameter('rmax', dtype='float64', direction=function.OUT, description = "heliocentric distance at which objects are considered ejected", unit=units.AU) function.result_type = 'int32' return function @legacy_function def set_rmax(): """ Set the maximal radius (rmax) -- heliocentric distance at which objects are considered ejected. """ function = LegacyFunctionSpecification() function.addParameter('rmax', dtype='float64', direction=function.IN, description = "heliocentric distance at which objects are considered ejected", unit=units.AU) function.result_type = 'int32' return function @legacy_function def get_cefac(): """ Retrieve the parameter to set the changeover distance RCRIT of the hybrid integrator: RCRIT = cefac * R_HILL (n_1 in section 4.2 of Chambers 1999) """ function = LegacyFunctionSpecification() function.addParameter('cefac', dtype='float64', direction=function.OUT, description = "Hybrid integrator changeover radius RCRIT (in Hill radii)", unit=units.none) function.result_type = 'int32' return function @legacy_function def set_cefac(): """ Set the parameter to set the changeover distance RCRIT of the hybrid integrator: RCRIT = cefac * R_HILL (n_1 in section 4.2 of Chambers 1999) """ function = LegacyFunctionSpecification() function.addParameter('cefac', dtype='float64', direction=function.IN, description = "Hybrid integrator changeover radius RCRIT (in Hill radii)", unit=units.none) function.result_type = 'int32' return function @legacy_function def get_elements_file(): function = LegacyFunctionSpecification() function.addParameter('elements_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_elements_file(): function = LegacyFunctionSpecification() function.addParameter('elements_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_close_encounters_file(): function = LegacyFunctionSpecification() function.addParameter('close_encounters_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_close_encounters_file(): function = LegacyFunctionSpecification() function.addParameter('close_encounters_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_info_file(): function = LegacyFunctionSpecification() function.addParameter('info_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_info_file(): function = LegacyFunctionSpecification() function.addParameter('info_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bigbody_file(): function = LegacyFunctionSpecification() function.addParameter('bigbody_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bigbody_file(): function = LegacyFunctionSpecification() function.addParameter('bigbody_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_smallbody_file(): function = LegacyFunctionSpecification() function.addParameter('smallbody_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_smallbody_file(): function = LegacyFunctionSpecification() function.addParameter('smallbody_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_integration_parameters_file(): function = LegacyFunctionSpecification() function.addParameter('integration_parameters_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_integration_parameters_file(): function = LegacyFunctionSpecification() function.addParameter('integration_parameters_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_restart_file(): function = LegacyFunctionSpecification() function.addParameter('restart_file', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_restart_file(): function = LegacyFunctionSpecification() function.addParameter('restart_file', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gravity_at_point(): """ Get the gravitational acceleration at the given points. To calculate the force on bodies at those points, multiply with the mass of the bodies """ function = LegacyFunctionSpecification() for x in ['eps','x','y','z']: function.addParameter( x, dtype='float64', direction=function.IN, unit=units.AU ) for x in ['ax','ay','az']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=units.AU/units.day**2 ) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_potential_at_point(): """ Determine the gravitational potential on any given point """ function = LegacyFunctionSpecification() for x in ['eps','x','y','z']: function.addParameter( x, dtype='float64', direction=function.IN, unit=units.AU ) for x in ['phi']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=units.AU**2/units.day**2 ) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function class MercuryDoc(object): def __get__(self, instance, owner): return instance.legacy_doc+"\n\n"+instance.parameters.__doc__ class MercuryWayWard(GravitationalDynamics): __doc__ = MercuryDoc() def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = MercuryInterface(**options) self.legacy_doc = legacy_interface.__doc__ GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def initialize_code(self): self.overridden().initialize_code() self.set_elements_file(os.devnull) self.set_close_encounters_file(os.devnull) self.set_info_file(os.devnull) self.set_bigbody_file(os.devnull) self.set_smallbody_file(os.devnull) self.set_integration_parameters_file(os.devnull) self.set_restart_file(os.devnull) def define_parameters(self, handler): handler.add_method_parameter( "get_time", None, "time", "current simulation time", default_value = 0.0 | units.day ) handler.add_method_parameter( "get_initial_timestep", "set_initial_timestep", "timestep", "initial timestep", default_value = 8.0 | units.day ) handler.add_method_parameter( "get_integrator", "set_integrator", "integrator", "integrator to use", default_value = 10 ) handler.add_method_parameter( "get_rmax", "set_rmax", "rmax", "heliocentric distance at for ejection", default_value = 100. | units.AU ) handler.add_method_parameter( "get_cefac", "set_cefac", "cefac", "Hybrid integrator changeover radius RCRIT (in Hill radii)", default_value = 3. | units.none ) handler.add_method_parameter( "get_elements_file", "set_elements_file", "elements_file", "outputfile for mercury data (orbital elements) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_close_encounters_file", "set_close_encounters_file", "close_encounters_file", "outputfile for mercury data (close encounters) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_info_file", "set_info_file", "info_file", "outputfile for mercury data (info) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_bigbody_file", "set_bigbody_file", "bigbody_file", "dumpfile for mercury data (big bodies) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_smallbody_file", "set_smallbody_file", "smallbody_file", "dumpfile for mercury data (small bodies) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_integration_parameters_file", "set_integration_parameters_file", "integration_parameters_file", "dumpfile for mercury data (integration parameters) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_restart_file", "set_restart_file", "restart_file", "dumpfile for mercury data (restart data - only mercury internal state) [/dev/null]", default_value = None ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time to start the simulation at", default_value = 0.0 | units.day ) self.stopping_conditions.define_parameters(handler) def define_properties(self, handler): handler.add_property("get_kinetic_energy") handler.add_property("get_potential_energy") handler.add_property("get_total_energy") handler.add_property("get_center_of_mass_position") handler.add_property("get_center_of_mass_velocity") handler.add_property("get_total_mass") def define_state(self, handler): GravitationalDynamics.define_state(self, handler) handler.add_method('EDIT', 'new_central_particle') handler.add_method('EDIT', 'new_orbiter') handler.add_method('UPDATE', 'new_orbiter') handler.add_transition('RUN', 'UPDATE', 'new_central_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_orbiter', False) self.stopping_conditions.define_state(handler) def define_particle_sets(self, handler): handler.define_super_set('particles', ['central_particle','orbiters'], index_to_default_set=0) handler.define_set('orbiters', 'id') handler.set_new('orbiters', 'new_orbiter') handler.set_delete('orbiters', 'delete_particle') handler.add_setter('orbiters', 'set_orbiter_state') handler.add_getter('orbiters', 'get_orbiter_state') handler.add_setter('orbiters', 'set_mass') handler.add_getter('orbiters', 'get_mass') handler.add_setter('orbiters', 'set_density') handler.add_getter('orbiters', 'get_density') handler.add_setter('orbiters', 'set_position') handler.add_getter('orbiters', 'get_position') handler.add_setter('orbiters', 'set_velocity') handler.add_getter('orbiters', 'get_velocity') handler.add_setter('orbiters', 'set_angularmomentum') handler.add_getter('orbiters', 'get_angularmomentum') handler.add_setter('orbiters', 'set_celimit') handler.add_getter('orbiters', 'get_celimit') handler.define_set('central_particle', 'id') handler.set_new('central_particle', 'new_central_particle') handler.add_setter('central_particle', 'set_central_particle_state') handler.add_getter('central_particle', 'get_central_particle_state') handler.add_setter('central_particle', 'set_central_mass') handler.add_getter('central_particle', 'get_central_mass') handler.add_setter('central_particle', 'set_central_radius') handler.add_getter('central_particle', 'get_central_radius') handler.add_setter('central_particle', 'set_central_oblateness') handler.add_getter('central_particle', 'get_central_oblateness') handler.add_setter('central_particle', 'set_central_spin') handler.add_getter('central_particle', 'get_central_spin') #GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) def define_methods(self, handler): #GravitationalDynamics.define_methods(self, handler) handler.add_method('evolve_model', (units.day), ( handler.ERROR_CODE, )) handler.add_method( 'new_orbiter', ( units.MSun, units.g/units.cm**3, units.AU, units.AU, units.AU, units.AUd, units.AUd, units.AUd, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.NO_UNIT ), ( handler.INDEX, handler.ERROR_CODE ) ) handler.add_method( 'get_orbiter_state', ( handler.INDEX, ), ( units.MSun, units.g/units.cm**3, units.AU, units.AU, units.AU, units.AUd, units.AUd, units.AUd, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( 'get_central_particle_state', ( handler.INDEX, ), ( units.MSun, units.AU, units.AU**2, units.AU**4, units.AU**6, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.ERROR_CODE ) ) handler.add_method( 'set_orbiter_state', ( handler.INDEX, units.MSun, units.g/units.cm**3, units.AU, units.AU, units.AU, units.AUd, units.AUd, units.AUd, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( 'new_central_particle', ( units.MSun, units.AU, units.AU**2, units.AU**4, units.AU**6, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day ), ( handler.INDEX, handler.ERROR_CODE ) ) handler.add_method( 'set_central_particle_state', ( handler.INDEX, units.MSun, units.AU, units.AU**2, units.AU**4, units.AU**6, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day ), ( handler.ERROR_CODE ) ) handler.add_method( "set_initial_timestep", ( units.day, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_initial_timestep", ( ), ( units.day, handler.ERROR_CODE ) ) handler.add_method( "set_mass", ( handler.INDEX, units.MSun, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_mass", ( handler.INDEX, ), ( units.MSun, handler.ERROR_CODE ) ) handler.add_method( "set_central_mass", ( handler.INDEX, units.MSun, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_central_mass", ( handler.INDEX, ), ( units.MSun, handler.ERROR_CODE ) ) #assuming celimit is RCEH, clouse-encounter limit #expressed in units Hill radius, I use unit none #see comments in: src/mercury_main.for handler.add_method( "set_celimit", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_celimit", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_position", ( handler.INDEX, units.AU, units.AU, units.AU, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_position", ( handler.INDEX, ), ( units.AU, units.AU, units.AU, handler.ERROR_CODE ) ) handler.add_method( "set_velocity", ( handler.INDEX, units.AUd, units.AUd, units.AUd, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_velocity", ( handler.INDEX, ), ( units.AUd, units.AUd, units.AUd, handler.ERROR_CODE ) ) handler.add_method( "set_angularmomentum", ( handler.INDEX, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_angularmomentum", ( handler.INDEX, ), ( units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.ERROR_CODE ) ) handler.add_method( "set_central_spin", ( handler.INDEX, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_central_spin", ( handler.INDEX, ), ( units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, units.MSun * units.AU**2/units.day, handler.ERROR_CODE ) ) handler.add_method( 'set_density', ( handler.INDEX, units.g/units.cm**3 ), ( handler.ERROR_CODE ) ) handler.add_method( 'get_density', ( handler.INDEX, ), ( units.g/units.cm**3, handler.ERROR_CODE ) ) handler.add_method( 'get_central_oblateness', ( handler.INDEX, ), ( units.AU**2, units.AU**4, units.AU**6, handler.ERROR_CODE ) ) handler.add_method( 'set_central_oblateness', ( handler.INDEX, units.AU**2, units.AU**4, units.AU**6, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_central_radius', ( handler.INDEX, ), ( units.AU, handler.ERROR_CODE ) ) handler.add_method( 'set_central_radius', ( handler.INDEX, units.AU, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_time", (), (units.day, handler.ERROR_CODE,) ) handler.add_method( "get_kinetic_energy", (), (units.MSun*units.AU**2/units.day**2, handler.ERROR_CODE,) ) handler.add_method( "get_total_angular_momentum", (), (units.MSun*units.AU**2/units.day, handler.ERROR_CODE,) ) handler.add_method( "get_potential_energy", (), (units.MSun*units.AU**2/units.day**2, handler.ERROR_CODE,) ) handler.add_method( "get_total_energy", (), (units.MSun*units.AU**2/units.day**2, handler.ERROR_CODE,) ) handler.add_method( "get_center_of_mass_position", (), (units.AU, units.AU, units.AU, handler.ERROR_CODE,) ) handler.add_method( "get_center_of_mass_velocity", (), (units.AUd, units.AUd, units.AUd, handler.ERROR_CODE,) ) handler.add_method( "get_total_mass", (), (units.MSun, handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) class Mercury(MercuryWayWard): def __init__(self, *args, **kargs): MercuryWayWard.__init__(self, *args, **kargs) self._particles=Particles(0) self.model_time=0.|units.s self.particles_accessed=True self.committed=False def define_parameters(self, handler): MercuryWayWard.define_parameters(self,handler) handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | units.AU * units.AU ) def get_eps2(self): return 0|units.AU * units.AU def set_eps2(self, eps2): if eps2.number!=0: raise Exception("Mercury cannot use non-zero smoothing") def get_number_of_particles(self): return len(self.particles) def get_total_radius(self): max_dist2 = 0|units.AU * units.AU for p in self.particles: dist2 = p.x*p.x + p.y*p.y + p.z*p.z if dist2 > max_dist2: max_dist2 = dist2 return ((max_dist2.number**0.5)|units.AU) @property def particles(self): if not self.particles_accessed: self.particles_accessed=True return self._particles @property def total_mass(self): return self.particles.total_mass() def get_center_of_mass_position(self): return self.particles.center_of_mass() def get_center_of_mass_velocity(self): return self.particles.center_of_mass_velocity() def commit_particles(self): N=len(self.particles) if N<=1: print("too few particles") return -11 ic=self.particles.mass.argmax() self.central_particle=self.particles[ic] orbiters=(self.particles-self.central_particle).copy() maxmass=orbiters.mass.amax() if (maxmass/self.central_particle.mass) > 0.1: print("orbiters too massive") return -12 orbiters.position=orbiters.position-self.central_particle.position orbiters.velocity=orbiters.velocity-self.central_particle.velocity # note: lx,ly,lz, celimit? if not hasattr(orbiters,'density'): orbiters.density=orbiters.mass*3/(4*numpy.pi)/orbiters.radius**3 self.overridden().central_particle.add_particle(self.central_particle) self.overridden().orbiters.add_particles(orbiters) self.overridden().commit_particles() # commit_particles may already change the particle positions (I think it doesn't though) """ com_position=self.particles.center_of_mass() com_velocity=self.particles.center_of_mass_velocity() self.particles.position=self.particles.position-self.central_particle.position self.particles.velocity=self.particles.velocity-self.central_particle.velocity channel=self.overridden().orbiters.new_channel_to(self.particles) channel.copy_attributes(["x","y","z","vx","vy","vz","mass"]) self.particles.move_to_center() self.particles.position+=com_position self.particles.velocity+=com_velocity """ self.model_time=self.overridden().get_time() self.committed=True self.particles_accessed=False return 0 def recommit_particles(self): if not self.particles_accessed: return 0 if self.overridden().central_particle[0] not in self.particles: raise Exception("you are not allowed to remove the central particle") # these are allowed now if self.overridden().central_particle[0].mass != self.central_particle.mass: self.overridden().central_particle.mass=self.central_particle.mass if self.overridden().central_particle.radius != self.central_particle.radius: self.overridden().central_particle.radius=self.central_particle.radius orbiters=(self.particles-self.central_particle).copy() maxmass=orbiters.mass.amax() if (maxmass/self.central_particle.mass) > 0.1: print("orbiters too massive") return -12 orbiters.position=orbiters.position-self.central_particle.position orbiters.velocity=orbiters.velocity-self.central_particle.velocity if not hasattr(orbiters,'density'): orbiters.density=orbiters.mass*3/(4*numpy.pi)/orbiters.radius**3 # note: lx,ly,lz, celimit? orbiters.synchronize_to(self.overridden().orbiters) channel=orbiters.new_channel_to(self.overridden().orbiters) channel.copy_attributes(["x","y","z","vx","vy","vz","mass","density"]) self.overridden().recommit_particles() # recommit_particles could already change the particle positions (I think it doesn't though) """ com_position=self.particles.center_of_mass() com_velocity=self.particles.center_of_mass_velocity() channel=self.overridden().orbiters.new_channel_to(self.particles) channel.copy_attributes(["x","y","z","vx","vy","vz","mass"]) self.central_particle.position*=0 self.central_particle.velocity*=0 self.particles.move_to_center() self.particles.position+=com_position self.particles.velocity+=com_velocity """ self.model_time=self.overridden().get_time() self.particles_accessed=False return 0 def evolve_model(self, tend): if self.particles_accessed: if not self.committed: ret=self.commit_particles() else: ret=self.recommit_particles() com_position=self.particles.center_of_mass() com_velocity=self.particles.center_of_mass_velocity() ret=self.overridden().evolve_model(tend) tmodel=self.overridden().get_time() com_position+=com_velocity*(tmodel-self.model_time) self.model_time=tmodel channel=self.overridden().orbiters.new_channel_to(self.particles) channel.copy_attributes(["x","y","z","vx","vy","vz","mass"]) self.central_particle.position*=0 self.central_particle.velocity*=0 self.particles.move_to_center() self.particles.position+=com_position self.particles.velocity+=com_velocity self.particles_accessed=False return ret def get_potential_at_point(self,eps,x,y,z): if self.particles_accessed: if not self.committed: ret=self.commit_particles() else: ret=self.recommit_particles() xx=x-self.central_particle.x yy=y-self.central_particle.y zz=z-self.central_particle.z return self.overridden().get_potential_at_point(eps,xx,yy,zz) def get_gravity_at_point(self,eps,x,y,z): if self.particles_accessed: if not self.committed: ret=self.commit_particles() else: ret=self.recommit_particles() xx=x-self.central_particle.x yy=y-self.central_particle.y zz=z-self.central_particle.z return self.overridden().get_gravity_at_point(eps,xx,yy,zz) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) handler.add_method('EDIT', 'new_central_particle') handler.add_method('EDIT', 'new_orbiter') handler.add_method('UPDATE', 'new_orbiter') handler.add_transition('RUN', 'UPDATE', 'new_central_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_orbiter', False) handler.add_method('RUN', 'recommit_particles') def cleanup_code(self): self._particles=Particles(0) self.model_time=0.|units.s self.particles_accessed=True self.committed=False
52,295
33.679045
154
py
amuse
amuse-main/src/amuse/community/nbody6xx/phigrape.py
import re from amuse.units import units from amuse.units import nbody_system from amuse import datamodel """ fileformat: =========== diskstep # diskstep is used to number out, should be 0 for input dat N # number of particles time # current time, usually starts with 0.0 index mass x y z vx vy vz # N data lines where # index is a running particle index starting at 0! # mass is the mass of a particle # x y z are the x-, y-, and z- positions # vx vy vz are velocities components """ LINEFORMAT16 = "{particle_index:8d} {mass:0.16E} {x: 0.16E} {y: 0.16E} {z: 0.16E} {vx: 0.16E} {vy: 0.16E} {vz: 0.16E}\n" LINEFORMAT8 = "{particle_index:8d} {mass:0.8E} {x: 0.8E} {y: 0.8E} {z: 0.8E} {vx: 0.8E} {vy: 0.8E} {vz: 0.8E}\n" HEADER = "0\n{no_particles:d}\n{current_time}:f\n" class Particles2Inp(object): def __init__(self): self.string = "" def __str__(self): return self.string def convert_to_inp(self, Particles, time, filename): self.no_particles = len(Particles) self.string += HEADER.format(no_particles=self.no_particles, current_time=time) masses = Particles.mass.value_in(nbody_system.mass) velocities = Particles.velocity.value_in(nbody_system.speed) positions = Particles.position.value_in(nbody_system.length) for i in range(self.no_particles): self.string += LINEFORMAT16.format(particle_index = i, mass = masses[i], x = positions[i][0], y = positions[i][1], z = positions[i][2], vx = velocities[i][0], vy = velocities[i][1], vz = velocities[i][2]) f = open(filename, 'w') f.write(self.string) f.close() class Inp2Particles(object): def __init__(self): pass def parse_int_from_group(self): pass def get_values_from_phase_line(self, line): """ The regexp is grouping, therefore we add strings in the following code.. """ values = re.findall('([-+])?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?',line) args = () n = int(values[0][1]) m = float(values[1][1]+values[1][3]) x = float(values[2][0]+values[2][1]+values[2][3]) y = float(values[3][0]+values[3][1]+values[3][3]) z = float(values[4][0]+values[4][1]+values[4][3]) vx = float(values[5][0]+values[5][1]+values[5][3]) vy = float(values[6][0]+values[6][1]+values[6][3]) vz = float(values[7][0]+values[7][1]+values[7][3]) return n, m, x, y, z, vx, vy, vz def read_to_ram(self, inputfile): f = open(inputfile,'r') lines = f.readlines() f.close() N_particles = int(lines[1]) Particles = datamodel.Particles(N_particles) for i, line in enumerate(lines): if i<3: pass#handle header else: n, m, x, y, z, vx, vy, vz = self.get_values_from_phase_line(line) Particles[n].mass = m | nbody_system.mass Particles[n].x = x |nbody_system.length Particles[n].y = y |nbody_system.length Particles[n].z = z |nbody_system.length Particles[n].vx = vx |nbody_system.speed Particles[n].vy = vy |nbody_system.speed Particles[n].vz = vz |nbody_system.speed return Particles def convert_to_particles(self, inputfile, converter = None): self.Particles = self.read_to_ram(inputfile) if not converter==None: self.Particles=datamodel.ParticlesWithUnitsConverted(self.Particles, converter.as_converter_from_si_to_generic())
4,248
37.627273
126
py
amuse
amuse-main/src/amuse/community/nbody6xx/interface_new.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode class Nbody6xxInterface(CodeInterface, GravitationalDynamicsInterface, GravitationalDynamics, GravityFieldInterface, GravityFieldCode): include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="nbody6xx_worker", **keyword_arguments) @legacy_function def main(): function = LegacyFunctionSpecification() #function.addParameter('int_in', dtype='int32', direction=function.IN) #function.addParameter('int_out', dtype='int32', direction=function.OUT) #function.result_type = 'int32' function.can_handle_array = True return function class Nbody6xx(InCodeComponentImplementation): def __init__(self): InCodeComponentImplementation.__init__(self, nbody6xxInterface())
1,140
33.575758
95
py
amuse
amuse-main/src/amuse/community/nbody6xx/__init__.py
# generated file from .interface import Nbody6xx
49
15.666667
31
py
amuse
amuse-main/src/amuse/community/nbody6xx/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode class Nbody6xxInterface( CodeInterface, GravitationalDynamicsInterface, GravityFieldInterface ): use_modules = ['AMUSE_INTERFACE'] include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="nbody6xx_worker", **keyword_arguments) @legacy_function def main(): function = LegacyFunctionSpecification() function.addParameter('int_in', dtype='int32', direction=function.IN) function.addParameter('int_out', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def set_kz(): function = LegacyFunctionSpecification() function.addParameter('kz_option', dtype='int32', direction=function.IN) function.addParameter('val', dtype='float64', direction=function.IN) function.result_type = 'int32' function.can_handle_array = False return function @legacy_function def get_kz(): function = LegacyFunctionSpecification() function.addParameter('kz_option', dtype='int32', direction=function.IN) function.addParameter('val', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = False return function @legacy_function def set_eta(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_etai(): """ Set the current irregular force time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('etai', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_etai(): """ Get the current system irregular force time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('etai', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_etar(): """ Set the current regular force time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('etar', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_etar(): """ Get the current system regular force time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('etar', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_rbar(): """ Set the scaling unit in parsec for one N-body unit of length. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.IN, unit=units.parsec) function.result_type = 'int32' return function @legacy_function def get_rbar(): """ Get the scaling unit in parsec for one N-body unit of length. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.OUT, unit=units.parsec) function.result_type = 'int32' return function @legacy_function def set_zmbar(): """ Set the scaling unit for average particle mass in solar masses. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.IN,unit=units.MSun) function.result_type = 'int32' return function @legacy_function def get_zmbar(): """ Get the scaling unit for average particle mass in solar masses. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.OUT,unit=units.MSun) function.result_type = 'int32' return function @legacy_function def set_qe(): """ Set the relative energy error tolerance. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_qe(): """ Get the relative energy error tolerance. """ function = LegacyFunctionSpecification() function.addParameter('val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function class Nbody6xx(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody = None, **kargs): GravitationalDynamics.__init__(self, Nbody6xxInterface(**kargs), convert_nbody, **kargs) # RBAR= virial radius in parsec # ZMBAR= mean particle mass in solar units # if convert_nbody is not None: # self.parameters.RBAR=convert_nbody.to_si(1 | nbody_system.length) # self.parameters.ZMBAR=convert_nbody.to_si(1 | nbody_system.mass) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) handler.add_method('RUN', 'get_particle_timestep') GravityFieldCode.define_state(self, handler) handler.add_method('EDIT', 'set_state') handler.add_method('EDIT', 'set_velocity') handler.add_method('EDIT', 'set_mass') handler.add_method('EDIT', 'set_position') handler.add_method('CHANGED','before_get_parameter') handler.add_transition('RUN', 'CHANGED', 'set_state', False) handler.add_transition('RUN', 'CHANGED', 'set_velocity', False) handler.add_transition('RUN', 'CHANGED', 'set_mass', False) handler.add_transition('RUN', 'CHANGED', 'set_position', False) handler.add_transition('CHANGED', 'RUN', 'synchronize_model') handler.add_method('CHANGED', 'get_state') handler.add_method('CHANGED', 'get_mass') handler.add_method('CHANGED', 'get_position') handler.add_method('CHANGED', 'get_velocity') handler.add_method('CHANGED', 'get_particle_timestep') def define_parameters(self, handler): # Set/get parameters specific to the module, not part of the # standard interface. Accessors used here must be defined # above and reflected in interface.cc. Python access is # (e.g.) # # ph4.parameters.timestep_parameter = xxx handler.add_method_parameter( "get_eta", # getter name in interface.cc "set_eta", # setter name in interface.cc "timestep_parameter", # python parameter name "timestep parameter", # description default_value = 0.05 ) handler.add_method_parameter( "get_eps2", # already defined in standard interface "set_eps2", # already defined in standard interface "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time to start the simulation at", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_qe", "set_qe", "QE", "Relative energy error tolerance", default_value = 2.0E-4 ) handler.add_method_parameter( "get_rbar", "set_rbar", "RBAR", "The scaling unit in parsec for one N-body unit of length", default_value = 1.0 | units.parsec ) handler.add_method_parameter( "get_zmbar", "set_zmbar", "ZMBAR", "The scaling unit for average particle mass in solar masses", default_value = 0.7 | units.MSun ) #self.stopping_conditions.define_parameters(handler) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) # Turn interface functions into methods. handler.add_method( "set_eps2", ( nbody_system.length * nbody_system.length ), ( handler.ERROR_CODE ) ) handler.add_method( "get_eps2", (), ( nbody_system.length * nbody_system.length, handler.ERROR_CODE ) )
10,090
32.976431
97
py
amuse
amuse-main/src/amuse/community/nbody6xx/debug.py
from amuse.lab import * from .interface import Nbody6xx from amuse.units import nbody_system if __name__ == "__main__": inst = Nbody6xx(redirection="none") inst.initialize_code() inst.particles.mass = 1 | nbody_system.mass inst.evolve_model(2|nbody_system.time) inst.get_velocity(1) inst.get_position(1) inst.get_number_of_particles() inst.get_total_mass() inst.get_total_radius() print(inst.particles) inst.particles.add_particles(new_plummer_model(10)) p=new_plummer_model(10) inst.new_particle(p[0].mass,p[0].x,p[0].y,p[0].z,p[0].vx,p[0].vy,p[0].vz,p[0].radius)
622
26.086957
89
py