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/src/amuse/community/galaxia/__init__.py
from .interface import Galaxia
31
15
30
py
amuse
amuse-main/src/amuse/community/galaxia/interface.py
""" Interface Definition for the galaxy models """ from amuse.units import units from amuse.community import CodeInterface from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community.interface.gd import GravityFieldCode from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification # note: angle units can be added (unit.rad) - however breaks current scripts class BarAndSpiralsInterface(CodeInterface, CommonCodeInterface): """ Galactic model of the Milky Way. The components of the Galaxy are: -- Axisymmetric part -- The axisymmetric component of the Galaxy has a bulge, disk and a dark matter halo. the potentials and parameters associated with them are taken from Allen & Santillan (1991). In this code, the parameters of the axisymmetric part of the Galaxy are defined as: CENTRAL BULGE (spherical potential) mass_bulge: mass of the bulge b_bulge: scale height DISK(Miyamoto-Nagai potential) mass_disk: mass of the disk a_disk: scale lenght b_disk: scale height DARK MATTER HALO (logaritmic potential) mass_halo: mass of the halo a_halo: scale lenght -- Central bar--- The central bar of the Milky Way is modelled as a Ferrers bar with n=1 ( Romero-Gomez et al. 2007, A&A, 472, 63R; Romero-Gomez et al. 2011, MNRAS, 418, 1176R and references therein) The parameters to set the bar potential are: bar_contribution= True (default: false) The parameters of the bar that can be set in the code are: aaxis_bar: semi-major axis of the bar axis_ratio_bar: b/a bar_phase: initial orientation of the bar mass_bar: mass of the bar nbt: number of revolutions to obtain a bar. This is used to set an adiabatic growing bar (default: 0, bar already present in the potential) omega_bar: Pattern speed of the bar tgrowth_bar: if nbt is not 0, growing time of the bar. This value can be only obtained -- Spiral arms-- There are two models for the spiral arms, 2D TWA and 3D CG02 The parameters to set the spiral arm potential are: spiral_contribution= True (default: false) spiral_phase: Initial orientation of the arms rsigma: scale lenght of the spiral arms. m: number of arms -- 2D TWA-- the Tight Winding Approximation. The model and default parameters are set according to locus 2 in Antoja et al. 2011, MNRAS, 418, 1423A. The parameters of the TWA model that can be set in the code are: amplitude: amplitude of the perturbation rsp: starting radius of the spiral locus -- 3D spiral arms, Cox & Gomez 2002 (CG02) Model from Cox & Gomez 2002, ApJS, 142, 261 The parameters to set this spiral arm model are: spiral_model=1 (default:0 = 2D TWA) The parameters of the CG02 potential that can be set are: fiducial_radius scale_height spiral_density_amplitude --Transient spirals-- By now the prescription is to have several non overlapping spiral events. The transient spirals only can be set when the bar potential is also set. Parameters: transient_spiral= True (default: false) sigma_s: duration of the transient event t_sim: total simulation time """ use_modules = ['BarAndSpiralsInterface'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="GalaxyModel_worker", **options) @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.kpc) for x in ['ax', 'ay', 'az']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=100*units.km**2 * units.s**-2/units.kpc ) 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.kpc ) for x in ['phi']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=100*units.km**2 * units.s**-2 ) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_local_density(): """ Retrieve the local stellar density at a given point """ function = LegacyFunctionSpecification() function.addParameter('t', dtype='float64', direction=function.IN, description="time", unit=97781310.5721*units.yr) function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('density', dtype='float64', direction=function.OUT, description="local density", unit=2.32e7*units.MSun/units.kpc**3) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_velcirc(): """ Retrieve the circular velocity due to the axisymmetric potetial at a given point """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('vel_circ', dtype='float64', direction=function.OUT, description="circular velocity", unit=10*units.km/units.s) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def get_epifreq(): """ Retrieve the epicyclic frequency due to the axisymmetric potetial at a given point """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('k', dtype='float64', direction=function.OUT, description="epicyclic freq", unit=10*units.kms) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_spiral_density(): """ Retrieve the density of the 3D spiral arms at a given point """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('dens', dtype='float64', direction=function.OUT, description="epicyclic freq", unit=2.32e7*units.MSun/units.kpc**3) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_tidal_tensor(): """ Retrieve the second derivatives of the total force at a given point and at a given time. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('t', dtype='float64', direction=function.IN, description="time", unit=97781310.5721*units.yr) function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('Fxx', dtype='float64', direction=function.OUT, description="fxx", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fyx', dtype='float64', direction=function.OUT, description="fyx", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fzx', dtype='float64', direction=function.OUT, description="fzx", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fxy', dtype='float64', direction=function.OUT, description="fxy", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fyy', dtype='float64', direction=function.OUT, description="fyy", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fzy', dtype='float64', direction=function.OUT, description="fzy", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fxz', dtype='float64', direction=function.OUT, description="fxz", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fyz', dtype='float64', direction=function.OUT, description="fyz", unit=100*units.kms**2/units.kpc**2) function.addParameter('Fzz', dtype='float64', direction=function.OUT, description="fzz", unit=100*units.kms**2/units.kpc**2) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_eigen_values(): """ Retrieve the eigen values of the tidal tensor. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('t', dtype='float64', direction=function.IN, description="time", unit=97781310.5721*units.yr) function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('lambda1', dtype='float64', direction=function.OUT, description="eigen values", unit=100*units.kms**2/units.kpc**2) function.addParameter('lambda2', dtype='float64', direction=function.OUT, description="eigen values", unit=100*units.kms**2/units.kpc**2) function.addParameter('lambda3', dtype='float64', direction=function.OUT, description="eigen values", unit=100*units.kms**2/units.kpc**2) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_tidal_radius(): """ Retrieve the tidal radius of a star cluster """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('t', dtype='float64', direction=function.IN, description="time", unit=97781310.5721*units.yr) function.addParameter('x', dtype='float64', direction=function.IN, description="x position", unit=units.kpc) function.addParameter('y', dtype='float64', direction=function.IN, description="y position", unit=units.kpc) function.addParameter('z', dtype='float64', direction=function.IN, description="z position", unit=units.kpc) function.addParameter('mc', dtype='float64', direction=function.IN, description="initial cluster mass", unit=2.32e7*units.MSun) function.addParameter('rt', dtype='float64', direction=function.OUT, description="tidal radius", unit=units.kpc) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' return function # The following functions set the constants from Amuse @legacy_function def set_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_omega_sys(): function = LegacyFunctionSpecification() function.addParameter('omega_system', dtype='float64', direction=function.OUT, unit=10*units.km/(units.s*units.kpc)) function.result_type = 'int32' return function @legacy_function def get_initial_phase(): function = LegacyFunctionSpecification() function.addParameter('initial_phase', dtype='float64', direction=function.OUT) # unit=units.rad function.result_type = 'int32' return function @legacy_function def get_flag(): function = LegacyFunctionSpecification() function.addParameter('xflag', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_flag(): function = LegacyFunctionSpecification() function.addParameter('xflag', dtype='float64', direction=function.IN) function.result_type = 'int32' return function # BAR @legacy_function def set_bar_phase(): function = LegacyFunctionSpecification() function.addParameter('bar_phase', dtype='float64', direction=function.IN) # unit=units.rad function.result_type = 'int32' return function @legacy_function def get_bar_phase(): function = LegacyFunctionSpecification() function.addParameter('bar_phase', dtype='float64', direction=function.OUT) # unit=units.rad function.result_type = 'int32' return function @legacy_function def set_mass_bar(): function = LegacyFunctionSpecification() function.addParameter('mass_bar', dtype='float64', direction=function.IN, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def get_mass_bar(): function = LegacyFunctionSpecification() function.addParameter('mass_bar', dtype='float64', direction=function.OUT, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def set_aaxis_bar(): function = LegacyFunctionSpecification() function.addParameter('aaxis_bar', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_aaxis_bar(): function = LegacyFunctionSpecification() function.addParameter('aaxis_bar', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_caxis_bar(): function = LegacyFunctionSpecification() function.addParameter('caxis_bar', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_caxis_bar(): function = LegacyFunctionSpecification() function.addParameter('caxis_bar', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_axis_ratio_bar(): function = LegacyFunctionSpecification() function.addParameter('axis_ratio_bar', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_axis_ratio_bar(): function = LegacyFunctionSpecification() function.addParameter('axis_ratio_bar', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_omega_bar(): function = LegacyFunctionSpecification() function.addParameter('omega_bar', dtype='float64', direction=function.IN, unit=10.*units.km/(units.s*units.kpc)) function.result_type = 'int32' return function @legacy_function def get_omega_bar(): function = LegacyFunctionSpecification() function.addParameter('omega_bar', dtype='float64', direction=function.OUT, unit=10.*units.km/(units.s*units.kpc)) function.result_type = 'int32' return function @legacy_function def set_nbt(): function = LegacyFunctionSpecification() function.addParameter('nbt', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nbt(): function = LegacyFunctionSpecification() function.addParameter('nbt', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tin(): function = LegacyFunctionSpecification() function.addParameter('Tin', dtype='float64', direction=function.IN, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_tin(): function = LegacyFunctionSpecification() function.addParameter('Tin', dtype='float64', direction=function.OUT, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_tgrowth(): function = LegacyFunctionSpecification() function.addParameter('tgrowth_bar', dtype='float64', direction=function.OUT, unit=97781310.5721*units.yr) function.result_type = 'int32' return function # SPIRAL @legacy_function def set_spiral_phase(): function = LegacyFunctionSpecification() function.addParameter('spiral_phase', dtype='float64', direction=function.IN) # unit=units.rad function.result_type = 'int32' return function @legacy_function def get_spiral_phase(): function = LegacyFunctionSpecification() function.addParameter('spiral_phase', dtype='float64', direction=function.OUT) # unit=units.rad function.result_type = 'int32' return function @legacy_function def set_m(): function = LegacyFunctionSpecification() function.addParameter('m', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_m(): function = LegacyFunctionSpecification() function.addParameter('m', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tan_pitch_angle(): function = LegacyFunctionSpecification() function.addParameter('tan_pitch_angle', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tan_pitch_angle(): function = LegacyFunctionSpecification() function.addParameter('tan_pitch_angle', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_r_sigma(): function = LegacyFunctionSpecification() function.addParameter('r_sigma', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_r_sigma(): function = LegacyFunctionSpecification() function.addParameter('r_sigma', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_omega_spiral(): function = LegacyFunctionSpecification() function.addParameter('omega_spiral', dtype='float64', direction=function.IN, unit=10*units.kms/units.kpc) function.result_type = 'int32' return function @legacy_function def get_omega_spiral(): function = LegacyFunctionSpecification() function.addParameter('omega_spiral', dtype='float64', direction=function.OUT, unit=10*units.kms/units.kpc) function.result_type = 'int32' return function # TWA @legacy_function def set_N(): function = LegacyFunctionSpecification() function.addParameter('N', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_N(): function = LegacyFunctionSpecification() function.addParameter('N', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_rsp(): function = LegacyFunctionSpecification() function.addParameter('rsp', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_rsp(): function = LegacyFunctionSpecification() function.addParameter('rsp', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_amplitude(): function = LegacyFunctionSpecification() function.addParameter('amplitude', dtype='float64', direction=function.IN, unit=100*units.kms**2/units.kpc) function.result_type = 'int32' return function @legacy_function def get_amplitude(): function = LegacyFunctionSpecification() function.addParameter('amplitude', dtype='float64', direction=function.OUT, unit=100*units.kms**2/units.kpc) function.result_type = 'int32' return function # CG02 spiral arms @legacy_function def set_spiral_density_amplitude(): """ CG02 model spiral arms density amplitude, measured at fiducial radius rho_0 in eqn(1--3) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('spiral_density_amplitude', dtype='float64', direction=function.IN, unit=2.32e7*units.MSun/units.kpc**3, description='CG02 model spiral arms density amplitude, measured at fiducial radius') function.result_type = 'int32' return function @legacy_function def get_spiral_density_amplitude(): """ CG02 model spiral arms density amplitude, measured at fiducial radius rho_0 in eqn(1--3) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('spiral_density_amplitude', dtype='float64', direction=function.OUT, unit=2.32e7*units.MSun/units.kpc**3, description='CG02 model spiral arms density amplitude, measured at fiducial radius') function.result_type = 'int32' return function @legacy_function def set_fiducial_radius(): """ CG02 model fiducial radius where the density amplitude and initial phase are measured R_0 in eqn(1--3) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('fiducial_radius', dtype='float64', direction=function.IN, unit=units.kpc, description='CG02 model fiducial radius where the density amplitude and initial phase are measured') function.result_type = 'int32' return function @legacy_function def get_fiducial_radius(): """ CG02 model fiducial radius where the density amplitude and initial phase are measured R_0 in eqn(1--3) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('fiducial_radius', dtype='float64', direction=function.OUT, unit=units.kpc, description='CG02 model fiducial radius where the density amplitude and initial phase are measured') function.result_type = 'int32' return function @legacy_function def set_scale_height(): """ CG02 model spiral arms scale height H in eqn(1) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('scale_height', dtype='float64', direction=function.IN, unit=units.kpc, description='CG02 model spiral arms scale height') function.result_type = 'int32' return function @legacy_function def get_scale_height(): """ CG02 model spiral arms scale height H in eqn(1) of CG02 """ function = LegacyFunctionSpecification() function.addParameter('scale_height', dtype='float64', direction=function.OUT, unit=units.kpc, description='CG02 model spiral arms scale height') function.result_type = 'int32' return function # transcient spirals @legacy_function def set_t_sim(): function = LegacyFunctionSpecification() function.addParameter('t_sim', dtype='float64', direction=function.IN, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_t_sim(): function = LegacyFunctionSpecification() function.addParameter('t_sim', dtype='float64', direction=function.OUT, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def set_sigma_s(): function = LegacyFunctionSpecification() function.addParameter('sigma_s', dtype='float64', direction=function.IN, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def get_sigma_s(): function = LegacyFunctionSpecification() function.addParameter('sigma_s', dtype='float64', direction=function.OUT, unit=97781310.5721*units.yr) function.result_type = 'int32' return function @legacy_function def set_omega_spiral2(): function = LegacyFunctionSpecification() function.addParameter('omega_spiral2', dtype='float64', direction=function.IN, unit=10.*units.km/(units.s*units.kpc)) function.result_type = 'int32' return function @legacy_function def get_omega_spiral2(): function = LegacyFunctionSpecification() function.addParameter('omega_spiral2', dtype='float64', direction=function.OUT, unit=10.*units.km/(units.s*units.kpc)) function.result_type = 'int32' return function @legacy_function def set_amplitude2(): function = LegacyFunctionSpecification() function.addParameter('amplitude2', dtype='float64', direction=function.IN, unit=100*units.kms**2/units.kpc) function.result_type = 'int32' return function @legacy_function def get_amplitude2(): function = LegacyFunctionSpecification() function.addParameter('amplitude2', dtype='float64', direction=function.OUT, unit=100*units.kms**2/units.kpc) function.result_type = 'int32' return function @legacy_function def set_tan_pitch_angle2(): function = LegacyFunctionSpecification() function.addParameter('tan_pitch_angle2', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tan_pitch_angle2(): function = LegacyFunctionSpecification() function.addParameter('tan_pitch_angle2', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_m2(): function = LegacyFunctionSpecification() function.addParameter('m2', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_m2(): function = LegacyFunctionSpecification() function.addParameter('m2', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_phi21(): function = LegacyFunctionSpecification() function.addParameter('phi21_spiral', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_phi21(): function = LegacyFunctionSpecification() function.addParameter('phi21_spiral', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function # _____________________ AXI_____________________________________________ @legacy_function def set_mass_bulge(): function = LegacyFunctionSpecification() function.addParameter('mass_bulge', dtype='float64', direction=function.IN, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def get_mass_bulge(): function = LegacyFunctionSpecification() function.addParameter('mass_bulge', dtype='float64', direction=function.OUT, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def set_b_bulge(): function = LegacyFunctionSpecification() function.addParameter('b_bulge', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_b_bulge(): function = LegacyFunctionSpecification() function.addParameter('b_bulge', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_mass_disk(): function = LegacyFunctionSpecification() function.addParameter('mass_disk', dtype='float64', direction=function.IN, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def get_mass_disk(): function = LegacyFunctionSpecification() function.addParameter('mass_disk', dtype='float64', direction=function.OUT, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def set_a_disk(): function = LegacyFunctionSpecification() function.addParameter('a_disk', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_a_disk(): function = LegacyFunctionSpecification() function.addParameter('a_disk', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_b_disk(): function = LegacyFunctionSpecification() function.addParameter('b_disk', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_b_disk(): function = LegacyFunctionSpecification() function.addParameter('b_disk', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def set_mass_halo(): function = LegacyFunctionSpecification() function.addParameter('mass_halo', dtype='float64', direction=function.IN, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def get_mass_halo(): function = LegacyFunctionSpecification() function.addParameter('mass_halo', dtype='float64', direction=function.OUT, unit=2.32e7*units.MSun) function.result_type = 'int32' return function @legacy_function def set_a_halo(): function = LegacyFunctionSpecification() function.addParameter('a_halo', dtype='float64', direction=function.IN, unit=units.kpc) function.result_type = 'int32' return function @legacy_function def get_a_halo(): function = LegacyFunctionSpecification() function.addParameter('a_halo', dtype='float64', direction=function.OUT, unit=units.kpc) function.result_type = 'int32' return function # The following function sets the force of the spiral TWA or bar @legacy_function def set_spiral_contribution(): function = LegacyFunctionSpecification() function.addParameter('spiral_contribution', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_spiral_contribution(): function = LegacyFunctionSpecification() function.addParameter('spiral_contribution', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_spiral_model(): """ set model of spiral arms 0 -- TWA (2D) 1 -- Cox and Gomez (3D) 2 -- Lepine (2D) """ function = LegacyFunctionSpecification() function.addParameter('spiral_model', dtype='int32', direction=function.IN, description='model of spiral arms (default: 0; TWA 2D arms)') function.result_type = 'int32' return function @legacy_function def get_spiral_model(): """ set model of spiral arms 0 -- TWA (2D) 1 -- Cox and Gomez (3D) 2 -- Lepine (2D) """ function = LegacyFunctionSpecification() function.addParameter('spiral_model', dtype='int32', direction=function.OUT, description='model of spiral arms (default: 0; TWA 2D arms)') function.result_type = 'int32' return function @legacy_function def set_bar_contribution(): function = LegacyFunctionSpecification() function.addParameter('bar_contribution', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bar_contribution(): function = LegacyFunctionSpecification() function.addParameter('bar_contribution', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_transient_spiral(): function = LegacyFunctionSpecification() function.addParameter('transient_spiral', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_transient_spiral(): function = LegacyFunctionSpecification() function.addParameter('transient_spiral', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function def before_set_parameter(self): pass def before_get_parameter(self): pass class BarAndSpiralsDoc(object): def __get__(self, instance, owner): return instance.interface_doc+"\n\n"+instance.parameters.__doc__ class BarAndSpirals3D(CommonCode, GravityFieldCode): NBODY = object() __doc__ = BarAndSpiralsDoc() def __init__(self, unit_converter=None, **options): self.unit_converter = unit_converter legacy_interface = BarAndSpiralsInterface(**options) self.interface_doc = legacy_interface.__doc__ CommonCode.__init__(self, legacy_interface, **options) def define_parameters(self, handler): handler.add_method_parameter( "get_time", "set_time", "time", "Evolution time in the model", default_value=0 | 97781310.5721*units.yr ) handler.add_method_parameter( "get_omega_sys", None, "omega_system", "pattern speed of the system", default_value=0 | 10*units.km/(units.s*units.kpc) ) handler.add_method_parameter( "get_initial_phase", None, "initial_phase", "phase of the system. To convert between inertial and rotating frames", default_value=0 # | units.rad ) handler.add_method_parameter( "get_flag", "set_flag", "xflag", "flag for the ref system to compute tidal tensor. 1-> corrotating sys, 2-> inertial sys", default_value=0 ) # BAR handler.add_method_parameter( "get_bar_phase", "set_bar_phase", "bar_phase", "Initial phase of the bar", default_value=0 # | units.rad ) handler.add_method_parameter( "get_mass_bar", "set_mass_bar", "mass_bar", "The mass of the bar in the model", default_value=431 | 2.32e7*units.MSun ) handler.add_method_parameter( "get_aaxis_bar", "set_aaxis_bar", "aaxis_bar", "The semimajor axis of the bar in the model", default_value=3.13 | units.kpc ) handler.add_method_parameter( "get_axis_ratio_bar", "set_axis_ratio_bar", "axis_ratio_bar", "b/a of the bar", default_value=0.32 ) handler.add_method_parameter( "get_caxis_bar", "set_caxis_bar", "caxis_bar", "The vertical axis of the bar in the model", default_value=0 | units.kpc ) handler.add_method_parameter( "get_omega_bar", "set_omega_bar", "omega_bar", "The pattern speed of the bar in the model", default_value=5 | 10.*units.km/(units.s*units.kpc) ) handler.add_method_parameter( "get_nbt", "set_nbt", "nbt", "The number of rotations over which bar in the model grows. This is to set tgrow.", default_value=0 ) handler.add_method_parameter( "get_tin", "set_tin", "Tin", "Bar formation start time. (takes nbt bar rotations). Bar forms from bulge mass.", default_value=0 ) handler.add_method_parameter( "get_tgrowth", None, "tgrowth_bar", "Growing time of the bar", default_value=0 | 97781310.5721*units.yr ) # SPIRAL handler.add_method_parameter( "get_spiral_phase", "set_spiral_phase", "spiral_phase", "Initial phase of the spiral arms", default_value=0 # | units.rad ) handler.add_method_parameter( "get_N", "set_N", "N", "How sharply spiral change to bar in the central region", default_value=100 ) handler.add_method_parameter( "get_tan_pitch_angle", "set_tan_pitch_angle", "tan_pitch_angle", " tangent of the pitch angle", default_value=0.277 ) handler.add_method_parameter( "get_rsp", "set_rsp", "rsp", "radius when the spiral starts", default_value=1.5 | units.kpc ) handler.add_method_parameter( "get_amplitude", "set_amplitude", "amplitude", "Amplitude of the perturbation", default_value=8.5 | 100*units.kms**2/units.kpc ) handler.add_method_parameter( "get_r_sigma", "set_r_sigma", "r_sigma", "scalelength rsigma of the spiral arms", default_value=2.5 | units.kpc ) handler.add_method_parameter( "get_omega_spiral", "set_omega_spiral", "omega_spiral", "Pattern speed of the spiral", default_value=2. | 10.*units.kms/units.kpc ) handler.add_method_parameter( "get_m", "set_m", "m", "Number of spirals", default_value=2 ) # CG02 3D spiral model # default values set as in onriginal CG02 paper handler.add_method_parameter( "get_spiral_density_amplitude", "set_spiral_density_amplitude", "spiral_density_amplitude", "CG02 model spiral arms density amplitude", default_value=1.35633 | 2.32e7*units.MSun/units.kpc**3 ) handler.add_method_parameter( "get_fiducial_radius", "set_fiducial_radius", "fiducial_radius", "CG02 spiral arms fiducial radius", default_value=8.0 | units.kpc ) handler.add_method_parameter( "get_scale_height", "set_scale_height", "scale_height", "CG02 spiral arms scale height", default_value=0.18 | units.kpc ) # transcient structure handler.add_method_parameter( "get_sigma_s", "set_sigma_s", "sigma_s", "Duration of the sp force", default_value=1.02269032206 | 97781310.5721*units.yr ) handler.add_method_parameter( "get_t_sim", "set_t_sim", "t_sim", "simulation time", default_value=47.0437548146 | 97781310.5721*units.yr ) # LEPINE MODEL handler.add_method_parameter( "get_spiral_model", "set_spiral_model", "spiral_model", "0 is TWA, 1 is C&G, 2 is Lepine ", default_value=0 ) handler.add_method_parameter( "get_omega_spiral2", "set_omega_spiral2", "omega_spiral2", "Pattern speed of the second SA ", default_value=2. | 10.*units.kms/units.kpc ) handler.add_method_parameter( "get_amplitude2", "set_amplitude2", "amplitude2", "Amplitude of the second SA pattern", default_value=6.8 | 100*units.kms**2/units.kpc ) handler.add_method_parameter( "get_tan_pitch_angle2", "set_tan_pitch_angle2", "tan_pitch_angle2", " tangent of the pitch angle second SA pattern", default_value=-0.1227845 ) handler.add_method_parameter( "get_m2", "set_m2", "m2", "Number of spirals of the second SA pattern", default_value=2 ) handler.add_method_parameter( "get_phi21", "set_phi21", "phi21_spiral", "Initial phase of the second pattern with respect to the primarly one", default_value=-3.49065850399 ) # AXI handler.add_method_parameter( "get_mass_bulge", "set_mass_bulge", "mass_bulge", "mass of the total central component in the model", default_value=606 | 2.32e7*units.MSun ) handler.add_method_parameter( "get_b_bulge", "set_b_bulge", "b_bulge", "b constant of the bulge's potential", default_value=0.3873 | units.kpc ) handler.add_method_parameter( "get_mass_disk", "set_mass_disk", "mass_disk", "The mass of the disk in the model", default_value=3690 | 2.32e7*units.MSun ) handler.add_method_parameter( "get_a_disk", "set_a_disk", "a_disk", "The constant a in the potential of the disk", default_value=5.3178 | units.kpc ) handler.add_method_parameter( "get_b_disk", "set_b_disk", "b_disk", "The constant b in the potential of the disk", default_value=0.25 | units.kpc ) handler.add_method_parameter( "get_mass_halo", "set_mass_halo", "mass_halo", "The mass of the dark matter halo in the model", default_value=4615 | 2.32e7*units.MSun ) handler.add_method_parameter( "get_a_halo", "set_a_halo", "a_halo", "The constant a in the potential of the dark matter halo", default_value=12.0 | units.kpc ) handler.add_boolean_parameter( "get_spiral_contribution", "set_spiral_contribution", "spiral_contribution", "Flag whether to include a spiral in the model", False ) handler.add_boolean_parameter( "get_bar_contribution", "set_bar_contribution", "bar_contribution", "Flag whether to include a bar in the model", False ) handler.add_boolean_parameter( "get_transient_spiral", "set_transient_spiral", "transient_spiral", "Flag whether to include transient spirals in the model", False ) def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED', 'RUN', 'commit_parameters') handler.add_transition('RUN', 'CHANGE_PARAMETERS_RUN', 'before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN', 'RUN', 'recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('RUN', 'before_get_parameter') GravityFieldCode.define_state(self, handler) handler.add_method('RUN', 'get_local_density') handler.add_method('RUN', 'get_velcirc') handler.add_method('RUN', 'get_epifreq') handler.add_method('RUN', 'get_spiral_density') handler.add_method('RUN', 'get_tidal_tensor') handler.add_method('RUN', 'get_eigen_values') handler.add_method('RUN', 'get_tidal_radius') def before_set_parameter(self): pass def before_get_parameter(self): pass def evolve_model(self, t_end): self.parameters.time = t_end @property def model_time(self): return self.parameters.time def get_density_at_point(self, x, y, z): return self.get_local_density(self.parameters.time, x, y, z) Barandspirals3d = BarAndSpirals3D Galaxia = BarAndSpirals3D
48,365
36.233256
147
py
amuse
amuse-main/src/amuse/community/athena/patch_files.py
#!/usr/bin/env python import os import sys import subprocess import re PATCHESDIR = "patches" QUILT_PC = ".pc" def execute_command_line(arguments, cwd = None): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd = cwd) stdoutstring, stderrstring = process.communicate() returncode = process.poll() return stdoutstring, stderrstring, returncode def which(executablename): stdoutstring, stderrstring, returncode = execute_command_line(['which', executablename]) if not returncode == 0: return None else: return stdoutstring def is_quilt_installed(): if sys.platform == 'win32': return False path = which('quilt') if path is None: return False stdoutstring, stderrstring, returncode = execute_command_line(['quilt', '--version']) if not returncode == 0: return False version_re = re.compile(r'(\d).(\d\d)') match = version_re.match(stdoutstring) if not match: return False return True def apply_patches_using_quilt(): returncode = subprocess.call(['quilt', 'push', '-a']) if not returncode == 0: raise Exception("error in applying the patches, please apply by hand using quilt push") def undo_patches_using_quilt(): returncode = subprocess.call(['quilt', 'pop', '-a']) if not returncode == 0: raise Exception("error in undoing the patches, please undo by hand using quilt pop -a") def run_patch(patchname, patchfile): arguments = ['patch', '-p1', '--backup', '--prefix={0}/{1}/'.format(QUILT_PC, patchname), '-E', '-i', patchfile] returncode = subprocess.call(arguments) if not returncode == 0: raise Exception("could not apply patch {0}".format(patchname)) def apply_patches_using_patch(): with open("patches/series", "r") as f: lines = f.readlines() patches = [x.strip() for x in lines] patches = [x for x in patches if len(x) > 0] for patch in patches: path = os.path.join(PATCHESDIR, patch) run_patch(patch, path) def main(undo_patches = False): print("checking if quilt is installed ... ") if not is_quilt_installed(): print("... no") if undo_patches: print("quilt is not installed, cannot undo the patches") sys.exit(1) else: print("applying patches to source code") apply_patches_using_patch() else: print("... yes") if undo_patches: print("quilt is install, will try to undo the patches") undo_patches_using_quilt() else: print("applying patches to source code") apply_patches_using_quilt() print("all patches applied") if __name__ == '__main__': main()
2,859
30.428571
116
py
amuse
amuse-main/src/amuse/community/athena/download.py
#!/usr/bin/env python import subprocess import os import sys import time import urllib.request import urllib.parse import urllib.error from optparse import OptionParser class GetCodeFromHttp(object): url_template = "http://amuse.strw.leidenuniv.nl/codes/athena{version}.tar.gz" filename_template = "athena{version}.tar.gz" version = "" def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename): print("unpacking", filename) arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( ['mv', 'athena{version}'.format(version = self.version), 'athena'], cwd = os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) os.mkdir('src') url = self.url_template.format(version=self.version) filename = self.filename_template.format(version=self.version) filepath = os.path.join(self.src_directory(), filename) print("downloading version", self.version, "from", url, "to", filename) urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file(filename) def main(version=''): instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--version", default='4.1', dest="version", help="version number to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
2,212
26.6625
81
py
amuse
amuse-main/src/amuse/community/athena/__init__.py
from .interface import Athena
30
14.5
29
py
amuse
amuse-main/src/amuse/community/athena/interface.py
from amuse.community import * from amuse.community.interface.mhd import MagnetohydrodynamicsInterface from amuse.community.interface.common import CommonCode import numpy from amuse.units.generic_unit_system import * class AthenaInterface(CodeInterface, MagnetohydrodynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface): """ Athena is a grid-based code for astrophysical hydrodynamics. Athena can solve magnetohydrodynamics (MHD) as well, but this is currently not supported from AMUSE. It was developed primarily for studies of the interstellar medium, star formation, and accretion flows. The current version (Athena v4.0) implements algorithms for the following physics: * compressible hydrodynamics and MHD in 1D, 2D, and 3D, * ideal gas equation of state with arbitrary gamma (including gamma = 1, an isothermal EOS), * an arbitrary number of passive scalars advected with the flow, * self-gravity, and/or a static gravitational potential, * Ohmic resistivity, ambipolar diffusion, and the Hall effect, * both Navier-Stokes and anisotropic (Braginskii) viscosity, * both isotropic and anisotropic thermal conduction, * optically-thin radiative cooling. In addition, Athena allows for the following grid and parallelization options: * Cartesian or cylindrical coordinates, * static (fixed) mesh refinement, * shearing-box source terms, and an orbital advection algorithm for MHD, * parallelization using domain decomposition and MPI. A variety of choices are also available for the numerical algorithms, such as different Riemann solvers and spatial reconstruction methods. The relevant references are: .. [#] ADS:2005JCoPh.205..509G (Gardiner & Stone 2005, JCP, 205, 509 (2D JCP Method)) .. [#] ADS:2008JCoPh.227.4123G (Gardiner & Stone 2007, JCP, 227, 4123 (3D JCP Method)) .. [#] ADS:2008ApJS..178..137S (Stone et al. 2008, ApJS, 178, 137 (Method)) .. [#] ADS:2009NewA...14..139S (Stone & Gardiner 2009, NewA, 14, 139 (van Leer Integrator)) .. [#] ADS:2010ApJS..188..290S (Skinner & Ostriker 2010, ApJ, 188, 290 (Cylindrical Integrator)) .. [#] ADS:2010ApJS..189..142S (Stone & Gardiner 2010, ApJS, 189, 142 (Shearing Box Method)) """ include_headers = ['worker_code.h', 'stopcond.h'] MODE_NORMAL = 'normal' MODE_SELF_GRAVITY = 'self-gravity' MODE_MHD = 'mhd' MODE_SCALAR = 'scalar' def __init__(self, mode = MODE_NORMAL, **options): self.mode = mode CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **options) self.set_auto_decomposition(1) self.par_seti("domain1", "AutoWithNProc", "%d", self.channel.number_of_workers, "-") LiteratureReferencesMixIn.__init__(self) self.number_of_grids = 1 def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL: return 'athena_worker' elif mode == self.MODE_SELF_GRAVITY: return 'athena_worker_selfgrav' elif mode == self.MODE_MHD: return 'athena_worker_mhd' elif mode == self.MODE_SCALAR: return 'athena_worker_scalar' else: return 'athena_worker' @legacy_function def par_seti(): function = LegacyFunctionSpecification() function.addParameter('block', dtype='s', direction=function.IN) function.addParameter('name', dtype='s', direction=function.IN) function.addParameter('fmt', dtype='s', direction=function.IN) function.addParameter('ival', dtype='int32', direction=function.IN) function.addParameter('comment', dtype='s', direction=function.IN) function.result_type = None return function @legacy_function def par_geti(): function = LegacyFunctionSpecification() function.addParameter('block', dtype='s', direction=function.IN) function.addParameter('name', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def par_setd(): function = LegacyFunctionSpecification() function.addParameter('block', dtype='s', direction=function.IN) function.addParameter('name', dtype='s', direction=function.IN) function.addParameter('fmt', dtype='s', direction=function.IN) function.addParameter('dval', dtype='float64', direction=function.IN) function.addParameter('comment', dtype='s', direction=function.IN) function.result_type = None return function @legacy_function def par_getd(): function = LegacyFunctionSpecification() function.addParameter('block', dtype='s', direction=function.IN) function.addParameter('name', dtype='s', direction=function.IN) function.result_type = 'float64' return function def setup_mesh(self, nmeshx, nmeshy, nmeshz, xlength, ylength, zlength): self.par_seti("job","num_domains", "%d", self.number_of_grids, "-") self.par_seti("domain1", "level", "%d", 0, "-") self.par_seti("domain1", "Nx1", "%d", nmeshx, "-") self.par_seti("domain1", "Nx2", "%d", nmeshy, "-") self.par_seti("domain1", "Nx3", "%d", nmeshz, "-") self.par_setd("domain1", "x1min", "%.15e", 0.0, "-") self.par_setd("domain1", "x1max", "%.15e", xlength, "-") self.par_setd("domain1", "x2min", "%.15e", 0.0, "-") self.par_setd("domain1", "x2max", "%.15e", ylength, "-") self.par_setd("domain1", "x3min", "%.15e", 0.0, "-") self.par_setd("domain1", "x3max", "%.15e", zlength, "-") self.par_seti("domain1", "iDisp", "%d", 0, "-") self.par_seti("domain1", "jDisp", "%d", 0, "-") self.par_seti("domain1", "kDisp", "%d", 0, "-") return 0 def define_subgrid(self, level, nmeshx, nmeshy, nmeshz, i, j, k): """ Define a new domain on the given level the number of cells in this domain is given by nmeshx, nmeshy, nmeshz. Each level is twice as dense as in every directory as the previous level (there are 8 cells per higher level cell). """ self.number_of_grids += 1 domain = "domain{0}".format(self.number_of_grids) self.par_seti("job","num_domains", "%d", self.number_of_grids, "-") self.par_seti(domain, "level", "%d", level, "-") self.par_seti(domain, "Nx1", "%d", nmeshx, "-") self.par_seti(domain, "Nx2", "%d", nmeshy, "-") self.par_seti(domain, "Nx3", "%d", nmeshz, "-") self.par_seti(domain, "iDisp", "%d", i, "-") self.par_seti(domain, "jDisp", "%d", j, "-") self.par_seti(domain, "kDisp", "%d", k, "-") return self.number_of_grids @legacy_function def get_position_of_index(): """ Retrieves the x, y and z position of the center of the cell with coordinates i, j, k in the grid specified by the index_of_grid """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function ''' @legacy_function def get_index_of_position(): """ Retrieves the i,j and k index of the grid cell containing the given x, y and z position. The cell is looked up in the grid specified by index_of_grid. """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['i','j','k']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function ''' def get_index_range_inclusive(self, index_of_grid = 1): """ Returns the min and max values of indices in each direction. The range is inclusive, the min index and max index both exist and can be queried. The total number of cells in one direction is max - min + 1. """ domainid = "domain{0}".format(index_of_grid) ni = self.par_geti(domainid, "Nx1") nj = self.par_geti(domainid, "Nx2") nk = self.par_geti(domainid, "Nx3") idisp = self.par_geti(domainid, "iDisp") jdisp = self.par_geti(domainid, "jDisp") kdisp = self.par_geti(domainid, "kDisp") #print index_of_grid, " === > ", (idisp, idisp+ni[0]-1, jdisp, jdisp + nj[0]-1, kdisp, kdisp + nk[0]-1) return (idisp, idisp+ni-1, jdisp, jdisp + nj-1, kdisp, kdisp + nk-1) def get_index_range_magnetic_field_inclusive(self, index_of_grid = 1): original = list(self.get_index_range_inclusive(index_of_grid)) original[1] += 1 original[3] += 1 original[5] += 1 return original def get_mesh_indices(self): """ Return 3 arrays, containing the indices for i, j and k """ si,ei,sj,ej,sk,ek = self.get_index_range_inclusive() indexgrid = numpy.mgrid[slice(si,ei+1),slice(sj,ej+1),slice(sk,ek+1)] return indexgrid.reshape(3, -1) def set_four_pi_G(self, value): self.par_setd("problem", "four_pi_G", "%.15e", value, "") return 0 def set_grav_mean_rho(self, value): self.par_setd("problem", "grav_mean_rho", "%.15e", value, "") return 0 def set_isocsound(self, value): self.par_setd("problem", "iso_csound", "%.15e", value, "") return 0 def set_gamma(self, value): self.par_setd("problem", "gamma", "%.15e", value, "-") return 0 def set_courant_friedrichs_lewy_number(self, value): self.par_setd("time", "cour_no", "%.15e", value, "-") return 0 def set_boundary(self, xbound1, xbound2, ybound1, ybound2, zbound1, zbound2): map_from_string_to_flag = { "reflective": 1, "outflow":2, "periodic":4, "interface": 10, } self.par_seti("domain1", "bc_ix1", "%d", map_from_string_to_flag[xbound1], "-") self.par_seti("domain1", "bc_ox1", "%d", map_from_string_to_flag[xbound2], "-") self.par_seti("domain1", "bc_ix2", "%d", map_from_string_to_flag[ybound1], "-") self.par_seti("domain1", "bc_ox2", "%d", map_from_string_to_flag[ybound2], "-") self.par_seti("domain1", "bc_ix3", "%d", map_from_string_to_flag[zbound1], "-") self.par_seti("domain1", "bc_ox3", "%d", map_from_string_to_flag[zbound2], "-") return 0 def set_parallel_decomposition(self, nx, ny, nz): if nx == 0 or ny == 0 or nz == 0: self.par_seti("domain1", "AutoWithNProc", "%d", self.channel.number_of_workers, "-") else: self.par_seti("domain1", "AutoWithNProc", "%d", 0, "-") self.par_seti("domain1", "NGrid_x1", "%d", nx, "-") self.par_seti("domain1", "NGrid_x2", "%d", ny, "-") self.par_seti("domain1", "NGrid_x3", "%d", nz, "-") return 0 def set_auto_decomposition(self, value): self.par_seti("parallel", "auto", "%d", value, "-") return 0 @legacy_function def initialize_grid(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def get_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_evolve_to_exact_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_evolve_to_exact_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_has_external_gravitational_potential(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_has_external_gravitational_potential(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_nghost(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def esys_roe_adb_hydro(): function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.OUT) function.addParameter('u', dtype='float64', direction=function.OUT) function.addParameter('v', dtype='float64', direction=function.OUT) function.addParameter('w', dtype='float64', direction=function.OUT) function.addParameter('h', dtype='float64', direction=function.OUT) function.addParameter('ev', dtype='float64', direction=function.OUT) for i in range(5): function.addParameter('rem{0}'.format(i), dtype='float64', direction=function.OUT) for i in range(5): function.addParameter('lem{0}'.format(i), dtype='float64', direction=function.OUT) function.result_type = 'i' function.can_handle_array = True return function @legacy_function def fill_grid_linearwave_1d(): function = LegacyFunctionSpecification() function.addParameter('wave_flag', dtype='int32', direction=function.IN) function.addParameter('amplitude', dtype='float64', direction=function.IN) function.addParameter('vflow', dtype='float64', direction=function.IN) function.addParameter('wave_dir', dtype='int32', direction=function.IN) function.result_type = 'i' function.can_handle_array = True return function def get_index_range_for_potential(self, index_of_grid = 1): """ Returns the min and max values of indices in each direction for the potential field, this range is 1 cell larger than the normal grid in all directions""" imin,imax,jmin,jmax,kmin,kmax = numpy.asarray(self.get_index_range_inclusive(index_of_grid = index_of_grid)) imin -= 1 imax += 1 if jmin != jmax: jmin -= 1 jmax += 1 if kmin != kmax: kmin -= 1 kmax += 1 return imin,imax, jmin, jmax, kmin, kmax @legacy_function def set_potential(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) #function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('potential', dtype='d', direction=function.IN) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_potential(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) #function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('potential', dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_interpolated_gravitational_potential(): """ Return the interpolated gravitational potential, can only interpolate over one axis at the time and only at half way points between the grid points. **For debugging purposes only** """ function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('potential', dtype='d', direction=function.OUT) function.result_type = 'i' return function def get_isocsound(self): return self.par_getd("problem", "iso_csound"), 0 def get_gamma(self): return self.par_getd("problem", "gamma"), 0 def get_four_pi_G(self): return self.par_getd("problem", "four_pi_G"), 0 def get_courant_friedrichs_lewy_number(self): return self.par_getd("time", "cour_no"), 0 def get_grav_mean_rho(self): return self.par_getd("problem", "grav_mean_rho"), 0 @legacy_function def get_grid_gravitational_potential(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['phi']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_acceleration(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['fx', 'fy', 'fz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_acceleration(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['fx', 'fy', 'fz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_gravitational_acceleration(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['fx', 'fy', 'fz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_gravity_at_point(): """ Determine the gravitational force on a given point """ function = LegacyFunctionSpecification() function.addParameter('eps', dtype='float64', direction=function.IN, description = "The smoothing parameter") function.addParameter('x', dtype='float64', direction=function.IN, description = "The position vector of the point") function.addParameter('y', dtype='float64', direction=function.IN, description = "The position vector of the point") function.addParameter('z', dtype='float64', direction=function.IN, description = "The position vector of the point") function.addParameter('forcex', dtype='float64', direction=function.OUT, description = "Force created by the particles in the code at the given position") function.addParameter('forcey', dtype='float64', direction=function.OUT, description = "Force created by the particles in the code at the given position") function.addParameter('forcez', dtype='float64', direction=function.OUT, description = "Force created by the particles in the code at the given position") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK Force could be calculated -1 - ERROR No force calculation supported """ return function @legacy_function def get_potential_at_point(): """ Determine the potential on a given point """ function = LegacyFunctionSpecification() function.addParameter('eps', dtype='float64', direction=function.IN, description = "The smoothing factor, may be ignored by the code") function.addParameter('x', dtype='float64', direction=function.IN) function.addParameter('y', dtype='float64', direction=function.IN) function.addParameter('z', dtype='float64', direction=function.IN) function.addParameter('phi', dtype='float64', direction=function.OUT) function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_scalar(): """ Retreives advected scalar property """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['scalar',]: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_scalar(): """ Stores advected scalar property """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['scalar',]: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_boundary_index_range_inclusive(): function = LegacyFunctionSpecification() function.addParameter('index_of_boundary', dtype='i', direction=function.IN) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('minx', dtype='i', direction=function.OUT) function.addParameter('maxx', dtype='i', direction=function.OUT) function.addParameter('miny', dtype='i', direction=function.OUT) function.addParameter('maxy', dtype='i', direction=function.OUT) function.addParameter('minz', dtype='i', direction=function.OUT) function.addParameter('maxz', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_boundary_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_boundary_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_boundary_position_of_index(): """ Retrieves the x, y and z position of the center of the cell with coordinates i, j, k in the grid specified by the index_of_grid """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) function.addParameter('index_of_grid', dtype='i', direction=function.IN, default = 1) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_hydro_state_at_point(): function = LegacyFunctionSpecification() for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN, default = 0) for x in ['rho','rhovx','rhovy','rhovz','rhoe']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'i' function.must_handle_array = True return function @legacy_function def get_hydro_state_for_cell(): function = LegacyFunctionSpecification() for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['dx','dy','dz']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN, default = 0) for x in ['rho','rhovx','rhovy','rhovz','rhoe']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'i' function.must_handle_array = True return function class Athena(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter self.stopping_conditions = StoppingConditions(self) CommonCode.__init__(self, AthenaInterface(**options), **options) def define_converter(self, handler): if self.unit_converter is None: return handler.set_converter(self.unit_converter.as_converter_from_si_to_generic()) def define_properties(self, handler): handler.add_property('get_time', public_name = "model_time") def define_methods(self, handler): handler.add_method( 'evolve_model', (time,), (handler.ERROR_CODE,) ) handler.add_method( 'get_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (length, length, length, handler.ERROR_CODE,) ) density = mass / (length**3) momentum = mass / (time * (length**2)) energy = mass / ((time**2) * length) potential_energy = length ** 2 / time ** 2 magnetic_field = mass / current / time ** 2 handler.add_method( 'set_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX, density, momentum, momentum, momentum, energy, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'set_grid_magnetic_field', (handler.INDEX, handler.INDEX, handler.INDEX, magnetic_field, magnetic_field, magnetic_field, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, momentum, momentum, momentum, energy, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX, energy, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), ( energy, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, density, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_scalar', (handler.INDEX, handler.INDEX, handler.INDEX, handler.NO_UNIT, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_scalar', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_momentum_density', (handler.INDEX, handler.INDEX, handler.INDEX, momentum, momentum, momentum, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_momentum_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), ( momentum, momentum, momentum, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_magnetic_field', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), ( magnetic_field, magnetic_field, magnetic_field, handler.ERROR_CODE,) ) handler.add_method( 'set_potential', (handler.INDEX, handler.INDEX, handler.INDEX, potential_energy), (handler.ERROR_CODE,) ) handler.add_method( 'get_potential', (handler.INDEX, handler.INDEX, handler.INDEX,), (potential_energy, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_gravitational_potential', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,), (potential_energy, handler.ERROR_CODE,) ) handler.add_method( 'get_interpolated_gravitational_potential', (length, length, length), (potential_energy, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_gravitational_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,), (acceleration,acceleration,acceleration, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX,), (acceleration,acceleration,acceleration, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX, acceleration,acceleration,acceleration, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_gravity_at_point', (length, length, length, length), (acceleration, acceleration, acceleration, handler.ERROR_CODE) ) handler.add_method( 'get_potential_at_point', (length, length, length, length), (potential, handler.ERROR_CODE) ) handler.add_method( "get_isocsound", (), (length / time, handler.ERROR_CODE,) ) handler.add_method( "set_isocsound", (length / time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_timestep", (), (time, handler.ERROR_CODE,) ) handler.add_method( "set_timestep", (time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_gamma", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_gamma", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_courant_friedrichs_lewy_number", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_courant_friedrichs_lewy_number", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (time, handler.ERROR_CODE,) ) handler.add_method( 'set_four_pi_G', ( length**3 / (mass * time**2)), (handler.ERROR_CODE,) ) handler.add_method( 'get_four_pi_G', (), ( (length**3) / (mass * (time**2)), handler.ERROR_CODE,) ) handler.add_method( 'set_grav_mean_rho', ( mass / length**3, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_grav_mean_rho', (), (mass / length**3, handler.ERROR_CODE,) ) handler.add_method( 'setup_mesh', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, length, length, length,), (handler.ERROR_CODE,) ) handler.add_method( 'set_boundary', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( 'set_boundary_state', (handler.INDEX, handler.INDEX, handler.INDEX, density, momentum, momentum, momentum, energy, handler.INDEX, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_state', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, momentum, momentum, momentum, energy, handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (length, length, length, handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_index_range_inclusive', (handler.INDEX, handler.INDEX), (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_hydro_state_at_point', (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed), (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE) ) handler.add_method( 'get_hydro_state_for_cell', (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed), (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE) ) self.stopping_conditions.define_methods(handler) def specify_grid(self, definition, index_of_grid = 1): definition.set_grid_range('get_index_range_inclusive') definition.add_getter('get_position_of_index', names=('x','y','z')) definition.add_getter('get_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_setter('set_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_getter('get_grid_density', names=('rho',)) definition.add_setter('set_grid_density', names=('rho',)) if self.mode == self.MODE_SCALAR: definition.add_getter('get_grid_scalar', names=('scalar',)) definition.add_setter('set_grid_scalar', names=('scalar',)) definition.add_getter('get_grid_momentum_density', names=('rhovx','rhovy','rhovz')) definition.add_setter('set_grid_momentum_density', names=('rhovx','rhovy','rhovz')) definition.add_getter('get_grid_energy_density', names=('energy',)) definition.add_setter('set_grid_energy_density', names=('energy',)) definition.add_getter('get_grid_gravitational_potential', names=('gravitational_potential',)) definition.add_getter('get_grid_gravitational_acceleration', names=('gravitational_acceleration_x','gravitational_acceleration_y','gravitational_acceleration_z',)) definition.add_getter('get_grid_acceleration', names=('ax','ay','az')) definition.add_setter('set_grid_acceleration', names=('ax','ay','az')) definition.define_extra_keywords({'index_of_grid':index_of_grid}) def specify_mangnetic_filed_grid(self, definition, index_of_grid = 1): definition.set_grid_range('get_index_range_magnetic_field_inclusive') definition.add_getter('get_position_of_index', names=('x','y','z')) definition.add_getter('get_grid_magnetic_field', names=('B1i','B2i','B3i')) definition.add_setter('set_grid_magnetic_field', names=('B1i','B2i','B3i')) definition.define_extra_keywords({'index_of_grid':index_of_grid}) def specify_boundary_grid(self, definition, index_of_boundary, index_of_grid = 1): definition.set_grid_range('get_boundary_index_range_inclusive') definition.add_getter('get_boundary_position_of_index', names=('x','y','z')) definition.add_getter('get_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_setter('set_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.define_extra_keywords({'index_of_boundary': index_of_boundary, 'index_of_grid':index_of_grid}) def sepecify_extended_grid(self, definition, index_of_grid = 1): self.specify_grid(definition, index_of_grid = index_of_grid) definition.set_grid_range('get_index_range_extended') @property def grid(self): return self._create_new_grid(self.specify_grid, index_of_grid = 1) BOUNDARY_NAME_TO_INDEX = { 'xbound1': 1, 'xbound2': 2, 'ybound1': 3, 'ybound2': 4, 'zbound1': 5, 'zbound2': 6, } def get_boundary_grid(self, name): if not name in self.BOUNDARY_NAME_TO_INDEX: raise Exception("boundary name is not known {0}".format(name)) index_of_boundary = self.BOUNDARY_NAME_TO_INDEX[name] return self._create_new_grid(self.specify_boundary_grid, index_of_boundary = index_of_boundary, index_of_grid = 1) def get_extended_grid(self, index_of_grid = 1): return self._create_new_grid(self.sepecify_extended_grid, index_of_grid = index_of_grid) def get_index_range_extended(self, index_of_grid = 1): i0,i1, j0,j1, k0,k1 = self.get_index_range_inclusive(index_of_grid = index_of_grid) dj = 2 if j1 > j0 else 0 dk = 2 if k1 > k0 else 0 return i0-2, i1+2, j0-dj, j0+dj, k0-dk, k1+dk def itergrids(self): n = self.get_number_of_grids() for x in range(1,n+1): yield self._create_new_grid(self.specify_grid, index_of_grid = x) def iter_magnetic_field_grids(self): n = self.get_number_of_grids() for x in range(1,n+1): yield self._create_new_grid(self.specify_mangnetic_filed_grid, index_of_grid = x) def iter_hydro_and_mhd_grids(self): n = self.get_number_of_grids() for x in range(1,n+1): yield ( self._create_new_grid(self.specify_grid, index_of_grid = x), self._create_new_grid(self.specify_mangnetic_filed_grid, index_of_grid = x), ) def define_particle_sets(self, handler): handler.define_grid('potential_grid') handler.set_grid_range('potential_grid', 'get_index_range_for_potential') handler.add_getter('potential_grid', 'get_position_of_index', names=('x','y','z')) handler.add_getter('potential_grid', 'get_potential', names=('potential',)) handler.add_setter('potential_grid', 'set_potential', names=('potential', )) handler.define_extra_keywords('potential_grid', {'index_of_grid':1}) def define_parameters(self, handler): handler.add_method_parameter( "get_isocsound", "set_isocsound", "isothermal_sound_speed", "isothermal sound speed, only used for isothermal EOS", default_value = 0.0 | length / time, must_set_before_get = True ) handler.add_method_parameter( "get_gamma", "set_gamma", "gamma", "ratio of specific heats used in equation of state", default_value = 1.6666666666666667, must_set_before_get = True ) handler.add_method_parameter( "get_four_pi_G", "set_four_pi_G", "four_pi_G", "value of four times pi time G", default_value = 4 * numpy.pi * (1| (length**3) / (mass * (time**2))), must_set_before_get = True ) handler.add_method_parameter( "get_grav_mean_rho", "set_grav_mean_rho", "gravity_mean_rho", "define the mean density in the field for self gravity calulations", default_value = 0 | mass / length ** 3, must_set_before_get = True ) handler.add_method_parameter( "get_courant_friedrichs_lewy_number", "set_courant_friedrichs_lewy_number", "courant_number", "CFL number", default_value = 0.3, must_set_before_get = True ) handler.add_method_parameter( "get_evolve_to_exact_time", "set_evolve_to_exact_time", "must_evolve_to_exact_time", "End the evolve model at the exact specified time", default_value = True ) handler.add_caching_parameter( "setup_mesh", "nmeshx", "nx", "number of cells in the x direction", 10, ) handler.add_caching_parameter( "setup_mesh", "nmeshy", "ny", "number of cells in the y direction", 10, ) handler.add_caching_parameter( "setup_mesh", "nmeshz", "nz", "number of cells in the z direction", 10, ) handler.add_caching_parameter( "setup_mesh", "xlength", "length_x", "length of model in the x direction", 10 | length, ) handler.add_caching_parameter( "setup_mesh", "ylength", "length_y", "length of model in the x direction", 10 | length, ) handler.add_caching_parameter( "setup_mesh", "zlength", "length_z", "length of model in the z direction", 10 | length, ) handler.add_vector_parameter( "mesh_size", "number of cells in the x, y and z directions", ("nx", "ny", "nz") ) handler.add_vector_parameter( "mesh_length", "length of the model in the x, y and z directions", ("length_x", "length_y", "length_z") ) handler.add_caching_parameter( "set_parallel_decomposition", "nx", "nproc_x", "number of processors for the x direction", 0, ) handler.add_caching_parameter( "set_parallel_decomposition", "ny", "nproc_y", "number of processors for the y direction", 0, ) handler.add_caching_parameter( "set_parallel_decomposition", "nz", "nproc_z", "number of processors for the z direction", 0, ) handler.add_vector_parameter( "parallel_decomposition", "number of processors for each dimensions", ("nproc_x", "nproc_y", "nproc_z") ) handler.add_caching_parameter( "set_boundary", "xbound1", "xbound1", "boundary conditions on first (inner, left) X boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "xbound2", "xbound2", "boundary conditions on second (outer, right) X boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "ybound1", "ybound1", "boundary conditions on first (inner, front) Y boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "ybound2", "ybound2", "boundary conditions on second (outer, back) Y boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "zbound1", "zbound1", "boundary conditions on first (inner, bottom) Z boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "zbound2", "zbound2", "boundary conditions on second (outer, top) Z boundary", "reflective", ) handler.add_vector_parameter( "x_boundary_conditions", "boundary conditions for the X directorion", ("xbound1", "xbound2") ) handler.add_vector_parameter( "y_boundary_conditions", "boundary conditions for the Y directorion", ("ybound1", "ybound2") ) handler.add_vector_parameter( "z_boundary_conditions", "boundary conditions for the Z directorion", ("zbound1", "zbound2") ) self.stopping_conditions.define_parameters(handler) def commit_parameters(self): self.parameters.send_not_set_parameters_to_code() self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() 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('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','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_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_transition('EDIT', 'RUN', 'initialize_grid') handler.add_method('RUN', 'evolve_model') handler.add_method('RUN', 'get_hydro_state_at_point') for state in ['EDIT', 'RUN']: for methodname in [ 'get_grid_state', 'set_grid_state', 'get_potential', 'set_potential', 'get_grid_density', 'set_grid_density', 'set_grid_energy_density', 'get_grid_energy_density', 'get_grid_momentum_density', 'set_grid_momentum_density', 'get_position_of_index', 'get_index_of_position', 'set_grid_scalar', 'get_grid_scalar', 'get_number_of_grids', 'get_index_range_inclusive', 'get_boundary_state', 'set_boundary_state', 'get_boundary_position_if_index', 'get_boundary_index_range_inclusive' ]: handler.add_method(state, methodname) self.stopping_conditions.define_state(handler)
53,617
37.938272
171
py
amuse
amuse-main/src/amuse/community/mikkola/scatterBH.py
import numpy from amuse.lab import * from amuse.community.mikkola.interface import Mikkola from optparse import OptionParser def new_system_of_Hulse_Taylor_pulsar(): stars = Particles(2) Hulse = stars[0] Hulse.mass = 1.441 | units.MSun Hulse.radius = 1.4e-5 | units.RSun Hulse.position = [-1546691.3719943422, 0, 0] | units.km Hulse.velocity = [0.0, -110.0, 0.0] | units.km/units.s Taylor = stars[1] Taylor.mass = 1.387 | units.MSun Taylor.radius = 1.4e-5 | units.RSun Taylor.position = [1606908.6280056578, 0, 0] | units.km Taylor.velocity = [0.0, 114.28262436914201, 0.0] | units.km/units.s return stars def HulseTaylor3(): instance = Mikkola() stars = self.new_system_of_Hulse_Taylor_pulsar() instance.particles.add_particles(stars) Hulse = stars[0] Taylor = stars[1] postion_at_start = Taylor.position.value_in(units.AU)[0] #orbital period #period_HTpulsar = 7.751939106 | units.hour #period_HTpulsar = 77.51939106 | units.hour # period for abseidal motion # period_HTpulsar = 85.0 | units.yr #4.2degrees/year period_HTpulsar = 1.0 | units.yr instance.evolve_model(period_HTpulsar) instance.particles.copy_values_of_state_attributes_to(stars) postion_after_full_rotation = Taylor.position.value_in(units.AU)[0] self.assertAlmostEqual(postion_at_start, postion_after_full_rotation, 4) instance.evolve_model(1.5 * period_HTpulsar) instance.particles.copy_values_of_state_attributes_to(stars) postion_after_half_a_rotation = Taylor.position.value_in(units.AU)[0] self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) instance.evolve_model(1.75 * period_HTpulsar) instance.particles.copy_values_of_state_attributes_to(stars) postion_after_half_a_rotation = Taylor.position.value_in(units.AU)[1] self.assertAlmostEqual(-postion_at_start, postion_after_half_a_rotation, 3) instance.cleanup_code() del instance def new_option_parser(): result = OptionParser() result.add_option("-M", dest="M",type="float",default=12.) result.add_option("-m", dest="m",type="float",default=10.) result.add_option("-a", dest="a",type="float",default=205.) result.add_option("-e", dest="e",type="float",default=0.6) result.add_option("-t", dest="tend",type="float",default=10.) result.add_option("-d", dest="dtdiag",type="float",default=1e99) return result def main(a=205, e=0.6, M=13., m=11., tend=10., dtdiag=1e99) : bs = new_system_of_Hulse_Taylor_pulsar() #(a, e, M, m) M = bs.p.get_mass() m = bs.s.get_mass() Porb = bs.OrbitalPeriod() bs.evolve(tend, dtdiag) # print "Th binary Orbial Velocity: ", bs.OrbitalVelocity() print("BINARY:", bs) bs.terminate() if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
2,959
33.022989
79
py
amuse
amuse-main/src/amuse/community/mikkola/__init__.py
# generated file from .interface import Mikkola
48
15.333333
30
py
amuse
amuse-main/src/amuse/community/mikkola/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from numpy import pi from amuse.units import constants class MikkolaInterface(CodeInterface, GravitationalDynamicsInterface, StoppingConditionInterface): use_modules = ['Mikkola', 'StoppingConditions'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="mikkola_worker", **keyword_arguments) @legacy_function def set_time_step(): """ Set the model timestep. """ function = LegacyFunctionSpecification() function.addParameter('time_step', dtype='float64', direction=function.IN, description = "The current model timestep") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time step was retrieved -1 - ERROR The code does not have support for querying the time """ return function @legacy_function def get_lightspeed(): """ Get the lightspeed value, the lightspeed scales the units (like G=1) and limits the valid velocity terms """ function = LegacyFunctionSpecification() function.addParameter('lightspeed', dtype='float64', direction=function.OUT, description = "value for the lightspeed") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_lightspeed(): """ Set the lightspeed value, the lightspeed scales the units (like G=1) and limits the valid velocity terms """ function = LegacyFunctionSpecification() function.addParameter('lightspeed', dtype='float64', direction=function.IN, description = "value for the lightspeed") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_tolerance(): """ Retrieve the accurancy parameter for the evolve """ function = LegacyFunctionSpecification() function.addParameter('tolerance', dtype='float64', direction=function.OUT, description = "tolerance for the evolve") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_tolerance(): """ Set the accurancy parameter for the evolve """ function = LegacyFunctionSpecification() function.addParameter('tolerance', dtype='float64', direction=function.IN, description = "tolerance for the evolve") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_maximum_number_of_particles(): """ Retrieve the maximum number of particles that can be evolved with this code """ function = LegacyFunctionSpecification() function.addParameter( 'maximum_number_of_particles', dtype='int32', direction=function.OUT ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_maximum_number_of_particles(): """ Change the maximum number of particles that can be evolved with this code """ function = LegacyFunctionSpecification() function.addParameter( 'maximum_number_of_particles', dtype='int32', direction=function.IN ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_evolve_to_exact_time(): """ Evolve to model to the exact time given in the evolve_model call (can be slower) """ function = LegacyFunctionSpecification() function.addParameter( 'evolve_to_exact_time', dtype='bool', direction=function.OUT ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_evolve_to_exact_time(): """ Evolve to model to the exact time given in the evolve_model call (can be slower) """ function = LegacyFunctionSpecification() function.addParameter( 'evolve_to_exact_time', dtype='bool', direction=function.IN ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_radiated_gravitational_energy(): """ Retrieve the current radiated gravitational energy of the model """ function = LegacyFunctionSpecification() function.addParameter('radiated_gravitational_energy', dtype='float64', direction=function.OUT, description = "The energy radiated by gravitational waves") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the energy was set -1 - ERROR Energy could not be provided """ return function @legacy_function def get_total_energy(): """ Retrieve the current total energy of the model """ function = LegacyFunctionSpecification() function.addParameter('energy', dtype='float64', direction=function.OUT, description = "The energy radiated by gravitational waves") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the energy was set -1 - ERROR Energy could not be provided """ return function @legacy_function def get_number_of_particles_added(): """ Return the number of particles added during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_id_of_added_particle(): """ Return the id of the new particle in the code """ function = LegacyFunctionSpecification() function.addParameter('index_of_add', dtype='int32', direction=function.IN, description = 'index in the added particles list (0-n)') function.addParameter('index_of_particle', dtype='int32', direction=function.OUT) function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def get_children_of_particle(): """ Return the number of particles added or deleted during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = 'index of the parent particle', unit = INDEX) function.addParameter('child1', dtype='int32', direction=function.OUT, description = 'index of the first child particle, -1 if none', unit = LINK('particles') ) function.addParameter('child2', dtype='int32', direction=function.OUT, unit = LINK('particles')) function.can_handle_array = True function.result_type = 'int32' return function class Mikkola(GravitationalDynamics): def __init__(self, convert_nbody=None, **options): self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, MikkolaInterface(**options), convert_nbody, **options ) def initialize_code(self): result = self.overridden().initialize_code() if not self.unit_converter is None: value=self.unit_converter.to_nbody(constants.c) self.parameters._original.lightspeed = value return result def define_parameters(self, handler): #~ GravitationalDynamics.define_parameters(self, handler) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "initial timestep for iteration", default_value = 1.0 | nbody_system.time ) handler.add_method_parameter( "get_lightspeed", "set_lightspeed", "lightspeed", "lightspeed used in the code", default_value = 1.0 | nbody_system.length / nbody_system.time ) handler.add_method_parameter( "get_tolerance", "set_tolerance", "tolerance", "tolerance used in the code", default_value = 1e-13 ) handler.add_method_parameter( "get_maximum_number_of_particles", "set_maximum_number_of_particles", "maximum_number_of_particles", "the code will evolve this number of particles, please be sure to account for mergers", default_value = 100 ) handler.add_boolean_parameter( "get_evolve_to_exact_time", "set_evolve_to_exact_time", "evolve_to_exact_time", "the code will evolve the model to the exact time given in evolve_model", True ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "set_lightspeed", ( nbody_system.length / nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_lightspeed", ( ), (nbody_system.length / nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_step", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "set_tolerance", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tolerance", ( ), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_radiated_gravitational_energy", (), (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) ) handler.add_method( "get_total_energy", (), (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) ) def define_properties(self, handler): GravitationalDynamics.define_properties(self, handler) handler.add_property("get_radiated_gravitational_energy") 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_added_particles = self.get_number_of_particles_added() if number_of_added_particles == 0: return indices_in_update_list = list(range(number_of_added_particles)) indices_to_add = self.get_id_of_added_particle(indices_in_update_list) incode_storage = self.particles._private.attribute_storage if len(indices_to_add) > 0: incode_storage._add_indices(indices_to_add) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler)
13,374
32.024691
106
py
amuse
amuse-main/src/amuse/community/higpus/__init__.py
# generated file from .interface import Higpus
47
15
29
py
amuse
amuse-main/src/amuse/community/higpus/interface.py
import os from amuse.community import * from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravitationalDynamicsInterface class HiGPUsInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, CodeWithDataDirectories ): """ HiGPUs is a parallel direct N-body code based on a 6th order Hermite integrator. It uses, at the same time, MPI, OpenMP and CUDA libraries to fully exploit all the capabilities offered by hybrid supercomputing platforms. Moreover, it is implemented using block time steps such to be able to deal with stiff problems like highly collisional gravitational N-body problems. NOTE_1: the code works with nbody units ( G = 1 ): please check the parameters, more info are given in the README file NOTE_2: the evolve method requires an input time (in nbody units) greater than or equal of the maximum time step ( 't' > or = 'max_step') NOTE_3: the code only seems to work when the number of particles is a power of 2 .. [#] ADS:2013JCoPh.236..580C (R. Capuzzo-Dolcetta, M. Spera, D.Punzo, *Journal of Computational Physics*, Volume 236, 1 March 2013, Pages 580-593: .. [#] ... 'A fully parallel, high precision, N-body code running on hybrid computing platforms') """ include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="higpus_worker_gpu", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def echo_int(): 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 new_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, 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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) function.result_type = 'int32' 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) function.addParameter('mass', dtype='float64', direction=function.IN, description = "The mass of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius 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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") 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) function.addParameter('mass', dtype='float64', direction=function.OUT, description = "The mass of the particle") function.addParameter('radius', dtype='float64', direction=function.OUT, description = "The radius of the particle") function.addParameter('x', dtype='float64', direction=function.OUT, description = "The initial position vector of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The initial position vector of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The initial position vector of the particle") function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The initial velocity vector of the particle") function.result_type = 'int32' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('dt', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_eta6(): function = LegacyFunctionSpecification() function.addParameter('eta6', dtype='float64', direction=function.IN, description = "eta parameter of time steps.") function.result_type = 'int32' return function @legacy_function def get_eta6(): function = LegacyFunctionSpecification() function.addParameter('eta6', dtype='float64', direction=function.OUT, description = "eta parameter of time steps.") function.result_type = 'int32' return function @legacy_function def set_eta4(): function = LegacyFunctionSpecification() function.addParameter('eta4', dtype='float64', direction=function.IN, description = "eta parameter of time steps.") function.result_type = 'int32' return function @legacy_function def get_eta4(): function = LegacyFunctionSpecification() function.addParameter('eta4', dtype='float64', direction=function.OUT, description = "eta parameter of time steps.") function.result_type = 'int32' return function @legacy_function def set_eps(): function = LegacyFunctionSpecification() function.addParameter('eps', dtype='float64', direction=function.IN, description = "softening parameter.") function.result_type = 'int32' return function @legacy_function def get_eps(): function = LegacyFunctionSpecification() function.addParameter('eps', dtype='float64', direction=function.OUT, description = "softening parameter.") function.result_type = 'int32' return function @legacy_function def set_Galaxy_core(): function = LegacyFunctionSpecification() function.addParameter('Galaxy_core', dtype='float64', direction=function.IN, description = "radius parameter for Galaxy potential.") function.result_type = 'int32' return function @legacy_function def get_Galaxy_core(): function = LegacyFunctionSpecification() function.addParameter('Galaxy_core', dtype='float64', direction=function.OUT, description = "radius parameter for Galaxy potential.") function.result_type = 'int32' return function @legacy_function def set_Galaxy_mass(): function = LegacyFunctionSpecification() function.addParameter('Galaxy_mass', dtype='float64', direction=function.IN, description = "analytical mass of the Galaxy potential.") function.result_type = 'int32' return function @legacy_function def get_Galaxy_mass(): function = LegacyFunctionSpecification() function.addParameter('Galaxy_mass', dtype='float64', direction=function.OUT, description = "analytical mass of the Galaxy potential.") function.result_type = 'int32' return function @legacy_function def set_Plummer_core(): function = LegacyFunctionSpecification() function.addParameter('Plummer_core', dtype='float64', direction=function.IN, description = "radius parameter for plummer potential.") function.result_type = 'int32' return function @legacy_function def get_Plummer_core(): function = LegacyFunctionSpecification() function.addParameter('Plummer_core', dtype='float64', direction=function.OUT, description = "radius parameter for plummer potential.") function.result_type = 'int32' return function @legacy_function def set_Plummer_mass(): function = LegacyFunctionSpecification() function.addParameter('Plummer_mass', dtype='float64', direction=function.IN, description = "analytical mass of the plummer potential.") function.result_type = 'int32' return function @legacy_function def get_Plummer_mass(): function = LegacyFunctionSpecification() function.addParameter('Plummer_mass', dtype='float64', direction=function.OUT, description = "analytical mass of the plummer potential.") function.result_type = 'int32' return function @legacy_function def set_number_of_GPU(): function = LegacyFunctionSpecification() function.addParameter('number_of_GPU', dtype='int32', direction=function.IN, description = "number of GPU.") function.result_type = 'int32' return function @legacy_function def get_number_of_GPU(): function = LegacyFunctionSpecification() function.addParameter('number_of_GPU', dtype='int32', direction=function.OUT, description = "number of GPU.") function.result_type = 'int32' return function @legacy_function def set_number_of_Threads(): function = LegacyFunctionSpecification() function.addParameter('number_of_Threads', dtype='int32', direction=function.IN, description = "number of Threads per block.") function.result_type = 'int32' return function @legacy_function def get_number_of_Threads(): function = LegacyFunctionSpecification() function.addParameter('number_of_Threads', dtype='int32', direction=function.OUT, description = "number of Threads per block.") function.result_type = 'int32' return function @legacy_function def set_number_of_Print(): function = LegacyFunctionSpecification() function.addParameter('number_of_Print', dtype='int32', direction=function.IN, description = "number of total file to print.") function.result_type = 'int32' return function @legacy_function def get_number_of_Print(): function = LegacyFunctionSpecification() function.addParameter('number_of_Print', dtype='int32', direction=function.OUT, description = "number of total file to print.") function.result_type = 'int32' return function @legacy_function def get_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('number_of_particles', dtype='int32', direction=function.OUT, description = "number of particles.") function.result_type = 'int32' return function @legacy_function def set_DTPrint(): function = LegacyFunctionSpecification() function.addParameter('DTPrint', dtype='float64', direction=function.IN, description = "unit time of snapshot.") function.result_type = 'int32' return function @legacy_function def get_DTPrint(): function = LegacyFunctionSpecification() function.addParameter('DTPrint', dtype='float64', direction=function.OUT, description = "unit time of snapshot.") function.result_type = 'int32' return function @legacy_function def set_max_time_step(): function = LegacyFunctionSpecification() function.addParameter('max_time_step', dtype='float64', direction=function.IN, description = "exponent of the maximum time step used.") function.result_type = 'int32' return function @legacy_function def get_max_time_step(): function = LegacyFunctionSpecification() function.addParameter('max_time_step', dtype='float64', direction=function.OUT, description = "maximum time step used.") function.result_type = 'int32' return function @legacy_function def set_min_time_step(): function = LegacyFunctionSpecification() function.addParameter('min_time_step', dtype='float64', direction=function.IN, description = "exponent of the minimum time step used.") function.result_type = 'int32' return function @legacy_function def get_min_time_step(): function = LegacyFunctionSpecification() function.addParameter('min_time_step', dtype='float64', direction=function.OUT, description = "minimum time step used.") function.result_type = 'int32' return function @legacy_function def set_gpu_name(): function = LegacyFunctionSpecification() function.addParameter('gpu_name', dtype='string', direction=function.IN, description = "name of the GPU used.") function.result_type = 'int32' return function @legacy_function def get_gpu_name(): function = LegacyFunctionSpecification() function.addParameter('gpu_name', dtype='string', direction=function.OUT, description = "name of the GPU used.") function.result_type = 'int32' return function @legacy_function def set_output_path_name(): function = LegacyFunctionSpecification() function.addParameter('output_path_name', dtype='string', direction=function.IN, description = "name of the path where higpus output will be stored.") function.result_type = 'int32' return function @legacy_function def get_output_path_name(): function = LegacyFunctionSpecification() function.addParameter('output_path_name', dtype='string', direction=function.OUT, description = "name of the path where higpus output will be stored.") function.result_type = 'int32' return function class HiGPUs(GravitationalDynamics): def __init__(self, convert_nbody = None, **keyword_arguments): legacy_interface = HiGPUsInterface(**keyword_arguments) GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **keyword_arguments) def define_parameters(self, handler): handler.add_method_parameter( "get_eta4", "set_eta4", "eta4", "timestep parameter", default_value = 0.01 ) handler.add_method_parameter( "get_eta6", "set_eta6", "eta6", "timestep parameter", default_value = 0.4 ) handler.add_method_parameter( "get_eps", "set_eps", "eps", "softening", default_value = 0.001 | 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_Plummer_core", "set_Plummer_core", "r_core_plummer", "radius of Plummer potential", default_value = 0.0 | nbody_system.length ) handler.add_method_parameter( "get_Plummer_mass", "set_Plummer_mass", "mass_plummer", "mass of Galaxy potential", default_value = 0.0 | nbody_system.mass ) handler.add_method_parameter( "get_Galaxy_core", "set_Galaxy_core", "r_scale_galaxy", "sclae radius of the Galaxy potential", default_value = 0.0 | nbody_system.length ) handler.add_method_parameter( "get_Galaxy_mass", "set_Galaxy_mass", "mass_galaxy", "mass of Plummer potential", default_value = 0.0 | nbody_system.mass ) handler.add_method_parameter( "get_number_of_Threads", "set_number_of_Threads", "Threads", "Threads per block", default_value = 128 ) handler.add_method_parameter( "get_number_of_Print", "set_number_of_Print", "n_Print", "start number to print file", default_value = 1000000 ) handler.add_method_parameter( "get_DTPrint", "set_DTPrint", "dt_Print", "time for snapshot", default_value = 1000000.0 | nbody_system.time ) handler.add_method_parameter( "get_max_time_step", "set_max_time_step", "max_step", "power of 2 for maximum time step", default_value = pow(2.,-3.0) | nbody_system.time ) handler.add_method_parameter( "get_min_time_step", "set_min_time_step", "min_step", "power of 2 for minmum time step", default_value = pow(2.,-30.0) | nbody_system.time ) handler.add_method_parameter( "get_gpu_name", "set_gpu_name", "gpu_name", "gpu name", default_value = "" ) handler.add_method_parameter( "get_output_path_name", "set_output_path_name", "output_path_name", "output path name", default_value = "./data/" ) handler.add_method_parameter( "get_number_of_GPU", "set_number_of_GPU", "n_gpu", "number of gpus per node", default_value = 1 ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "new_particle", ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, ), ( handler.INDEX, handler.ERROR_CODE ) ) handler.add_method( "set_state", ( handler.INDEX, nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_state", ( handler.INDEX ), ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, handler.ERROR_CODE ) ) handler.add_method( "set_time_begin", ( nbody_system.time ), ( handler.ERROR_CODE ) ) handler.add_method( "get_time_begin", (), ( nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( "set_Plummer_core", ( nbody_system.length ), ( handler.ERROR_CODE ) ) handler.add_method( "get_Plummer_core", (), ( nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_Plummer_mass", ( nbody_system.mass ), ( handler.ERROR_CODE ) ) handler.add_method( "get_Plummer_mass", (), ( nbody_system.mass, handler.ERROR_CODE ) ) handler.add_method( "set_Galaxy_core", ( nbody_system.length ), ( handler.ERROR_CODE ) ) handler.add_method( "get_Galaxy_core", (), ( nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_Galaxy_mass", ( nbody_system.mass ), ( handler.ERROR_CODE ) ) handler.add_method( "get_Galaxy_mass", (), ( nbody_system.mass, handler.ERROR_CODE ) ) handler.add_method( "set_eps", ( nbody_system.length ), ( handler.ERROR_CODE ) ) handler.add_method( "get_eps", (), ( nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_eta6", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_eta6", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_eta4", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_eta4", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_number_of_GPU", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_number_of_GPU", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "get_number_of_particles", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_number_of_Threads", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_number_of_Threads", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_number_of_Print", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_number_of_Print", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_DTPrint", ( nbody_system.time ), ( handler.ERROR_CODE ) ) handler.add_method( "get_DTPrint", (), ( nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( "set_max_time_step", ( nbody_system.time ), ( handler.ERROR_CODE ) ) handler.add_method( "get_max_time_step", (), ( nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( "set_min_time_step", ( nbody_system.time ), ( handler.ERROR_CODE ) ) handler.add_method( "get_min_time_step", (), ( nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( "set_gpu_name", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_gpu_name", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_output_path_name", ( handler.NO_UNIT ), ( handler.ERROR_CODE ) ) handler.add_method( "get_output_path_name", (), ( handler.NO_UNIT, handler.ERROR_CODE ) ) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) def initialize_code(self): self.overridden().initialize_code() self.parameters.send_not_set_parameters_to_code() self.parameters.output_path_name=self.output_directory def commit_particles(self): n=len(self.particles) if (n & (n-1) != 0): raise Exception(f"Higpus needs a power of two number of particles not {n}, try padding with zero mass particles") self.overridden().commit_particles() Higpus = HiGPUs
29,293
32.364465
159
py
amuse
amuse-main/src/amuse/community/mobse/__init__.py
from .interface import Mobse
29
14
28
py
amuse
amuse-main/src/amuse/community/mobse/interface.py
from amuse.community import * from amuse.units import units from amuse.units import constants from amuse.units.quantities import Quantity from amuse.community.interface import common from amuse.datamodel import Particles from amuse.datamodel import ParticlesSubset import numpy class MOBSEInterface(CodeInterface, common.CommonCodeInterface , LiteratureReferencesMixIn): """ MOBSE (Massive Object in BSE) is an updated version of the **rapid** binary-star evolution (BSE) algorithm. With respect to BSE, the major upgrades are that MOBSE includes up-to-date equations for metal-dependent stellar winds and new prescriptions for core-collapse supernova explosion (SNe). Moreover, MOBSE includes the dependence of stellar winds on the Eddington factor: if a star approaches the Eddington limit stellar winds become almost insensitive to metallicity. MOBSE includes also the effects of Pulsation Pair Instability SNe and Pair Instability SNe, it has more precise formulas to compute the core radii and it can use a different velocity distribution to calculate the velocity kick due to electron-capture SNe. More details about MOBSE can be found in paper: .. [#] ADS:2018MNRAS.474.2959G (Nicola Giacobbo, Michela Mapelli & Mario Spera, 2018, MNRAS, 474, 2959: .. [#] ... Merging black hole binaries: the effects of progenitor s metallicity, mass-loss rate and Eddington factor) The details about BSE can be found in the BSE paper: .. [#] ADS:2002MNRAS.329..897H (Hurley J.R., Tout C.A., & Pols O.R., 2002, MNRAS, 329, 897: .. [#] ... Evolution of binary stars and the effect of tides on binary populations) .. [#] ADS:2000MNRAS.315..543H (Hurley J.R., Pols O.R., Tout C.A., 2000, MNRAS, 315, 543: .. [#] ... Comprehensive analytic formulae for stellar evolution as a function of mass and metallicity) """ def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="mobse_worker", **options) LiteratureReferencesMixIn.__init__(self) @legacy_function def initialize(): function = LegacyFunctionSpecification() function.addParameter('z_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('neta_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('bwind_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('hewind_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('alpha1_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('CElambda_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('ceflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('tflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('ifflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('wdflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('bhflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('nsflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('piflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('mxns_in', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('idum_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('pts1_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('pts2_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('pts3_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('sigma1_in', dtype='d', direction=function.IN, unit = units.km / units.s) function.addParameter('sigma2_in', dtype='d', direction=function.IN, unit = units.km / units.s) function.addParameter('beta_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('xi_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('acc2_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('epsnov_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('eddfac_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('gamma_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('status', dtype='i', direction=function.OUT, unit = NO_UNIT) return function @legacy_function def evolve_binary(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('type1', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('type2', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('initial_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('initial_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('luminosity1', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('luminosity2', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('core_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('core_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('core_radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('core_radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('convective_envelope_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('convective_envelope_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('convective_envelope_radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('convective_envelope_radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('spin1', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('spin2', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('epoch1', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('epoch2', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('MS_lifetime1', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('MS_lifetime2', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('age', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('orbital_period', dtype='d', direction=function.INOUT, unit = units.day) function.addParameter('eccentricity', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('end_time', dtype='d', direction=function.INOUT, unit = units.Myr) return function @legacy_function def get_time_step(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('type1', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('type2', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('initial_mass1', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('initial_mass2', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mass1', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mass2', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('MS_lifetime1', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('MS_lifetime2', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch1', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch2', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('age', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('time_step', dtype='d', direction=function.OUT, unit = units.Myr) return function def get_time_step_for_binary(self, binary): current_values = {} current_values['type1'] = binary.type1.value_in(units.stellar_type) current_values['type2'] = binary.type2.value_in(units.stellar_type) current_values['initial_mass1'] = binary.initial_mass1.value_in(units.MSun) current_values['initial_mass2'] = binary.initial_mass2.value_in(units.MSun) current_values['mass1'] = binary.mass1.value_in(units.MSun) current_values['mass2'] = binary.mass2.value_in(units.MSun) current_values['MS_lifetime1'] = binary.MS_lifetime1.value_in(units.Myr) current_values['MS_lifetime2'] = binary.MS_lifetime2.value_in(units.Myr) current_values['epoch1'] = binary.epoch1.value_in(units.Myr) current_values['epoch2'] = binary.epoch2.value_in(units.Myr) current_values['age'] = binary.age.value_in(units.Myr) result = self.get_time_step(**current_values) return result | units.Myr def evolve_particle(self, particle, time_end): t = particle.current_time if particle.stellar_type == 15: return while t < time_end: t0 = t t = t0 + self.get_time_step_for_binary(particle) if t > time_end: t = time_end self.evolve_star(particle, t) t1 = particle.current_time dt = t1 - t0 t0 = t1 if dt.value_in(units.Myr) == 0.0: #print t, t0, t1, dt, "BREAK BREAK BREAK!" return if particle.stellar_type == 15: return def initialize_code(self): return 0 def commit_parameters(self): return 0 def recommit_parameters(self): return 0 def cleanup_code(self): return 0 def commit_particles(self): return 0 class MOBSEStars(Particles): def __init__(self, code_interface, storage = None): Particles.__init__(self, storage = storage) self._private.code_interface = code_interface self.add_calculated_attribute("temperature", self.calculate_effective_temperature, ["luminosity", "radius"]) def calculate_effective_temperature(self, luminosity, radius): return ((luminosity/(constants.four_pi_stefan_boltzmann*radius**2))**.25).in_(units.K) def add_particles_to_store(self, keys, attributes = [], values = []): if len(keys) == 0: return all_attributes = [] all_attributes.extend(attributes) all_values = [] all_values.extend(values) mapping_from_attribute_to_default_value = { "stellar_type" : 1 | units.stellar_type, "radius": 0 | units.RSun, "luminosity": 0 | units.LSun, "core_mass": 0 | units.MSun, "core_radius": 0 | units.RSun, "convective_envelope_mass": 0 | units.MSun, "convective_envelope_radius": 0 | units.RSun, "epoch": 0 | units.Myr, "spin": 0 | units.none, "main_sequence_lifetime": 0 | units.Myr, "age": 0 | units.Myr, "stellar_type": 0 | units.stellar_type #units.stellar_type("Main Sequence star"), } given_attributes = set(attributes) if not "initial_mass" in given_attributes: index_of_mass_attibute = attributes.index("mass") all_attributes.append("initial_mass") all_values.append(values[index_of_mass_attibute] * 1.0) for attribute, default_value in mapping_from_attribute_to_default_value.items(): if not attribute in given_attributes: all_attributes.append(attribute) all_values.append(default_value.as_vector_with_length(len(keys))) super(MOBSEStars, self).add_particles_to_store(keys, all_attributes, all_values) def get_defined_attribute_names(self): return ["mass", "radius"] class MOBSEBinaries(Particles): def __init__(self, code_interface, storage = None): Particles.__init__(self, storage = storage) self._private.code_interface = code_interface def add_particles_to_store(self, keys, attributes = [], values = []): if len(keys) == 0: return given_attributes = set(attributes) if not "child1" in given_attributes: raise Exception("a binary must always have a child1 attribute") if not "child2" in given_attributes: raise Exception("a binary must always have a child2 attribute") all_attributes = [] all_values = [] for attribute, value in zip(attributes, values): all_attributes.append(attribute) if attribute == 'child1' or attribute == 'child2': value = value.copy_with_link_transfer(None, self._private.code_interface.particles) all_values.append(value) else: all_values.append(value) mapping_from_attribute_to_default_value = { "eccentricity": 0.0 | units.none, "age": 0 | units.Myr } for attribute, default_value in mapping_from_attribute_to_default_value.items(): if not attribute in given_attributes: all_attributes.append(attribute) all_values.append(default_value.as_vector_with_length(len(keys))) super(MOBSEBinaries, self).add_particles_to_store(keys, all_attributes, all_values) added_particles = ParticlesSubset(self, keys) self._private.code_interface._evolve_binaries(added_particles, 1e-08 | units.yr) def get_defined_attribute_names(self): return ["eccentricity", "orbital_period", "age", "child1", "child2"] class MOBSE(common.CommonCode): def __init__(self, **options): InCodeComponentImplementation.__init__(self, MOBSEInterface(**options), **options) self.model_time = 0.0 | units.yr def define_parameters(self, handler): handler.add_caching_parameter( "initialize", "z_in", "metallicity", "Metallicity of all stars", 0.02 ) handler.add_caching_parameter( "initialize", "neta_in", "reimers_mass_loss_coefficient", "Reimers mass-loss coefficient (neta*4x10^-13; 0.5 normally)", 0.5 ) handler.add_caching_parameter( "initialize", "bwind_in", "binary_enhanced_mass_loss_parameter", "The binary enhanced mass loss parameter (inactive for single).", 0.0 ) handler.add_caching_parameter( "initialize", "hewind_in", "helium_star_mass_loss_factor", "Helium star mass loss factor", 1.0 ) handler.add_caching_parameter( "initialize", "alpha1_in", "common_envelope_efficiency", "The common-envelope efficiency parameter", 1.0 ) handler.add_caching_parameter( "initialize", "CElambda_in", "common_envelope_binding_energy_factor", "The binding energy factor for common envelope evolution", 0.1 ) handler.add_caching_parameter( "initialize", "ceflag_in", "common_envelope_model_flag", "ceflag > 0 activates spin-energy correction in common-envelope. ceflag = 3 activates de Kool common-envelope model (0).", 0 ) handler.add_caching_parameter( "initialize", "tflag_in", "tidal_circularisation_flag", "tflag > 0 activates tidal circularisation (1).", 1 ) handler.add_caching_parameter( "initialize", "ifflag_in", "white_dwarf_IFMR_flag", "ifflag > 0 uses white dwarf IFMR (initial-final mass relation) of HPE, 1995, MNRAS, 272, 800 (0).", 0 ) handler.add_caching_parameter( "initialize", "wdflag_in", "white_dwarf_cooling_flag", "wdflag > 0 uses modified-Mestel cooling for WDs (0).", 1 ) handler.add_caching_parameter( "initialize", "bhflag_in", "black_hole_kick_flag", "bhflag > 0 allows velocity kick at BH formation (0).", 1 ) handler.add_caching_parameter( "initialize", "nsflag_in", "neutron_star_mass_flag", "nsflag = 3 Delayed SNe model from Fryer et al. 2012, ApJ, 749, 91.", 3 ) handler.add_caching_parameter( "initialize", "piflag_in", "pair_instability_flag", "piflag > 0 activates the PPISN and PISN from Spera & Mapelli 2017, MNRAS, 470, 4739 (1).", 1 ) handler.add_caching_parameter( "initialize", "mxns_in", "maximum_neutron_star_mass", "The maximum neutron star mass (1.8, nsflag=0; 3.0, nsflag=1).", 3.0 | units.MSun ) handler.add_caching_parameter( "initialize", "idum_in", "SN_kick_random_seed", "The random number seed used in the kick routine.", 29769 ) handler.add_caching_parameter( "initialize", "pts1_in", "fractional_time_step_1", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: MS (0.05)", 0.05 ) handler.add_caching_parameter( "initialize", "pts2_in", "fractional_time_step_2", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: GB, CHeB, AGB, HeGB (0.01)", 0.01 ) handler.add_caching_parameter( "initialize", "pts3_in", "fractional_time_step_3", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: HG, HeMS (0.02)", 0.02 ) handler.add_caching_parameter( "initialize", "sigma1_in", "SN_kick_speed_dispersion_ICS", "The dispersion in the Maxwellian for the SN kick speed (265 km/s from Hobbs et al. 2005).", 265.0 | units.km / units.s ) handler.add_caching_parameter( "initialize", "sigma2_in", "SN_kick_speed_dispersion_ECS", "The dispersion in the Maxwellian for the SN kick speed (7 km/s).", 7.0 | units.km / units.s ) handler.add_caching_parameter( "initialize", "beta_in", "wind_velocity_factor", "The wind velocity factor: proportional to vwind**2 (1/8).", 0.125 ) handler.add_caching_parameter( "initialize", "xi_in", "wind_accretion_efficiency", "The wind accretion efficiency factor (1.0).", 1.0 ) handler.add_caching_parameter( "initialize", "acc2_in", "wind_accretion_factor", "The Bondi-Hoyle wind accretion factor (3/2).", 1.5 ) handler.add_caching_parameter( "initialize", "epsnov_in", "nova_retained_accreted_matter_fraction", "The fraction of accreted matter retained in nova eruption (0.001).", 0.001 ) handler.add_caching_parameter( "initialize", "eddfac_in", "Eddington_mass_transfer_limit_factor", "The Eddington limit factor for mass transfer (1.0).", 1.0 ) handler.add_caching_parameter( "initialize", "gamma_in", "Roche_angular_momentum_factor", "The angular momentum factor for mass lost during Roche (-1.0). ", -1.0 ) def define_state(self, handler): common.CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','RUN','commit_parameters') handler.add_method('RUN', 'evolve_binary') handler.add_method('RUN','before_get_parameter') handler.add_method('RUN','before_set_parameter') def define_particle_sets(self, handler): handler.define_inmemory_set('particles', MOBSEStars) handler.define_inmemory_set('binaries', MOBSEBinaries) handler.add_attribute( 'binaries', 'time_step', '_get_time_step', ('child1', 'child2', 'age') #('child1', 'type2', # 'initial_mass1', 'initial_mass2', # 'mass1', 'mass2', # 'MS_lifetime1', 'MS_lifetime2', # 'epoch1', 'epoch2', #'age') ) def _get_time_step(self, child1, child2, age): child1 = child1.as_set() child2 = child2.as_set() return self.get_time_step( child1.stellar_type, child2.stellar_type, child1.initial_mass, child2.initial_mass, child1.mass, child2.mass, child1.age, child2.age, child1.epoch, child2.epoch, age ) def orbital_period_to_semi_major_axis(self, orbital_period, mass1, mass2): mu = (mass1 + mass2) * constants.G return (((orbital_period / (2.0 * numpy.pi))**2)*mu)**(1.0/3.0) def semi_major_axis_to_orbital_period(self, semi_major_axis, mass1, mass2): mu = (mass1 + mass2) * constants.G return 2.0 * numpy.pi * ((semi_major_axis**3/mu)**0.5) def _evolve_binaries(self, particles, end_time): binary_attributes = ( "age", "semi_major_axis", "eccentricity" ) single_attributes = ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "age", ) children1 = particles.child1.as_set() children2 = particles.child2.as_set() children1_arguments = children1.get_values_in_store(children1.get_all_indices_in_store(), single_attributes) children2_arguments = children2.get_values_in_store(children2.get_all_indices_in_store(), single_attributes) binaries_arguments = particles.get_values_in_store(particles.get_all_indices_in_store(), binary_attributes) binaries_arguments[1] = self.semi_major_axis_to_orbital_period(binaries_arguments[1] , children1_arguments[2], children2_arguments[2]) arguments = [] for argument1, argument2 in zip(children1_arguments, children2_arguments): arguments.append(argument1) arguments.append(argument2) arguments.extend(binaries_arguments) arguments.append(end_time.as_vector_with_length(len(particles))) result = self.evolve_binary(*arguments) result[-3] = self.orbital_period_to_semi_major_axis(result[-3] , result[4], result[5]) children1_results = [] children2_results = [] index = 0 for dummy in range(len(children1_arguments)): children1_results.append(result[index]) index += 1 children2_results.append(result[index]) index += 1 children1.set_values_in_store(children1.get_all_indices_in_store(), single_attributes, children1_results) children2.set_values_in_store(children2.get_all_indices_in_store(), single_attributes, children2_results) particles.set_values_in_store(particles.get_all_indices_in_store(), binary_attributes, result[index:]) def evolve_model(self, end_time = None, keep_synchronous = True): if not keep_synchronous: self._evolve_binaries(self.binaries, self.binaries.time_step + self.binaries.age) return if end_time is None: end_time = self.model_time + min(self.binaries.time_step) self._evolve_binaries(self.binaries, end_time - self.model_time + self.binaries.age) self.model_time = end_time def commit_particles(self): pass def update_time_steps(self): pass def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def initialize_module_with_current_parameters(self): self.commit_parameters() def initialize_module_with_default_parameters(self): """ * neta is the Reimers mass-loss coefficent (neta*4x10^-13; 0.5 normally). * bwind is the binary enhanced mass loss parameter (inactive for single). * hewind is a helium star mass loss factor (1.0 normally, inactive). * sigma1 is the dispersion in the Maxwellian for the ICSN kick speed (265 km/s). * sigma2 is the dispersion in the Maxwellian for the ECSN kick speed (7 km/s). * * ifflag > 0 uses WD IFMR of HPE, 1995, MNRAS, 272, 800 (0). * wdflag > 0 uses modified-Mestel cooling for WDs (0). * bhflag > 0 allows velocity kick at BH formation (1). * nsflag = 1 takes NS/BH mass from Belczynski et al. 2002, ApJ, 572, 407.", * = 2 Rapid SNe model from Fryer et al. 2012, ApJ, 749, 91.", * = 3 Delayed SNe model from Fryer et al. 2012, ApJ, 749, 91.", * mxns is the maximum NS mass (1.8, nsflag=0; 3.0, nsflag=1). * piflag > 0 activates the PPISN and PISN from Spera & Mapelli 2017, MNRAS, 470, 4739 (1).", * idum is the random number seed used in the kick routine. * * Next come the parameters that determine the timesteps chosen in each * evolution phase: * pts1 - MS (0.05) * pts2 - GB, CHeB, AGB, HeGB (0.01) * pts3 - HG, HeMS (0.02) * as decimal fractions of the time taken in that phase. """ self.parameters.set_defaults() self.commit_parameters() Mobse = MOBSE
28,342
42.271756
142
py
amuse
amuse-main/src/amuse/community/bonsai2/download.py
#!/usr/bin/env python import subprocess import os import sys import time import urllib.request import urllib.parse import urllib.error from optparse import OptionParser class GetCodeFromHttp(object): url_template = "https://github.com/treecode/Bonsai/archive/{version}.zip" filename_template = "{version}.zip" version = "" def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename): print("unpacking", filename) arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( ['mv', 'bonsai-{version}'.format(version = self.version), 'bonsai'], cwd = os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) os.mkdir('src') url = self.url_template.format(version=self.version) filename = self.filename_template.format(version=self.version) filepath = os.path.join(self.src_directory(), filename) print("downloading version", self.version, "from", url, "to", filename) urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file(filename) def main(version=''): instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--version", default='d1c23d33263090fcf681aa727f300b31efef0f03', dest="version", help="version number to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
2,237
26.975
80
py
amuse
amuse-main/src/amuse/community/bonsai2/__init__.py
# generated file from .interface import Bonsai2
48
15.333333
30
py
amuse
amuse-main/src/amuse/community/bonsai2/interface.py
import os.path from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface, GravitationalDynamics class Bonsai2Interface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, CodeWithDataDirectories): """ .. [#] ADS:2014hpcn.conf...54B (Bedorf J., et al., 2014, SC'14 proceedings, 54-65, https://doi.org/10.1109/SC.2014.10) .. [#] ADS:2012JCoPh.231.2825B (Bedorf J., Gaburov E., Portegies Zwart S., 2012, JCoPh, 231, 2825) """ include_headers = ['worker_code.h', 'stopcond.h'] def name_of_worker(self,mode): return 'bonsai_worker' def __init__(self, mode=None, **options): CodeInterface.__init__(self, name_of_the_worker = self.name_of_worker(mode), **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) self.set_src_directory( os.path.join(self.amuse_root_directory, 'src', 'amuse', 'community', 'bonsai2', 'src', '') ) @legacy_function def set_src_directory(): function = LegacyFunctionSpecification() function.addParameter('src_directory', dtype='string', direction=function.IN, description = "The path to the Bonsai2 src directory.") 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 current timestep for the system") function.result_type = 'int32' return function @legacy_function def set_mass(): """ Update the mass of a particle. Mass is a scalar property of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('length', 'int32', function.LENGTH) 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 @legacy_function def set_state(): """ Update the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, position and velocity) is updated. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('radius', dtype='float64', direction=function.IN, description = "The new radius of the particle") function.addParameter('x', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('vx', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) 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 @legacy_function def set_position(): """ Update the position of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('x', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('length', 'int32', function.LENGTH) 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 -2 - ERROR code does not support updating of a particle """ return function @legacy_function def set_velocity(): """ Set the velocity vector of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('vx', dtype='float64', direction=function.IN, description = "The current x component of the velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The current y component of the velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The current z component of the velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_acceleration(): """ Set the velocity vector of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('ax', dtype='float64', direction=function.IN, description = "The current x component of the velocity vector of the particle") function.addParameter('ay', dtype='float64', direction=function.IN, description = "The current y component of the velocity vector of the particle") function.addParameter('az', dtype='float64', direction=function.IN, description = "The current z component of the velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def get_theta_for_tree(): """ Get theta, the opening angle for building the tree: between 0 and 1. """ function = LegacyFunctionSpecification() function.addParameter('theta_for_tree', dtype='float64', direction=function.OUT, description = "theta, the opening angle for building the tree: between 0 and 1") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_theta_for_tree(): """ Set theta, the opening angle for building the tree: between 0 and 1. """ function = LegacyFunctionSpecification() function.addParameter('theta_for_tree', dtype='float64', direction=function.IN, description = "theta, the opening angle for building the tree: between 0 and 1") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function # @legacy_function # def get_eta(): # """ # Get eta, the block time-step parameter. # """ # function = LegacyFunctionSpecification() # function.addParameter('eta', dtype='float64', direction=function.OUT, # description = "Eta, time-step parameter") # function.result_type = 'int32' # return function # # @legacy_function # def set_eta(): # """ # Set eta, the block time-step parameter. # """ # function = LegacyFunctionSpecification() # function.addParameter('eta', dtype='float64', direction=function.IN, # description = "Eta, time-step parameter") # function.result_type = 'int32' # return function class Bonsai2(GravitationalDynamics): def __init__(self, unit_converter = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = Bonsai2Interface(**options) GravitationalDynamics.__init__( self, legacy_interface, unit_converter, **options ) def define_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.05**2 | nbody_system.length**2 ) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "timestep for the system", default_value = 1.0 / 64 | nbody_system.time ) # handler.add_method_parameter( # "get_eta", # "set_eta", # "timestep_parameter", # "timestep parameter for the block time-step", # default_value = 0.1 # ) 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.75 ) 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( "set_time", (nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "set_time_step", (nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "get_eps2", (), (nbody_system.length**2, handler.ERROR_CODE,) ) handler.add_method( "get_time", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length**2,), (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_errorcodes(self, handler): handler.add_errorcode(-1, 'Unspecified, other error.') handler.add_errorcode(-2, 'Called function is not implemented.') handler.add_errorcode(-3, 'A particle with the given index was not found.') handler.add_errorcode(-4, 'The tree has become too deep, consider the removal of far away particles to prevent a too large box.') def define_state(self, handler): GravitationalDynamics.define_state(self, handler) self.stopping_conditions.define_state(handler)
13,710
41.448916
166
py
amuse
amuse-main/src/amuse/community/mi6/__init__.py
from .interface import Mi6
27
13
26
py
amuse
amuse-main/src/amuse/community/mi6/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 MI6Interface( CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, GravityFieldInterface): """ MI6 - Masaki's Integrator 6th order N-body module with mixed 4th and 6th order Hermite integration scheme, aimed at simulating the Galactic center. It has different treatments for supermassive black holes (SMBHs), intermediate mass black holes (IMBHs), and normal "field stars". The post-newtonian effects are included up to 2.5. NOTE: there is always a SMBH fixed at the center, with a mass of unity (nbody units). Masses of other particles are assumed to be much less than unity, such that the SMBH remains at the origin. Therefore a test particle will orbit around the SMBH with a velocity proportional to sqrt(GM/r), with GM=1, since the mass of the test particle itself is neglected. Validity of the results is questionable when using particles with masses of order unity or greater, or when the center-of-mass (-velocity) does not coincide with the origin. """ include_headers = ['worker_code.h', 'stopcond.h', 'interface.h'] MODE_GPU = 'gpu' MODE_CPU = 'cpu' def __init__(self, mode = MODE_CPU, **options): CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **options) LiteratureReferencesMixIn.__init__(self) def name_of_the_worker(self, mode): if mode == self.MODE_CPU: return 'mi6_worker' elif mode == self.MODE_GPU: return 'mi6_worker_gpu' else: print("Warning: unknown mode: '{0}' - using default ('{1}').".format(mode, self.MODE_CPU)) return 'mi6_worker' @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.") 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.") 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.") 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.") 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.") 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.") 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 supermassive 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 supermassive black holes.") function.result_type = 'int32' return function @legacy_function def get_eta_imbh(): function = LegacyFunctionSpecification() function.addParameter('eta_intermediate_mass_black_hole', dtype='float64', direction=function.OUT, description = "The current value of the timestep parameter for intermediate mass black holes.") function.result_type = 'int32' return function @legacy_function def set_eta_imbh(): function = LegacyFunctionSpecification() function.addParameter('eta_intermediate_mass_black_hole', dtype='float64', direction=function.IN, description = "The new value of the timestep parameter for intermediate mass black holes.") function.result_type = 'int32' return function @legacy_function def get_max_relative_energy_error(): function = LegacyFunctionSpecification() function.addParameter('max_relative_energy_error', dtype='float64', direction=function.OUT, description = "The current value of the maximum relative energy error per full step.") function.result_type = 'int32' return function @legacy_function def set_max_relative_energy_error(): function = LegacyFunctionSpecification() function.addParameter('max_relative_energy_error', dtype='float64', direction=function.IN, description = "The new value of the maximum relative energy error per full step.") function.result_type = 'int32' return function @legacy_function def get_maximum_timestep(): function = LegacyFunctionSpecification() function.addParameter('maximum_timestep', dtype='float64', direction=function.OUT, description = "The current value of the maximum timestep a particle may take.") function.result_type = 'int32' return function @legacy_function def set_maximum_timestep(): function = LegacyFunctionSpecification() function.addParameter('maximum_timestep', dtype='float64', direction=function.IN, description = "The new value of the maximum timestep a particle may take.") function.result_type = 'int32' return function @legacy_function def get_smbh_mass(): function = LegacyFunctionSpecification() function.addParameter('smbh_mass', dtype='float64', direction=function.OUT, description = "The current value of the mass of the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def set_smbh_mass(): function = LegacyFunctionSpecification() function.addParameter('smbh_mass', dtype='float64', direction=function.IN, description = "The new value of the mass of the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def get_include_smbh_flag(): function = LegacyFunctionSpecification() function.addParameter('include_smbh_flag', dtype='int32', direction=function.OUT, description = "Flag to control whether MI6 includes a supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def set_include_smbh_flag(): function = LegacyFunctionSpecification() function.addParameter('include_smbh_flag', dtype='int32', direction=function.IN, description = "Flag to control whether MI6 includes a supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def get_calculate_postnewtonian(): function = LegacyFunctionSpecification() function.addParameter('calculate_postnewtonian_flag', dtype='int32', direction=function.OUT, description = "Flag to control whether post-newtonian corrections are calculated for the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def set_calculate_postnewtonian(): function = LegacyFunctionSpecification() function.addParameter('calculate_postnewtonian_flag', dtype='int32', direction=function.IN, description = "Flag to control whether post-newtonian corrections are calculated for the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def get_calculate_postnewtonian_only_first_order(): function = LegacyFunctionSpecification() function.addParameter('calculate_postnewtonian_only_first_order_flag', dtype='int32', direction=function.OUT, description = "Flag to control whether post-newtonian corrections are calculated for the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def set_calculate_postnewtonian_only_first_order(): function = LegacyFunctionSpecification() function.addParameter('calculate_postnewtonian_only_first_order_flag', dtype='int32', direction=function.IN, description = "Flag to control whether post-newtonian corrections are calculated for the supermassive black hole at the center.") function.result_type = 'int32' return function @legacy_function def get_lightspeed(): function = LegacyFunctionSpecification() function.addParameter('lightspeed', dtype='float64', direction=function.OUT, description = "value for the lightspeed") function.result_type = 'int32' return function @legacy_function def set_lightspeed(): function = LegacyFunctionSpecification() function.addParameter('lightspeed', dtype='float64', direction=function.IN, description = "value for the lightspeed") function.result_type = 'int32' return function class MI6(GravitationalDynamics, GravityFieldCode): ## __doc__ = MasakiDoc() def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = MI6Interface(**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_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 = 0.0 | 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 = 0.0 | 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 = 1.0e-4 ) handler.add_method_parameter( "get_eta_fs", "set_eta_fs", "timestep_parameter", "timestep parameter (eta) for field stars (alias for timestep_parameter_stars)", default_value = 0.1 ) handler.add_method_parameter( "get_eta_fs", "set_eta_fs", "timestep_parameter_stars", "timestep parameter (eta) for field stars", default_value = 0.1 ) handler.add_method_parameter( "get_eta_smbh", "set_eta_smbh", "timestep_parameter_supermassive_black_holes", "timestep parameter (eta) for supermassive black holes", default_value = 0.4 ) handler.add_method_parameter( "get_eta_imbh", "set_eta_imbh", "timestep_parameter_intermediate_mass_black_holes", "timestep parameter (eta) for intermediate mass black holes", default_value = 0.4 ) handler.add_method_parameter( "get_drink", None, "drink", "Order a drink at MI6", default_value = "" ) handler.add_method_parameter( "get_max_relative_energy_error", "set_max_relative_energy_error", "max_relative_energy_error", "the maximum relative energy error per full step", default_value = 5e-5 # or nbody_system.time**-1 ??? why /dt_max ??? ) handler.add_method_parameter( "get_maximum_timestep", "set_maximum_timestep", "maximum_timestep", "the maximum timestep a particle may take", default_value = 1.0/1024.0 | nbody_system.time ) handler.add_method_parameter( "get_smbh_mass", "set_smbh_mass", "smbh_mass", "the mass of the supermassive black hole at the center", default_value = 1.0 | nbody_system.mass ) handler.add_boolean_parameter( "get_include_smbh_flag", "set_include_smbh_flag", "include_smbh", "Flag that specifies whether to include a supermassive black hole at the center", False ) handler.add_boolean_parameter( "get_calculate_postnewtonian", "set_calculate_postnewtonian", "calculate_postnewtonian", "Flag that specifies whether post-newtonian corrections are calculated for the " "supermassive black hole at the center (has no effect when include_smbh is False)", True ) handler.add_boolean_parameter( "get_calculate_postnewtonian_only_first_order", "set_calculate_postnewtonian_only_first_order", "calculate_postnewtonian_only_first_order", "Flag that specifies whether (only!) first order post-newtonian corrections are calculated for the " "supermassive black hole at the center (has no effect when include_smbh is False)", False ) handler.add_method_parameter( "get_lightspeed", "set_lightspeed", "lightspeed", "lightspeed used in the code", default_value = 1.0 | nbody_system.speed ) def get_drink(self): return "Vodka martini. Shaken, not stirred." def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) handler.add_method("get_eps2", (), (nbody_system.length**2, handler.ERROR_CODE)) handler.add_method("set_eps2", (nbody_system.length**2,), (handler.ERROR_CODE,)) handler.add_method("get_eps2_fs_fs", (), (nbody_system.length**2, handler.ERROR_CODE)) handler.add_method("set_eps2_fs_fs", (nbody_system.length**2,), (handler.ERROR_CODE,)) handler.add_method("get_eps2_fs_bh", (), (nbody_system.length**2, handler.ERROR_CODE)) handler.add_method("set_eps2_fs_bh", (nbody_system.length**2,), (handler.ERROR_CODE,)) handler.add_method("get_eps2_bh_bh", (), (nbody_system.length**2, handler.ERROR_CODE)) handler.add_method("set_eps2_bh_bh", (nbody_system.length**2,), (handler.ERROR_CODE,)) handler.add_method("get_eta_s", (), (handler.NO_UNIT, handler.ERROR_CODE)) handler.add_method("set_eta_s", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_eta_fs", (), (handler.NO_UNIT, handler.ERROR_CODE)) handler.add_method("set_eta_fs", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_eta_smbh", (), (handler.NO_UNIT, handler.ERROR_CODE)) handler.add_method("set_eta_smbh", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_eta_imbh", (), (handler.NO_UNIT, handler.ERROR_CODE)) handler.add_method("set_eta_imbh", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_max_relative_energy_error", (), (handler.NO_UNIT, handler.ERROR_CODE)) handler.add_method("set_max_relative_energy_error", (handler.NO_UNIT,), (handler.ERROR_CODE,)) handler.add_method("get_maximum_timestep", (), (nbody_system.time, handler.ERROR_CODE)) handler.add_method("set_maximum_timestep", (nbody_system.time,), (handler.ERROR_CODE,)) handler.add_method("get_smbh_mass", (), (nbody_system.mass, handler.ERROR_CODE)) handler.add_method("set_smbh_mass", (nbody_system.mass,), (handler.ERROR_CODE,)) handler.add_method("get_lightspeed", (), (nbody_system.speed, handler.ERROR_CODE)) handler.add_method("set_lightspeed", (nbody_system.speed,), (handler.ERROR_CODE,)) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) Mi6 = MI6
20,630
44.745011
141
py
amuse
amuse-main/src/amuse/community/gadget2/__init__.py
from .interface import Gadget2
31
15
30
py
amuse
amuse-main/src/amuse/community/gadget2/interface.py
import os import numpy from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import SinglePointGravityFieldInterface from amuse.community.interface.gd import GravityFieldCode from amuse.community import * from amuse.support.options import option class Gadget2Interface( CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, SinglePointGravityFieldInterface, CodeWithDataDirectories ): """ GADGET-2 computes gravitational forces with a hierarchical tree algorithm (optionally in combination with a particle-mesh scheme for long-range gravitational forces, currently not supported from the AMUSE interface) and represents fluids by means of smoothed particle hydrodynamics (SPH). The code can be used for studies of isolated systems, or for simulations that include the cosmological expansion of space, both with or without periodic boundary conditions. In all these types of simulations, GADGET follows the evolution of a self- gravitating collisionless N-body system, and allows gas dynamics to be optionally included. Both the force computation and the time stepping of GADGET are fully adaptive, with a dynamic range which is, in principle, unlimited. The relevant references are: .. [#] ADS:2005MNRAS.364.1105S (Springel V., 2005, MNRAS, 364, 1105 (GADGET-2)) .. [#] ADS:2001NewA....6...79S (Springel V., Yoshida N., White S. D. M., 2001, New Astronomy, 6, 51 (GADGET-1)) .. [#] ADS:2012MNRAS.419..465D (Durier F., Dalla Vecchia C., 2012, MNRAS (Time integration scheme fix)) """ include_headers = ['interface.h', 'worker_code.h', 'stopcond.h'] MODE_NORMAL = 'normal' MODE_PERIODIC_BOUNDARIES = 'periodic' MODE_PERIODIC_NOGRAVITY = 'periodic_nogravity' MODE_NOGRAVITY = 'nogravity' 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): return 'gadget2_worker_'+mode @legacy_function def new_dm_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) for x in ['mass','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'int32' return function def new_particle(self, mass, x, y, z, vx, vy, vz): return self.new_dm_particle(mass, x, y, z, vx, vy, vz) @legacy_function def new_sph_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) for x in ['mass','x','y','z','vx','vy','vz','u']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_state(): """ Retrieve the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, position and velocity) is returned. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('x', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found in the model and the information was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def get_potential(): """ Retrieve the current potential of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the potential from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('Potential', dtype='float64', direction=function.OUT, description = "The current potential of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found in the model and the information was retrieved -1 - ERROR particle could not be found """ return function @legacy_function def set_state(): """ Update the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, position and velocity) is updated. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('x', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('vx', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The new velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) 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 @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.must_handle_array = True 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('length', 'int32', function.LENGTH) function.result_type = 'int32' 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.must_handle_array = True 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('length', 'int32', function.LENGTH) 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 -2 - ERROR code does not support updating of a particle """ return function @legacy_function def get_position(): """ Retrieve the position vector of a particle. Position is a vector property, this function has 3 OUT arguments. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('x', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_position(): """ Update the position of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('x', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('y', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('z', dtype='float64', direction=function.IN, description = "The new position vector of the particle") function.addParameter('length', 'int32', function.LENGTH) 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 -2 - ERROR code does not support updating of a particle """ return function @legacy_function def get_velocity(): """ Retrieve the velocity vector of a particle. Position is a vector property, this function has 3 OUT arguments. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the velocity 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 component of the position vector of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current y component of the position vector of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current z component of the position vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_velocity(): """ Set the velocity vector of a particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('vx', dtype='float64', direction=function.IN, description = "The current x component of the velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The current y component of the velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The current z component of the velocity vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def get_acceleration(): """ Retrieve the acceleration vector of a particle. Second time derivative of the position. """ function = LegacyFunctionSpecification() function.must_handle_array = True 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('ax', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('ay', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('az', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def get_state_sph(): function = LegacyFunctionSpecification() function.must_handle_array = True 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`") for x in ['mass','x','y','z','vx','vy','vz','u']: function.addParameter(x, dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_state_sph(): function = LegacyFunctionSpecification() function.must_handle_array = True 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`") for x in ['mass','x','y','z','vx','vy','vz','u']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_internal_energy(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('u', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_internal_energy(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('u', dtype='float64', direction=function.IN) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_smoothing_length(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('h_smooth', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_alpha_visc(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description="alpha_SPH, the artificial viscosity of a particle") function.addParameter('alpha', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_dalphadt_visc(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description="dalpha/dt, the rate of change with time of the artificial viscosity parameter alpha_SPH") function.addParameter('dalphadt', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_density(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('rho', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_pressure(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('pressure', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_d_internal_energy_dt(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('du_dt', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_n_neighbours(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('num_neighbours', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_thermal_energy(): function = LegacyFunctionSpecification() function.addParameter('thermal_energy', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_epsilon_dm_part(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('radius', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_epsilon_gas_part(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('radius', dtype='float64', direction=function.OUT) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' return function # setting/ getting parameters @legacy_function def set_time_step(): """ timestep (code units)""" function = LegacyFunctionSpecification() function.addParameter('time_step', dtype='float64', direction=function.IN, description = "The current model timestep") function.result_type = 'int32' return function @legacy_function def get_epsilon(): """Get epsilon, a softening parameter for gravitational potentials with point particles.""" function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='float64', direction=function.OUT, description = "epsilon, a softening parameter for gravitational potentials with point particles") function.result_type = 'int32' return function @legacy_function def set_epsilon(): """Set epsilon, a softening parameter for gravitational potentials with point particles.""" function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='float64', direction=function.IN, description = "epsilon, a softening parameter for gravitational potentials with point particles") function.result_type = 'int32' return function def set_epsilon_squared(self,epsilon_squared): return self.set_epsilon(epsilon_squared**0.5) def get_epsilon_squared(self): epsilon, err = self.get_epsilon() return epsilon**2, err @legacy_function def get_gadget_output_directory(): function = LegacyFunctionSpecification() function.addParameter('gadget_output_directory', dtype='string', direction=function.OUT, description = "The path to the Gadget-2 OutputDir.") function.result_type = 'int32' return function @legacy_function def get_viscosity_switch(): function = LegacyFunctionSpecification() function.addParameter('viscosity_switch', dtype='string', direction=function.OUT, description = "The viscosity switch used by Gadget2.") function.result_type = 'int32' return function @legacy_function def set_gadget_output_directory(): function = LegacyFunctionSpecification() function.addParameter('gadget_output_directory', dtype='string', direction=function.IN, description = "The path to the Gadget-2 OutputDir.") function.result_type = 'int32' return function @legacy_function def get_unit_mass(): """Get the code mass unit (in g/h, default: 1.989e43 g = 10^10 MSun).""" function = LegacyFunctionSpecification() function.addParameter('code_mass_unit', dtype='float64', direction=function.OUT, description = "The code mass unit (in g/h, default: 1.989e43 g = 10^10 MSun).") function.result_type = 'int32' return function @legacy_function def set_unit_mass(): """Set the code mass unit (in g/h, default: 1.989e43 g = 10^10 MSun).""" function = LegacyFunctionSpecification() function.addParameter('code_mass_unit', dtype='float64', direction=function.IN, description = "The code mass unit (in g/h, default: 1.989e43 g = 10^10 MSun).") function.result_type = 'int32' return function @legacy_function def get_unit_length(): """Get the code length unit (in cm/h, default: 3.085678e21 cm = 1 kpc).""" function = LegacyFunctionSpecification() function.addParameter('code_length_unit', dtype='float64', direction=function.OUT, description = "The code length unit (in cm/h, default: 3.085678e21 cm = 1 kpc).") function.result_type = 'int32' return function @legacy_function def set_unit_length(): """Set the code length unit (in cm/h, default: 3.085678e21 cm = 1 kpc).""" function = LegacyFunctionSpecification() function.addParameter('code_length_unit', dtype='float64', direction=function.IN, description = "The code length unit (in cm/h, default: 3.085678e21 cm = 1 kpc).") function.result_type = 'int32' return function @legacy_function def get_unit_time(): """Get the code time unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr). Implicitly changes velocity unit.""" function = LegacyFunctionSpecification() function.addParameter('code_time_unit', dtype='float64', direction=function.OUT, description = "The code time unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).") function.result_type = 'int32' return function @legacy_function def set_unit_time(): """Set the code time unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).""" function = LegacyFunctionSpecification() function.addParameter('code_time_unit', dtype='float64', direction=function.IN, description = "The code time unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).") function.result_type = 'int32' return function @legacy_function def get_unit_velocity(): """Get the code velocity unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).""" function = LegacyFunctionSpecification() function.addParameter('code_velocity_unit', dtype='float64', direction=function.OUT, description = "The code velocity unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).") function.result_type = 'int32' return function @legacy_function def set_unit_velocity(): """Set the code velocity unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).""" function = LegacyFunctionSpecification() function.addParameter('code_velocity_unit', dtype='float64', direction=function.IN, description = "The code velocity unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).") function.result_type = 'int32' return function @legacy_function def get_nogravity(): """ get_nogravity(): get no-gravity flag. True means: gravitational forces are switched of for all particles (read-only: makefile option NOGRAVITY).""" function = LegacyFunctionSpecification() function.addParameter('no_gravity_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_gdgop(): """ set_gdgop([0,1]): use of gadget cell opening criterion if 1 """ function = LegacyFunctionSpecification() function.addParameter('gadget_cell_opening_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_gdgop(): """ get_gdgop(): use of gadget cell opening criterion if 1 """ function = LegacyFunctionSpecification() function.addParameter('gadget_cell_opening_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_epsgas(): """ gas grav smoothing eps""" function = LegacyFunctionSpecification() function.addParameter('gas_epsilon', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_epsgas(): """ gas grav smoothing eps""" function = LegacyFunctionSpecification() function.addParameter('gas_epsilon', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_isotherm(): """(default: False) True means: isothermal gas (read-only: makefile option ISOTHERM_EQS). """ function = LegacyFunctionSpecification() function.addParameter('isothermal_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_eps_is_h(): """ get_eps_is_h(): gas particles grav. eps to SPH h if 1""" function = LegacyFunctionSpecification() function.addParameter('eps_is_h_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_nsmooth(): """ target number of SPH neighbours""" function = LegacyFunctionSpecification() function.addParameter('nsmooth', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_nsmooth(): """ target number of SPH neighbours""" function = LegacyFunctionSpecification() function.addParameter('nsmooth', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_bh_tol(): """ Barnes Hut opening angle parameter (unitless, 0.5) """ function = LegacyFunctionSpecification() function.addParameter('bh_tol', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_bh_tol(): """ Barnes Hut opening angle parameter (unitless, 0.5) """ function = LegacyFunctionSpecification() function.addParameter('bh_tol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_gdgtol(): """ Gadget cell openings criterion parameter (unitless, .005) """ function = LegacyFunctionSpecification() function.addParameter('gdgtol', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_gdgtol(): """ Gadget cell openings criterion parameter (unitless, .005) """ function = LegacyFunctionSpecification() function.addParameter('gdgtol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_gamma(): """ gas polytropic index (1.666667) """ function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_alpha(): """ SPH artificial viscosity alpha parameter (0.5) """ function = LegacyFunctionSpecification() function.addParameter('alpha', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_alpha(): """ SPH artificial viscosity alpha parameter (0.5) """ function = LegacyFunctionSpecification() function.addParameter('alpha', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_beta(): """ SPH artificial viscosity beta parameter (2*viscosity alpha parameter) """ function = LegacyFunctionSpecification() function.addParameter('beta', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_beta(): """ SPH artificial viscosity beta parameter (2*viscosity alpha parameter) """ function = LegacyFunctionSpecification() function.addParameter('beta', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_courant(): """ SPH courant condition parameter (0.3) """ function = LegacyFunctionSpecification() function.addParameter('courant', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_courant(): """ SPH courant condition parameter (0.3) """ function = LegacyFunctionSpecification() function.addParameter('courant', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_nsmtol(): """ fractional tolerance in number of SPH neighbours """ function = LegacyFunctionSpecification() function.addParameter('n_neighbour_tol', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_nsmtol(): """ fractional tolerance in number of SPH neighbours """ function = LegacyFunctionSpecification() function.addParameter('n_neighbour_tol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_energy_file(): function = LegacyFunctionSpecification() function.addParameter('energy_file', dtype='string', direction=function.OUT, description = "The path to the Gadget-2 energy statistics output file.") function.result_type = 'int32' return function @legacy_function def set_energy_file(): function = LegacyFunctionSpecification() function.addParameter('energy_file', dtype='string', direction=function.IN, description = "The path to the Gadget-2 energy statistics output file.") function.result_type = 'int32' return function @legacy_function def get_info_file(): function = LegacyFunctionSpecification() function.addParameter('info_file', dtype='string', direction=function.OUT, description = "The path to the Gadget-2 info output file.") function.result_type = 'int32' return function @legacy_function def set_info_file(): function = LegacyFunctionSpecification() function.addParameter('info_file', dtype='string', direction=function.IN, description = "The path to the Gadget-2 info output file.") function.result_type = 'int32' return function @legacy_function def get_timings_file(): function = LegacyFunctionSpecification() function.addParameter('timings_file', dtype='string', direction=function.OUT, description = "The path to the Gadget-2 timings output file.") function.result_type = 'int32' return function @legacy_function def set_timings_file(): function = LegacyFunctionSpecification() function.addParameter('timings_file', dtype='string', direction=function.IN, description = "The path to the Gadget-2 timings output file.") function.result_type = 'int32' return function @legacy_function def get_cpu_file(): function = LegacyFunctionSpecification() function.addParameter('cpu_file', dtype='string', direction=function.OUT, description = "The path to the Gadget-2 cpu statistics output file.") function.result_type = 'int32' return function @legacy_function def set_cpu_file(): function = LegacyFunctionSpecification() function.addParameter('cpu_file', dtype='string', direction=function.IN, description = "The path to the Gadget-2 cpu statistics output file.") function.result_type = 'int32' return function @legacy_function def get_time_limit_cpu(): function = LegacyFunctionSpecification() function.addParameter('time_limit_cpu', dtype='d', direction=function.OUT, description = "The cpu-time limit. Gadget2 will stop once 85% of this (wall-clock) time has passed.") function.result_type = 'i' return function @legacy_function def set_time_limit_cpu(): function = LegacyFunctionSpecification() function.addParameter('time_limit_cpu', dtype='d', direction=function.IN, description = "The cpu-time limit. Gadget2 will stop once 85% of this (wall-clock) time has passed.") function.result_type = 'i' return function @legacy_function def get_comoving_integration_flag(): function = LegacyFunctionSpecification() function.addParameter('comoving_integration_flag', dtype='bool', direction=function.OUT, description = "Flag to do a cosmological run with comoving coordinates.") function.result_type = 'i' return function @legacy_function def set_comoving_integration_flag(): function = LegacyFunctionSpecification() function.addParameter('comoving_integration_flag', dtype='bool', direction=function.IN, description = "Flag to do a cosmological run with comoving coordinates.") function.result_type = 'i' return function @legacy_function def get_type_of_timestep_criterion(): function = LegacyFunctionSpecification() function.addParameter('type_of_timestep_criterion', dtype='i', direction=function.OUT, description = "Timestep criterion to use. Can only be zero: timestep proportional to acceleration^-0.5") function.result_type = 'i' return function @legacy_function def set_type_of_timestep_criterion(): function = LegacyFunctionSpecification() function.addParameter('type_of_timestep_criterion', dtype='i', direction=function.IN, description = "Timestep criterion to use. Can only be zero: timestep proportional to acceleration^-0.5") function.result_type = 'i' return function @legacy_function def get_time_max(): function = LegacyFunctionSpecification() function.addParameter('time_max', dtype='d', direction=function.OUT, description = "The time at the end of the run.") function.result_type = 'i' return function @legacy_function def set_time_max(): function = LegacyFunctionSpecification() function.addParameter('time_max', dtype='d', direction=function.IN, description = "The time at the end of the run.") function.result_type = 'i' return function @legacy_function def evolve_to_redshift(): function = LegacyFunctionSpecification() function.addParameter('redshift', dtype='d', direction=function.IN, description = "Model redshift to evolve to (for cosmological integrations).") function.result_type = 'i' return function @legacy_function def get_redshift(): function = LegacyFunctionSpecification() function.addParameter('redshift', dtype='d', direction=function.OUT, description = "The current redshift (for cosmological integrations).") function.result_type = 'i' return function @legacy_function def get_redshift_begin(): function = LegacyFunctionSpecification() function.addParameter('redshift_begin', dtype='d', direction=function.OUT, description = "The redshift at the start of the run.") function.result_type = 'i' return function @legacy_function def set_redshift_begin(): function = LegacyFunctionSpecification() function.addParameter('redshift_begin', dtype='d', direction=function.IN, description = "The redshift at the start of the run.") function.result_type = 'i' return function @legacy_function def get_redshift_max(): function = LegacyFunctionSpecification() function.addParameter('redshift_max', dtype='d', direction=function.OUT, description = "The redshift at the end of the run.") function.result_type = 'i' return function @legacy_function def set_redshift_max(): function = LegacyFunctionSpecification() function.addParameter('redshift_max', dtype='d', direction=function.IN, description = "The redshift at the end of the run.") function.result_type = 'i' return function @legacy_function def get_omega_zero(): function = LegacyFunctionSpecification() function.addParameter('omega_zero', dtype='d', direction=function.OUT, description = "Cosmological matter density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def set_omega_zero(): function = LegacyFunctionSpecification() function.addParameter('omega_zero', dtype='d', direction=function.IN, description = "Cosmological matter density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def get_omega_lambda(): function = LegacyFunctionSpecification() function.addParameter('omega_lambda', dtype='d', direction=function.OUT, description = "Cosmological vacuum energy density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def set_omega_lambda(): function = LegacyFunctionSpecification() function.addParameter('omega_lambda', dtype='d', direction=function.IN, description = "Cosmological vacuum energy density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def get_omega_baryon(): function = LegacyFunctionSpecification() function.addParameter('omega_baryon', dtype='d', direction=function.OUT, description = "Cosmological baryonic density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def set_omega_baryon(): function = LegacyFunctionSpecification() function.addParameter('omega_baryon', dtype='d', direction=function.IN, description = "Cosmological baryonic density parameter in units of the critical density at z=0.") function.result_type = 'i' return function @legacy_function def get_hubble_param(): function = LegacyFunctionSpecification() function.addParameter('hubble_param', dtype='d', direction=function.OUT, description = "The cosmological Hubble parameter.") function.result_type = 'i' return function @legacy_function def set_hubble_param(): function = LegacyFunctionSpecification() function.addParameter('hubble_param', dtype='d', direction=function.IN, description = "The cosmological Hubble parameter.") function.result_type = 'i' return function @legacy_function def get_err_tol_int_accuracy(): function = LegacyFunctionSpecification() function.addParameter('err_tol_int_accuracy', dtype='d', direction=function.OUT, description = "Accuracy parameter used in timestep criterion. Actual timesteps are proportional to err_tol_int_accuracy^0.5") function.result_type = 'i' return function @legacy_function def set_err_tol_int_accuracy(): function = LegacyFunctionSpecification() function.addParameter('err_tol_int_accuracy', dtype='d', direction=function.IN, description = "Accuracy parameter used in timestep criterion. Actual timesteps are proportional to err_tol_int_accuracy^0.5") function.result_type = 'i' return function @legacy_function def get_max_size_timestep(): function = LegacyFunctionSpecification() function.addParameter('max_size_timestep', dtype='d', direction=function.OUT, description = "The maximum size of the timestep a particle may take.") function.result_type = 'i' return function @legacy_function def set_max_size_timestep(): function = LegacyFunctionSpecification() function.addParameter('max_size_timestep', dtype='d', direction=function.IN, description = "The maximum size of the timestep a particle may take.") function.result_type = 'i' return function @legacy_function def get_min_size_timestep(): function = LegacyFunctionSpecification() function.addParameter('min_size_timestep', dtype='d', direction=function.OUT, description = "The minimum size of the timestep a particle may take.") function.result_type = 'i' return function @legacy_function def set_min_size_timestep(): function = LegacyFunctionSpecification() function.addParameter('min_size_timestep', dtype='d', direction=function.IN, description = "The minimum size of the timestep a particle may take.") function.result_type = 'i' return function @legacy_function def get_tree_domain_update_frequency(): function = LegacyFunctionSpecification() function.addParameter('tree_domain_update_frequency', dtype='d', direction=function.OUT, description = "The frequency with which the tree and domain decomposition are fully updated, in terms of (# force computations / # particles).") function.result_type = 'i' return function @legacy_function def set_tree_domain_update_frequency(): function = LegacyFunctionSpecification() function.addParameter('tree_domain_update_frequency', dtype='d', direction=function.IN, description = "The frequency with which the tree and domain decomposition are fully updated, in terms of (# force computations / # particles).") function.result_type = 'i' return function @legacy_function def get_time_between_statistics(): function = LegacyFunctionSpecification() function.addParameter('time_between_statistics', dtype='d', direction=function.OUT, description = "The time between statistics output written to the output files.") function.result_type = 'i' return function @legacy_function def set_time_between_statistics(): function = LegacyFunctionSpecification() function.addParameter('time_between_statistics', dtype='d', direction=function.IN, description = "The time between statistics output written to the output files.") function.result_type = 'i' return function @legacy_function def get_min_gas_temp(): function = LegacyFunctionSpecification() function.addParameter('min_gas_temp', dtype='d', direction=function.OUT, description = "The minimum temperature of gas particles.") function.result_type = 'i' return function @legacy_function def set_min_gas_temp(): function = LegacyFunctionSpecification() function.addParameter('min_gas_temp', dtype='d', direction=function.IN, description = "The minimum temperature of gas particles.") function.result_type = 'i' return function @legacy_function def get_min_gas_hsmooth_fractional(): function = LegacyFunctionSpecification() function.addParameter('min_gas_hsmooth_fractional', dtype='d', direction=function.OUT, description = "The minimum smoothing length of gas particles relative to their softening lengths.") function.result_type = 'i' return function @legacy_function def set_min_gas_hsmooth_fractional(): function = LegacyFunctionSpecification() function.addParameter('min_gas_hsmooth_fractional', dtype='d', direction=function.IN, description = "The minimum smoothing length of gas particles relative to their softening lengths.") function.result_type = 'i' return function @legacy_function def get_softening_gas_max_phys(): function = LegacyFunctionSpecification() function.addParameter('softening_gas_max_phys', dtype='d', direction=function.OUT, description = "The maximum physical softening of gas particles for comoving integrations.") function.result_type = 'i' return function @legacy_function def set_softening_gas_max_phys(): function = LegacyFunctionSpecification() function.addParameter('softening_gas_max_phys', dtype='d', direction=function.IN, description = "The maximum physical softening of gas particles for comoving integrations.") function.result_type = 'i' return function @legacy_function def get_softening_halo_max_phys(): function = LegacyFunctionSpecification() function.addParameter('softening_halo_max_phys', dtype='d', direction=function.OUT, description = "The maximum physical softening of dm particles for comoving integrations.") function.result_type = 'i' return function @legacy_function def set_softening_halo_max_phys(): function = LegacyFunctionSpecification() function.addParameter('softening_halo_max_phys', dtype='d', direction=function.IN, description = "The maximum physical softening of dm particles for comoving integrations.") function.result_type = 'i' return function @legacy_function def set_periodic_boundaries_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_periodic_boundaries_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_interpret_kicks_as_feedback_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_interpret_kicks_as_feedback_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_interpret_heat_as_feedback_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_interpret_heat_as_feedback_flag(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_box_size(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_box_size(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_hydro_state_at_point(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN, default = 0) for x in ['rho','rhovx','rhovy','rhovz','rhoe']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function class Gadget2Doc(object): def __get__(self, instance, owner): return instance.legacy_interface.__doc__+"\n\n"+instance.parameters.__doc__ class Gadget2(GravitationalDynamics, GravityFieldCode): __doc__ = Gadget2Doc() def __init__(self, unit_converter = None, mode = 'normal', **options): self.mode = mode legacy_interface = Gadget2Interface(mode = mode, **options) if unit_converter is None: unit_converter = ConvertBetweenGenericAndSiUnits( 3.085678e21 | units.cm, # 1.0 kpc 1.989e43 | units.g, # 1.0e10 solar masses 1e5 | units.cm / units.s) # 1 km/sec self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, legacy_interface, unit_converter, **options ) def initialize_code(self): result = self.overridden().initialize_code() self.parameters.gadget_output_directory = self.get_output_directory() # The code's units are read-only, and set here to ensure they always match with the unit_converter self.set_unit_mass(self.unit_converter.to_si(generic_unit_system.mass).value_in(units.g)) self.set_unit_length(self.unit_converter.to_si(generic_unit_system.length).value_in(units.cm)) self.set_unit_time(self.unit_converter.to_si(generic_unit_system.time).value_in(units.s)) return result def commit_parameters(self): if self.parameters.comoving_integration_flag: h = self.parameters.hubble_parameter self.set_unit_mass(self.unit_converter.to_si(generic_unit_system.mass).value_in(units.g/h)) self.set_unit_length(self.unit_converter.to_si(generic_unit_system.length).value_in(units.cm/h)) self.set_unit_time(self.unit_converter.to_si(generic_unit_system.time).value_in(units.s/h)) handler=self.get_handler("PARTICLES") self.define_additional_particle_attributes(handler) return self.overridden().commit_parameters() def define_properties(self, handler): handler.add_property("get_kinetic_energy") handler.add_property("get_potential_energy") handler.add_property("get_thermal_energy") handler.add_property("get_total_radius") handler.add_property("get_center_of_mass_position") handler.add_property("get_center_of_mass_velocity") handler.add_property("get_total_mass") handler.add_property('get_time', public_name = "model_time") handler.add_property('get_redshift', public_name = "model_redshift") def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) handler.add_method('EDIT', 'before_new_set_instance') handler.add_method('EDIT', 'new_dm_particle') handler.add_method('UPDATE', 'new_dm_particle') handler.add_transition('RUN', 'UPDATE', 'new_dm_particle', False) handler.add_method('EDIT', 'new_sph_particle') handler.add_method('UPDATE', 'new_sph_particle') handler.add_transition('RUN', 'UPDATE', 'new_sph_particle', False) handler.add_transition('RUN', 'EVOLVED', 'evolve_to_redshift', False) handler.add_method('EVOLVED', 'evolve_to_redshift') handler.add_method('RUN', 'get_state_sph') handler.add_method('RUN', 'get_acceleration') handler.add_method('RUN', 'get_internal_energy') handler.add_method('RUN', 'get_smoothing_length') handler.add_method('RUN', 'get_density') handler.add_method('RUN', 'get_alpha_visc') handler.add_method('RUN', 'get_dalphadt_visc') handler.add_method('RUN', 'get_pressure') handler.add_method('RUN', 'get_d_internal_energy_dt') handler.add_method('RUN', 'get_n_neighbours') handler.add_method('RUN', 'get_epsilon_dm_part') handler.add_method('RUN', 'get_epsilon_gas_part') handler.add_method('RUN', 'set_state') handler.add_method('RUN', 'set_state_sph') handler.add_method('RUN', 'set_mass') handler.add_method('RUN', 'set_position') handler.add_method('RUN', 'set_velocity') handler.add_method('RUN', 'set_internal_energy') handler.add_method('RUN', 'get_kinetic_energy') handler.add_method('RUN', 'get_potential_energy') handler.add_method('RUN', 'get_thermal_energy') handler.add_method('RUN', 'get_total_radius') handler.add_method('RUN', 'get_center_of_mass_position') handler.add_method('RUN', 'get_center_of_mass_velocity') handler.add_method('RUN', 'get_total_mass') handler.add_method('RUN', 'get_hydro_state_at_point') self.stopping_conditions.define_state(handler) def define_parameters(self, handler): handler.add_method_parameter( "get_epsilon_squared", "set_epsilon_squared", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0001 | generic_unit_system.length * generic_unit_system.length ) handler.add_method_parameter( "get_time_step", None, "timestep", "timestep for system, Gadget2 calculates this by itself, based on particle acceleration.", default_value = 1.0 | generic_unit_system.time ) handler.add_boolean_parameter( "get_nogravity", None, "no_gravity_flag", "No-gravity flag. True means: gravitational forces are switched of for all particles " "(read-only: makefile option NOGRAVITY).", False ) handler.add_boolean_parameter( "get_gdgop", "set_gdgop", "gadget_cell_opening_flag", "Gadget-cell-opening flag. True means: use of Gadget cell opening criterion; Barnes-Hut otherwise", True ) handler.add_boolean_parameter( "get_isotherm", None, "isothermal_flag", "Isothermal flag. True means: isothermal gas, u is interpreted as c_s^2 " "(read-only: makefile option ISOTHERM_EQS).", False ) handler.add_boolean_parameter( "get_eps_is_h", None, "eps_is_h_flag", "Eps-is-h flag. True means: set gas particles gravitational epsilon to h (SPH smoothing length) " "(read-only: makefile option ADAPTIVE_GRAVSOFT_FORGAS).", False ) handler.add_method_parameter( "get_nsmooth", "set_nsmooth", "n_smooth", "The target number of SPH neighbours.", default_value = 50 ) handler.add_method_parameter( "get_unit_mass", None, "code_mass_unit", "The code mass unit (in g/h, 1.989e43 g = 10^10 MSun standard).", default_value = 1.989e43 | units.g ) handler.add_method_parameter( "get_unit_length", None, "code_length_unit", "The code length unit (in cm/h, 3.085678e21 cm = 1 kpc standard).", default_value = 3.085678e21 | units.cm ) handler.add_method_parameter( "get_unit_time", None, "code_time_unit", "The code time unit (in s/h, default: 3.085678e16 s = (1 kpc) / (1 km/s) ~ 0.9778 Gyr).", default_value = 3.085678e16 | units.s ) handler.add_method_parameter( "get_unit_velocity", None, "code_velocity_unit", "The code velocity unit (in cm/s, default: 1e5 cm/s = 1 km/s).", default_value = 1e5 | units.cm / units.s ) handler.add_method_parameter( "get_bh_tol", "set_bh_tol", "opening_angle", "Opening angle, theta, for building the tree: between 0 and 1 (unitless, 0.5).", default_value = 0.5 ) handler.add_method_parameter( "get_gdgtol", "set_gdgtol", "gadget_cell_opening_constant", "Gadget-cell-openings criterion parameter (unitless, 0.005)", default_value = 0.005 ) handler.add_method_parameter( "get_epsgas", "set_epsgas", "gas_epsilon", "The gas gravitational smoothing epsilon.", default_value = 0.01 | generic_unit_system.length ) handler.add_method_parameter( "get_gamma", None, "polytropic_index_gamma", "gas polytropic index (1.6666667 or 1 for isothermal" "(read-only: makefile option ISOTHERM_EQS).", default_value = (5.0/3) ) handler.add_method_parameter( "get_alpha", "set_alpha", "artificial_viscosity_alpha", "SPH artificial viscosity alpha parameter (0.5)", default_value = 0.5 ) handler.add_method_parameter( "get_beta", "set_beta", "artificial_viscosity_beta", "SPH artificial viscosity beta parameter (2*viscosity alpha parameter)", default_value = 1.0 ) handler.add_method_parameter( "get_courant", "set_courant", "courant", "SPH courant condition parameter (0.3). Note that we follow conventional smoothing length " "definitions, implying a factor 2 difference with Gadget's CourantFac parameter", default_value = 0.3 ) handler.add_method_parameter( "get_nsmtol", "set_nsmtol", "n_smooth_tol", "fractional tolerance in number of SPH neighbours", default_value = 0.1 ) handler.add_method_parameter( "get_gadget_output_directory", "set_gadget_output_directory", "gadget_output_directory", "Name of the Gadget-2 OutputDir", default_value = "" ) handler.add_method_parameter( "get_viscosity_switch", None, "viscosity_switch", "Viscosity switch used by Gadget2", default_value = "standard Gadget2 viscosity" ) handler.add_method_parameter( "get_energy_file", "set_energy_file", "energy_file", "The path to the Gadget-2 energy statistics output file.", default_value = "energy.txt" ) handler.add_method_parameter( "get_info_file", "set_info_file", "info_file", "The path to the Gadget-2 info output file.", default_value = "info.txt" ) handler.add_method_parameter( "get_timings_file", "set_timings_file", "timings_file", "The path to the Gadget-2 timings output file.", default_value = "timings.txt" ) handler.add_method_parameter( "get_cpu_file", "set_cpu_file", "cpu_file", "The path to the Gadget-2 cpu statistics output file.", default_value = "cpu.txt" ) handler.add_method_parameter( "get_time_limit_cpu", "set_time_limit_cpu", "time_limit_cpu", "The cpu-time limit. Gadget2 will stop once 85% of this (wall-clock) time has passed.", default_value = 36000 | units.s ) handler.add_boolean_parameter( "get_comoving_integration_flag", "set_comoving_integration_flag", "comoving_integration_flag", "Flag to do a cosmological run with comoving coordinates.", False ) handler.add_method_parameter( "get_type_of_timestep_criterion", "set_type_of_timestep_criterion", "type_of_timestep_criterion", "Timestep criterion to use. Can only be zero: timestep proportional to acceleration^-0.5", default_value = 0 ) 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_time_max", "set_time_max", "time_max", "The time at the end of the run.", default_value = 100.0 | generic_unit_system.time ) handler.add_method_parameter( "get_redshift_begin", "set_redshift_begin", "redshift_begin", "The redshift at the start of the run.", default_value = 20.0 ) handler.add_method_parameter( "get_redshift_max", "set_redshift_max", "redshift_max", "The redshift at the end of the run.", default_value = 0.0 ) handler.add_method_parameter( "get_omega_zero", "set_omega_zero", "omega_zero", "Cosmological matter density parameter in units of the critical density at z=0.", default_value = 0.0 ) handler.add_method_parameter( "get_omega_lambda", "set_omega_lambda", "omega_lambda", "Cosmological vacuum energy density parameter in units of the critical density at z=0.", default_value = 0.0 ) handler.add_method_parameter( "get_omega_baryon", "set_omega_baryon", "omega_baryon", "Cosmological baryonic density parameter in units of the critical density at z=0.", default_value = 0.0 ) handler.add_method_parameter( "get_hubble_param", "set_hubble_param", "hubble_parameter", "The cosmological Hubble parameter, value of Hubble constant in units of 100 km/s / Mpc.", default_value = 0.7 ) handler.add_method_parameter( "get_err_tol_int_accuracy", "set_err_tol_int_accuracy", "timestep_accuracy_parameter", "Accuracy parameter used in timestep criterion. Actual timesteps are proportional to err_tol_int_accuracy^0.5", default_value = 0.025 ) handler.add_method_parameter( "get_max_size_timestep", "set_max_size_timestep", "max_size_timestep", "The maximum size of the timestep a particle may take.", default_value = 0.01 | generic_unit_system.time ) handler.add_method_parameter( "get_min_size_timestep", "set_min_size_timestep", "min_size_timestep", "The minimum size of the timestep a particle may take.", default_value = 0.0 | generic_unit_system.time ) handler.add_method_parameter( "get_tree_domain_update_frequency", "set_tree_domain_update_frequency", "tree_domain_update_frequency", "The frequency with which the tree and domain decomposition are fully updated, in terms of (# force computations / # particles).", default_value = 0.05 ) handler.add_method_parameter( "get_time_between_statistics", "set_time_between_statistics", "time_between_statistics", "The time between statistics output written to the output files.", default_value = 0.1 | generic_unit_system.time ) handler.add_method_parameter( "get_min_gas_temp", "set_min_gas_temp", "min_gas_temp", "The minimum temperature of gas particles.", default_value = 0.0 | units.K ) handler.add_method_parameter( "get_min_gas_hsmooth_fractional", "set_min_gas_hsmooth_fractional", "min_gas_hsmooth_fractional", "The minimum smoothing length of gas particles relative to their softening lengths.", default_value = 0.0 ) handler.add_method_parameter( "get_softening_gas_max_phys", "set_softening_gas_max_phys", "softening_gas_max_phys", "The maximum physical softening of gas particles for comoving integrations.", default_value = 0.0 | generic_unit_system.length ) handler.add_method_parameter( "get_softening_halo_max_phys", "set_softening_halo_max_phys", "softening_halo_max_phys", "The maximum physical softening of dm particles for comoving integrations.", default_value = 0.0 | generic_unit_system.length ) handler.add_method_parameter( "get_box_size", "set_box_size", "periodic_box_size", "The size of the box in case of periodic boundary conditions.", default_value = 1.0 | generic_unit_system.length ) handler.add_boolean_parameter( "get_periodic_boundaries_flag", None, "periodic_boundaries_flag", "Periodic boundaries flag. Read-only. True means: use periodic boundary conditions", False ) handler.add_boolean_parameter( "get_interpret_kicks_as_feedback_flag", "set_interpret_kicks_as_feedback_flag", "interpret_kicks_as_feedback", "Flag telling Gadget2 whether to interpret external changes to particles' velocities as feedback (for timestepping).", False ) handler.add_boolean_parameter( "get_interpret_heat_as_feedback_flag", "set_interpret_heat_as_feedback_flag", "interpret_heat_as_feedback", "Flag telling Gadget2 whether to interpret external changes to particles' internal energy as feedback (for timestepping).", True ) self.stopping_conditions.define_parameters(handler) def define_particle_sets(self, handler): handler.define_super_set('particles', ['dm_particles','gas_particles'], index_to_default_set = 0) handler.define_set('dm_particles', 'index_of_the_particle') handler.set_new('dm_particles', 'new_dm_particle') handler.set_delete('dm_particles', 'delete_particle') handler.add_setter('dm_particles', 'set_state') handler.add_getter('dm_particles', 'get_state') handler.add_setter('dm_particles', 'set_mass') handler.add_getter('dm_particles', 'get_mass', names = ('mass',)) handler.add_setter('dm_particles', 'set_position') handler.add_getter('dm_particles', 'get_position') handler.add_setter('dm_particles', 'set_velocity') handler.add_getter('dm_particles', 'get_velocity') handler.add_getter('dm_particles', 'get_acceleration') handler.add_getter('dm_particles', 'get_epsilon_dm_part', names = ('radius',)) handler.add_getter('dm_particles', 'get_epsilon_dm_part', names = ('epsilon',)) handler.define_set('gas_particles', 'index_of_the_particle',state_guard="before_new_set_instance") handler.set_new('gas_particles', 'new_sph_particle') handler.set_delete('gas_particles', 'delete_particle') handler.add_setter('gas_particles', 'set_state_sph') handler.add_getter('gas_particles', 'get_state_sph') handler.add_setter('gas_particles', 'set_mass') handler.add_getter('gas_particles', 'get_mass', names = ('mass',)) handler.add_setter('gas_particles', 'set_position') handler.add_getter('gas_particles', 'get_position') handler.add_setter('gas_particles', 'set_velocity') handler.add_getter('gas_particles', 'get_velocity') handler.add_getter('gas_particles', 'get_acceleration') handler.add_setter('gas_particles', 'set_internal_energy') handler.add_getter('gas_particles', 'get_internal_energy') handler.add_getter('gas_particles', 'get_smoothing_length') handler.add_getter('gas_particles', 'get_density', names = ('rho',)) handler.add_getter('gas_particles', 'get_density', names = ('density',)) handler.add_getter('gas_particles', 'get_pressure') handler.add_getter('gas_particles', 'get_d_internal_energy_dt') handler.add_getter('gas_particles', 'get_n_neighbours') handler.add_getter('gas_particles', 'get_epsilon_gas_part', names = ('radius',)) handler.add_getter('gas_particles', 'get_epsilon_gas_part', names = ('epsilon',)) self.stopping_conditions.define_particle_set(handler) def define_additional_particle_attributes(self, handler): if self.parameters.viscosity_switch=="Morris & Monaghan 1997": handler.add_getter('gas_particles', 'get_alpha_visc', names = ('viscosity_alpha',)) handler.add_getter('gas_particles', 'get_dalphadt_visc', names = ('viscosity_dalphadt',)) def define_errorcodes(self, handler): handler.add_errorcode(-1, 'Unspecified, other error.') handler.add_errorcode(-2, 'Called function is not implemented.') handler.add_errorcode(-3, 'A particle with the given index was not found.') handler.add_errorcode(-4, 'Parameter check failed.') handler.add_errorcode(-5, 'CPU-time limit reached.') handler.add_errorcode(-6, "Can't evolve backwards in time.") handler.add_errorcode(-7, "Can't evolve further than time_max.") handler.add_errorcode(-8, "A particle was assigned a timestep of size zero. The code_time_unit used may be too large.") handler.add_errorcode(-9, "This function should not be used with the current value of comoving_integration_flag") def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method('evolve_model', (generic_unit_system.time,), ( handler.ERROR_CODE, )) handler.add_method('evolve_to_redshift', (handler.NO_UNIT,), ( handler.ERROR_CODE, )) handler.add_method( "new_particle", ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "delete_particle", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state", ( handler.NO_UNIT, ), ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, handler.ERROR_CODE ) ) handler.add_method( "set_state", ( handler.NO_UNIT, generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.ERROR_CODE ) ) handler.add_method( "set_mass", ( handler.NO_UNIT, generic_unit_system.mass, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_mass", ( handler.NO_UNIT, ), ( generic_unit_system.mass, handler.ERROR_CODE ) ) handler.add_method( "set_radius", ( handler.NO_UNIT, generic_unit_system.length, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_radius", ( handler.NO_UNIT, ), ( generic_unit_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_position", ( handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_position", ( handler.NO_UNIT, ), ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_velocity", ( handler.INDEX, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_velocity", ( handler.INDEX, ), ( generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, handler.ERROR_CODE ) ) handler.add_method( "get_acceleration", ( handler.INDEX, ), ( generic_unit_system.acceleration, generic_unit_system.acceleration, generic_unit_system.acceleration, handler.ERROR_CODE ) ) handler.add_method( "get_potential", ( handler.NO_UNIT, ), ( generic_unit_system.potential, handler.ERROR_CODE ) ) handler.add_method( "new_dm_particle", ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "new_sph_particle", ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.specific_energy, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "get_state_sph", ( handler.INDEX, ), ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.specific_energy, handler.ERROR_CODE ) ) handler.add_method( "set_state_sph", ( handler.INDEX, generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.specific_energy, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_internal_energy", ( handler.INDEX, generic_unit_system.specific_energy, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_internal_energy", ( handler.INDEX, ), ( generic_unit_system.specific_energy, handler.ERROR_CODE ) ) handler.add_method( "get_smoothing_length", (handler.INDEX,), (generic_unit_system.length, handler.ERROR_CODE) ) handler.add_method( "get_density", (handler.INDEX,), (generic_unit_system.density, handler.ERROR_CODE) ) handler.add_method( "get_pressure", (handler.INDEX,), (generic_unit_system.pressure, handler.ERROR_CODE) ) handler.add_method( "get_d_internal_energy_dt", (handler.INDEX,), (generic_unit_system.specific_energy / generic_unit_system.time, handler.ERROR_CODE) ) handler.add_method( "get_n_neighbours", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( "get_epsilon_dm_part", (handler.INDEX,), (generic_unit_system.length, handler.ERROR_CODE) ) handler.add_method( "get_epsilon_gas_part", (handler.INDEX,), (generic_unit_system.length, handler.ERROR_CODE) ) handler.add_method( 'get_hydro_state_at_point', (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed), (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE) ) handler.add_method( "get_epsilon_squared", (), (generic_unit_system.length * generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_epsilon_squared", (generic_unit_system.length * generic_unit_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "get_nsmooth", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_nsmooth", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_unit_mass", (), (units.g, handler.ERROR_CODE,) ) handler.add_method( "get_unit_length", (), (units.cm, handler.ERROR_CODE,) ) handler.add_method( "get_unit_time", (), (units.s, handler.ERROR_CODE,) ) handler.add_method( "get_unit_velocity", (), (units.cm / units.s, handler.ERROR_CODE,) ) handler.add_method( "get_bh_tol", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_bh_tol", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_gdgtol", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_gdgtol", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_epsgas", (), (generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_epsgas", (generic_unit_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_gamma", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_alpha", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_alpha", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_beta", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_beta", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_courant", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_courant", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_nsmtol", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_nsmtol", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_gadget_output_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_gadget_output_directory", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_energy_file", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_energy_file", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_info_file", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_info_file", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_timings_file", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_timings_file", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_cpu_file", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_cpu_file", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_time_limit_cpu", (), (units.s, handler.ERROR_CODE,) ) handler.add_method( "set_time_limit_cpu", (units.s, ), (handler.ERROR_CODE,) ) handler.add_method( "get_type_of_timestep_criterion", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_type_of_timestep_criterion", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_begin_time", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_begin_time", (generic_unit_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_time_max", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_max", (generic_unit_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_redshift_begin", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_redshift_begin", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_redshift_max", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_redshift_max", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_omega_zero", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_omega_zero", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_omega_lambda", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_omega_lambda", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_omega_baryon", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_omega_baryon", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_hubble_param", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_hubble_param", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_err_tol_int_accuracy", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_err_tol_int_accuracy", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_max_size_timestep", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_max_size_timestep", (generic_unit_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_min_size_timestep", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_min_size_timestep", (generic_unit_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tree_domain_update_frequency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_tree_domain_update_frequency", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_time_between_statistics", (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_between_statistics", (generic_unit_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_min_gas_temp", (), (units.K, handler.ERROR_CODE,) ) handler.add_method( "set_min_gas_temp", (units.K, ), (handler.ERROR_CODE,) ) handler.add_method( "get_min_gas_hsmooth_fractional", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_min_gas_hsmooth_fractional", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_softening_gas_max_phys", (), (generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_softening_gas_max_phys", (generic_unit_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_softening_halo_max_phys", (), (generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_softening_halo_max_phys", (generic_unit_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_box_size", (), (generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_box_size", (generic_unit_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_kinetic_energy", (), (generic_unit_system.energy, handler.ERROR_CODE,) ) handler.add_method( "get_potential_energy", (), (generic_unit_system.energy, handler.ERROR_CODE,) ) handler.add_method( "get_thermal_energy", (), (generic_unit_system.energy, handler.ERROR_CODE,) ) handler.add_method( "get_total_radius", (), (generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "get_center_of_mass_position", (), (generic_unit_system.length,generic_unit_system.length,generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( "get_center_of_mass_velocity", (), (generic_unit_system.speed,generic_unit_system.speed,generic_unit_system.speed, handler.ERROR_CODE,) ) handler.add_method( "get_total_mass", (), (generic_unit_system.mass, handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( 'get_redshift', (), (handler.NO_UNIT, handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler)
99,817
37.824582
195
py
amuse
amuse-main/src/amuse/community/smalln/scatter32.py
#!/usr/bin/env python # Scatter32: binary scattering package replicating most of the # functionality of the scatter3 tool in Starlab. See McMillan & Hut # 1996, ApJ, 467, 348. This version uses (possibly) separate modules # to evolve the dynamics and to check for the end of the scattering. import sys, unittest, numpy, random, collections, getopt, os, math from time import * from amuse.units import nbody_system from amuse.units import units from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.datamodel import trees 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_nbody #----------------------------------------------------------------------- class Initial_state(): # modeled on the Starlab scatter3 class m = 0.5 # no units in init -- add in make_triple M = 0.5 eccentricity = 0. impact_parameter = 0. v_infinity = 1.0 planar = 0 class Final_state(): # modeled on the Starlab scatter3 class is_over = 0 time = 0.0 mbinary = 0.0 semimajoraxis = 0.0 eccentricity = 0.0 mescaper = 0.0 escaper = 0 separation = 0.0 v_rel = 0.0 #----------------------------------------------------------------------- # Build functions could/should be offloaded to a separate module. zero = 0.0|units.none one = 1.0|units.none def normalized(a): amagi = 1./math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]) b = [a[0]*amagi, a[1]*amagi, a[2]*amagi] return b def sum3(a, b): c = [a[0] + b[0], a[1] + b[1], a[2] + b[2]] return c def cross(a, b): c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c def set_inner_orbit(init, kep): semi = 1.0|nbody_system.length ecc = init.eccentricity kep.set_longitudinal_unit_vector(one, zero, zero) kep.set_normal_unit_vector(zero, zero, one) mean_an = 2*math.pi*numpy.random.random() kep.initialize_from_elements(1.0|nbody_system.mass, semi, ecc, mean_an) print('inner semi, ecc =', semi.number, ecc) def set_outer_orbit(init, kep): mtotal = 1 + init.M # Multiply the incoming velocity by the critical value (see Hut & # Bahcall 1983). v_inf = init.v_infinity \ * math.sqrt( (1 - init.m) * init.m * mtotal / init.M ) energy3 = 0.5 * v_inf * v_inf print('m1, m2, m3 =', 1-init.m, init.m, init.M) print('v_inf =', v_inf, 'energy3 =', energy3, \ 'rho =', init.impact_parameter) if energy3 > 0: semi = -0.5*mtotal/energy3|nbody_system.length ang_mom3 = init.impact_parameter * v_inf ecc = math.sqrt( 1 + 2 * energy3 * (ang_mom3/mtotal)**2) periastron = -semi*max(ecc-1.0, 0.0) # not used else: semi = 0|nbody_system.length # not used ecc = 1 periastron = init.impact_parameter|nbody_system.length # Orientation: if init.planar != 0: kep.set_longitudinal_unit_vector(one, zero, zero) if init.planar == 1: kep.set_normal_unit_vector(zero, zero, one) else: kep.set_normal_unit_vector(zero, zero, -one) else: costheta = 2*numpy.random.random() - 1 sintheta = math.sqrt(max(0, 1-costheta**2)) phi = 2*math.pi*numpy.random.random() longv = [sintheta*math.cos(phi), sintheta*math.sin(phi), costheta] kep.set_longitudinal_unit_vector(longv[0], longv[1], longv[2]) if abs(longv[0]) < 0.5: temp = [1, 0, 0] else: temp = [0, 1, 0] trans = normalized(cross(longv, temp)) normal = cross(longv, trans) psi = 2*math.pi*numpy.random.random() cospsi = math.cos(psi) sinpsi = math.sin(psi) normal = [cospsi*trans[0]+sinpsi*normal[0], cospsi*trans[1]+sinpsi*normal[1], cospsi*trans[2]+sinpsi*normal[2]] kep.set_normal_unit_vector(normal[0], normal[1], normal[2]) time = 0.0|nbody_system.time mean_anomaly = 0 # t = 0 at periastron if periastron.number == 0: mean_anomaly = -1.e-3 print('mean_anomaly =', mean_anomaly) print('outer semi, ecc =', semi.number, ecc) kep.initialize_from_elements(mtotal|nbody_system.mass, semi, ecc, mean_anomaly, time, periastron) print('outer normal =', kep.get_normal_unit_vector()) print('outer periastron =', kep.get_periastron().number) #kep.print_all() def make_triple(init, kep, gamma): # Create IDs and initial masses, positions, and velocities. # Convention: initial binary is (1,2). # Inner orbit (1,2). set_inner_orbit(init, kep) rel_pos = kep.get_separation_vector() rel_vel = kep.get_velocity_vector() f = init.m pos1 = [-f*rel_pos[0], -f*rel_pos[1], -f*rel_pos[2]] vel1 = [-f*rel_vel[0], -f*rel_vel[1], -f*rel_vel[2]] pos2 = [(1-f)*rel_pos[0], (1-f)*rel_pos[1], (1-f)*rel_pos[2]] vel2 = [(1-f)*rel_vel[0], (1-f)*rel_vel[1], (1-f)*rel_vel[2]] # Outer orbit ((1,2),3). set_outer_orbit(init, kep) # print '----------' # kep.print_all() # gamma = gravity.parameters.unperturbed_threshold # won't work, in general kep.return_to_radius((gamma/init.M)**(-1./3)|nbody_system.length) # print '----------' # kep.print_all() # print '----------' time = kep.get_time() rel_pos = kep.get_separation_vector() rel_vel = kep.get_velocity_vector() f = init.M/(1+init.M) pos12 = [-f*rel_pos[0], -f*rel_pos[1], -f*rel_pos[2]] vel12 = [-f*rel_vel[0], -f*rel_vel[1], -f*rel_vel[2]] print('outer separation =', kep.get_separation().number, \ ' time =', kep.get_time().number) pos1 = sum3(pos1, pos12) vel1 = sum3(vel1, vel12) pos2 = sum3(pos2, pos12) vel2 = sum3(vel2, vel12) pos3 = [(1-f)*rel_pos[0], (1-f)*rel_pos[1], (1-f)*rel_pos[2]] vel3 = [(1-f)*rel_vel[0], (1-f)*rel_vel[1], (1-f)*rel_vel[2]] print('initial time =', time.number, "(time of outer periastron = 0)") # Create the 3-body system. id = [1, 2, 3] mass = [1-init.m, init.m, init.M] | nbody_system.mass pos = [pos1, pos2, pos3] vel = [vel1, vel2, vel3] return time, id, mass, pos, vel def make_triple2(init, kep, gamma): # Use a kepler built-in to replace the Python functionality of # make_triple. # Create IDs and initial masses, positions, and velocities. # Convention: initial binary is (1,2). t,m1,m2,m3,x1,x2,x3,y1,y2,y3,z1,z2,z3, \ vx1,vx2,vx3,vy1,vy2,vy3,vz1,vz2,vz3 \ = kep.make_binary_scattering(init.m|nbody_system.mass, init.eccentricity, init.M|nbody_system.mass, init.v_infinity|nbody_system.speed, init.impact_parameter|nbody_system.length, gamma, init.planar) id = [1, 2, 3] mass = [m1,m2,m3] pos = [[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]] vel = [[vx1,vy1,vz1], [vx2,vy2,vz2], [vx3,vy3,vz3]] return t, id, mass, pos, vel #----------------------------------------------------------------------- def get_binary_elements(p, kep): comp1 = p.child1 comp2 = p.child2 m = comp1.mass + comp2.mass kep.initialize_from_dyn(m, comp2.x-comp1.x, comp2.y-comp1.y, comp2.z-comp1.z, comp2.vx-comp1.vx, comp2.vy-comp1.vy, comp2.vz-comp1.vz) a,e = kep.get_elements() return m,a,e def get_final_state(stars, kep): final = Final_state() final.is_over = 1 final.escaper = -1 ionized = 1 tree = stars.as_binary_tree() sep = numpy.zeros(3) vel = numpy.zeros(3) for node in tree.iter_children(): if node.particle.child1 is None: final.escaper = node.particle.id final.mescaper = node.particle.mass.number sep += numpy.array([node.particle.x.number, node.particle.y.number, node.particle.z.number]) vel += numpy.array([node.particle.vx.number, node.particle.vy.number, node.particle.vz.number]) else: M,a,e = get_binary_elements(node.particle, kep) final.mbinary = M.number final.semimajoraxis = a.number final.eccentricity = e ionized = 0 sep -= numpy.array([node.particle.x.number, node.particle.y.number, node.particle.z.number]) vel -= numpy.array([node.particle.vx.number, node.particle.vy.number, node.particle.vz.number]) if ionized == 0: final.separation = math.sqrt((sep*sep).sum()) final.v_rel = math.sqrt((vel*vel).sum()) else: final.mbinary = -1.0 final.semimajoraxis = -1.0 final.eccentricity = -1.0 final.escaper = -1 final.mescaper = -1.0 final.separation = -1.0 final.v_rel = -1.0 return final def scatter32(init, kep, gravity, treecheck, gamma = 1.e-6, delta_t = 0 | nbody_system.time, t_end = 1.e4 | nbody_system.time): # Kepler manages the two-body dynamics. # Gravity manages the N-body integration. # Treecheck determines the structure of the 3-body system. # Treecheck = gravity is OK. t1 = clock() # <----------------- t1 ----------------- # Create the 3-body system; time = 0 at outer peri. #time, id, mass, pos, vel = make_triple(init, kep, gamma) time, id, mass, pos, vel = make_triple2(init, kep, gamma) stars = datamodel.Particles(3) stars.id = id stars.mass = mass stars.position = pos stars.velocity = vel stars.radius = 0. | nbody_system.length #print stars print("adding particles") sys.stdout.flush() gravity.set_time(time) gravity.particles.add_particles(stars) #print "committing particles" #gravity.commit_particles() sys.stdout.flush() # Channel to copy values from the codes to the set in memory. channel = gravity.particles.new_channel_to(stars) if treecheck != gravity: channel2 = treecheck.particles.new_channel_to(stars) else: channel2 = channel # Don't have a proper unperturbed termination criterion in smallN. # For now, insist that the final time exceed minus the initial # time (recall that outer peri is at t = 0). t_crit = -time if delta_t.number <= 0.0: delta_t = 2*t_crit # for efficiency print("evolving triple to completion in steps of", delta_t.number) sys.stdout.flush() t2 = clock() # <----------------- t2 ----------------- dt_init = t2 - t1 dt_evolve = 0.0 dt_over = 0.0 dt_tree = 0.0 dt_clean = 0.0 final = Final_state() over = 0 while time < t_end and over == 0: tt3 = clock() # <----------------- tt3 ---------------- time += delta_t gravity.evolve_model(time) energy = gravity.get_kinetic_energy()+gravity.get_potential_energy() print("time =", time.number, "energy =", energy.number) tt4 = clock() # <----------------- tt4 ---------------- if time > t_crit: # Check to see if the interaction is over. # Update the local stars data from the module. # Should still be a flat tree, even for SmallN. ttt5 = clock() # <---------------- ttt5 ---------------- if treecheck != gravity: channel.copy() channel.copy_attribute("index_in_code", "id") # Send the data to the treecheck module and test if the # interaction is over. treecheck.particles.add_particles(stars) treecheck.commit_particles() over = treecheck.is_over() ttt6 = clock() # <---------------- ttt6 ---------------- if over: #print '\nscatter32: interaction is over' # The rest of the work is done by treecheck. Note # that we are assuming that the outcomes of gravity # and treecheck are qualitatively similar... treecheck.update_particle_tree() # builds an internal tree # in the SmallN case treecheck.update_particle_set() # updates local bookkeeping treecheck.particles.synchronize_to(stars) channel2.copy() channel2.copy_attribute("index_in_code", "id") # Determine the final state. final = get_final_state(stars, kep) final.time = time.number ttt7 = clock() # <---------------- ttt7 ---------------- # Clean up treecheck for the next use. #treecheck.particles.remove_particles(treecheck.particles) treecheck.reset() ttt8 = clock() # <---------------- ttt8 ---------------- dt_over += ttt6 - ttt5 dt_tree += ttt7 - ttt6 dt_clean += ttt8 - ttt7 dt_evolve += tt4 - tt3 if not over: #print '\nscatter32: interaction is not over' final.is_over = 0 final.mbinary = -1.0 final.semimajoraxis = -1.0 final.eccentricity = -1.0 final.escaper = -1 final.mescaper = -1.0 final.separation = -1.0 final.v_rel = -1.0 # Clean up internal data for recycling. # Reset children so that the garbage collection can do its work. stars.child1 = None stars.child2 = None gravity.reset() return final,numpy.array([dt_init, dt_evolve, dt_over, dt_tree, dt_clean]) if __name__ == '__main__': nscatter = 1 accuracy_parameter = 0.1 gamma = 1.e-6 delta_t = 0.0 | nbody_system.time t_end = 1.e5 | nbody_system.time random_seed = -1 init = Initial_state() try: opts, args = getopt.getopt(sys.argv[1:], "A:d:e:g:m:M:n:pPr:s:t:v:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) # Command-line arguments are modeled on those in starlab. # Units: G = 1, binary mass = 1, binary semi-major axis = 1. for o, a in opts: if o == "-A": accuracy_parameter = float(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": init.eccentricity = float(a) if init.eccentricity >= 1: raise Exception("e < 1 required") elif o == "-g": gamma = float(a) elif o == "-m": init.m = float(a) if init.m <= 0 or init.m >= 1: raise Exception("0 < m < 1 required") elif o == "-M": init.M = float(a) if init.M <= 0: raise Exception("M > 0 required") elif o == "-n": nscatter = int(a) elif o == "-p": init.planar = 1 elif o == "-P": init.planar = -1 elif o == "-r": init.impact_parameter = float(a) if init.impact_parameter < 0: raise Exception("r >= 0 required") elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a)|nbody_system.time elif o == "-v": init.v_infinity = float(a) if init.v_infinity < 0: raise Exception("v >= 0 required") else: print("unexpected argument", o) if random_seed <= 0: numpy.random.seed() random_seed = numpy.random.randint(1, pow(2,31)-1) numpy.random.seed(random_seed) print("random seed =", random_seed, numpy.random.random()) #----------------------------------------------------------------- assert is_mpd_running() # Instantiate worker modules once only and pass them to scatter32 # as arguments. # Kepler manages two-body dynamics. kep = Kepler(redirection = "none") #, debugger="gdb") kep.initialize_code() kep.set_random(random_seed) # ** Note potential conflict between C++ # ** and Python random generators. # Gravity manages the N-body integration. gravity = SmallN(redirection = "none") gravity.initialize_code() gravity.parameters.set_defaults() gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.unperturbed_threshold = gamma # Treecheck determines the structure of the 3-body system. # Treecheck = gravity is OK. treecheck = SmallN(redirection = "none") treecheck.initialize_code() treecheck.parameters.set_defaults() treecheck.parameters.timestep_parameter = accuracy_parameter treecheck.parameters.unperturbed_threshold = gamma # Timing: cpu = numpy.zeros(5) for i in range(nscatter): final,dcpu = scatter32(init, kep, gravity, treecheck, gamma, delta_t, t_end) #final,dcpu = scatter32(init, kep, gravity, gravity, # gamma, delta_t, t_end) cpu += dcpu print('') if final.is_over == 0: print('interaction is not over') else: if final.escaper > 0: print('escaper =', final.escaper, \ 'sep =', final.separation, \ 'vel =', final.v_rel) print('binary (mass =', final.mbinary, \ 'semi =', final.semimajoraxis, \ 'ecc =', final.eccentricity, ')') else: print('ionization') if nscatter > 1: print('\n--------------------\n') print('timing: init', cpu[0], 'evol', cpu[1], 'over', cpu[2], \ 'tree', cpu[3], 'clean', cpu[4]) print('') gravity.stop() treecheck.stop() kep.stop()
18,261
31.552585
79
py
amuse
amuse-main/src/amuse/community/smalln/test_smallN.py
import sys import unittest import numpy import random import collections import getopt import os from amuse.units import nbody_system from amuse.units import units from amuse.community.smalln.interface import SmallN as grav from amuse.community.kepler.interface import Kepler from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.datamodel import trees 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_nbody def print_log(time, gravity, E0 = 0.0 | nbody_system.energy): M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy E = T + U if E0 == 0 | nbody_system.energy: E0 = E Rv = -0.5*M*M/U Q = -T/U print("") print("smallN: time =", time.number, " energy = ", E.number, \ " dE/E0 = ", (E/E0 - 1)) print('%s %.4f %.6f %.6f %.6f %.6f %.6f %.6f' % \ ("smallN%%", time.number, M.number, T.number, U.number, \ E.number, Rv.number, Q)) sys.stdout.flush() return E def get_binary_elements(p): comp1 = p.child1 comp2 = p.child2 kep = Kepler(redirection = "none") kep.initialize_code() mass = comp1.mass + comp2.mass pos = [comp2.x-comp1.x, comp2.y-comp1.y, comp2.z-comp1.z] vel = [comp2.vx-comp1.vx, comp2.vy-comp1.vy, comp2.vz-comp1.vz] kep.initialize_from_dyn(mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a,e = kep.get_elements() kep.stop() return mass,a,e def run_smallN(infile = None, number_of_stars = 10, end_time = 10 | nbody_system.time, delta_t = 1 | nbody_system.time, accuracy_parameter = 0.1): if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("delta_t =", delta_t.number) print("\ninitializing the gravity module") sys.stdout.flush() gravity = grav(redirection = "none") gravity.initialize_code() gravity.parameters.set_defaults() #----------------------------------------------------------------- if infile == None: print("making a Plummer model") stars = new_plummer_model(number_of_stars) id = numpy.arange(number_of_stars) stars.id = id+1 print("setting particle masses and radii") #stars.mass = (1.0 / number_of_stars) | nbody_system.mass scaled_mass = new_salpeter_mass_distribution_nbody(number_of_stars) stars.mass = scaled_mass stars.radius = 0.0 | nbody_system.length print("centering stars") stars.move_to_center() print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = 0 \ | nbody_system.length*nbody_system.length) time = 0.0 | nbody_system.time sys.stdout.flush() else: # Read the input data. Units are dynamical. print("reading file", infile) id = [] mass = [] pos = [] vel = [] f = open(infile, 'r') count = 0 for line in f: if len(line) > 0: count += 1 cols = line.split() if count == 1: snap = int(cols[0]) elif count == 2: number_of_stars = int(cols[0]) elif count == 3: time = float(cols[0]) | nbody_system.time else: if len(cols) >= 8: id.append(int(cols[0])) mass.append(float(cols[1])) pos.append((float(cols[2]), float(cols[3]), float(cols[4]))) vel.append((float(cols[5]), float(cols[6]), float(cols[7]))) f.close() stars = datamodel.Particles(number_of_stars) stars.id = id stars.mass = mass | nbody_system.mass stars.position = pos | nbody_system.length stars.velocity = vel | nbody_system.speed stars.radius = 0. | nbody_system.length # print "IDs:", stars.id.number sys.stdout.flush() #----------------------------------------------------------------- gravity.parameters.timestep_parameter = accuracy_parameter print("adding particles") # print stars sys.stdout.flush() gravity.parameters.begin_time = time gravity.particles.add_particles(stars) print("committing particles") gravity.commit_particles() print('') print("number_of_stars =", number_of_stars) print("evolving to time =", end_time.number, \ "in steps of", delta_t.number) sys.stdout.flush() E0 = print_log(time, gravity) # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) while time < end_time: time += delta_t #gravity.parameters.outfile = 'abc' gravity.evolve_model(time) # Ensure that the stars list is consistent with the internal # data in the module. ls = len(stars) # Update the bookkeeping: synchronize stars with the module data. try: gravity.update_particle_set() gravity.particles.synchronize_to(stars) except: pass # Copy values from the module to the set in memory. channel.copy() # Copy the index (ID) as used in the module to the id field in # memory. The index is not copied by default, as different # codes may have different indices for the same particle and # we don't want to overwrite silently. channel.copy_attribute("index_in_code", "id") if len(stars) != ls: if 0: print("stars:") for s in stars: print(" ", s.id.number, s.mass.number, \ s.x.number, s.y.number, s.z.number) else: print("number of stars =", len(stars)) sys.stdout.flush() print_log(time, gravity, E0) over = gravity.is_over() if over: gravity.update_particle_tree() gravity.update_particle_set() gravity.particles.synchronize_to(stars) channel.copy() channel.copy_attribute("index_in_code", "id") print("binaries:") x = trees.BinaryTreesOnAParticleSet(stars, "child1", "child2") roots = list(x.iter_roots()) for r in roots: for level, particle in r.iter_levels(): print(' '*level, int(particle.id), end=' ') if not particle.child1 is None: m,a,e = get_binary_elements(particle) print(' (', m, a, e, ')') else: print('') break sys.stdout.flush() if not over: print('\ninteraction is not over') gravity.stop() if __name__ == '__main__': infile = None N = 3 t_end = 50.0 | nbody_system.time delta_t = 1.0 | nbody_system.time accuracy_parameter = 0.1 random_seed = 123432111 try: opts, args = getopt.getopt(sys.argv[1:], "a:c:d:e:f:gGn:s:t:w:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) for o, a in opts: if o == "-a": accuracy_parameter = float(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-f": infile = a elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time else: print("unexpected argument", o) if random_seed <= 0: numpy.random.seed() random_seed = numpy.random.randint(1, pow(2,31)-1) numpy.random.seed(random_seed) print("random seed =", random_seed) assert is_mpd_running() run_smallN(infile, N, t_end, delta_t, accuracy_parameter)
8,080
29.843511
76
py
amuse
amuse-main/src/amuse/community/smalln/__init__.py
# generated file from .interface import Smalln
47
15
29
py
amuse
amuse-main/src/amuse/community/smalln/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravitationalDynamicsInterface # *** This script, together with the defaults in # *** GravitationalDynamicsInterface, will be used to generate both # *** the header file interface.h and the stub interface.cc. class SmallNInterface(CodeInterface, StoppingConditionInterface, GravitationalDynamicsInterface): """ Self-contained few-body integrator, using a fourth-order, shared-timestep, time-symmetrized Hermite scheme including a modified unperturbed treatment of close approaches. """ # Interface specification. include_headers = ['interface.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__( self, name_of_the_worker='smallN_worker', **options ) # Interface functions: @legacy_function def new_particle(): """ Define a new particle in the stellar dynamics code. The particle is initialized with the provided mass, radius, position and velocity. This function returns an index 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, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) 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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) function.addParameter('id', dtype='int32', direction=function.IN, description = "Identifier of the particle, " +"option for restoring state after loading", default = -1) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was created and added to the model -1 - ERROR particle could not be created""" return function # Inheritance from GravitationalDynamicsInterface means that # functions in the standard interface don't need to be defined. # Additional functions defined here will be reflected in # interface.h and must be provided in interface.cc in order for # smallN_worker to build. @legacy_function def set_time(): """ Set the model time. Should use set_begin_time """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN, description = "The model time to start at", unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK Time value was changed -2 - ERROR The code does not support setting the time """ 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_gamma(): """ Set the unperturbed threshold. """ function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gamma(): """ Get the unperturbed threshold. """ function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_allow_full_unperturbed(): """ Set flag to allow full unperturbed motion. """ function = LegacyFunctionSpecification() function.addParameter('allow_full_unpert', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_allow_full_unperturbed(): """ Get flag to allow full unperturbed motion. """ function = LegacyFunctionSpecification() function.addParameter('allow_full_unpert', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_cm_index(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('cm_index', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_cm_index(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('cm_index', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_break_scale(): """ Set the scale at which smallN should stop. """ function = LegacyFunctionSpecification() function.addParameter('break_scale', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_outfile(): """ Set debug output file name. """ function = LegacyFunctionSpecification() function.addParameter('outfile', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outfile(): """ Get debug output file name. """ function = LegacyFunctionSpecification() function.addParameter('outfile', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_structure_check_interval(): """ Set the time scale at which smallN should check structure. """ function = LegacyFunctionSpecification() function.addParameter('check_interval', dtype='float64', direction=function.IN, unit = nbody_system.time) function.result_type = 'int32' return function @legacy_function def is_over(): """ Return 1 if the run is over, according to analyze(). Return 2 for a quasi-stable system. Return 3 if the size of the system exceeds rlimit. Return 0 otherwise. """ function = LegacyFunctionSpecification() function.addParameter('over', dtype='int32', direction=function.OUT) function.addParameter('rlimit', dtype='float64', direction=function.IN, unit = nbody_system.length, default = 0 ) function.addParameter('verbose', dtype='int32', direction=function.IN, default = 0) function.result_type = 'int32' return function @legacy_function def update_particle_tree(): """ Update the internal particle tree to reflect the binary structure created in evolve """ function = LegacyFunctionSpecification() function.addParameter('over', dtype='int32', direction=function.IN, default = 0) function.result_type = 'int32' return function @legacy_function def get_number_of_particles_added(): """ Return the number of particles added or deleted during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('n_added', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_id_of_added_particle(): """ Return the number of particles added or deleted during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('index_of_update', dtype='int32', direction=function.IN, description = 'index in the updated particles list') function.addParameter('index_of_particle', dtype='int32', direction=function.OUT) function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def get_children_of_particle(): """ Return the number of particles added or deleted during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = 'index of the parent particle', unit = INDEX) function.addParameter('child1', dtype='int32', direction=function.OUT, description = 'index of the first child particle, -1 if none', unit = LINK('particles') ) function.addParameter('child2', dtype='int32', direction=function.OUT, unit = LINK('particles')) function.can_handle_array = True function.result_type = 'int32' return function class SmallN(GravitationalDynamics): # The actual module. def __init__(self, convert_nbody = None, **keyword_arguments): self.stopping_conditions = StoppingConditions(self) legacy_interface = SmallNInterface(**keyword_arguments) GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **keyword_arguments) def define_parameters(self, handler): self.stopping_conditions.define_parameters(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.) # # SmallN.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.14 ) handler.add_method_parameter( "get_gamma", # getter name in interface.cc "set_gamma", # setter name in interface.cc "unperturbed_threshold", # python parameter name "unperturbed threshold", # description default_value = 1.e-6 ) handler.add_method_parameter( "get_allow_full_unperturbed", # getter name in interface.cc "set_allow_full_unperturbed", # setter name in interface.cc "allow_full_unperturbed", # python parameter name "full unperturbed motion", # description default_value = 1 ) handler.add_method_parameter( "get_outfile", # getter name in interface.cc "set_outfile", # setter name in interface.cc "outfile", # python parameter name "debug output file", # description default_value = "" ) handler.add_method_parameter( "get_cm_index", # getter name in interface.cc "set_cm_index", # setter name in interface.cc "cm_index", # python parameter name "current CM index", # description default_value = 100000 ) 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 ) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) handler.add_getter("particles", 'get_children_of_particle') def define_methods(self, handler): self.stopping_conditions.define_methods(handler) GravitationalDynamics.define_methods(self, handler) # Turn interface functions into methods. handler.add_method("new_particle", ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, handler.NO_UNIT ), ( handler.INDEX, handler.ERROR_CODE ) ) def update_particle_set(self): """ update the particle set after the code has added binaries """ number_of_updated_particles = self.get_number_of_particles_added() #print "number_of_updated_particles =", number_of_updated_particles if number_of_updated_particles == 0: return indices_in_update_list = list(range(number_of_updated_particles)) indices_to_add = self.get_id_of_added_particle(indices_in_update_list) #print "indices_to_add:", indices_to_add, indices_in_update_list incode_storage = self.particles._private.attribute_storage try: if len(indices_to_add) > 0: incode_storage._add_indices(indices_to_add) except: print("Crash while adding indicies to incode_storage.") print("indices_to_add=", indices_to_add) print("number_of_updated_particles=", number_of_updated_particles) print("incode_storage=", incode_storage) print("dir(incode_storage)=", dir(incode_storage)) raise def define_state(self, handler): GravitationalDynamics.define_state(self, handler) self.stopping_conditions.define_state(handler) Smalln = SmallN
16,711
36.22049
81
py
amuse
amuse-main/src/amuse/community/smalln/scatter3.py
#!/usr/bin/env python # Scatter3: binary scattering package replicating most of the # functionality of the scatter3 tool in Starlab. See McMillan & Hut # 1996, ApJ, 467, 348. import sys, unittest, numpy, random, collections, getopt, os, math from time import * from amuse.units import nbody_system from amuse.units import units from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.datamodel import trees 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_nbody #----------------------------------------------------------------------- class Initial_state(): # modeled on the Starlab scatter3 class m = 0.5 # no units in init -- add in make_triple M = 0.5 eccentricity = 0. impact_parameter = 0. v_infinity = 1.0 planar = 0 class Final_state(): # modeled on the Starlab scatter3 class is_over = 0 time = 0.0 mbinary = 0.0 semimajoraxis = 0.0 eccentricity = 0.0 mescaper = 0.0 escaper = 0 separation = 0.0 v_rel = 0.0 #----------------------------------------------------------------------- # Build functions could/should be offloaded to a separate module. zero = 0.0|units.none one = 1.0|units.none def normalized(a): amagi = 1./math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]) b = [a[0]*amagi, a[1]*amagi, a[2]*amagi] return b def sum3(a, b): c = [a[0] + b[0], a[1] + b[1], a[2] + b[2]] return c def cross(a, b): c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c def set_inner_orbit(init, kep): semi = 1.0|nbody_system.length ecc = init.eccentricity kep.set_longitudinal_unit_vector(one, zero, zero) kep.set_normal_unit_vector(zero, zero, one) mean_an = 2*math.pi*numpy.random.random() kep.initialize_from_elements(1.0|nbody_system.mass, semi, ecc, mean_an) print('inner semi, ecc =', semi.number, ecc) def set_outer_orbit(init, kep): mtotal = 1 + init.M # Multiply the incoming velocity by the critical value (see Hut & # Bahcall 1983). v_inf = init.v_infinity \ * math.sqrt( (1 - init.m) * init.m * mtotal / init.M ) energy3 = 0.5 * v_inf * v_inf print('m1, m2, m3 =', 1-init.m, init.m, init.M) print('v_inf =', v_inf, 'energy3 =', energy3, \ 'rho =', init.impact_parameter) if energy3 > 0: semi = -0.5*mtotal/energy3|nbody_system.length ang_mom3 = init.impact_parameter * v_inf ecc = math.sqrt( 1 + 2 * energy3 * (ang_mom3/mtotal)**2) periastron = -semi*max(ecc-1.0, 0.0) # not used else: semi = 0|nbody_system.length # not used ecc = 1 periastron = init.impact_parameter|nbody_system.length # Orientation: if init.planar != 0: kep.set_longitudinal_unit_vector(one, zero, zero) if init.planar == 1: kep.set_normal_unit_vector(zero, zero, one) else: kep.set_normal_unit_vector(zero, zero, -one) else: costheta = 2*numpy.random.random() - 1 sintheta = math.sqrt(max(0, 1-costheta**2)) phi = 2*math.pi*numpy.random.random() longv = [sintheta*math.cos(phi), sintheta*math.sin(phi), costheta] kep.set_longitudinal_unit_vector(longv[0], longv[1], longv[2]) if abs(longv[0]) < 0.5: temp = [1, 0, 0] else: temp = [0, 1, 0] trans = normalized(cross(longv, temp)) normal = cross(longv, trans) psi = 2*math.pi*numpy.random.random() cospsi = math.cos(psi) sinpsi = math.sin(psi) normal = [cospsi*trans[0]+sinpsi*normal[0], cospsi*trans[1]+sinpsi*normal[1], cospsi*trans[2]+sinpsi*normal[2]] kep.set_normal_unit_vector(normal[0], normal[1], normal[2]) time = 0.0|nbody_system.time mean_anomaly = 0 # t = 0 at periastron if periastron.number == 0: mean_anomaly = -1.e-3 print('mean_anomaly =', mean_anomaly) print('outer semi, ecc =', semi.number, ecc) kep.initialize_from_elements(mtotal|nbody_system.mass, semi, ecc, mean_anomaly, time, periastron) print('outer normal =', kep.get_normal_unit_vector()) print('outer periastron =', kep.get_periastron().number) #kep.print_all() def make_triple(init, kep, gamma): # Create IDs and initial masses, positions, and velocities. # Convention: initial binary is (1,2). # Inner orbit (1,2). set_inner_orbit(init, kep) rel_pos = kep.get_separation_vector() rel_vel = kep.get_velocity_vector() f = init.m pos1 = [-f*rel_pos[0], -f*rel_pos[1], -f*rel_pos[2]] vel1 = [-f*rel_vel[0], -f*rel_vel[1], -f*rel_vel[2]] pos2 = [(1-f)*rel_pos[0], (1-f)*rel_pos[1], (1-f)*rel_pos[2]] vel2 = [(1-f)*rel_vel[0], (1-f)*rel_vel[1], (1-f)*rel_vel[2]] # Outer orbit ((1,2),3). set_outer_orbit(init, kep) # print '----------' # kep.print_all() # gamma = gravity.parameters.unperturbed_threshold # won't work in general kep.return_to_radius((gamma/init.M)**(-1./3)|nbody_system.length) # print '----------' # kep.print_all() # print '----------' time = kep.get_time() rel_pos = kep.get_separation_vector() rel_vel = kep.get_velocity_vector() f = init.M/(1+init.M) pos12 = [-f*rel_pos[0], -f*rel_pos[1], -f*rel_pos[2]] vel12 = [-f*rel_vel[0], -f*rel_vel[1], -f*rel_vel[2]] print('outer separation =', kep.get_separation().number, \ ' time =', kep.get_time().number) pos1 = sum3(pos1, pos12) vel1 = sum3(vel1, vel12) pos2 = sum3(pos2, pos12) vel2 = sum3(vel2, vel12) pos3 = [(1-f)*rel_pos[0], (1-f)*rel_pos[1], (1-f)*rel_pos[2]] vel3 = [(1-f)*rel_vel[0], (1-f)*rel_vel[1], (1-f)*rel_vel[2]] print('initial time =', time.number, "(time of outer periastron = 0)") # Create the 3-body system. id = [1, 2, 3] mass = [1-init.m, init.m, init.M] | nbody_system.mass pos = [pos1, pos2, pos3] vel = [vel1, vel2, vel3] return time, id, mass, pos, vel def make_triple2(init, kep, gamma): # Use a kepler built-in to replace the Python functionality of # make_triple. # Create IDs and initial masses, positions, and velocities. # Convention: initial binary is (1,2). t,m1,m2,m3,x1,x2,x3,y1,y2,y3,z1,z2,z3, \ vx1,vx2,vx3,vy1,vy2,vy3,vz1,vz2,vz3 \ = kep.make_binary_scattering(init.m|nbody_system.mass, init.eccentricity, init.M|nbody_system.mass, init.v_infinity|nbody_system.speed, init.impact_parameter|nbody_system.length, gamma, init.planar) id = [1, 2, 3] mass = [m1,m2,m3] pos = [[x1,y1,z1], [x2,y2,z2], [x3,y3,z3]] vel = [[vx1,vy1,vz1], [vx2,vy2,vz2], [vx3,vy3,vz3]] return t, id, mass, pos, vel #----------------------------------------------------------------------- def get_binary_elements(p, kep): comp1 = p.child1 comp2 = p.child2 m = comp1.mass + comp2.mass kep.initialize_from_dyn(m, comp2.x-comp1.x, comp2.y-comp1.y, comp2.z-comp1.z, comp2.vx-comp1.vx, comp2.vy-comp1.vy, comp2.vz-comp1.vz) a,e = kep.get_elements() return m,a,e def get_final_state(stars, kep): final = Final_state() final.is_over = 1 final.escaper = -1 ionized = 1 tree = stars.as_binary_tree() sep = numpy.zeros(3) vel = numpy.zeros(3) for node in tree.iter_children(): if node.particle.child1 is None: final.escaper = node.particle.id final.mescaper = node.particle.mass.number sep += numpy.array([node.particle.x.number, node.particle.y.number, node.particle.z.number]) vel += numpy.array([node.particle.vx.number, node.particle.vy.number, node.particle.vz.number]) else: M,a,e = get_binary_elements(node.particle, kep) final.mbinary = M.number final.semimajoraxis = a.number final.eccentricity = e ionized = 0 sep -= numpy.array([node.particle.x.number, node.particle.y.number, node.particle.z.number]) vel -= numpy.array([node.particle.vx.number, node.particle.vy.number, node.particle.vz.number]) if ionized == 0: final.separation = math.sqrt((sep*sep).sum()) final.v_rel = math.sqrt((vel*vel).sum()) else: final.mbinary = -1.0 final.semimajoraxis = -1.0 final.eccentricity = -1.0 final.escaper = -1 final.mescaper = -1.0 final.separation = -1.0 final.v_rel = -1.0 return final def scatter3(init, kep, gravity, gamma = 1.e-6, delta_t = 0 | nbody_system.time, t_end = 1.e4 | nbody_system.time): t1 = clock() # <----------------- t1 ----------------- # Create the 3-body system; time = 0 at outer periastron. #time, id, mass, pos, vel = make_triple(init, kep, gamma) time, id, mass, pos, vel = make_triple2(init, kep, gamma) stars = datamodel.Particles(3) stars.id = id stars.mass = mass stars.position = pos stars.velocity = vel stars.radius = 0. | nbody_system.length #print stars print("adding particles") sys.stdout.flush() gravity.set_time(time) gravity.particles.add_particles(stars) #print "committing particles" #gravity.commit_particles() sys.stdout.flush() # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) # Don't have a proper unperturbed termination criterion in smallN. # For now, insist that the final time exceed minus the initial # time (recall that outer peri is at t = 0). t_crit = -time if delta_t.number <= 0.0: delta_t = 2*t_crit # for efficiency print("evolving triple to completion in steps of", delta_t.number) sys.stdout.flush() t2 = clock() # <----------------- t2 ----------------- dt_init = t2 - t1 dt_evolve = 0.0 dt_over = 0.0 dt_tree = 0.0 final = Final_state() over = 0 while time < t_end and over == 0: tt3 = clock() # <----------------- tt3 ---------------- time += delta_t gravity.evolve_model(time) energy = gravity.get_kinetic_energy()+gravity.get_potential_energy() print("time =", time.number, "energy =", energy.number) tt4 = clock() # <----------------- tt4 ---------------- if time > t_crit: ttt5 = clock() # <---------------- ttt5 ---------------- over = gravity.is_over() ttt6 = clock() # <---------------- ttt6 ---------------- if over: #print '\nscatter3: interaction is over' gravity.update_particle_tree() gravity.update_particle_set() gravity.particles.synchronize_to(stars) channel.copy() channel.copy_attribute("index_in_code", "id") # Determine the final state. final = get_final_state(stars, kep) final.time = time.number ttt7 = clock() # <---------------- ttt7 ---------------- dt_over += ttt6 - ttt5 dt_tree += ttt7 - ttt6 dt_evolve += tt4 - tt3 if not over: #print '\nscatter3: interaction is not over' final.is_over = 0 final.mbinary = -1.0 final.semimajoraxis = -1.0 final.eccentricity = -1.0 final.escaper = -1 final.mescaper = -1.0 final.separation = -1.0 final.v_rel = -1.0 # Clean up internal data for recycling. # Reset children so that the garbage collection can do its work. stars.child1 = None stars.child2 = None gravity.reset() return final,numpy.array([dt_init, dt_evolve, dt_over, dt_tree]) if __name__ == '__main__': nscatter = 1 accuracy_parameter = 0.1 gamma = 1.e-6 delta_t = 0.0 | nbody_system.time t_end = 1.e5 | nbody_system.time random_seed = -1 init = Initial_state() try: opts, args = getopt.getopt(sys.argv[1:], "A:d:e:g:m:M:n:pPr:s:t:v:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) # Command-line arguments are modeled on those in starlab. # Units: G = 1, binary mass = 1, binary semi-major axis = 1. for o, a in opts: if o == "-A": accuracy_parameter = float(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": init.eccentricity = float(a) if init.eccentricity >= 1: raise Exception("e < 1 required") elif o == "-g": gamma = float(a) elif o == "-m": init.m = float(a) if init.m <= 0 or init.m >= 1: raise Exception("0 < m < 1 required") elif o == "-M": init.M = float(a) if init.M <= 0: raise Exception("M > 0 required") elif o == "-n": nscatter = int(a) elif o == "-p": init.planar = 1 elif o == "-P": init.planar = -1 elif o == "-r": init.impact_parameter = float(a) if init.impact_parameter < 0: raise Exception("r >= 0 required") elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a)|nbody_system.time elif o == "-v": init.v_infinity = float(a) if init.v_infinity < 0: raise Exception("v >= 0 required") else: print("unexpected argument", o) if random_seed <= 0: numpy.random.seed() random_seed = numpy.random.randint(1, pow(2,31)-1) numpy.random.seed(random_seed) print("random seed =", random_seed, numpy.random.random()) #----------------------------------------------------------------- assert is_mpd_running() # Instantiate workers once only and pass to scatter3 as arguments. gravity = SmallN(redirection = "none") #gravity = SmallN(redirection = "none", debugger="valgrind") # search for # memory leaks gravity.initialize_code() gravity.parameters.set_defaults() gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.unperturbed_threshold = gamma kep = Kepler(redirection = "none") #, debugger="gdb") kep.initialize_code() kep.set_random(random_seed) # ** Note potential conflict between C++ # ** and Python random generators. # Timing: cpu = numpy.zeros(4) for i in range(nscatter): final,dcpu = scatter3(init, kep, gravity, gamma, delta_t, t_end) cpu += dcpu print('') if final.is_over == 0: print('interaction is not over') else: if final.escaper > 0: print('escaper =', final.escaper, \ 'sep =', final.separation, \ 'vel =', final.v_rel) print('binary (mass =', final.mbinary, \ 'semi =', final.semimajoraxis, \ 'ecc =', final.eccentricity, ')') else: print('ionization') if nscatter > 1: print('\n--------------------\n') print('timing: init', cpu[0], 'evol', cpu[1], 'over', cpu[2], \ 'tree', cpu[3]) print('') gravity.stop() kep.stop()
16,174
31.029703
79
py
amuse
amuse-main/src/amuse/community/bse/__init__.py
from .interface import Bse
27
13
26
py
amuse
amuse-main/src/amuse/community/bse/interface.py
from amuse.community import * from amuse.units import units from amuse.units import constants from amuse.units.quantities import Quantity from amuse.community.interface import common from amuse.datamodel import Particles from amuse.datamodel import ParticlesSubset import numpy class BSEInterface(CodeInterface, common.CommonCodeInterface , LiteratureReferencesMixIn): """ Binary evolution is performed by the **rapid** binary-star evolution (BSE) algorithm. Circularization of eccentric orbits and synchronization of stellar rotation with the orbital motion owing to tidal interaction is modelled in detail. Angular momentum loss mechanisms, such as gravitational radiation and magnetic braking, are also modelled. Wind accretion, where the secondary may accrete some of the material lost from the primary in a wind, is allowed with the necessary adjustments made to the orbital parameters in the event of any mass variations. Mass transfer also occurs if either star fills its Roche lobe and may proceed on a nuclear, thermal or dynamical time-scale. In the latter regime, the radius of the primary increases in response to mass-loss at a faster rate than the Roche-lobe of the star. Stars with deep surface convection zones and degenerate stars are unstable to such dynamical time-scale mass loss unless the mass ratio of the system is less than some critical value. The outcome is a common-envelope event if the primary is a giant star. This results in merging or formation of a close binary, or a direct merging if the primary is a white dwarf or low-mass main-sequence star. On the other hand, mass transfer on a nuclear or thermal time-scale is assumed to be a steady process. Prescriptions to determine the type and rate of mass transfer, the response of the secondary to accretion and the outcome of any merger events are in place in BSE and the details can be found in the BSE paper: .. [#] ADS:2002MNRAS.329..897H (Hurley J.R., Tout C.A., & Pols O.R., 2002, MNRAS, 329, 897) .. [#] ADS:2000MNRAS.315..543H (Hurley J.R., Pols O.R., Tout C.A., 2000, MNRAS, 315, 543) """ def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="bse_worker", **options) LiteratureReferencesMixIn.__init__(self) @legacy_function def initialize(): function = LegacyFunctionSpecification() function.addParameter('z_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('neta_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('bwind_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('hewind_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('alpha1_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('CElambda_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('ceflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('tflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('ifflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('wdflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('bhflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('nsflag_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('mxns_in', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('idum_in', dtype='i', direction=function.IN, unit = NO_UNIT) function.addParameter('pts1_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('pts2_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('pts3_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('sigma_in', dtype='d', direction=function.IN, unit = units.km / units.s) function.addParameter('beta_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('xi_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('acc2_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('epsnov_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('eddfac_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('gamma_in', dtype='d', direction=function.IN, unit = NO_UNIT) function.addParameter('status', dtype='i', direction=function.OUT, unit = NO_UNIT) return function @legacy_function def evolve_binary(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('type1', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('type2', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('initial_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('initial_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('luminosity1', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('luminosity2', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('core_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('core_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('core_radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('core_radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('convective_envelope_mass1', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('convective_envelope_mass2', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('convective_envelope_radius1', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('convective_envelope_radius2', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('spin1', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('spin2', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('epoch1', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('epoch2', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('MS_lifetime1', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('MS_lifetime2', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('age', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('orbital_period', dtype='d', direction=function.INOUT, unit = units.day) function.addParameter('eccentricity', dtype='d', direction=function.INOUT, unit = NO_UNIT) function.addParameter('end_time', dtype='d', direction=function.INOUT, unit = units.Myr) return function @legacy_function def get_time_step(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('type1', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('type2', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('initial_mass1', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('initial_mass2', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mass1', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mass2', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('MS_lifetime1', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('MS_lifetime2', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch1', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch2', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('age', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('time_step', dtype='d', direction=function.OUT, unit = units.Myr) return function def get_time_step_for_binary(self, binary): current_values = {} current_values['type1'] = binary.type1.value_in(units.stellar_type) current_values['type2'] = binary.type2.value_in(units.stellar_type) current_values['initial_mass1'] = binary.initial_mass1.value_in(units.MSun) current_values['initial_mass2'] = binary.initial_mass2.value_in(units.MSun) current_values['mass1'] = binary.mass1.value_in(units.MSun) current_values['mass2'] = binary.mass2.value_in(units.MSun) current_values['MS_lifetime1'] = binary.MS_lifetime1.value_in(units.Myr) current_values['MS_lifetime2'] = binary.MS_lifetime2.value_in(units.Myr) current_values['epoch1'] = binary.epoch1.value_in(units.Myr) current_values['epoch2'] = binary.epoch2.value_in(units.Myr) current_values['age'] = binary.age.value_in(units.Myr) result = self.get_time_step(**current_values) return result | units.Myr def evolve_particle(self, particle, time_end): t = particle.current_time if particle.stellar_type == 15: return while t < time_end: t0 = t t = t0 + self.get_time_step_for_binary(particle) if t > time_end: t = time_end self.evolve_star(particle, t) t1 = particle.current_time dt = t1 - t0 t0 = t1 if dt.value_in(units.Myr) == 0.0: #print t, t0, t1, dt, "BREAK BREAK BREAK!" return if particle.stellar_type == 15: return def initialize_code(self): return 0 def commit_parameters(self): return 0 def recommit_parameters(self): return 0 def cleanup_code(self): return 0 def commit_particles(self): return 0 class BSEStars(Particles): def __init__(self, code_interface, storage = None): Particles.__init__(self, storage = storage) self._private.code_interface = code_interface self.add_calculated_attribute("temperature", self.calculate_effective_temperature, ["luminosity", "radius"]) def calculate_effective_temperature(self, luminosity, radius): return ((luminosity/(constants.four_pi_stefan_boltzmann*radius**2))**.25).in_(units.K) def add_particles_to_store(self, keys, attributes = [], values = []): if len(keys) == 0: return all_attributes = [] all_attributes.extend(attributes) all_values = [] all_values.extend(values) mapping_from_attribute_to_default_value = { "stellar_type" : 1 | units.stellar_type, "radius": 0 | units.RSun, "luminosity": 0 | units.LSun, "core_mass": 0 | units.MSun, "core_radius": 0 | units.RSun, "convective_envelope_mass": 0 | units.MSun, "convective_envelope_radius": 0 | units.RSun, "epoch": 0 | units.Myr, "spin": 0 | units.none, "main_sequence_lifetime": 0 | units.Myr, "age": 0 | units.Myr, "stellar_type": 0 | units.stellar_type #units.stellar_type("Main Sequence star"), } given_attributes = set(attributes) if not "initial_mass" in given_attributes: index_of_mass_attibute = attributes.index("mass") all_attributes.append("initial_mass") all_values.append(values[index_of_mass_attibute] * 1.0) for attribute, default_value in mapping_from_attribute_to_default_value.items(): if not attribute in given_attributes: all_attributes.append(attribute) all_values.append(default_value.as_vector_with_length(len(keys))) super(BSEStars, self).add_particles_to_store(keys, all_attributes, all_values) def get_defined_attribute_names(self): return ["mass", "radius"] class BSEBinaries(Particles): def __init__(self, code_interface, storage = None): Particles.__init__(self, storage = storage) self._private.code_interface = code_interface def add_particles_to_store(self, keys, attributes = [], values = []): if len(keys) == 0: return given_attributes = set(attributes) if not "child1" in given_attributes: raise Exception("a binary must always have a child1 attribute") if not "child2" in given_attributes: raise Exception("a binary must always have a child2 attribute") all_attributes = [] all_values = [] for attribute, value in zip(attributes, values): all_attributes.append(attribute) if attribute == 'child1' or attribute == 'child2': value = value.copy_with_link_transfer(None, self._private.code_interface.particles) all_values.append(value) else: all_values.append(value) mapping_from_attribute_to_default_value = { "eccentricity": 0.0 | units.none, "age": 0 | units.Myr } for attribute, default_value in mapping_from_attribute_to_default_value.items(): if not attribute in given_attributes: all_attributes.append(attribute) all_values.append(default_value.as_vector_with_length(len(keys))) super(BSEBinaries, self).add_particles_to_store(keys, all_attributes, all_values) added_particles = ParticlesSubset(self, keys) self._private.code_interface._evolve_binaries(added_particles, 1e-08 | units.yr) def get_defined_attribute_names(self): return ["eccentricity", "orbital_period", "age", "child1", "child2"] class BSE(common.CommonCode): def __init__(self, **options): InCodeComponentImplementation.__init__(self, BSEInterface(**options), **options) self.model_time = 0.0 | units.yr def define_parameters(self, handler): handler.add_caching_parameter( "initialize", "z_in", "metallicity", "Metallicity of all stars", 0.02 ) handler.add_caching_parameter( "initialize", "neta_in", "reimers_mass_loss_coefficient", "Reimers mass-loss coefficient (neta*4x10^-13; 0.5 normally)", 0.5 ) handler.add_caching_parameter( "initialize", "bwind_in", "binary_enhanced_mass_loss_parameter", "The binary enhanced mass loss parameter (inactive for single).", 0.0 ) handler.add_caching_parameter( "initialize", "hewind_in", "helium_star_mass_loss_factor", "Helium star mass loss factor", 1.0 ) handler.add_caching_parameter( "initialize", "alpha1_in", "common_envelope_efficiency", "The common-envelope efficiency parameter", 1.0 ) handler.add_caching_parameter( "initialize", "CElambda_in", "common_envelope_binding_energy_factor", "The binding energy factor for common envelope evolution", 0.5 ) handler.add_caching_parameter( "initialize", "ceflag_in", "common_envelope_model_flag", "ceflag > 0 activates spin-energy correction in common-envelope. ceflag = 3 activates de Kool common-envelope model (0).", 0 ) handler.add_caching_parameter( "initialize", "tflag_in", "tidal_circularisation_flag", "tflag > 0 activates tidal circularisation (1).", 1 ) handler.add_caching_parameter( "initialize", "ifflag_in", "white_dwarf_IFMR_flag", "ifflag > 0 uses white dwarf IFMR (initial-final mass relation) of HPE, 1995, MNRAS, 272, 800 (0).", 0 ) handler.add_caching_parameter( "initialize", "wdflag_in", "white_dwarf_cooling_flag", "wdflag > 0 uses modified-Mestel cooling for WDs (0).", 1 ) handler.add_caching_parameter( "initialize", "bhflag_in", "black_hole_kick_flag", "bhflag > 0 allows velocity kick at BH formation (0).", 0 ) handler.add_caching_parameter( "initialize", "nsflag_in", "neutron_star_mass_flag", "nsflag > 0 takes NS/BH mass from Belczynski et al. 2002, ApJ, 572, 407 (1).", 1 ) handler.add_caching_parameter( "initialize", "mxns_in", "maximum_neutron_star_mass", "The maximum neutron star mass (1.8, nsflag=0; 3.0, nsflag=1).", 3.0 | units.MSun ) handler.add_caching_parameter( "initialize", "idum_in", "SN_kick_random_seed", "The random number seed used in the kick routine.", 29769 ) handler.add_caching_parameter( "initialize", "pts1_in", "fractional_time_step_1", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: MS (0.05)", 0.05 ) handler.add_caching_parameter( "initialize", "pts2_in", "fractional_time_step_2", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: GB, CHeB, AGB, HeGB (0.01)", 0.01 ) handler.add_caching_parameter( "initialize", "pts3_in", "fractional_time_step_3", "The timesteps chosen in each evolution phase as decimal fractions of the time taken in that phase: HG, HeMS (0.02)", 0.02 ) handler.add_caching_parameter( "initialize", "sigma_in", "SN_kick_speed_dispersion", "The dispersion in the Maxwellian for the SN kick speed (190 km/s).", 190.0 | units.km / units.s ) handler.add_caching_parameter( "initialize", "beta_in", "wind_velocity_factor", "The wind velocity factor: proportional to vwind**2 (1/8).", 0.125 ) handler.add_caching_parameter( "initialize", "xi_in", "wind_accretion_efficiency", "The wind accretion efficiency factor (1.0).", 1.0 ) handler.add_caching_parameter( "initialize", "acc2_in", "wind_accretion_factor", "The Bondi-Hoyle wind accretion factor (3/2).", 1.5 ) handler.add_caching_parameter( "initialize", "epsnov_in", "nova_retained_accreted_matter_fraction", "The fraction of accreted matter retained in nova eruption (0.001).", 0.001 ) handler.add_caching_parameter( "initialize", "eddfac_in", "Eddington_mass_transfer_limit_factor", "The Eddington limit factor for mass transfer (1.0).", 1.0 ) handler.add_caching_parameter( "initialize", "gamma_in", "Roche_angular_momentum_factor", "The angular momentum factor for mass lost during Roche (-1.0). ", -1.0 ) def define_state(self, handler): common.CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','RUN','commit_parameters') handler.add_method('RUN', 'evolve_binary') handler.add_method('RUN','before_get_parameter') handler.add_method('RUN','before_set_parameter') def define_particle_sets(self, handler): handler.define_inmemory_set('particles', BSEStars) handler.define_inmemory_set('binaries', BSEBinaries) handler.add_attribute( 'binaries', 'time_step', '_get_time_step', ('child1', 'child2', 'age') #('child1', 'type2', # 'initial_mass1', 'initial_mass2', # 'mass1', 'mass2', # 'MS_lifetime1', 'MS_lifetime2', # 'epoch1', 'epoch2', #'age') ) def _get_time_step(self, child1, child2, age): child1 = child1.as_set() child2 = child2.as_set() return self.get_time_step( child1.stellar_type, child2.stellar_type, child1.initial_mass, child2.initial_mass, child1.mass, child2.mass, child1.age, child2.age, child1.epoch, child2.epoch, age ) def orbital_period_to_semi_major_axis(self, orbital_period, mass1, mass2): mu = (mass1 + mass2) * constants.G return (((orbital_period / (2.0 * numpy.pi))**2)*mu)**(1.0/3.0) def semi_major_axis_to_orbital_period(self, semi_major_axis, mass1, mass2): mu = (mass1 + mass2) * constants.G return 2.0 * numpy.pi * ((semi_major_axis**3/mu)**0.5) def _evolve_binaries(self, particles, end_time): binary_attributes = ( "age", "semi_major_axis", "eccentricity" ) single_attributes = ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "age", ) children1 = particles.child1.as_set() children2 = particles.child2.as_set() children1_arguments = children1.get_values_in_store(children1.get_all_indices_in_store(), single_attributes) children2_arguments = children2.get_values_in_store(children2.get_all_indices_in_store(), single_attributes) binaries_arguments = particles.get_values_in_store(particles.get_all_indices_in_store(), binary_attributes) binaries_arguments[1] = self.semi_major_axis_to_orbital_period(binaries_arguments[1] , children1_arguments[2], children2_arguments[2]) arguments = [] for argument1, argument2 in zip(children1_arguments, children2_arguments): arguments.append(argument1) arguments.append(argument2) arguments.extend(binaries_arguments) arguments.append(end_time.as_vector_with_length(len(particles))) result = self.evolve_binary(*arguments) result[-3] = self.orbital_period_to_semi_major_axis(result[-3] , result[4], result[5]) children1_results = [] children2_results = [] index = 0 for dummy in range(len(children1_arguments)): children1_results.append(result[index]) index += 1 children2_results.append(result[index]) index += 1 children1.set_values_in_store(children1.get_all_indices_in_store(), single_attributes, children1_results) children2.set_values_in_store(children2.get_all_indices_in_store(), single_attributes, children2_results) particles.set_values_in_store(particles.get_all_indices_in_store(), binary_attributes, result[index:]) def evolve_model(self, end_time = None, keep_synchronous = True): if not keep_synchronous: self._evolve_binaries(self.binaries, self.binaries.time_step + self.binaries.age) return if end_time is None: end_time = self.model_time + min(self.binaries.time_step) self._evolve_binaries(self.binaries, end_time - self.model_time + self.binaries.age) self.model_time = end_time def commit_particles(self): pass def update_time_steps(self): pass def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def initialize_module_with_current_parameters(self): self.commit_parameters() def initialize_module_with_default_parameters(self): """ * neta is the Reimers mass-loss coefficent (neta*4x10^-13; 0.5 normally). * bwind is the binary enhanced mass loss parameter (inactive for single). * hewind is a helium star mass loss factor (1.0 normally). * sigma is the dispersion in the Maxwellian for the SN kick speed (190 km/s). * * ifflag > 0 uses WD IFMR of HPE, 1995, MNRAS, 272, 800 (0). * wdflag > 0 uses modified-Mestel cooling for WDs (0). * bhflag > 0 allows velocity kick at BH formation (0). * nsflag > 0 takes NS/BH mass from Belczynski et al. 2002, ApJ, 572, 407 (1). * mxns is the maximum NS mass (1.8, nsflag=0; 3.0, nsflag=1). * idum is the random number seed used in the kick routine. * * Next come the parameters that determine the timesteps chosen in each * evolution phase: * pts1 - MS (0.05) * pts2 - GB, CHeB, AGB, HeGB (0.01) * pts3 - HG, HeMS (0.02) * as decimal fractions of the time taken in that phase. """ self.parameters.set_defaults() self.commit_parameters() Bse = BSE
27,599
41.790698
142
py
amuse
amuse-main/src/amuse/community/rebound/patch_files.py
#!/usr/bin/env python import os import sys import subprocess import re PATCHESDIR = "patches" QUILT_PC = ".pc" def execute_command_line(arguments, cwd = None): process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd = cwd) stdoutstring, stderrstring = process.communicate() returncode = process.poll() return stdoutstring, stderrstring, returncode def which(executablename): stdoutstring, stderrstring, returncode = execute_command_line(['which', executablename]) if not returncode == 0: return None else: return stdoutstring def is_quilt_installed(): path = which('quilt') if path is None: return False stdoutstring, stderrstring, returncode = execute_command_line(['quilt', '--version']) if not returncode == 0: return False version_re = re.compile(r'(\d).(\d\d)') match = version_re.match(stdoutstring) if not match: return False return True def apply_patches_using_quilt(): returncode = subprocess.call(['quilt', 'push', '-a']) if not returncode == 0: raise Exception("error in applying the patches, please apply by hand using quilt push") def undo_patches_using_quilt(): returncode = subprocess.call(['quilt', 'pop', '-a']) if not returncode == 0: raise Exception("error in undoing the patches, please undo by hand using quilt pop -a") def run_patch(patchname, patchfile): arguments = ['patch', '-p1', '--backup', '--prefix={0}/{1}/'.format(QUILT_PC, patchname), '-E', '-i', patchfile] returncode = subprocess.call(arguments) if not returncode == 0: raise Exception("could not apply patch {0}".format(patchname)) def apply_patches_using_patch(): with open("patches/series", "r") as f: lines = f.readlines() patches = [x.strip() for x in lines] patches = [x for x in patches if len(x) > 0] for patch in patches: path = os.path.join(PATCHESDIR, patch) run_patch(patch, path) def main(undo_patches = False): print("checking if quilt is installed ... ", end=' ') if not is_quilt_installed(): print("no") if undo_patches: print("quilt is not installed, cannot undo the patches") sys.exit(1) else: print("applying patches to source code") apply_patches_using_patch() else: print("yes") if undo_patches: print("quilt is install, will try to undo the patches") undo_patches_using_quilt() else: print("applying patches to source code") apply_patches_using_quilt() print("all patches applied") if __name__ == '__main__': main()
2,808
30.561798
116
py
amuse
amuse-main/src/amuse/community/rebound/download.py
#!/usr/bin/env python import subprocess import os import sys import time import urllib.request import urllib.parse import urllib.error from optparse import OptionParser class GetCodeFromHttp(object): url_template = "https://github.com/hannorein/rebound/archive/{version}.tar.gz" filename_template = "{version}.tar.gz" version = "" def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename): print("unpacking", filename) arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( ['mv', 'rebound-{version}'.format(version = self.version), 'rebound'], cwd = os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) os.mkdir('src') url = self.url_template.format(version=self.version) filename = self.filename_template.format(version=self.version) filepath = os.path.join(self.src_directory(), filename) print("downloading version", self.version, "from", url, "to", filename) urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file(filename) def main(version=''): instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--version", default='31d117bdc92182073d0941c331f76e95f515bfc6', dest="version", help="version number to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
2,247
27.1
82
py
amuse
amuse-main/src/amuse/community/rebound/__init__.py
# generated file from .interface import Rebound
48
15.333333
30
py
amuse
amuse-main/src/amuse/community/rebound/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 SinglePointGravityFieldInterface from amuse.community.interface.gd import GravityFieldCode class ReboundInterface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, #SinglePointGravityFieldInterface ): """ REBOUND - An open-source multi-purpose N-body code .. [#] ADS:2012A&A...537A.128R (Rein, H., Liu, S.F., *Astronomy and Astrophysics* , **Volume 537**, A128 (2012)) For different integrators, cite: .. [#] ADS:2015MNRAS.446.1424R (IAS15: Rein, H., Spiegel, D.S., *MNRAS* , **Volume 446**, Issue 2, p.1424-1437 (2015)) .. [#] ADS:2015MNRAS.452..376R (WHFast: Rein, H., Tamayo, D., *MNRAS* , **Volume 452**, Issue 1, p.376-388 (2015)) ... Hermes: Silburt, A., et al., in prep. .. [#] ADS:2011MNRAS.415.3168R (SEI: Rein, H., Tremaine, S., *MNRAS* , **Volume 415**, Issue 4, p.3168-3176 (2011)) .. [#] ADS:2017MNRAS.467.2377R (JANUS: Rein, H., Tamayo, D., *arXiv* , 1704.07715 (2017)) """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="rebound_worker", **options) LiteratureReferencesMixIn.__init__(self) @legacy_function def new_particle(): """ Define a new particle in the stellar dynamics code. The particle is initialized with the provided mass, radius, position and velocity. This function returns an index 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, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) 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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) function.addParameter('subset', dtype='int32', direction=function.IN, description = "The subset index of the particle (defaults to 0, use new_subset for higher indices)", default = 0) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was created and added to the model -1 - ERROR particle could not be created""" return function def delete_particle(self, index_of_the_particle, code_index=0): return self._delete_particle(index_of_the_particle, code_index) @legacy_function def _delete_particle(): """ Delete a particle. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description ="Index of the particle") function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was deleted -1 - ERROR particle not deleted""" return function @legacy_function def _set_integrator(): function = LegacyFunctionSpecification() function.addParameter('integrator_name', dtype='i', direction=function.IN) function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.can_handle_array = False return function @legacy_function def _get_integrator(): function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('integrator_name', dtype='i', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = False return function INTEGRATORS = {"ias15": 0, "whfast": 1, "sei": 2, "leapfrog": 4, "hermes": 5, "whfast-helio": 6, "none": 7, "janus": 8} def set_integrator(self, name, code_index = 0 ): return self._set_integrator(self.INTEGRATORS[name], code_index) def get_integrator(self, code_index = 0): value, error = self._get_integrator(code_index) for key, index in self.INTEGRATORS.items(): if value == index: return key return "none" @legacy_function def _set_solver(): function = LegacyFunctionSpecification() function.addParameter('solver_name', dtype='i', direction=function.IN) function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.can_handle_array = False return function @legacy_function def _get_solver(): function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('solver_name', dtype='i', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = False return function SOLVERS = {"none": 0, "basic": 1, "compensated": 2, "tree": 3} def set_solver(self, name, code_index = 0 ): return self._set_solver(self.SOLVERS[name], code_index) def get_solver(self, code_index = 0): value, error = self._get_solver(code_index) for key, index in self.SOLVERS.items(): if value == index: return key return "none" @legacy_function def get_opening_angle2(): function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('opening_angle2', dtype='float64', direction=function.OUT, description = "theta, the opening angle for building the tree: between 0 and 1") function.result_type = 'int32' return function @legacy_function def set_opening_angle2(): function = LegacyFunctionSpecification() function.addParameter('opening_angle2', dtype='float64', direction=function.IN, description = "theta, the opening angle for building the tree: between 0 and 1") function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' return function @legacy_function def get_eps2(): function = LegacyFunctionSpecification() """ Get epsilon^2, a softening parameter for gravitational potentials with point particles. """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('epsilon_squared', dtype='float64', direction=function.OUT, description = "epsilon^2, a softening parameter for gravitational potentials with point particles", unit = nbody_system.length * nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_eps2(): """ Set epsilon^2, a softening parameter for gravitational potentials with point particles. """ function = LegacyFunctionSpecification() function.addParameter('epsilon_squared', dtype='float64', direction=function.IN, description = "epsilon^2, a softening parameter for gravitational potentials with point particles", unit = nbody_system.length * nbody_system.length) function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def _set_boundary(): function = LegacyFunctionSpecification() function.addParameter('boundary_name', dtype='i', direction=function.IN) function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.can_handle_array = False return function @legacy_function def _get_boundary(): function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('boundary_name', dtype='i', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = False return function BOUNDARIES = {"none": 0, "open": 1, "periodic": 2, "shear": 3} def set_boundary(self, name, code_index = 0 ): return self._set_boundary(self.BOUNDARIES[name], code_index) def get_boundary(self, code_index = 0): value, error = self._get_boundary(code_index) for key, index in self.BOUNDARIES.items(): if value == index: return key return "none" @legacy_function def get_boundary_size(): function = LegacyFunctionSpecification() """ Get the size of the boundaries. """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('boundary_size', dtype='float64', direction=function.OUT, description = "boundary size", unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_boundary_size(): """ Set size of the boundaries. """ function = LegacyFunctionSpecification() function.addParameter('boundary_size', dtype='float64', direction=function.IN, description = "boundary size", unit = nbody_system.length) function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def set_time_step(): """ Update timestep. """ function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.IN, description = "timestep") function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.result_type = 'int32' function.result_doc = """ 0 - OK timestep was changed """ return function @legacy_function def get_potential_energy(): """ Retrieve the current potential energy of the model """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('potential_energy', dtype='float64', direction=function.OUT, description = "The potential energy of the model") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the potential energy was set -1 - ERROR Kinetic potential could not be provided """ return function @legacy_function def get_kinetic_energy(): """ Retrieve the current kinetic energy of the model """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('kinetic_energy', dtype='float64', direction=function.OUT, description = "The kinetic energy of the model") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the kinetic energy was set -1 - ERROR Kinetic energy could not be provided """ return function @legacy_function def evolve_model(): """ Evolve the model until the given time, or until a stopping condition is set. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN, description = "Model time to evolve the code to. The model will be " "evolved until this time is reached exactly or just after.") function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound (default -1, evolve all systems)", default = -1) function.result_type = 'int32' return function @legacy_function def get_time(): """ Retrieve the model time. This time should be close to the end time specified in the evolve code. Or, when a collision was detected, it will be the model time of the collision. """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('time', dtype='float64', direction=function.OUT, description = "The current model time") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time was retrieved -1 - ERROR The code does not have support for querying the time """ return function @legacy_function def get_time_step(): """ Retrieve the model timestep. """ function = LegacyFunctionSpecification() function.addParameter('code_index', dtype='int32', direction=function.IN, description = "Index of the code in rebound", default = 0) function.addParameter('time_step', dtype='float64', direction=function.OUT, description = "The current model timestep") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time step was retrieved -1 - ERROR The code does not have support for querying the time """ return function @legacy_function def new_subset(): """ Create a new particle subset (and corresponding code). This subset will evolve seperately from others. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_subset', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created subset """ ) function.addParameter('time_offset', dtype='float64', direction=function.IN, description = "Time of the system (defaults to the current model time)", default = -1) function.result_type = 'int32' function.result_doc = """ 0 - OK code was created -1 - ERROR code could not be created""" return function @legacy_function def get_state(): """ Retrieve the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, radius, position and velocity) is returned. """ 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 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('x', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('y', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('z', dtype='float64', direction=function.OUT, description = "The current position vector of the particle") function.addParameter('vx', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.OUT, description = "The current velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.OUT, description = "The current radius of the particle") function.addParameter('subset', dtype='int32', direction=function.OUT, description = "The current subset of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK particle was removed from the model -1 - ERROR particle could not be found """ return function @legacy_function def get_subset(): """ Retrieve the subset index of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('subset', dtype='int32', direction=function.OUT, description = "The current subset of the particle") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK particle was found in the model and the information was retreived -1 - ERROR particle could not be found """ return function @legacy_function def stop_subset(): """ Stop a subset code """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_subset', dtype='int32', direction=function.IN, description = """ An index assigned to an existing subset """ ) function.result_type = 'int32' function.result_doc = """ 0 - OK subset evolving was stopped -1 - ERROR subset evolving was already stopped""" return function @legacy_function def set_subset(): """ Retrieve the subset index of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the subset of. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('subset', dtype='int32', direction=function.IN, description = "The new subset of the particle, as this is actually read only this will fail if changed!") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK particle was found in the model and the information was retreived -1 - ERROR particle could not be found """ return function class Rebound(GravitationalDynamics, GravityFieldCode): __interface__ = ReboundInterface 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 define_state(self, handler): GravitationalDynamics.define_state(self, handler) #GravityFieldCode.define_state(self, handler) self.stopping_conditions.define_state(handler) handler.add_method('EDIT', 'new_subset') handler.add_method('RUN', 'new_subset') def define_parameters(self, handler): self.stopping_conditions.define_parameters(handler) #~ GravitationalDynamics.define_parameters(self, handler) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "constant timestep for iteration", default_value = 0.0001 | nbody_system.time ) handler.add_method_parameter( "get_integrator", "set_integrator", "integrator", "name of the integrator to use ({0})".format(sorted(self.INTEGRATORS.keys())), default_value = "ias15" ) handler.add_method_parameter( "get_solver", "set_solver", "solver", "name of the gravity solver to use ({0})".format(sorted(self.SOLVERS.keys())), default_value = "compensated" ) 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_opening_angle2", "set_opening_angle2", "opening_angle2", "opening angle, theta, for building the tree in case of tree solver: between 0 and 1", default_value = 0.5 ) handler.add_method_parameter( "get_boundary", "set_boundary", "boundary", "name of the boundary type to use ({0}) (required for tree solver)".format(sorted(self.BOUNDARIES.keys())), default_value = "none" ) handler.add_method_parameter( "get_boundary_size", "set_boundary_size", "boundary_size", "size of the boundaries, if the type is not none", default_value = 1.0 | nbody_system.length ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "new_particle", ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, handler.NO_UNIT, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "get_potential_energy", (handler.INDEX,), (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) ) handler.add_method( "get_kinetic_energy", (handler.INDEX,), (nbody_system.mass * nbody_system.length ** 2 * nbody_system.time ** -2, handler.ERROR_CODE,) ) handler.add_method( 'evolve_model', ( nbody_system.time, handler.INDEX ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_time', (handler.INDEX,), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (handler.INDEX,), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_step", (nbody_system.time, handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "get_state", ( handler.NO_UNIT, ), ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "get_subset", ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "set_subset", ( handler.NO_UNIT, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'new_subset', ( nbody_system.time, ), ( handler.INDEX, 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) handler.add_getter('particles', 'get_subset') handler.add_setter('particles', 'set_subset')
28,403
38.615063
191
py
amuse
amuse-main/src/amuse/community/brutus/__init__.py
from .interface import Brutus
30
14.5
29
py
amuse
amuse-main/src/amuse/community/brutus/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface, GravitationalDynamics try: import mpmath HAS_MPMATH=True except ImportError: HAS_MPMATH=False """ currently setting the particle (and possibly model time) as strings (ie to conserve precision) is not yet supported fully (no high level, low level untested) """ class BrutusInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, CodeWithDataDirectories): """ Brutus (Brute force N-body code) .. [#] ADS:2015ComAC...2....2B (Boekholt, Tjarda and Portegies Zwart, Simon, Computational Astrophysics and Cosmology, Volume 2, article id.2, 21 pp.) """ include_headers = ['worker_code.h', 'stopcond.h'] #### def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="brutus_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) #### @legacy_function def get_brutus_output_directory(): function = LegacyFunctionSpecification() function.addParameter('brutus_output_directory', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_brutus_output_directory(): function = LegacyFunctionSpecification() function.addParameter('brutus_output_directory', dtype='string', direction=function.IN) function.result_type = 'int32' return function #### @legacy_function def new_particle_float64(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('identity_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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) function.result_type = 'int32' return function @legacy_function def new_particle_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('identity_of_the_particle', dtype='int32', direction=function.OUT) function.addParameter('mass', dtype='string', direction=function.IN, description = "The mass of the particle") function.addParameter('x', dtype='string', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('y', dtype='string', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('z', dtype='string', direction=function.IN, description = "The initial position vector of the particle") function.addParameter('vx', dtype='string', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='string', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='string', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='string', direction=function.IN, description = "The radius of the particle", default='0') function.result_type = 'int32' return function @legacy_function def set_state_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='string', direction=function.IN, description = "new mass of the particle") function.addParameter('x', dtype='string', direction=function.IN, description = "new initial position vector of the particle") function.addParameter('y', dtype='string', direction=function.IN, description = "new initial position vector of the particle") function.addParameter('z', dtype='string', direction=function.IN, description = "new initial position vector of the particle") function.addParameter('vx', dtype='string', direction=function.IN, description = "new initial velocity vector of the particle") function.addParameter('vy', dtype='string', direction=function.IN, description = "new initial velocity vector of the particle") function.addParameter('vz', dtype='string', direction=function.IN, description = "new initial velocity vector of the particle") function.addParameter('radius', dtype='string', direction=function.IN, description = "new radius of the particle", default='0') function.result_type = 'int32' return function @legacy_function def set_mass_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='string', direction=function.IN, description = "new mass of the particle") function.result_type = 'int32' return function @legacy_function def set_radius_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('radius', dtype='string', direction=function.IN, description = "new radius of the particle", default='0') function.result_type = 'int32' return function @legacy_function def set_position_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('x', dtype='string', direction=function.IN, description = "new position vector of the particle") function.addParameter('y', dtype='string', direction=function.IN, description = "new position vector of the particle") function.addParameter('z', dtype='string', direction=function.IN, description = "new position vector of the particle") function.result_type = 'int32' return function @legacy_function def set_velocity_string(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('vx', dtype='string', direction=function.IN, description = "new velocity vector of the particle") function.addParameter('vy', dtype='string', direction=function.IN, description = "new velocity vector of the particle") function.addParameter('vz', dtype='string', direction=function.IN, description = "new velocity vector of the particle") function.result_type = 'int32' return function def new_particle(self, mass, x,y,z, vx,vy,vz, radius = 0): if isinstance(mass, str): return self.new_particle_string(mass, x,y,z, vx,vy,vz, radius = str(radius)) else: return self.new_particle_float64(mass, x,y,z, vx,vy,vz, radius = radius) #### @legacy_function def get_bs_tolerance_string(): function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bs_tolerance_string(): function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bs_tolerance(): function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bs_tolerance(): function = LegacyFunctionSpecification() function.addParameter('epsilon', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #### @legacy_function def get_word_length(): function = LegacyFunctionSpecification() function.addParameter('numBits', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_word_length(): function = LegacyFunctionSpecification() function.addParameter('numBits', dtype='int32', direction=function.IN) function.result_type = 'int32' return function #### @legacy_function def get_eta_string(): function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eta_string(): function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta(): function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eta(): function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #### @legacy_function def get_t_string(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_t_string(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_t(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_t(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_potential_energy_string(): function = LegacyFunctionSpecification() function.addParameter('potential_energy_string', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_total_mass_string(): function = LegacyFunctionSpecification() function.addParameter('M', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_total_energy_string(): function = LegacyFunctionSpecification() function.addParameter('total_energy_string', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_kinetic_energy_string(): function = LegacyFunctionSpecification() function.addParameter('kinetic_energy_string', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_velocity_string(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('vx', dtype='string', direction=function.OUT) function.addParameter('vy', dtype='string', direction=function.OUT) function.addParameter('vz', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_position_string(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('x', dtype='string', direction=function.OUT) function.addParameter('y', dtype='string', direction=function.OUT) function.addParameter('z', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_mass_string(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('m', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_radius_string(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('radius', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_state_string(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('m', dtype='string', direction=function.OUT) function.addParameter('x', dtype='string', direction=function.OUT) function.addParameter('y', dtype='string', direction=function.OUT) function.addParameter('z', dtype='string', direction=function.OUT) function.addParameter('vx', dtype='string', direction=function.OUT) function.addParameter('vy', dtype='string', direction=function.OUT) function.addParameter('vz', dtype='string', direction=function.OUT) function.addParameter('radius', dtype='string', direction=function.OUT) function.result_type = 'int32' return function class Brutus(GravitationalDynamics): def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = BrutusInterface(**options) self.legacy_doc = legacy_interface.__doc__ GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) self.convert_nbody=convert_nbody if HAS_MPMATH: self.adjust_prec() def adjust_prec(self): if not HAS_MPMATH: raise Exception("mpmath not available") len_ = self.parameters.word_length if (len_ > mpmath.mp.prec): mpmath.mp.prec=len_ def initialize_code(self): result = self.overridden().initialize_code() self.parameters.brutus_output_directory = self.output_directory return result def get_potential_energy_p_si(self): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.energy).number b=mpmath.mpf(self.get_potential_energy_string())*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_total_energy_p_si(self): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.energy).number b=mpmath.mpf(self.get_total_energy_string())*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_kinetic_energy_p_si(self): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.energy).number b=mpmath.mpf(self.get_kinetic_energy_string())*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_total_mass_p_si(self): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.mass).number b=mpmath.mpf(self.get_total_mass_string())*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_mass_p_si(self,index): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.mass).number b=mpmath.mpf(self.get_mass_string(index))*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_radius_p_si(self,index): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.length).number b=mpmath.mpf(self.get_radius_string(index))*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_time_p_si(self): self.adjust_prec() return mpmath.mpf(self.get_time().number) def get_velocity_p_si(self,index): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.speed).number b=mpmath.matrix(self.get_velocity_string(index))*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def get_position_p_si(self,index): self.adjust_prec() a=self.convert_nbody.to_si(nbody_system.length).number b=mpmath.matrix(self.get_position_string(index))*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def new_particle_p_si(self,m,x,y,z,vx,vy,vz,radius): self.adjust_prec() um=self.convert_nbody.to_si(nbody_system.mass).number ul=self.convert_nbody.to_si(nbody_system.length).number us=self.convert_nbody.to_si(nbody_system.speed).number return self.new_particle_string(str(m/um) ,str(x/ul) , str(y/ul) ,str(z/ul) , str(vx/us) ,str(vy/us) , str(vz/us) ,str(radius/ul)) def set_state_p_si(self,index,m,x,y,z,vx,vy,vz,radius): self.adjust_prec() um=self.convert_nbody.to_si(nbody_system.mass).number ul=self.convert_nbody.to_si(nbody_system.length).number us=self.convert_nbody.to_si(nbody_system.speed).number return self.set_state_string(index ,str(m/um) ,str(x/ul) , str(y/ul) ,str(z/ul) , str(vx/us) ,str(vy/us) , str(vz/us) ,str(radius/ul)) def set_mass_p_si(self,index,m): self.adjust_prec() um=self.convert_nbody.to_si(nbody_system.mass).number self.set_mass_string(index ,str(m/um)) def set_radius_p_si(self,index,radius): self.adjust_prec() ul=self.convert_nbody.to_si(nbody_system.length).number self.set_radius_string(index ,str(radius/ul)) def set_position_p_si(self,index,x,y,z): self.adjust_prec() ul=self.convert_nbody.to_si(nbody_system.length).number self.set_position_string(index ,str(x/ul) ,str(y/ul) ,str(z/ul)) def set_velocity_p_si(self,index,vx,vy,vz): self.adjust_prec() us=self.convert_nbody.to_si(nbody_system.speed).number self.set_velocity_string(index ,str(vx/us) ,str(vy/us) ,str(vz/us)) def get_state_p_si(self,index): self.adjust_prec() b=mpmath.matrix(self.get_state_string(index)) a=self.convert_nbody.to_si(nbody_system.mass).number b[0]=b[0]*a a=self.convert_nbody.to_si(nbody_system.length).number b[1]=b[1]*a b[2]=b[2]*a b[3]=b[3]*a a=self.convert_nbody.to_si(nbody_system.speed).number b[4]=b[4]*a b[5]=b[5]*a b[6]=b[6]*a a=self.convert_nbody.to_si(nbody_system.length).number b[7]=b[7]*a return b #* self.convert_nbody.to_si(nbody_system.energy).unit def define_parameters(self, handler): GravitationalDynamics.define_parameters(self, handler) self.stopping_conditions.define_parameters(handler) handler.add_method_parameter( "get_bs_tolerance", "set_bs_tolerance", "bs_tolerance", "Error tolerance of the Bulirsch-Stoer integrator", default_value = 1.0e-8 ) handler.add_method_parameter( "get_word_length", "set_word_length", "word_length", "The word length, or number of bits for the mantissa, used for the arbitrary precision calculations (#digits = log10(2**# bits) ", default_value = 72 ) handler.add_method_parameter( "get_eta", "set_eta", "dt_param", "dt_param, the time-step parameter for the adaptive time-step criterion", default_value = 0.24 ) handler.add_method_parameter( "get_brutus_output_directory", "set_brutus_output_directory", "brutus_output_directory", "Path to the directory where Brutus stores its output", default_value = "./" ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) handler.add_method("get_bs_tolerance", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_bs_tolerance", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_word_length", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_word_length", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_eta", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_eta", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_brutus_output_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_brutus_output_directory", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler)
23,027
44.064579
158
py
amuse
amuse-main/src/amuse/community/asterisk/__init__.py
# generated file from .interface import Asterisk
49
15.666667
31
py
amuse
amuse-main/src/amuse/community/asterisk/interface.py
from amuse.community import * from amuse.community.interface.common import CommonCodeInterface from amuse.community.interface.common import CommonCode from amuse.units import units class AsteriskInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn): """ Asterisk is a 3D visualization package for AMUSE simulations. .. [#] The Asterisk 3D visualization project is a collaboration between Sterrewacht Leiden and The Netherlands eScience Center. """ classpath = 'worker.jar', 'src', 'src/dist/*', 'src/lib/*', 'src/lib/jogl/*' def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="asterisk_worker_java", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @option(choices=['mpi','remote','distributed', 'sockets'], sections=("channel",)) def channel_type(self): return 'sockets' @option(type="boolean", sections=("channel",)) def initialize_mpi(self): """Is MPI initialized in the code or not. Defaults to True if MPI is available""" return False @legacy_function def new_star_particle(): """ Define a new particle in the visualisation code. The particle is initialized with the provided radius, position and color. This function returns an index that can be used to refer to this particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The initial position vector of the particle") function.addParameter('radius', dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The radius of the particle") for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.IN, description = "The RGB color of the particle") function.addParameter("alpha", dtype='float64', direction=function.IN, description = "The opacity of the particle", default = 1.0) function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def new_gas_particle(): """ Define a new particle in the visualisation code. The particle is initialized with the provided radius, position and color. This function returns an index that can be used to refer to this particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The initial position vector of the particle") function.addParameter('radius', dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The radius of the particle") for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.IN, description = "The RGB color of the particle") function.addParameter("alpha", dtype='float64', direction=function.IN, description = "The opacity of the particle", default = 1.0) function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def new_sphere_particle(): """ Define a new particle in the visualisation code. The particle is initialized with the provided radius, position and color. This function returns an index that can be used to refer to this particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The initial position vector of the particle") function.addParameter('radius', dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The radius of the particle") for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.IN, description = "The RGB color of the particle") function.addParameter("alpha", dtype='float64', direction=function.IN, description = "The opacity of the particle", default = 1.0) function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def new_marker_particle(): """ Define a new particle in the visualisation code. The particle is initialized with the provided radius, position and color. This function returns an index that can be used to refer to this particle. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The initial position vector of the particle") function.addParameter('radius', dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The radius of the particle") for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.IN, description = "The RGB color of the particle") function.addParameter("alpha", dtype='float64', direction=function.IN, description = "The opacity of the particle", default = 1.0) function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_particle(): """ Remove the definition of particle from the code. After calling this function the particle is no longer part of the model evolution. It is up to the code if the index will be reused. This function is optional. """ function = LegacyFunctionSpecification() function.must_handle_array = True #function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to be removed. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was removed from the model -1 - ERROR particle could not be removed -2 - ERROR not yet implemented """ return function @legacy_function def get_radius(): """ Retrieve the radius of a particle. Radius 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 radius of. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('radius', dtype='float64', direction=function.OUT, description = "The current radius of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' #function.can_handle_array = True function.must_handle_array = True return function @legacy_function def set_radius(): """ Set the radius of a particle. Radius 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 to get the radius of. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('radius', dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The new radius of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' #function.can_handle_array = True function.must_handle_array = True 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(): """ 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 get_position(): """ Retrieve the position vector of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.OUT, description = "The current position vector of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def set_position(): """ Update the position of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for par in ["x", "y", "z"]: function.addParameter(par, dtype='float64', unit=generic_unit_system.length, direction=function.IN, description = "The new position vector of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_color(): """ Retrieve the RGB color vector of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.OUT, description = "The current RGB color vector of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def set_color(): """ Update the RGB color of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) for par in ["red", "green", "blue"]: function.addParameter(par, dtype='float64', direction=function.IN, description = "The new RGB color vector of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_opacity(): """ Retrieve the alpha (opacity) of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter("alpha", dtype='float64', direction=function.OUT, description = "The opacity of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def set_opacity(): """ Update the alpha (opacity) of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter("alpha", dtype='float64', direction=function.IN, description = "The new opacity of the particle") function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_use_star_shader_flag(): function = LegacyFunctionSpecification() function.addParameter("use_star_shader_flag", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_use_star_shader_flag(): function = LegacyFunctionSpecification() function.addParameter("use_star_shader_flag", dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_x_rotation(): function = LegacyFunctionSpecification() function.addParameter("x_rotation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_y_rotation(): function = LegacyFunctionSpecification() function.addParameter("y_rotation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_z_rotation(): function = LegacyFunctionSpecification() function.addParameter("z_rotation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_x_rotation(): function = LegacyFunctionSpecification() function.addParameter("x_rotation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_y_rotation(): function = LegacyFunctionSpecification() function.addParameter("y_rotation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_z_rotation(): function = LegacyFunctionSpecification() function.addParameter("z_rotation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_x_translation(): function = LegacyFunctionSpecification() function.addParameter("x_translation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_y_translation(): function = LegacyFunctionSpecification() function.addParameter("y_translation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_z_translation(): function = LegacyFunctionSpecification() function.addParameter("z_translation", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_x_translation(): function = LegacyFunctionSpecification() function.addParameter("x_translation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_y_translation(): function = LegacyFunctionSpecification() function.addParameter("y_translation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_z_translation(): function = LegacyFunctionSpecification() function.addParameter("z_translation", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_camera_distance(): function = LegacyFunctionSpecification() function.addParameter("camera_distance", dtype='float64', unit=nbody_system.length, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_camera_distance(): function = LegacyFunctionSpecification() function.addParameter("camera_distance", dtype='float64', unit=nbody_system.length, direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_scene_number(): """ Get the number of the currently displayed scene, which can be used to redisplay it later """ function = LegacyFunctionSpecification() function.addParameter("scene_number", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_scene(): """ Display the specified scene """ function = LegacyFunctionSpecification() function.addParameter("scene_number", dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def screenshot(): function = LegacyFunctionSpecification() function.addParameter('screenshot_file_name', dtype='string', direction=function.IN, description = "Name of the file to write the (PNG) screenshot to") function.result_type = 'int32' return function @legacy_function def store_view(): """ Store and view the current model, corresponding to the given description. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='string', direction=function.IN, description = "The description of the scene.") function.result_type = 'int32' return function @legacy_function def get_field_of_view(): function = LegacyFunctionSpecification() function.addParameter("field_of_view", dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_field_of_view(): function = LegacyFunctionSpecification() function.addParameter("field_of_view", dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_z_near(): function = LegacyFunctionSpecification() function.addParameter("z_near", dtype='float64', unit=nbody_system.length, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_z_near(): function = LegacyFunctionSpecification() function.addParameter("z_near", dtype='float64', unit=nbody_system.length, direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_z_far(): function = LegacyFunctionSpecification() function.addParameter("z_far", dtype='float64', unit=nbody_system.length, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_z_far(): function = LegacyFunctionSpecification() function.addParameter("z_far", dtype='float64', unit=nbody_system.length, direction=function.IN) function.result_type = 'int32' return function class Asterisk(CommonCode): def __init__(self, unit_converter=None, **options): self.unit_converter = unit_converter CommonCode.__init__(self, AsteriskInterface(**options), **options) def store_view(self, description=""): self.overridden().store_view(str(description)) def define_properties(self, handler): handler.add_property("get_current_rotation") handler.add_property("get_current_translation") handler.add_property("get_current_rotation", public_name = "rotation") handler.add_property("get_current_translation", public_name = "translation") def define_particle_sets(self, handler): handler.define_super_set('particles', ['star_particles', 'gas_particles', 'sphere_particles', 'marker_particles'], index_to_default_set = 0) handler.define_set('star_particles', 'index_of_the_particle') handler.set_new('star_particles', 'new_star_particle') handler.set_delete('star_particles', 'delete_particle') handler.define_set('gas_particles', 'index_of_the_particle') handler.set_new('gas_particles', 'new_gas_particle') handler.set_delete('gas_particles', 'delete_particle') handler.define_set('sphere_particles', 'index_of_the_particle') handler.set_new('sphere_particles', 'new_sphere_particle') handler.set_delete('sphere_particles', 'delete_particle') handler.define_set('marker_particles', 'index_of_the_particle') handler.set_new('marker_particles', 'new_marker_particle') handler.set_delete('marker_particles', 'delete_particle') for particle_set_name in ['star_particles', 'gas_particles', 'sphere_particles', 'marker_particles']: handler.add_getter(particle_set_name, 'get_position') handler.add_setter(particle_set_name, 'set_position') handler.add_getter(particle_set_name, 'get_color') handler.add_setter(particle_set_name, 'set_color') handler.add_getter(particle_set_name, 'get_opacity') handler.add_setter(particle_set_name, 'set_opacity') handler.add_getter(particle_set_name, 'get_radius') handler.add_setter(particle_set_name, 'set_radius') 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_star_particle') handler.add_method('EDIT', 'new_gas_particle') handler.add_method('EDIT', 'new_sphere_particle') handler.add_method('EDIT', 'new_marker_particle') handler.add_method('EDIT', 'delete_particle') handler.add_method('UPDATE', 'new_star_particle') handler.add_method('UPDATE', 'new_gas_particle') handler.add_method('UPDATE', 'new_sphere_particle') handler.add_method('UPDATE', 'new_marker_particle') handler.add_method('UPDATE', 'delete_particle') handler.add_transition('EDIT', 'RUN', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_star_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_gas_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_sphere_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_marker_particle', False) handler.add_transition('RUN', 'UPDATE', 'delete_particle', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') handler.add_method('RUN', 'store_view') handler.add_method('RUN', 'set_position') handler.add_method('RUN', 'set_color') handler.add_method('RUN', 'set_opacity') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_color') handler.add_method('RUN', 'get_opacity') def define_parameters(self, handler): handler.add_boolean_parameter( "get_use_star_shader_flag", "set_use_star_shader_flag", "use_star_shader", "Use-star-shader flag. False means: plain spheres.", True ) handler.add_method_parameter( "get_x_rotation", "set_x_rotation", "x_rotation", "Rotation of the scene about the x axis (degrees)", default_value = 15.0 ) handler.add_method_parameter( "get_y_rotation", "set_y_rotation", "y_rotation", "Rotation of the scene about the y axis (degrees)", default_value = -15.0 ) handler.add_method_parameter( "get_z_rotation", "set_z_rotation", "z_rotation", "Rotation of the scene about the z axis (degrees)", default_value = 0.0 ) handler.add_vector_parameter( "rotation", "Rotation of the scene about the x, y, and z axes (degrees)", ("x_rotation", "y_rotation","z_rotation") ) handler.add_method_parameter( "get_x_translation", "set_x_translation", "x_translation", "Translation of the scene, corresponding to a rotation of the scene w.r.t. the view point (degrees)", default_value = 0.0 ) handler.add_method_parameter( "get_y_translation", "set_y_translation", "y_translation", "Translation of the scene, corresponding to a rotation of the scene w.r.t. the view point (degrees)", default_value = 0.0 ) handler.add_method_parameter( "get_z_translation", "set_z_translation", "z_translation", "Translation of the scene, corresponding to a rotation of the scene w.r.t. the view point (degrees)", default_value = 0.0 ) handler.add_vector_parameter( "translation", "Translation of the scene, corresponding to a rotation of the scene w.r.t. the view point (degrees)", ("x_translation", "y_translation","z_translation") ) handler.add_method_parameter( "get_camera_distance", "set_camera_distance", "camera_distance", "Distance from the view point to the scene", default_value = 2 | nbody_system.length ) handler.add_method_parameter( "get_scene_number", "set_scene", "scene", "set: Set the scene to display; get: Get the current scene number, which can be used to display it later", default_value = 0 ) def define_converter(self, handler): if not self.unit_converter is None: handler.set_converter(self.unit_converter.as_converter_from_si_to_generic())
30,723
44.449704
160
py
amuse
amuse-main/src/amuse/community/sakura/__init__.py
from .interface import Sakura
30
14.5
29
py
amuse
amuse-main/src/amuse/community/sakura/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface, GravitationalDynamics MODULES_MISSING = False class SakuraInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, CodeWithDataDirectories): """ .. [#] ADS:2014MNRAS.440..719G (Goncalves Ferrari, Boekholt, Portegies Zwart; 2014 MNRAS, 440, 719 """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="sakura_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) @legacy_function def get_sakura_output_directory(): function = LegacyFunctionSpecification() function.addParameter('sakura_output_directory', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_sakura_output_directory(): function = LegacyFunctionSpecification() function.addParameter('sakura_output_directory', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_particle_float64(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('identity_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('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle") function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = 0) function.result_type = 'int32' return function def new_particle(self, mass, x,y,z, vx,vy,vz, radius = 0): return self.new_particle_float64(mass, x,y,z, vx,vy,vz, radius = radius) ############################################## @legacy_function def get_t_begin(): function = LegacyFunctionSpecification() function.addParameter('t_begin', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_t_begin(): function = LegacyFunctionSpecification() function.addParameter('t_begin', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dt(): function = LegacyFunctionSpecification() function.addParameter('dt', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dt(): function = LegacyFunctionSpecification() function.addParameter('dt', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_t(): function = LegacyFunctionSpecification() function.addParameter('t', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_t(): function = LegacyFunctionSpecification() function.addParameter('t', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #################################################### class Sakura(GravitationalDynamics): def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = SakuraInterface(**options) self.legacy_doc = legacy_interface.__doc__ GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def initialize_code(self): result = self.overridden().initialize_code() self.parameters.sakura_output_directory = self.output_directory return result def define_parameters(self, handler): #~ GravitationalDynamics.define_parameters(self, handler) self.stopping_conditions.define_parameters(handler) #################################################### handler.add_method_parameter( "get_t_begin", "set_t_begin", "begin_time", "Time at start of simulation", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_dt", "set_dt", "timestep", "Constant time-step size", default_value = 1e-3 | nbody_system.time ) handler.add_method_parameter( "get_t", "set_t", "current_time", "Current time", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_sakura_output_directory", "set_sakura_output_directory", "sakura_output_directory", "Output directory", default_value = "./" ) #################################################### def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) #################################################### handler.add_method("get_t_begin", (), (nbody_system.time, handler.ERROR_CODE,)) handler.add_method("set_t_begin", (nbody_system.time, ), (handler.ERROR_CODE,)) handler.add_method("get_dt", (), (nbody_system.time, handler.ERROR_CODE,)) handler.add_method("set_dt", (nbody_system.time, ), (handler.ERROR_CODE,)) handler.add_method("get_t", (), (nbody_system.time, handler.ERROR_CODE,)) handler.add_method("set_t", (nbody_system.time, ), (handler.ERROR_CODE,)) #################################################### 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) self.stopping_conditions.define_state(handler)
7,208
38.828729
136
py
amuse
amuse-main/src/amuse/community/sakura/ggf/__init__.py
0
0
0
py
amuse
amuse-main/src/amuse/community/sakura/ggf/interface.py
""" placeholder this is not the proper way to distribute a code. for now we keep it until Tjarda's version of Sakura is ready to be copied here FIP-19032014 """ from amuse.community.interface.gd import GravitationalDynamics from amuse.rfi.core import PythonCodeInterface from amuse.community.tupan.interface import TupanImplementation, TupanInterface, Tupan, MODULES_MISSING class SakuraImplementation(TupanImplementation): def __init__(self): super(SakuraImplementation, self).__init__() self.integrator_method = "sakura" class SakuraInterface(TupanInterface): def __init__(self, **options): PythonCodeInterface.__init__( self, SakuraImplementation, 'sakura_worker', **options) class Sakura(Tupan): def __init__(self, convert_nbody=None, **options): nbody_interface = SakuraInterface(**options) GravitationalDynamics.__init__( self, nbody_interface, convert_nbody, **options ) def define_parameters(self, object): super(Sakura, self).define_parameters(object) object.add_method_parameter( "get_integrator_method", "set_integrator_method", "integrator_method", "The method to use to integrate the evolution \ of the system (choices: [sakura, asakura]) \ Note: 'asakura' is sakura with adaptive time-steps.", default_value="sakura" ) ### end of file ###
1,547
22.454545
103
py
amuse
amuse-main/src/amuse/community/sakura/ggf/old_test_sakura.py
import numpy import math from amuse.test.amusetest import TestWithMPI from amuse.units import nbody_system, units, constants from amuse.datamodel import Particles from amuse.ic.plummer import new_plummer_model try: from amuse.community.sakura.interface import SakuraInterface, Sakura, MODULES_MISSING except ImportError: MODULES_MISSING = True class TestSakuraInterface(TestWithMPI): def test01(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Test SakuraInterface initialization") instance = SakuraInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() def test02(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Test SakuraInterface new_particle / get_state") instance = SakuraInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) id, error = instance.new_particle(mass = 11.0, radius = 2.0, x = 0.0, y = 0.0, z = 0.0, vx = 0.0, vy = 0.0, vz = 0.0) self.assertEqual(0, error) self.assertEqual(0, id) id, error = instance.new_particle(mass = 21.0, radius = 5.0, x = 10.0, y = 0.0, z = 0.0, vx = 10.0, vy = 0.0, vz = 0.0) self.assertEqual(0, error) self.assertEqual(1, id) self.assertEqual(0, instance.commit_particles()) retrieved_state1 = instance.get_state(0) retrieved_state2 = instance.get_state(1) self.assertEqual(0, retrieved_state1['__result']) self.assertEqual(0, retrieved_state2['__result']) self.assertEqual(11.0, retrieved_state1['mass']) self.assertEqual(21.0, retrieved_state2['mass']) self.assertEqual( 0.0, retrieved_state1['x']) self.assertEqual(10.0, retrieved_state2['x']) self.assertEqual(0, instance.cleanup_code()) instance.stop() def test03(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Test SakuraInterface particle property getters/setters") instance = SakuraInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.01, 1, 0, 0, 0, 1, 0, 0.1).values())) self.assertEqual([1, 0], list(instance.new_particle(0.02, -1, 0, 0, 0,-1, 0, 0.1).values())) #### self.assertEquals(-1, instance.get_mass(1)['__result']) # Have to commit first self.assertEqual(0, instance.commit_particles()) # getters mass, result = instance.get_mass(0) self.assertAlmostEqual(0.01, mass) self.assertEqual(0,result) radius, result = instance.get_radius(1) self.assertAlmostEqual(0.1, radius) self.assertEqual(0,result) self.assertEqual(-1, instance.get_mass(2)['__result']) # Particle not found self.assertEqual([ 1, 0, 0, 0], list(instance.get_position(0).values())) self.assertEqual([-1, 0, 0, 0], list(instance.get_position(1).values())) self.assertEqual([ 0, 1, 0, 0], list(instance.get_velocity(0).values())) self.assertEqual([ 0,-1, 0, 0], list(instance.get_velocity(1).values())) # setters self.assertEqual(0, instance.set_state(0, 0.01, 1,2,3, 4,5,6, 0.1)) self.assertEqual([0.01, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_mass(0, 0.02)) self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.1, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_radius(0, 0.2)) self.assertEqual([0.02, 1.0,2.0,3.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_position(0, 10,20,30)) self.assertEqual([0.02, 10.0,20.0,30.0, 4.0,5.0,6.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.set_velocity(0, 40,50,60)) self.assertEqual([0.02, 10.0,20.0,30.0, 40.0,50.0,60.0, 0.2, 0], list(instance.get_state(0).values())) self.assertEqual(0, instance.cleanup_code()) instance.stop() def xtest04(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Test SakuraInterface parameters") instance = SakuraInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual([0.03125, 0], list(instance.get_eta().values())) self.assertEqual(0, instance.set_eta(0.001)) self.assertEqual([0.001, 0], list(instance.get_eta().values())) self.assertEqual([0.0, 0], list(instance.get_begin_time().values())) self.assertEqual(0, instance.set_begin_time(1.0)) self.assertEqual([1.0, 0], list(instance.get_begin_time().values())) self.assertEqual(["sakura", 0], list(instance.get_integrator_method().values())) self.assertEqual(0, instance.set_integrator_method("bogus")) self.assertEqual(["bogus", 0], list(instance.get_integrator_method().values())) self.assertEqual(-1, instance.commit_parameters()) self.assertEqual(0, instance.set_integrator_method("asakura")) self.assertEqual(["asakura", 0], list(instance.get_integrator_method().values())) self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.set_pn_order(7)) self.assertEqual([7, 0], list(instance.get_pn_order().values())) self.assertEqual(-1, instance.commit_parameters()) self.assertEqual(0, instance.set_clight(1024)) self.assertEqual([1024, 0], list(instance.get_clight().values())) self.assertEqual(0, instance.commit_parameters()) self.assertEqual(0, instance.cleanup_code()) instance.stop() def test05(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Test SakuraInterface evolve_model, binary") instance = SakuraInterface() self.assertEqual(0, instance.initialize_code()) self.assertEqual(0, instance.commit_parameters()) self.assertEqual([0, 0], list(instance.new_particle(0.5, 0.5, 0, 0, 0, 0.5, 0, 0.001).values())) self.assertEqual([1, 0], list(instance.new_particle(0.5, -0.5, 0, 0, 0,-0.5, 0, 0.001).values())) self.assertEqual(0, instance.commit_particles()) P = 2 * math.pi self.assertEqual(0, instance.evolve_model(P / 2)) # half an orbit for result, expected in zip(list(instance.get_position(0).values()), [-0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) self.assertEqual(0, instance.evolve_model(P)) # full orbit for result, expected in zip(list(instance.get_position(0).values()), [0.5, 0.0, 0.0, 0]): self.assertAlmostEqual(result, expected, 2) self.assertEqual(0, instance.cleanup_code()) instance.stop() class TestSakura(TestWithMPI): default_converter = nbody_system.nbody_to_si(1.0e4 | units.MSun, 1.0 | units.AU) def new_sun_earth_system(self): particles = Particles(2) particles.mass = [1.0, 3.0037e-6] | units.MSun particles.radius = 1.0 | units.RSun particles.position = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s particles[1].vy = (constants.G * particles.total_mass() / (1.0 | units.AU)).sqrt() return particles def test01(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura initialization") instance = Sakura(self.default_converter, ) instance.initialize_code() instance.commit_parameters() instance.cleanup_code() instance.stop() def xtest02(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura parameters") instance = Sakura(self.default_converter, ) instance.initialize_code() self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(0.0 | nbody_system.length**2)) self.assertEqual(instance.parameters.timestep_parameter, 0.125) for par, value in [('epsilon_squared_star_star', 0.0 | nbody_system.length**2), ('epsilon_squared_star_blackhole', 0.0 | nbody_system.length**2), ('epsilon_squared_blackhole_blackhole', 0.0 | nbody_system.length**2), ('initial_timestep_parameter', 1.0e-4), ('timestep_parameter_stars', 0.1), ('timestep_parameter_supermassive_black_holes', 0.4), ('timestep_parameter_intermediate_mass_black_holes', 0.4), ('max_relative_energy_error', 5.0e-5), ('maximum_timestep', 1.0/1024.0 | nbody_system.time), ('smbh_mass', 1.0 | nbody_system.mass)]: self.assertEqual(instance.unit_converter.to_si(value), getattr(instance.parameters, par)) setattr(instance.parameters, par, 3.0 | value.unit) self.assertEqual(instance.unit_converter.to_si(3.0 | value.unit), getattr(instance.parameters, par)) # epsilon_squared is an alias for epsilon_squared_star_star, so epsilon_squared also has become 3: self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(3.0 | nbody_system.length**2)) instance.parameters.epsilon_squared = 0.1 | nbody_system.length**2 self.assertEqual(instance.parameters.epsilon_squared, instance.unit_converter.to_si(0.1 | nbody_system.length**2)) # timestep_parameter is an alias for timestep_parameter_stars, so timestep_parameter also has become 3: self.assertEqual(instance.parameters.timestep_parameter, 3.0) instance.parameters.timestep_parameter = 0.01 self.assertEqual(instance.parameters.timestep_parameter, 0.01) self.assertEqual(instance.parameters.include_smbh, False) instance.parameters.include_smbh = True self.assertEqual(instance.parameters.include_smbh, True) self.assertEqual(instance.parameters.calculate_postnewtonian, True) instance.parameters.calculate_postnewtonian = False self.assertEqual(instance.parameters.calculate_postnewtonian, False) self.assertEqual(instance.parameters.drink, "Vodka martini. Shaken, not stirred.") instance.stop() def test03(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura particles") instance = Sakura(self.default_converter, ) instance.initialize_code() instance.commit_parameters() instance.particles.add_particles(self.new_sun_earth_system()) instance.commit_particles() self.assertAlmostEqual(instance.particles.mass, [1.0, 3.0037e-6] | units.MSun) self.assertAlmostEqual(instance.particles.radius, 1.0 | units.RSun) self.assertAlmostEqual(instance.particles.position, [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]] | units.AU) self.assertAlmostEqual(instance.particles.velocity, [[0.0, 0.0, 0.0], [0.0, 29.7885, 0.0]] | units.km / units.s, 3) instance.cleanup_code() instance.stop() def xtest04(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura evolve_model, 2 particles orbiting the SMBH") particles = Particles(2) particles.mass = 1.0 | units.MSun particles.radius = 1.0 | units.RSun particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | units.AU particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s particles[1].vy = ((constants.G * (10001.0 | units.MSun) / (1.0 | units.AU)).sqrt() + (constants.G * (10000.0 | units.MSun) / (1.0 | units.AU)).sqrt()) particles.move_to_center() print(particles) instance = Sakura(self.default_converter, ) instance.initialize_code() # instance.parameters.include_smbh = True instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() primary = instance.particles[0] P = 2 * math.pi * primary.x / primary.vy P_corrected = (P) * (2.0 / (1.0 + math.sqrt(1.0001))) position_at_start = primary.position.x instance.evolve_model(P_corrected / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 3) instance.evolve_model(P_corrected / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 3) instance.evolve_model(P_corrected) self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 3) instance.cleanup_code() instance.stop() def test05(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura evolve_model, 2 particles, no SMBH") particles = Particles(2) particles.mass = 1.0 | units.MSun particles.radius = 1.0 | units.RSun particles.position = [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]] | units.AU particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | units.km / units.s particles[1].vy = (constants.G * (2.0 | units.MSun) / (2.0 | units.AU)).sqrt() particles.move_to_center() print(particles) converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = Sakura(converter, ) instance.initialize_code() instance.parameters.integrator_method = "asakura" instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() primary = instance.particles[0] P = 2 * math.pi * primary.x / primary.vy position_at_start = primary.position.x instance.evolve_model(P / 4.0) self.assertAlmostRelativeEqual(position_at_start, primary.position.y, 3) instance.evolve_model(P / 2.0) self.assertAlmostRelativeEqual(position_at_start, -primary.position.x, 3) instance.evolve_model(P) self.assertAlmostRelativeEqual(position_at_start, primary.position.x, 3) instance.cleanup_code() instance.stop() def test06(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura evolve_model, earth-sun system, no SMBH") converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) instance = Sakura(converter, ) instance.initialize_code() # instance.parameters.smbh_mass = 0.0 | units.MSun instance.commit_parameters() instance.particles.add_particles(self.new_sun_earth_system()) instance.commit_particles() earth = instance.particles[1] position_at_start = earth.position.x instance.evolve_model(0.25 | units.yr) self.assertAlmostRelativeEqual(position_at_start, earth.position.y, 3) instance.evolve_model(0.5 | units.yr) self.assertAlmostRelativeEqual(position_at_start, -earth.position.x, 3) instance.evolve_model(1.0 | units.yr) self.assertAlmostRelativeEqual(position_at_start, earth.position.x, 3) instance.cleanup_code() instance.stop() def xtest07(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing effect of Sakura parameter epsilon_squared") converter = nbody_system.nbody_to_si(1.0 | units.MSun, 1.0 | units.AU) particles = self.new_sun_earth_system() particles.rotate(0.0, 0.0, -math.pi/4) particles.move_to_center() tan_initial_direction = particles[1].vy/particles[1].vx self.assertAlmostEqual(tan_initial_direction, math.tan(math.pi/4)) tan_final_direction = [] for log_eps2 in range(-9,10,2): instance = Sakura(converter, ) instance.initialize_code() instance.parameters.epsilon_squared = 10.0**log_eps2 | units.AU ** 2 # instance.parameters.smbh_mass = 0.0 | units.MSun instance.commit_parameters() instance.particles.add_particles(particles) instance.commit_particles() instance.evolve_model(0.25 | units.yr) tan_final_direction.append(instance.particles[1].velocity[1]/ instance.particles[1].velocity[0]) instance.cleanup_code() instance.stop() # Small values of epsilon_squared should result in normal earth-sun dynamics: rotation of 90 degrees self.assertAlmostEqual(tan_final_direction[0], math.tan(3 * math.pi / 4.0), 2) # Large values of epsilon_squared should result in ~ no interaction self.assertAlmostEqual(tan_final_direction[-1], tan_initial_direction, 2) # Outcome is most sensitive to epsilon_squared when epsilon_squared = d(earth, sun)^2 delta = [abs(tan_final_direction[i+1]-tan_final_direction[i]) for i in range(len(tan_final_direction)-1)] self.assertEqual(delta[len(tan_final_direction)/2 -1], max(delta)) def xtest08(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura get_gravity_at_point and get_potential_at_point") instance = Sakura() instance.initialize_code() instance.parameters.epsilon_squared = 0.0 | nbody_system.length**2 # instance.parameters.smbh_mass = 0.0 | nbody_system.mass particles = Particles(2) particles.mass = 1.0 | nbody_system.mass particles.radius = 0.0 | nbody_system.length particles.position = [[0.0,0.0,0.0], [2.0,0.0,0.0]] | nbody_system.length particles.velocity = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]] | nbody_system.speed instance.particles.add_particles(particles) zero = 0.0 | nbody_system.length fx, fy, fz = instance.get_gravity_at_point(zero, 1.0 | nbody_system.length, zero, zero) self.assertAlmostEqual(fx, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fy, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz, 0.0 | nbody_system.acceleration) for x in (0.25, 0.5, 0.75): x0 = x | nbody_system.length x1 = (2.0 - x) | nbody_system.length potential0 = instance.get_potential_at_point(zero, x0, zero, zero) potential1 = instance.get_potential_at_point(zero, x1, zero, zero) fx0, fy0, fz0 = instance.get_gravity_at_point(zero, x0, zero, zero) fx1, fy1, fz1 = instance.get_gravity_at_point(zero, x1, zero, zero) self.assertAlmostEqual(fy0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz0, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fy1, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fz1, 0.0 | nbody_system.acceleration) self.assertAlmostEqual(fx0, -1.0 * fx1) fx = (-1.0 / (x0**2) + 1.0 / (x1**2)) * (1.0 | nbody_system.length ** 3 / nbody_system.time ** 2) self.assertAlmostEqual(fx, fx0) self.assertAlmostEqual(potential0, potential1) instance.stop() def test09(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura evolve_model and getters energy, plummer sphere, no SMBH") converter = nbody_system.nbody_to_si(1.0e2 | units.MSun, 1.0 | units.parsec) instance = Sakura(converter, ) instance.parameters.timestep_parameter = 1.0/256 instance.initialize_code() # instance.parameters.smbh_mass = 0.0 | units.MSun instance.commit_parameters() numpy.random.seed(987654321) instance.particles.add_particles(new_plummer_model(100, convert_nbody=converter)) instance.commit_particles() kinetic_energy = instance.kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 2.12292810174e+37 | units.J, 10) self.assertAlmostRelativeEqual(potential_energy, -4.33511391248e+37 | units.J, 10) initial_total_energy = kinetic_energy + potential_energy instance.evolve_model(0.1 | nbody_system.time) kinetic_energy = instance.kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 2.1362368884e+37 | units.J, 4) self.assertAlmostRelativeEqual(potential_energy, -4.34842269914e+37 | units.J, 4) self.assertAlmostRelativeEqual(potential_energy + kinetic_energy, initial_total_energy, 4) instance.cleanup_code() instance.stop() def xtest10(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura collision_detection") particles = Particles(7) particles.mass = 0.00000001 | nbody_system.mass particles.radius = 0.01 | nbody_system.length particles.x = [-101.0, -100.0, -0.5, 0.5, 100.0, 101.0, 104.0] | nbody_system.length particles.y = 0 | nbody_system.length particles.z = 0 | nbody_system.length particles.velocity = [[2, 0, 0], [-2, 0, 0]]*3 + [[-4, 0, 0]] | nbody_system.speed instance = Sakura() instance.initialize_code() instance.parameters.set_defaults() instance.particles.add_particles(particles) collisions = instance.stopping_conditions.collision_detection collisions.enable() instance.evolve_model(1.0 | nbody_system.time) self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 0.5 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 3) self.assertEqual(len(collisions.particles(1)), 3) self.assertEqual(len(particles - collisions.particles(0) - collisions.particles(1)), 1) self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True, True, True]) sticky_merged = Particles(len(collisions.particles(0))) sticky_merged.mass = collisions.particles(0).mass + collisions.particles(1).mass sticky_merged.radius = collisions.particles(0).radius for p1, p2, merged in zip(collisions.particles(0), collisions.particles(1), sticky_merged): merged.position = (p1 + p2).center_of_mass() merged.velocity = (p1 + p2).center_of_mass_velocity() print(instance.model_time) print(instance.particles) instance.particles.remove_particles(collisions.particles(0) + collisions.particles(1)) instance.particles.add_particles(sticky_merged) instance.evolve_model(1.0 | nbody_system.time) print() print(instance.model_time) print(instance.particles) self.assertTrue(collisions.is_set()) self.assertTrue(instance.model_time < 1.0 | nbody_system.time) self.assertEqual(len(collisions.particles(0)), 1) self.assertEqual(len(collisions.particles(1)), 1) self.assertEqual(len(instance.particles - collisions.particles(0) - collisions.particles(1)), 2) self.assertEqual(abs(collisions.particles(0).x - collisions.particles(1).x) < (collisions.particles(0).radius + collisions.particles(1).radius), [True]) instance.stop() def test11(self): if MODULES_MISSING: self.skip("Failed to import a module required for Sakura") print("Testing Sakura properties") numpy.random.seed(12345) particles = new_plummer_model(100, do_scale=True) particles.position += [1, 2, 3] | nbody_system.length cluster_velocity = [4, 5, 6] | nbody_system.speed particles.velocity += cluster_velocity external_kinetic_energy = (0.5 | nbody_system.mass) * cluster_velocity.length_squared() instance = Sakura() instance.particles.add_particles(particles) kinetic_energy = instance.kinetic_energy - external_kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy, 0.25 | nbody_system.energy, 10) self.assertAlmostRelativeEqual(potential_energy, -0.5 | nbody_system.energy, 10) self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 10) self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1, 2, 3] | nbody_system.length, 10) self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 10) initial_total_energy = kinetic_energy + potential_energy instance.evolve_model(0.1 | nbody_system.time) self.assertAlmostRelativeEqual(instance.model_time, 0.1 | nbody_system.time, 3) kinetic_energy = instance.kinetic_energy - external_kinetic_energy potential_energy = instance.potential_energy self.assertAlmostRelativeEqual(kinetic_energy+potential_energy, -0.25 | nbody_system.energy, 3) self.assertAlmostRelativeEqual(instance.total_mass, 1.0 | nbody_system.mass, 3) self.assertAlmostRelativeEqual(instance.center_of_mass_position, [1.4, 2.5, 3.6] | nbody_system.length, 3) self.assertAlmostRelativeEqual(instance.center_of_mass_velocity, [4, 5, 6] | nbody_system.speed, 3) instance.cleanup_code() instance.stop()
26,337
47.062044
127
py
amuse
amuse-main/src/amuse/community/distributed/distributed_datamodel.py
from amuse.datamodel import Particles, Particle class Resources(Particles): def __getitem__(self, index): keys = self.get_all_keys_in_store()[index] index = self.get_all_indices_in_store()[index] if hasattr(keys, '__iter__'): return self._subset(keys) else: return Resource(keys, self, index, self._get_version()) def __iter__(self): keys = self.get_all_keys_in_store() indices = self.get_all_indices_in_store() version = self._get_version() for i in range(len(keys)): yield Resource(keys[i], self, indices[i], version) add_resource = Particles.add_particle add_resources = Particles.add_particles remove_resource = Particles.remove_particle remove_resources = Particles.remove_particles class Resource(Particle): def __init__(self, key = None, particles_set = None, set_index = -1, set_version = -1, **keyword_arguments): if particles_set is None: if key == None: particles_set = Resources(1) key = particles_set.get_all_keys_in_store()[0] else: particles_set = Resources(1, keys = [key]) object.__setattr__(self, "key", key) object.__setattr__(self, "particles_set", particles_set) object.__setattr__(self, "_set_index", set_index) object.__setattr__(self, "_set_version", set_version) for attribute_name in keyword_arguments: attribute_value = keyword_arguments[attribute_name] setattr(self, attribute_name, attribute_value) class Pilots(Particles): def __getitem__(self, index): keys = self.get_all_keys_in_store()[index] index = self.get_all_indices_in_store()[index] if hasattr(keys, '__iter__'): return self._subset(keys) else: return Pilot(keys, self, index, self._get_version()) def __iter__(self): keys = self.get_all_keys_in_store() indices = self.get_all_indices_in_store() version = self._get_version() for i in range(len(keys)): yield Pilot(keys[i], self, indices[i], version) add_pilot = Particles.add_particle add_pilots = Particles.add_particles remove_pilot = Particles.remove_particle remove_pilots = Particles.remove_particles class Pilot(Particle): def __init__(self, key = None, particles_set = None, set_index = -1, set_version = -1, **keyword_arguments): if particles_set is None: if key == None: particles_set = Pilots(1) key = particles_set.get_all_keys_in_store()[0] else: particles_set = Pilots(1, keys = [key]) object.__setattr__(self, "key", key) object.__setattr__(self, "particles_set", particles_set) object.__setattr__(self, "_set_index", set_index) object.__setattr__(self, "_set_version", set_version) for attribute_name in keyword_arguments: attribute_value = keyword_arguments[attribute_name] setattr(self, attribute_name, attribute_value) class ScriptJobs(Particles): def __getitem__(self, index): keys = self.get_all_keys_in_store()[index] index = self.get_all_indices_in_store()[index] if hasattr(keys, '__iter__'): return self._subset(keys) else: return ScriptJob(keys, self, index, self._get_version()) def __iter__(self): keys = self.get_all_keys_in_store() indices = self.get_all_indices_in_store() version = self._get_version() for i in range(len(keys)): yield ScriptJob(keys[i], self, indices[i], version) submit_script_job = Particles.add_particle submit_script_jobs = Particles.add_particles cancel_script_job = Particles.remove_particle cancel_script_jobs = Particles.remove_particles remove_script_job = Particles.remove_particle remove_script_jobs = Particles.remove_particles class ScriptJob(Particle): def __init__(self, key = None, particles_set = None, set_index = -1, set_version = -1, **keyword_arguments): if particles_set is None: if key == None: particles_set = ScriptJobs(1) key = particles_set.get_all_keys_in_store()[0] else: particles_set = ScriptJobs(1, keys = [key]) object.__setattr__(self, "key", key) object.__setattr__(self, "particles_set", particles_set) object.__setattr__(self, "_set_index", set_index) object.__setattr__(self, "_set_version", set_version) for attribute_name in keyword_arguments: attribute_value = keyword_arguments[attribute_name] setattr(self, attribute_name, attribute_value) class FunctionJobs(Particles): def __getitem__(self, index): keys = self.get_all_keys_in_store()[index] index = self.get_all_indices_in_store()[index] if hasattr(keys, '__iter__'): return self._subset(keys) else: return FunctionJob(keys, self, index, self._get_version()) def __iter__(self): keys = self.get_all_keys_in_store() indices = self.get_all_indices_in_store() version = self._get_version() for i in range(len(keys)): yield FunctionJob(keys[i], self, indices[i], version) submit_function_job = Particles.add_particle submit_function_jobs = Particles.add_particles cancel_function_job = Particles.remove_particle cancel_function_jobs = Particles.remove_particles remove_function_job = Particles.remove_particle remove_function_jobs = Particles.remove_particles class FunctionJob(Particle): def __init__(self, key = None, particles_set = None, set_index = -1, set_version = -1, **keyword_arguments): if particles_set is None: if key == None: particles_set = FunctionJobs(1) key = particles_set.get_all_keys_in_store()[0] else: particles_set = FunctionJobs(1, keys = [key]) object.__setattr__(self, "key", key) object.__setattr__(self, "particles_set", particles_set) object.__setattr__(self, "_set_index", set_index) object.__setattr__(self, "_set_version", set_version) for attribute_name in keyword_arguments: attribute_value = keyword_arguments[attribute_name] setattr(self, attribute_name, attribute_value)
6,655
33.848168
112
py
amuse
amuse-main/src/amuse/community/distributed/__init__.py
# relative import hack # https://stackoverflow.com/questions/16981921/relative-imports-in-python-3 import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__))) from .interface import Distributed
211
41.4
76
py
amuse
amuse-main/src/amuse/community/distributed/interface.py
import logging from amuse.community import * from amuse.community.interface.common import CommonCodeInterface from amuse.community.interface.common import CommonCode from amuse.support import options from amuse.rfi.channel import DistributedChannel from distributed_datamodel import Resources, Resource from distributed_datamodel import Pilots, Pilot from distributed_datamodel import ScriptJobs, ScriptJob from distributed_datamodel import FunctionJobs, FunctionJob import pickle logger = logging.getLogger(__name__) class DistributedAmuseInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn): """ Distributed Amuse Code .. [#] The Distributed Amuse project is a collaboration between Sterrewacht Leiden and The Netherlands eScience Center. """ classpath = ['data/','data/*'] # keeping a reference is no longer necessary def __init__(self, **keyword_arguments): if self.channel_type != 'sockets': raise Exception("Distributed Amuse must be started with sockets channel, not '%s'" % self.channel_type) CodeInterface.__init__(self, name_of_the_worker="distributed_worker", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @option(choices=['sockets'], sections=("channel",)) def channel_type(self): return 'sockets' @option(type="boolean", sections=("channel",)) def initialize_mpi(self): """Is MPI initialized in the code or not. Defaults to True if MPI is available""" return False @legacy_function def get_worker_port(): """ Returns the server socket port of the code. Used by the distributed channel """ function = LegacyFunctionSpecification() function.addParameter("worker_port", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_debug(): """ Returns if debugging is enabled """ function = LegacyFunctionSpecification() function.addParameter("debug", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_debug(): """ Enable or disable debugging """ function = LegacyFunctionSpecification() function.addParameter("debug", dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_start_hubs(): """ Returns if starting hubs is enabled """ function = LegacyFunctionSpecification() function.addParameter("start_hubs", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_start_hubs(): """ Enable or disable starting hubs. """ function = LegacyFunctionSpecification() function.addParameter("start_hubs", dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_webinterface_port(): """ Returns the port the webinterface is running on """ function = LegacyFunctionSpecification() function.addParameter("webinterface_port", dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_webinterface_port(): """ Set the port the webinterface is running on """ function = LegacyFunctionSpecification() function.addParameter("webinterface_port", dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_worker_startup_timeout(): """ Returns the time to wait before the worker is started on the remote note onc e a pilot to run on is acquired """ function = LegacyFunctionSpecification() function.addParameter("worker_startup_timeout", dtype='int32', unit=units.s, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_worker_startup_timeout(): """ Set the time to wait before the worker is started on the remote note onc e a pilot to run on is acquired """ function = LegacyFunctionSpecification() function.addParameter("worker_startup_timeout", dtype='int32', unit=units.s, direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_worker_queue_timeout(): """ Returns the amount of time to wait until a slot becomes available to run a worker on. """ function = LegacyFunctionSpecification() function.addParameter("worker_queue_timeout", dtype='int32', unit=units.s, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_worker_queue_timeout(): """ Set the amount of time to wait until a slot becomes available to run a worker on. """ function = LegacyFunctionSpecification() function.addParameter("worker_queue_timeout", dtype='int32', unit=units.s, direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_resource(): """ Define a new resource. This function returns an index that can be used to refer to this resource. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('resource_id', dtype='int32', direction=function.OUT) function.addParameter("name", dtype='string', direction=function.IN) function.addParameter("location", dtype='string', direction=function.IN) function.addParameter("amuse_dir", dtype='string', direction=function.IN) function.addParameter("tmp_dir", dtype='string', direction=function.IN, default="") function.addParameter("gateway", dtype='string', direction=function.IN, default="") function.addParameter("scheduler_type", dtype='string', direction=function.IN, default="ssh") function.addParameter("hub_queue_name", dtype='string', direction=function.IN, default="") function.addParameter("hub_time_minutes", dtype='int32', direction=function.IN, unit = units.minute, default = 1) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_resource_state(): """ Get all the attributes of a resource. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('resource_id', dtype='int32', direction=function.IN) function.addParameter("name", dtype='string', direction=function.OUT) function.addParameter("location", dtype='string', direction=function.OUT) function.addParameter("gateway", dtype='string', direction=function.OUT) function.addParameter("amuse_dir", dtype='string', direction=function.OUT) function.addParameter("tmp_dir", dtype='string', direction=function.OUT) function.addParameter("scheduler_type", dtype='string', direction=function.OUT) function.addParameter("hub_queue_name", dtype='string', direction=function.OUT) function.addParameter("hub_time_minutes", dtype='int32', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_resource(): """ Remove the definition of resource from the code. After calling this function the resource is no longer part of the model evolution. It is up to the code if the index will be reused. This function is optional. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('resource_id', dtype='int32', direction=function.IN, description = "Index of the resource to be removed. This index must have been returned by an earlier call to :meth:`new_resource`") function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.result_doc = """ 0 - OK resource was removed from the model -1 - ERROR resource could not be removed -2 - ERROR not yet implemented """ return function @legacy_function def new_pilot(): """ Reserve one or more nodes for later use by the simulation. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('pilot_id', dtype='int32', direction=function.OUT) function.addParameter("resource_name", dtype='string', direction=function.IN) function.addParameter("queue_name", dtype='string', direction=function.IN, default="") function.addParameter("node_count", dtype='int32', direction=function.IN, default = 1) function.addParameter("time", dtype='int32', direction=function.IN, unit = units.minute, default = 60) function.addParameter("slots_per_node", dtype='int32', direction=function.IN, default = 1) function.addParameter("label", dtype='string', direction=function.IN, default = "default") function.addParameter("options", dtype='string', direction=function.IN, default = "") function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_pilot_state(): """ Get all attributes of a pilot """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('pilot_id', dtype='int32', direction=function.IN) function.addParameter("resource_name", dtype='string', direction=function.OUT) function.addParameter("queue_name", dtype='string', direction=function.OUT) function.addParameter("node_count", dtype='int32', direction=function.OUT) function.addParameter("time", dtype='int32', direction=function.OUT, unit = units.minute) function.addParameter("slots_per_node", dtype='int32', direction=function.OUT) function.addParameter("label", dtype='string', direction=function.OUT) function.addParameter('status', dtype='string', direction=function.OUT) function.addParameter("options", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_pilot_status(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('pilot_id', dtype='int32', direction=function.IN) function.addParameter('status', dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_pilot(): """ Delete (stop) a pilot. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('pilot_id', dtype='int32', direction=function.IN) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def wait_for_pilots(): """ Wait until all pilots are started, and all nodes are available to run jobs and/or workers """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def submit_script_job(): """ Submit a job, specified by a script """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.OUT) function.addParameter('script_dir', dtype='string', direction=function.IN) function.addParameter('script_name', dtype='string', direction=function.IN) function.addParameter('arguments', dtype='string', direction=function.IN, default = "") function.addParameter('input_dir', dtype='string', direction=function.IN, default = "") function.addParameter('output_dir', dtype='string', direction=function.IN, default = "") function.addParameter('stdout_file', dtype='string', direction=function.IN, default = "") function.addParameter('stderr_file', dtype='string', direction=function.IN, default = "") function.addParameter("label", dtype='string', direction=function.IN, default = "") function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_script_job_state(): """ Get all attributes of a script job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('script_dir', dtype='string', direction=function.OUT) function.addParameter('script_name', dtype='string', direction=function.OUT) function.addParameter('arguments', dtype='string', direction=function.OUT) function.addParameter('input_dir', dtype='string', direction=function.OUT) function.addParameter('output_dir', dtype='string', direction=function.OUT) function.addParameter('stdout_file', dtype='string', direction=function.OUT) function.addParameter('stderr_file', dtype='string', direction=function.OUT) function.addParameter("label", dtype='string', direction=function.OUT) function.addParameter("status", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_script_job_status(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('status', dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_script_job(): """ Delete (cancel) a script job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def wait_for_script_jobs(): """ Wait until all script jobs are done. """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def submit_function_job(): """ Submit a job, specified by a pickle of the function, and a pickle of the arguments. """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.OUT) function.addParameter('function', dtype='string', direction=function.IN) function.addParameter('arguments', dtype='string', direction=function.IN) function.addParameter('kwarguments', dtype='string', direction=function.IN) function.addParameter('stdout_file', dtype='string', direction=function.IN) function.addParameter('stderr_file', dtype='string', direction=function.IN) function.addParameter("label", dtype='string', direction=function.IN, default = "default") function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_function_job_state(): """ Get all attributes of a pickled job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('stdout_file', dtype='string', direction=function.OUT) function.addParameter('stderr_file', dtype='string', direction=function.OUT) function.addParameter("label", dtype='string', direction=function.OUT) function.addParameter("status", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_function_job_status(): """ Get all attributes of a pickled job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter("status", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_function_job_result(): """ Get a result of a picked function job. Will block until the result is available """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('result', dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def delete_function_job(): """ Delete (cancel) a script job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('job_id', dtype='int32', direction=function.IN) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_worker_state(): """ Get all attributes of a pickled job """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('worker_id', dtype='int32', direction=function.IN) function.addParameter('executable', dtype='string', direction=function.OUT) function.addParameter("label", dtype='string', direction=function.OUT) function.addParameter("worker_count", dtype='int32', direction=function.OUT) function.addParameter("thread_count", dtype='int32', direction=function.OUT) function.addParameter("status", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_worker_status(): """ Get all attributes of a worker """ function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('worker_id', dtype='int32', direction=function.IN) function.addParameter("status", dtype='string', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_number_of_workers(): function = LegacyFunctionSpecification() function.addParameter('number_of_workers', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_worker_ids(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('index', dtype='int32', direction=function.IN) # probably unused, but required to get 'count' function.addParameter('id_of_the_worker', dtype='int32', direction=function.OUT) function.addParameter('count', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_current_error(): """When a function returns an error, this will retrieve a description (if possible) """ function = LegacyFunctionSpecification() function.addParameter('string', dtype='string', direction=function.OUT, description = "description of the error" ) function.result_type = 'int32' return function @legacy_function def end_all(): """ Stop all jobs, resources and pilots """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def startup_viz(): """ start up simple visualisation of used smartsockets """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function def cleanup_code(self): self.end_all() return 0 def new_worker(self): raise exceptions.AmuseException("Can't add to 'workers' directly. Create community code instances in the usual way instead.") def delete_worker(self): raise exceptions.AmuseException("Can't remove from 'workers' directly. Stop community code instances in the usual way instead.") class DistributedAmuse(CommonCode): def __init__(self, **options): CommonCode.__init__(self, DistributedAmuseInterface(**options), **options) def submit_function_job(self, label, stdout_file, stderr_file, function, *args, **kwargs): # pickle the input function pickled_function = pickle.dumps(function,0) pickled_arguments = pickle.dumps(args,0) pickled_kwarguments = pickle.dumps(kwargs,0) return self.overridden().submit_function_job(function=pickled_function, arguments=pickled_arguments, kwarguments=pickled_kwarguments, label=label, stdout_file=stdout_file, stderr_file=stderr_file) def get_function_job_result(self, job_id): pickled_result = self.overridden().get_function_job_result(job_id) result = pickle.load(pickled_result) return result def get_webinterface_url(self): return "http://localhost:" + str(self.parameters.webinterface_port) def commit_parameters(self): self.parameters.send_not_set_parameters_to_code() self.parameters.send_cached_parameters_to_code() #initialization of java code self.overridden().commit_parameters() self.port = self.get_worker_port() #logging.basicConfig(level=logging.DEBUG) logger.debug("running on port %d", self.port) # self.stdoutHandler = OutputHandler(sys.stdout, port) # self.stderrHandler = OutputHandler(sys.stderr, port) #add local resource resource = Resource() resource.name = "local" resource.location = "" resource.amuse_dir = options.GlobalOptions.instance().amuse_rootdirectory resource.scheduler_type = "local" self.resources.add_resource(resource) if self.parameters.startup_viz: self.startup_viz() def use_for_distributed_workers(self, enable=True): if enable: DistributedChannel.default_distributed_instance=self elif DistributedChannel.default_distributed_instance is self: DistributedChannel.default_distributed_instance=None def use_for_all_workers(self, enable=True): if enable: DistributedChannel.default_distributed_instance=self options.GlobalOptions.instance().override_value_for_option("channel_type", "distributed") else: if DistributedChannel.default_distributed_instance is self \ and "channel_type" in options.GlobalOptions.instance().overriden_options: DistributedChannel.default_distributed_instance=None del options.GlobalOptions.instance().overriden_options["channel_type"] def cleanup_code(self): if DistributedChannel.default_distributed_instance is self: DistributedChannel.default_distributed_instance=None if "channel_type" in options.GlobalOptions.instance().overriden_options: del options.GlobalOptions.instance().overriden_options["channel_type"] self.overridden().cleanup_code() def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','RUN','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_method('RUN', 'before_get_parameter') handler.add_method('INITIALIZED', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('RUN', 'startup_viz') handler.add_method('RUN', 'new_resource') handler.add_method('RUN', 'new_pilot') handler.add_method('RUN', 'submit_script_job') handler.add_method('RUN', 'submit_function_job') handler.add_method('RUN', 'get_resource_state') handler.add_method('RUN', 'get_pilot_state') handler.add_method('RUN', 'get_pilot_status') handler.add_method('RUN', 'get_script_job_state') handler.add_method('RUN', 'get_script_job_status') handler.add_method('RUN', 'get_function_job_state') handler.add_method('RUN', 'get_function_job_status') handler.add_method('RUN', 'get_worker_state') handler.add_method('RUN', 'get_worker_status') handler.add_method('RUN', 'use_for_distributed_workers') handler.add_method('RUN', 'use_for_all_workers') def define_parameters(self, handler): handler.add_boolean_parameter( "get_debug", "set_debug", "debug", "If true, will output additional debugging information and logs", default_value = False ) handler.add_boolean_parameter( "get_start_hubs", "set_start_hubs", "start_hubs", "If true, start a communication support hub on each resource", default_value = True ) handler.add_method_parameter( "get_worker_port", None, "worker_port", "Port that the distributed code uses to handle new worker requests on from the distributed channel", default_value = 0 ) handler.add_method_parameter( "get_webinterface_port", "set_webinterface_port", "webinterface_port", "Port for monitoring webinterface", default_value = 0 ) handler.add_method_parameter( "get_worker_startup_timeout", "set_worker_startup_timeout", "worker_startup_timeout", "Time to wait until workers have started once a pilot has been aquired", default_value = 60 | units.s ) handler.add_method_parameter( "get_worker_queue_timeout", "set_worker_queue_timeout", "worker_queue_timeout", "Time to wait in the queue for a pilot to become available", default_value = 60 | units.s ) handler.add_interface_parameter( "startup_viz", "whether to startup simple smartsockets vizualization", False ) def define_particle_sets(self, handler): handler.define_super_set('items', ['_resources', 'pilots', 'script_jobs', 'function_jobs', '_workers']) #resources handler.define_set('resources', 'resource_id') handler.set_new('resources', 'new_resource') handler.set_delete('resources', 'delete_resource') handler.add_getter('resources', 'get_resource_state') handler.mapping_from_name_to_set_definition['resources'].particles_factory = Resources #pilots handler.define_set('pilots', 'pilot_id') handler.set_new('pilots', 'new_pilot') handler.set_delete('pilots', 'delete_pilot') handler.add_getter('pilots', 'get_pilot_state') handler.add_getter('pilots', 'get_pilot_status', names = ('status',)) handler.mapping_from_name_to_set_definition['pilots'].particles_factory = Pilots #script jobs #FOR NOW, SCRIPT AND FUNCTION JOBS ARE DISABLED #handler.define_set('script_jobs', 'job_id') #handler.set_new('script_jobs', 'submit_script_job') #handler.set_delete('script_jobs', 'delete_script_job') #handler.add_getter('script_jobs', 'get_script_job_state') #handler.add_getter('script_jobs', 'get_script_job_status', names = ('status',)) #handler.mapping_from_name_to_set_definition['script_jobs'].particles_factory = ScriptJobs #function jobs #FOR NOW, SCRIPT AND FUNCTION JOBS ARE DISABLED #handler.define_set('function_jobs', 'job_id') #handler.set_new('function_jobs', 'submit_function_job') #handler.set_delete('function_jobs', 'delete_function_job') #handler.add_getter('function_jobs', 'get_function_job_state') #handler.add_getter('function_jobs', 'get_function_job_status') #handler.mapping_from_name_to_set_definition['function_jobs'].particles_factory = FunctionJobs #workers handler.define_set('_workers', 'worker_id') handler.set_new('_workers', 'new_worker') handler.set_delete('_workers', 'delete_worker') handler.add_getter('_workers', 'get_worker_state') handler.add_getter('_workers', 'get_worker_status', names = ('status',)) @property def workers(self): self.update_workers_particle_set() return self._workers def update_workers_particle_set(self): """ Update the "workers" particle set after new instances of codes have been created or previously created instances have been stopped. """ old_ids = set(self._workers.get_all_indices_in_store()) number_of_workers = self.get_number_of_workers() if not number_of_workers == 0: new_ids = set(self.get_worker_ids(list(range(number_of_workers)))) else: new_ids=set() ids_to_remove = old_ids - new_ids ids_to_add = new_ids - old_ids if not len(ids_to_remove) == 0: self._workers._remove_indices_in_attribute_storage(list(ids_to_remove)) if not len(ids_to_add) == 0: self._workers._add_indices_in_attribute_storage(list(ids_to_add)) Distributed = DistributedAmuse Distributedamuse = DistributedAmuse
32,213
41.05483
204
py
amuse
amuse-main/src/amuse/community/interface/mhd.py
""" Magnetohydrodynamics Interface Definition """ from amuse.community.interface.hydro import HydrodynamicsInterface from amuse.support.interface import InCodeComponentImplementation from amuse.units import nbody_system from amuse.units import generic_unit_converter from amuse.community.interface import common from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class MagnetohydrodynamicsInterface(HydrodynamicsInterface): @legacy_function def get_grid_magnetic_field(): """ Retreives the densitity at the given grid-point """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['B1i', 'B2i', 'B3i']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_magnetic_field(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['B1i', 'B2i', 'B3i']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function
1,756
36.382979
73
py
amuse
amuse-main/src/amuse/community/interface/example.py
""" Example function for documentation purposess """ from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class ExampleInterface(object): @legacy_function def example_function(): """ Example template for the other functions defined in this specification. All functions should follow this example.. """ function = LegacyFunctionSpecification() function.addParameter( 'input', dtype='int32', direction=function.IN, description=( "Typical input parameter, the argument is passed by value " "to the function." ) ) function.addParameter( 'output', dtype='float64', direction=function.OUT, description=( "Typical output parameter, the argument is passed " "by reference.\n" "The argument should point to a valid memory location." ) ) function.addParameter( 'inout', dtype='float64', direction=function.INOUT, description=( "Some arguments can be both input as well as output. " "The function will update the value of the passed argument." ) ) function.result_type = 'int32' function.result_doc = "Function will return an error code." return function @legacy_function def get_example_parameter(): """ Retrieve the current value of the parameter. Note, values can be any of the supported types. """ function = LegacyFunctionSpecification() function.addParameter( 'value', dtype='float64', direction=function.OUT, description="The current value of the parameter." ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was retrieved -1 - ERROR The code does not have support for this parameter, use this when a code does not support a parameter pre-defined in a physical domain """ return function @legacy_function def set_example_parameter(): """ Update the value of the parameter. The type of the new value argument must be the same as the :meth:`get_example_parameter` function. """ function = LegacyFunctionSpecification() function.addParameter( 'value', dtype='float64', direction=function.IN, description="The new value of the parameter." ) function.result_type = 'int32' function.result_doc = """ 0 - OK New value of the parameter was set -1 - ERROR The code does not have support for this parameter """ return function @legacy_function def initialize_code(): """ Let the code perform initialization actions after all parameters have been set. Should be called once per running code instance. """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK Code is initialized -1 - ERROR Error happened during initialization, this error needs to be further specified by every code implemention """ return function
3,439
33.4
77
py
amuse
amuse-main/src/amuse/community/interface/gd.py
""" Stellar Dynamics Interface Defintion """ from amuse.support.interface import InCodeComponentImplementation from amuse.units import nbody_system from amuse.units import generic_unit_converter from amuse.community.interface import common from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class GravitationalDynamicsInterface(common.CommonCodeInterface): @legacy_function def new_particle(): """ Define a new particle in the stellar dynamics code. The particle is initialized with the provided mass, radius, position and velocity. This function returns an index 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, description=( "An index assigned to the newly created particle. " "This index is supposed to be a local index for the code " "(and not valid in other instances of the code or in other " "codes)" ) ) 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( 'vx', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'vy', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'vz', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'radius', dtype='float64', direction=function.IN, description="The radius of the particle", default=0) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was created and added to the model -1 - ERROR particle could not be created""" return function @legacy_function def delete_particle(): """ Remove the definition of particle from the code. After calling this function the particle is no longer part of the model evolution. It is up to the code if the index will be reused. This function is optional. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description=( "Index of the particle to be removed. This index must have " "been returned by an earlier call to :meth:`new_particle`" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK particle was removed from the model -1 - ERROR particle could not be removed -2 - ERROR not yet implemented """ return function @legacy_function def get_state(): """ Retrieve the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, radius, position and velocity) is returned. """ 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 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( 'x', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.addParameter( 'y', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.addParameter( 'z', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.addParameter( 'vx', dtype='float64', direction=function.OUT, description="The current velocity vector of the particle") function.addParameter( 'vy', dtype='float64', direction=function.OUT, description="The current velocity vector of the particle") function.addParameter( 'vz', dtype='float64', direction=function.OUT, description="The current velocity vector of the particle") function.addParameter( 'radius', dtype='float64', direction=function.OUT, description="The current radius of the particle") function.result_type = 'int32' function.result_doc = """ 0 - OK particle was removed from the model -1 - ERROR particle could not be found """ return function @legacy_function def set_state(): """ Update the current state of a particle. The *minimal* information of a stellar dynamics particle (mass, radius, position and velocity) is updated. """ function = LegacyFunctionSpecification() function.can_handle_array = True 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( 'x', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.addParameter( 'y', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.addParameter( 'z', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.addParameter( 'vx', dtype='float64', direction=function.IN, description="The new velocity vector of the particle") function.addParameter( 'vy', dtype='float64', direction=function.IN, description="The new velocity vector of the particle") function.addParameter( 'vz', dtype='float64', direction=function.IN, description="The new velocity vector of the particle") function.addParameter( 'radius', dtype='float64', direction=function.IN, description="The new radius of the particle", default=0) 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 -2 - ERROR code does not support updating of a particle -3 - ERROR not yet implemented """ 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.result_type = 'int32' function.can_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.result_type = 'int32' function.can_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 @legacy_function def get_radius(): """ Retrieve the radius of a particle. Radius 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 radius of. This index must " "have been returned by an earlier call to :meth:`new_particle`" ) ) function.addParameter( 'radius', dtype='float64', direction=function.OUT, description="The current radius of the particle" ) function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK particle was found in the model and the information was retreived -1 - ERROR particle could not be found """ return function @legacy_function def set_radius(): """ Set the radius of a particle. Radius 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 to get the radius of. This index must " "have been returned by an earlier call to :meth:`new_particle`" ) ) function.addParameter( 'radius', dtype='float64', direction=function.IN, description="The new radius of the particle" ) function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK particle was found in the model and the information was retreived -1 - ERROR particle could not be found """ return function @legacy_function def get_position(): """ Retrieve the position vector of a particle. Position is a vector property, this function has 3 OUT arguments. """ 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( 'x', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.addParameter( 'y', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.addParameter( 'z', dtype='float64', direction=function.OUT, description="The current position vector of the particle") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_position(): """ Update the position 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( 'x', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.addParameter( 'y', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.addParameter( 'z', dtype='float64', direction=function.IN, description="The new position vector of the particle") function.result_type = 'int32' function.can_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 @legacy_function def get_velocity(): """ Retrieve the velocity vector of a particle. Position is a vector property, this function has 3 OUT arguments. """ function = LegacyFunctionSpecification() function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description=( "Index of the particle to get the velocity 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 component of the position vector of the " "particle" ) ) function.addParameter( 'vy', dtype='float64', direction=function.OUT, description=( "The current y component of the position vector of the " "particle" ) ) function.addParameter( 'vz', 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 function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_velocity(): """ Set the velocity vector of a particle. """ 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( 'vx', dtype='float64', direction=function.IN, description=( "The current x component of the velocity vector of the " "particle" ) ) function.addParameter( 'vy', dtype='float64', direction=function.IN, description=( "The current y component of the velocity vector of the " "particle" ) ) function.addParameter( 'vz', dtype='float64', direction=function.IN, description=( "The current z component of the velocity vector of the " "particle" ) ) function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def get_acceleration(): """ Retrieve the acceleration vector of a particle. Second time derivative of the position. """ 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( 'ax', dtype='float64', direction=function.OUT, description="The current acceleration vector of the particle") function.addParameter( 'ay', dtype='float64', direction=function.OUT, description="The current acceleration vector of the particle") function.addParameter( 'az', dtype='float64', direction=function.OUT, description="The current acceleration vector of the particle") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def set_acceleration(): """ Update the acceleration of a particle. *Defined for symetry with the get_acceleration function.* *Should be removed if physaccily unsound* *Maybe moved to snapshot support functionality* """ 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( 'ax', dtype='float64', direction=function.IN, description="The new acceleration vector of the particle") function.addParameter( 'ay', dtype='float64', direction=function.IN, description="The new acceleration vector of the particle") function.addParameter( 'az', dtype='float64', direction=function.IN, description="The new acceleration vector of the particle") function.result_type = 'int32' function.can_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 -3 - ERROR not yet implemented """ return function @legacy_function def get_potential(): """ Retrieve the potential at a particle position, for retrieving the potential anywhere in the field use get_potential_at_point. """ 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( 'potential', dtype='float64', direction=function.OUT, description="The current scalar potential...") function.result_type = 'int32' function.can_handle_array = True function.result_doc = """ 0 - OK current value was retrieved -1 - ERROR particle could not be found -2 - ERROR not yet implemented """ return function @legacy_function def evolve_model(): """ Evolve the model until the given time, or until a stopping condition is set. """ function = LegacyFunctionSpecification() function.addParameter( 'time', dtype='float64', direction=function.IN, description=( "Model time to evolve the code to. The model will be " "evolved until this time is reached exactly or just after." ) ) function.result_type = 'int32' 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 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 recommit_particles(): """ Let the code perform initialization actions after the number of particles have been updated or particle attributes have been updated from the script. """ 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 get_eps2(): """ Retrieve the current value of the squared smoothing parameter. """ function = LegacyFunctionSpecification() function.addParameter( 'epsilon_squared', dtype='float64', direction=function.OUT, description="The current value of the smooting parameter, squared." ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the smoothing parameter was set -1 - ERROR The code does not have support for a smoothing parameter """ return function @legacy_function def set_eps2(): """ Update the value of the squared smoothing parameter. """ function = LegacyFunctionSpecification() function.addParameter( 'epsilon_squared', dtype='float64', direction=function.IN, description="The new value of the smooting parameter, squared." ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the smoothing parameter was set -1 - ERROR The code does not have support for a smoothing parameter """ return function @legacy_function def get_kinetic_energy(): """ Retrieve the current kinetic energy of the model """ function = LegacyFunctionSpecification() function.addParameter( 'kinetic_energy', dtype='float64', direction=function.OUT, description="The kinetic energy of the model" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the kinetic energy was set -1 - ERROR Kinetic energy could not be provided """ return function @legacy_function def get_potential_energy(): """ Retrieve the current potential energy of the model """ function = LegacyFunctionSpecification() function.addParameter( 'potential_energy', dtype='float64', direction=function.OUT, description="The potential energy of the model" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the potential energy was set -1 - ERROR Kinetic potential could not be provided """ return function @legacy_function def get_time(): """ Retrieve the model time. This time should be close to the end time specified in the evolve code. Or, when a collision was detected, it will be the model time of the collision. """ function = LegacyFunctionSpecification() function.addParameter( 'time', dtype='float64', direction=function.OUT, description="The current model time") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time was retrieved -1 - ERROR The code does not have support for querying the time """ 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=nbody_system.time) 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=nbody_system.time) 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_time_step(): """ Retrieve the model timestep. """ function = LegacyFunctionSpecification() function.addParameter( 'time_step', dtype='float64', direction=function.OUT, description="The current model timestep" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time step was retrieved -1 - ERROR The code does not have support for querying the time """ return function @legacy_function def get_total_mass(): """ Retrieve the sum of the masses of all particles. """ function = LegacyFunctionSpecification() function.addParameter( 'mass', dtype='float64', direction=function.OUT, description="The total mass of the model" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the kinetic mass was retrieved -1 - ERROR Total mass could not be provided -2 - ERROR not yet implemented """ return function @legacy_function def get_center_of_mass_position(): """ Retrieve the center of mass (a point in space) of all particles. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'x', dtype='float64', direction=function.OUT, description="The center of mass of the model") function.addParameter( 'y', dtype='float64', direction=function.OUT, description="The center of mass of the model") function.addParameter( 'z', dtype='float64', direction=function.OUT, description="The center of mass of the model") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the center was retrieved -1 - ERROR The mass could not be provided -2 - ERROR not yet implemented """ return function @legacy_function def get_center_of_mass_velocity(): """ Retrieve the velocity of the center of mass of all particles. This velocity is mass weighted mean of the velocity of all particles. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'vx', dtype='float64', direction=function.OUT, description="The mean velocity of the model") function.addParameter( 'vy', dtype='float64', direction=function.OUT, description="The mean velocity of the model") function.addParameter( 'vz', dtype='float64', direction=function.OUT, description="The mean velocity of the model") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the center of mass velocity was retrieved -1 - ERROR The value could not be provided """ return function @legacy_function def get_total_radius(): """ Return the radius of the sphere, centered on the center of mass that contains all the particles. *get_size?* """ function = LegacyFunctionSpecification() function.addParameter( 'radius', dtype='float64', direction=function.OUT, description=( "The maximum distance from a star to the center of mass of " "the model" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the radius was retrieved -1 - ERROR The value could not be provided """ return function @legacy_function def get_number_of_particles(): """ Retrieve the total number of particles define d in the code """ function = LegacyFunctionSpecification() function.addParameter( 'number_of_particles', dtype='int32', direction=function.OUT, description="Count of the particles in the code") function.result_type = 'int32' function.result_doc = """ 0 - OK Count could be determined -1 - ERROR Unable to determine the count """ return function @legacy_function def get_index_of_first_particle(): """ Retrieve the index of first particle. When this index is used as the starting index for the ``get_index_of_next_particle`` method, all particles can be iterated over:: error, first_index = instance.get_index_of_first_particle() current_index = first_index while error == 0: status, mass = instance.get_mass(current_index) print mass error, current_index = instance.get_index_of_next_particle(current_index) """ function = LegacyFunctionSpecification() function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.OUT, description="Index of the first particle") function.result_type = 'int32' function.result_doc = """ 0 - OK Index was set 1 - ERROR Code has no particles, or cannot set the index """ return function @legacy_function def get_index_of_next_particle(): """ Retrieve the index of the particle following the provided index. The iteration direction is determined by the code. """ function = LegacyFunctionSpecification() function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description="Index of the particle") function.addParameter( 'index_of_the_next_particle', dtype='int32', direction=function.OUT, description=( "Index of the particle following the particle with the " "provided index" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK Index was set 1 - STATE Last index was reached -1 - ERROR Particle could not be found """ return function class GravityFieldInterface(object): """ Codes implementing the gravity field interface provide functions to calculate the force and potential energy fields at any point. """ @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=nbody_system.length ) for x in ['ax', 'ay', 'az']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=nbody_system.acceleration ) 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=nbody_system.length ) for x in ['phi']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=nbody_system.potential ) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function class SinglePointGravityFieldInterface(object): """ Codes implementing the gravity field interface provide functions to calculate the force and potential energy fields at any point. """ @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=nbody_system.length ) for x in ['ax', 'ay', 'az']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=nbody_system.acceleration ) function.result_type = 'int32' function.can_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=nbody_system.length ) for x in ['phi']: function.addParameter( x, dtype='float64', direction=function.OUT, unit=nbody_system.potential ) function.result_type = 'int32' function.can_handle_array = True return function class GravitationalDynamicsDocumentation(object): def __get__(self, instance, owner): string = "" string = instance.parameters.__doc__ return string class GravitationalDynamics(common.CommonCode): NBODY = object() __doc__ = GravitationalDynamicsDocumentation() def __init__(self, legacy_interface, unit_converter=None, **options): self.unit_converter = unit_converter common.CommonCode.__init__(self, legacy_interface, **options) def define_properties(self, handler): handler.add_property("get_kinetic_energy") handler.add_property("get_potential_energy") handler.add_property("get_total_radius") handler.add_property("get_center_of_mass_position") handler.add_property("get_center_of_mass_velocity") handler.add_property("get_total_mass") handler.add_property('get_time', public_name="model_time") def define_state(self, handler): common.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('EVOLVED', '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') 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_mass') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_velocity') handler.add_method('RUN', 'get_potential') handler.add_method('RUN', 'get_potential_energy') handler.add_method('RUN', 'get_kinetic_energy') handler.add_transition('RUN', 'UPDATE', 'set_mass', False) handler.add_transition('RUN', 'UPDATE', 'set_position', False) handler.add_transition('RUN', 'UPDATE', 'set_velocity', False) handler.add_transition('RUN', 'UPDATE', 'set_radius', False) handler.add_method('UPDATE', 'set_mass') handler.add_method('UPDATE', 'set_position') handler.add_method('UPDATE', 'set_velocity') handler.add_method('UPDATE', 'set_radius') def define_parameters(self, handler): handler.add_method_parameter( "get_time_step", None, "timestep", "constant timestep for iteration", default_value=0.7 | nbody_system.time ) 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 ) def define_methods(self, handler): common.CommonCode.define_methods(self, handler) handler.add_method( 'evolve_model', ( nbody_system.time, ), ( handler.ERROR_CODE, ) ) handler.add_method( "new_particle", ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "delete_particle", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state", ( handler.NO_UNIT, ), ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_state", ( handler.NO_UNIT, nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, 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 ) ) handler.add_method( "set_radius", ( handler.NO_UNIT, nbody_system.length, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_radius", ( handler.NO_UNIT, ), ( nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_position", ( handler.NO_UNIT, nbody_system.length, nbody_system.length, nbody_system.length, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_position", ( handler.NO_UNIT, ), ( nbody_system.length, nbody_system.length, nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_velocity", ( handler.NO_UNIT, nbody_system.speed, nbody_system.speed, nbody_system.speed, ), ( handler.ERROR_CODE ) ) handler.add_method( "get_velocity", ( handler.NO_UNIT, ), ( nbody_system.speed, nbody_system.speed, nbody_system.speed, handler.ERROR_CODE ) ) handler.add_method( "get_acceleration", ( handler.NO_UNIT, ), ( nbody_system.acceleration, nbody_system.acceleration, nbody_system.acceleration, handler.ERROR_CODE ) ) handler.add_method( "get_potential", ( handler.NO_UNIT, ), ( nbody_system.length**2 * nbody_system.time**-2, handler.ERROR_CODE, ) ) handler.add_method( 'get_indices_of_colliding_particles', (), ( 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( 'synchronize_model', (), (handler.ERROR_CODE) ) handler.add_method( "get_time_step", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "get_kinetic_energy", (), ( nbody_system.mass * nbody_system.length**2 * nbody_system.time**-2, handler.ERROR_CODE, ) ) handler.add_method( "get_potential_energy", (), ( nbody_system.mass * nbody_system.length**2 * nbody_system.time**-2, handler.ERROR_CODE, ) ) handler.add_method( "get_total_radius", (), (nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "get_center_of_mass_position", (), ( nbody_system.length, nbody_system.length, nbody_system.length, handler.ERROR_CODE, ) ) handler.add_method( "get_center_of_mass_velocity", (), ( nbody_system.length / nbody_system.time, nbody_system.length / nbody_system.time, nbody_system.length / nbody_system.time, handler.ERROR_CODE, ) ) handler.add_method( "get_total_mass", (), (nbody_system.mass, handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (nbody_system.time, 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_mass') handler.add_getter('particles', 'get_mass', names=('mass',)) handler.add_setter('particles', 'set_position') handler.add_getter('particles', 'get_position') handler.add_setter('particles', 'set_velocity') handler.add_getter('particles', 'get_velocity') handler.add_setter('particles', 'set_radius') handler.add_getter('particles', 'get_radius') handler.add_query( 'particles', 'get_indices_of_colliding_particles', public_name='select_colliding_particles' ) def get_colliding_particles(self): subset = self.colliding_particles_method._run(self, self.particles) return subset def define_converter(self, handler): if self.unit_converter is not 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 get_total_energy(self): return self.get_potential_energy() + self.get_kinetic_energy() class GravityFieldCode(object): def define_state(self, handler): handler.add_method('RUN', 'get_gravity_at_point') handler.add_method('RUN', 'get_potential_at_point')
52,603
33.471822
89
py
amuse
amuse-main/src/amuse/community/interface/stopping_conditions.py
from amuse.units import units, generic_unit_system from amuse.units import nbody_system as nbody from amuse.support.exceptions import AmuseException from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class StoppingConditionInterface: @legacy_function def has_stopping_condition(): """ Return 1 if the stopping condition with the given index is supported by the code, 0 otherwise. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'type', dtype='int32', direction=function.IN, description="The type index of the stopping condition") function.addParameter( 'result', dtype='int32', direction=function.OUT, description="1 if the stopping condition is supported") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def enable_stopping_condition(): """ Will enable the stopping if it is supported """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'type', dtype='int32', direction=function.IN, description="The type index of the stopping condition") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def disable_stopping_condition(): """ Will disable the stopping if it is supported """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'type', dtype='int32', direction=function.IN, description="The index of the stopping condition") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def is_stopping_condition_enabled(): """ Return 1 if the stopping condition with the given index is enabled,0 otherwise. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'type', dtype='int32', direction=function.IN, description="The index of the stopping condition") function.addParameter( 'result', dtype='int32', direction=function.OUT, description="1 if the stopping condition is enabled") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def is_stopping_condition_set(): """ Return 1 if the stopping condition with the given index is enabled,0 otherwise. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'type', dtype='int32', direction=function.IN, description="The index of the stopping condition") function.addParameter( 'result', dtype='int32', direction=function.OUT, description="1 if the stopping condition is enabled") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_number_of_stopping_conditions_set(): """ Return the number of stopping conditions set, one condition can be set multiple times. Stopping conditions are set when the code determines that the conditions are met. The objects or information about the condition can be retrieved with the get_stopping_condition_info method. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'result', dtype='int32', direction=function.OUT, description="> 1 if any stopping condition is set") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_stopping_condition_info(): """ Generic function for getting the information connected to a stopping condition. Index can be between 0 and the result of the :method:`get_number_of_stopping_conditions_set` method. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index', dtype='int32', direction=function.IN, description=( "Index in the array[0,number_of_stopping_conditions_set>" ) ) function.addParameter( 'type', dtype='int32', direction=function.OUT, description=( "Kind of the condition, can be used to retrieve specific " "information" ) ) function.addParameter( 'number_of_particles', dtype='int32', direction=function.OUT, description="Number of particles that met this condition") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_stopping_condition_particle_index(): """ For collision detection """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index', dtype='int32', direction=function.IN, description=( "Index in the array[0,number_of_stopping_conditions_set>" ) ) function.addParameter( 'index_of_the_column', dtype='int32', direction=function.IN, description=( "Column index involved in the condition (for pair collisions " "0 and 1 are possible)" ) ) function.addParameter( 'index_of_particle', dtype='int32', direction=function.OUT, description=( "Set to the identifier of particle[index_of_the_column][index]" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_stopping_condition_timeout_parameter(): """ Set max computer time available (in seconds). """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='float64', direction=function.IN, description="Available wallclock time in seconds") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function @legacy_function def get_stopping_condition_timeout_parameter(): """ Retrieve max computer time available (in seconds). """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='float64', direction=function.OUT, description="Current value of available wallclock time in seconds") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_stopping_condition_number_of_steps_parameter(): """ Set max inner loop evaluations. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='int32', direction=function.IN, description="Available inner loop evaluations") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function @legacy_function def get_stopping_condition_number_of_steps_parameter(): """ Retrieve max inner loop evaluations. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='int32', direction=function.OUT, description="Current number of available inner loop evaluations") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_stopping_condition_out_of_box_parameter(): """ Set size of box. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='float64', direction=function.IN, description="Size of box") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function @legacy_function def get_stopping_condition_out_of_box_parameter(): """ Get size of box """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='float64', direction=function.OUT, description="Size of box") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function @legacy_function def set_stopping_condition_minimum_density_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stopping_condition_minimum_density_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_stopping_condition_maximum_density_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stopping_condition_maximum_density_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_stopping_condition_minimum_internal_energy_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stopping_condition_minimum_internal_energy_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_stopping_condition_maximum_internal_energy_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stopping_condition_maximum_internal_energy_parameter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_stopping_condition_out_of_box_use_center_of_mass_parameter(): """ If True use the center of mass to determine the location of the box, if False use (0,0,0) """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='bool', direction=function.OUT, description="True if detection should use center of mass") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function @legacy_function def set_stopping_condition_out_of_box_use_center_of_mass_parameter(): """ If True use the center of mass to determine the location of the box, if False use (0,0,0) """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter( 'value', dtype='bool', direction=function.IN, description="True if detection should use center of mass") function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - Value out of range """ return function class StoppingCondition: def __init__(self, conditions, type, description): self.conditions = conditions self.type = type self.description = description self.__doc__ = description def enable(self): if self.is_supported(): self.conditions.code.enable_stopping_condition(self.type) else: name = [ name for name, value in self.conditions.all_conditions() if value is self ][0] raise AmuseException( f"Can't enable stopping condition '{name}', since " f"'{type(self.conditions.code).__name__}' does not " "support this condition." ) def disable(self): if self.is_supported(): self.conditions.code.disable_stopping_condition(self.type) else: name = [ name for name, value in self.conditions.all_conditions() if value is self ][0] raise AmuseException( f"Can't disable stopping condition '{name}', since " f"'{type(self.conditions.code).__name__}' does not " "support this condition." ) def is_enabled(self): return self.conditions.code.is_stopping_condition_enabled( self.type ) == 1 def is_supported(self): return self.conditions.code.has_stopping_condition(self.type) == 1 def is_set(self): return self.conditions.code.is_stopping_condition_set(self.type) == 1 def get_set_condition_indices(self, index_in_condition): indices = list( range(self.conditions.code.get_number_of_stopping_conditions_set()) ) if len(indices) == 0: return [] types, number_of_particles = \ self.conditions.code.get_stopping_condition_info( indices ) result = [] for index, type, number_of_particles_in_condition in zip( indices, types, number_of_particles ): if ( type == self.type and index_in_condition < number_of_particles_in_condition ): result.append(index) return result def particles( self, index_in_the_condition=0, particles_set_name="particles" ): selected = self.get_set_condition_indices(index_in_the_condition) particles = getattr(self.conditions.code, particles_set_name) if len(selected) == 0: return particles[0:0] else: return particles.get_stopping_condition_particle_index( selected, [index_in_the_condition]*len(selected) ) class StoppingConditions: def __init__(self, code): self.code = code self.collision_detection = StoppingCondition( self, 0, ( "If enabled, the code will stop at the end of the inner loop " "when two stars connect" ) ) self.pair_detection = StoppingCondition( self, 1, ( "If enabled, the code will stop at the end of the inner loop " "when two stars are bound" ) ) self.escaper_detection = StoppingCondition( self, 2, ( "If enabled, the code will stop at the end of the inner loop " "when a star escapes" ) ) self.timeout_detection = StoppingCondition( self, 3, ( "If enabled, the code will stop at the end of the inner loop " "when the computer time is above a set timeout" ) ) self.number_of_steps_detection = StoppingCondition( self, 4, ( "If enabled, the code will stop at the end of the inner loop " "when the number of evaluations reached the set max number" ) ) self.out_of_box_detection = StoppingCondition( self, 5, ( "If enabled, the code will stop if a particle escapes the box " "of size out_of_box_size" ) ) self.density_limit_detection = StoppingCondition( self, 6, ( "If enabled, the code will stop if a gas particle has a " "density out of the range " "[stopping_condition_minimum_density, " "stopping_condition_maximum_density]" ) ) self.internal_energy_limit_detection = StoppingCondition( self, 7, ( "If enabled, the code will stop if a gas particle has an " "internal energy out of the range " "[stopping_condition_minimum_internal_energy, " "stopping_condition_maximum_internal_energy]" ) ) self.interaction_over_detection = StoppingCondition( self, 8, ( "If enabled, the code will stop if the interaction between " "particles is over" ) ) self.supernova_detection = StoppingCondition( self, 9, ( "If enabled, the code will stop at the end of the inner loop " "when two a star goes supernova" ) ) def all_conditions(self): for name in dir(self): if name.startswith("_"): continue else: value = getattr(self, name) if isinstance(value, StoppingCondition): yield name, value def __str__(self): parts = [] parts.append( f"Stopping conditions of a '{type(self.code).__name__}' object\n" ) supported = self.supported_conditions() enabled = [ name for name, condition in self.all_conditions() if condition.is_enabled() ] hit = [ name for name, condition in self.all_conditions() if condition.is_set() ] parts.append('* supported conditions: ') parts.append(', '.join(supported)) parts.append('\n') parts.append('* enabled conditions: ') if enabled: parts.append(', '.join(enabled)) else: parts.append('none') parts.append('\n') parts.append('* set conditions: ') if hit: parts.append(', '.join(hit)) else: parts.append('none') parts.append('\n') return ''.join(parts) def supported_conditions(self): return [ name for name, condition in self.all_conditions() if condition.is_supported() ] def define_parameters(self, handler): handler.add_method_parameter( "get_stopping_condition_timeout_parameter", "set_stopping_condition_timeout_parameter", "stopping_conditions_timeout", "max wallclock time available for the evolve step", default_value=4.0 | units.s ) handler.add_method_parameter( "get_stopping_condition_number_of_steps_parameter", "set_stopping_condition_number_of_steps_parameter", "stopping_conditions_number_of_steps", "max inner loop evals", default_value=1.0 ) handler.add_method_parameter( "get_stopping_condition_out_of_box_parameter", "set_stopping_condition_out_of_box_parameter", "stopping_conditions_out_of_box_size", "size of cube", default_value=0.0 | nbody.length ) handler.add_method_parameter( "get_stopping_condition_minimum_density_parameter", "set_stopping_condition_minimum_density_parameter", "stopping_condition_minimum_density", "minimum density of a gas particle", default_value=-1.0 | generic_unit_system.density ) handler.add_method_parameter( "get_stopping_condition_maximum_density_parameter", "set_stopping_condition_maximum_density_parameter", "stopping_condition_maximum_density", "maximum density of a gas particle", default_value=-1.0 | generic_unit_system.density ) handler.add_method_parameter( "get_stopping_condition_minimum_internal_energy_parameter", "set_stopping_condition_minimum_internal_energy_parameter", "stopping_condition_minimum_internal_energy", "minimum internal energy of a gas particle", default_value=-1.0 | generic_unit_system.specific_energy ) handler.add_method_parameter( "get_stopping_condition_maximum_internal_energy_parameter", "set_stopping_condition_maximum_internal_energy_parameter", "stopping_condition_maximum_internal_energy", "maximum internal energy of a gas particle", default_value=-1.0 | generic_unit_system.specific_energy ) handler.add_method_parameter( "get_stopping_condition_out_of_box_use_center_of_mass_parameter", "set_stopping_condition_out_of_box_use_center_of_mass_parameter", "stopping_conditions_out_of_box_use_center_of_mass", ( "if True use the center of mass to determine the location of " "the box, if False use (0,0,0), is not used by all codes" ), default_value=False ) def define_methods(self, handler): handler.add_method( 'get_stopping_condition_particle_index', ( handler.NO_UNIT, handler.NO_UNIT, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( 'has_stopping_condition', ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'is_stopping_condition_enabled', ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'is_stopping_condition_set', ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'get_stopping_condition_info', ( handler.NO_UNIT, ), ( handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'get_number_of_stopping_conditions_set', ( ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'enable_stopping_condition', (handler.NO_UNIT,), ( handler.ERROR_CODE ) ) handler.add_method( 'disable_stopping_condition', (handler.NO_UNIT,), ( handler.ERROR_CODE ) ) handler.add_method( "get_stopping_condition_timeout_parameter", (), (units.s, handler.ERROR_CODE,) ) handler.add_method( "set_stopping_condition_timeout_parameter", (units.s, ), (handler.ERROR_CODE,) ) handler.add_method( "get_stopping_condition_number_of_steps_parameter", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_stopping_condition_number_of_steps_parameter", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_stopping_condition_out_of_box_parameter", (), (nbody.length, handler.ERROR_CODE,) ) handler.add_method( "set_stopping_condition_out_of_box_parameter", (nbody.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_stopping_condition_minimum_density_parameter", (), (generic_unit_system.density, handler.ERROR_CODE,)) handler.add_method( "set_stopping_condition_minimum_density_parameter", (generic_unit_system.density, ), (handler.ERROR_CODE,)) handler.add_method( "get_stopping_condition_maximum_density_parameter", (), (generic_unit_system.density, handler.ERROR_CODE,)) handler.add_method( "set_stopping_condition_maximum_density_parameter", (generic_unit_system.density, ), (handler.ERROR_CODE,)) handler.add_method( "get_stopping_condition_minimum_internal_energy_parameter", (), (generic_unit_system.specific_energy, handler.ERROR_CODE,)) handler.add_method( "set_stopping_condition_minimum_internal_energy_parameter", (generic_unit_system.specific_energy, ), (handler.ERROR_CODE,)) handler.add_method( "get_stopping_condition_maximum_internal_energy_parameter", (), (generic_unit_system.specific_energy, handler.ERROR_CODE,)) handler.add_method( "set_stopping_condition_maximum_internal_energy_parameter", (generic_unit_system.specific_energy, ), (handler.ERROR_CODE,)) def define_particle_set(self, handler, name_of_the_set='particles'): handler.add_query( name_of_the_set, 'get_stopping_condition_particle_index' ) def define_state(self, handler): for method_name in [ 'get_stopping_condition_particle_index', 'has_stopping_condition', 'is_stopping_condition_enabled', 'is_stopping_condition_set', 'get_stopping_condition_info', 'get_number_of_stopping_conditions_set', 'enable_stopping_condition', 'disable_stopping_condition' ]: handler.add_method('!UNINITIALIZED!END', method_name)
28,066
32.45292
79
py
amuse
amuse-main/src/amuse/community/interface/common.py
""" Common code functions """ from amuse.support.interface import InCodeComponentImplementation from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class CommonCodeInterface(object): @legacy_function def initialize_code(): """ Run the initialization for the code, called before any other call on the code (so before any parameters are set or particles are defined in the code). """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK Code is initialized -1 - ERROR Error happened during initialization, this error needs to be further specified by every code implemention -2 - ERROR not yet implemented """ return function @legacy_function def cleanup_code(): """ Run the cleanup for the code, called just before stopping the code. No functions should be called after this code. """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK Code is initialized -1 - ERROR Error happened during cleanup, this error needs to be further specified by every code implemention -2 - ERROR not yet implemented """ return function @legacy_function def commit_parameters(): """ Perform initialization in the code dependent on the values of the parameters. Called after the parameters have been set or updated. """ function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = """ 0 - OK Code is initialized -1 - ERROR Error happened during initialization, this error needs to be further specified by every code implemention -2 - ERROR not yet implemented """ return function @legacy_function def recommit_parameters(): """ Perform initialization actions after parameters have been updated (after commit_parameters and particles have been loaded). """ 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 def invoke_state_change(self): pass class CommonCode(InCodeComponentImplementation): def define_state(self, handler): handler.set_initial_state('UNINITIALIZED') handler.add_transition( 'UNINITIALIZED', 'INITIALIZED', 'initialize_code') handler.add_method('INITIALIZED', 'before_get_parameter') handler.add_method('INITIALIZED', 'before_set_parameter') handler.add_method('END', 'before_get_parameter') handler.add_transition('!UNINITIALIZED!STOPPED', 'END', 'cleanup_code') handler.add_transition('END', 'STOPPED', 'stop', False) handler.add_method('STOPPED', 'stop') def define_methods(self, handler): handler.add_method( 'initialize_code', (), (handler.ERROR_CODE) ) handler.add_method( 'cleanup_code', (), (handler.ERROR_CODE) ) handler.add_method( 'commit_parameters', (), (handler.ERROR_CODE) ) handler.add_method( 'recommit_parameters', (), (handler.ERROR_CODE) )
3,894
28.732824
79
py
amuse
amuse-main/src/amuse/community/interface/__init__.py
1
0
0
py
amuse
amuse-main/src/amuse/community/interface/hydro.py
""" Hydrodynamics Interface Defintion """ from amuse.support.interface import InCodeComponentImplementation from amuse.units import nbody_system from amuse.units import generic_unit_converter from amuse.community.interface import common from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class HydrodynamicsInterface(common.CommonCodeInterface): def get_index_range_inclusive(self): """ Returns the min and max values of indices in each direction. The range is inclusive, the min index and max index both exist and can be queried. The total number of cells in one direction is max - min + 1. The returntype is a list of 3 tuples, each tuples contains the minimum and maximum value in the index range. For C/C++ codes the returned values will usually be: ((0, nmeshx-1), (0, nmeshy-1), (0, nmeshz-1)) For Fortran codes the returned values will usually be: ((1, nmeshx), (1, nmeshy), (1, nmeshz)) """ pass @legacy_function def get_position_of_index(): """ Retrieves the x, y and z position of the center of the cell with coordinates i, j, k in the grid specified by the index_of_grid """ function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['x', 'y', 'z']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_index_of_position(): """ Retrieves the i,j and k index of the grid cell containing the given x, y and z position. The cell is looked up in the grid specified by index_of_grid. """ function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['x', 'y', 'z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['i', 'j', 'k']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function def setup_mesh(self, nmeshx, nmeshy, nmeshz, xlength, ylength, zlength): """ Sets the number of mesh cells in each direction, and the length of the grid in each direction. :argument nmeshx: number of mesh cells in the x direction :argument nmeshy: number of mesh cells in the y direction :argument nmeshz: number of mesh cells in the z direction :argument xlength: total length of the grid in the x direction :argument ylength: total length of the grid in the y direction :argument zlength: total length of the grid in the z direction """ def set_boundary( self, xbound1, xbound2, ybound1, ybound2, zbound1, zbound2): """ Sets the boundary conditions on the grid. Boundaries can be: "reflective", "periodic". :argument xbound1: inner or left boundary in the x direction :argument xbound2: outer or right boundary in the x direction :argument ybound1: inner or front boundary in the y direction :argument ybound2: outer or back boundary in the y direction :argument zbound1: inner or bottom boundary in the z direction :argument zbound1: outer or top boundary in the z direction """ @legacy_function def initialize_grid(): """ Perform accounting before evolving the model. This method will be called after setting the parameters and filling the grid points but just before evolving the system """ function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def get_time(): """ Returns the current model time. """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def evolve_model(): """ Evolve the model until the given end time (or just before). """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_grid_density(): """ Retreives the densitity at the given grid-point """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['rho', ]: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_energy_density(): """ Retreives the energy densitity at the given grid-point """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['en', ]: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_momentum_density(): """ Retreives the momentum densitity at the given grid-point """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['rhovx', 'rhovy', 'rhovz', ]: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) for x in ['rho', 'rhovx', 'rhovy', 'rhovz', 'en']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho', 'rhovx', 'rhovy', 'rhovz', 'en']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho', ]: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_energy_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['en', ]: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_grid_momentum_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rhovx', 'rhovy', 'rhovz', ]: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter( 'index_of_grid', dtype='i', direction=function.IN, default=1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_number_of_grids(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='i', direction=function.OUT) function.result_type = 'i' return function class HydrodynamicsWithExternalGravitationalPotentialInterface(): def get_index_range_for_potential(self): """ Returns the min and max values of indices in each direction for the potential field, this range is 1 cell larger than the normal grid in all directions""" pass @legacy_function def set_potential(): """ Sets the gravitational potential on the given gridpoint (only for codes supporting an external gravitational potential). """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('potential', dtype='d', direction=function.IN) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_potential(): """ Retrieves the gravitational potential on the given gridpoint (only for codes supporting an external gravitational potential). """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i', 'j', 'k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('potential', dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_interpolated_gravitational_potential(): """ Return the interpolated gravitational potential. """ function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['x', 'y', 'z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('potential', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_has_external_gravitational_potential(): """ Returns true if an external gravitational potential is enabled. """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_has_external_gravitational_potential(): """ When True enables the script to set and external gravitational potential. note:: Not every hydrodynamics code supports an external gravitational potential """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'i' return function
12,910
37.085546
79
py
amuse
amuse-main/src/amuse/community/interface/se.py
""" Stellar Dynamics Interface Defintion """ import numpy from amuse.units import units from amuse.datamodel import Particles, Particle from amuse.support import exceptions from amuse.ext.spherical_model import EnclosedMassInterpolator from amuse.community.interface import common from amuse.rfi.core import legacy_function from amuse.rfi.core import LegacyFunctionSpecification class StellarEvolutionInterface(common.CommonCodeInterface): @legacy_function def delete_star(): """ Remove the star with the given index from the code. """ function = LegacyFunctionSpecification() function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to remove") function.result_type = 'int32' function.result_doc = """ 0 - OK The star has been deleted -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_luminosity(): """ Retrieve the current luminosity of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'luminosity', dtype='float64', direction=function.OUT, description="The current luminosit of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_mass(): """ Retrieve the current mass of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'mass', dtype='float64', direction=function.OUT, description="The current mass of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_radius(): """ Retrieve the current radius of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'radius', dtype='float64', direction=function.OUT, description="The current radius of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_temperature(): """ Retrieve the current temperature of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'temperature', dtype='float64', direction=function.OUT, description="The current temperature of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_age(): """ Retrieve the current age of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'age', dtype='float64', direction=function.OUT, description="The current age of the star. ") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_time_step(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'time_step', dtype='float64', direction=function.OUT, description="The next timestep for the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function # @legacy_function # def get_type(): # """ # Retrieve the type of the star. The meaning of the stellar type is # defined by the code. (Difference between stellar type and type must # be explained) # """ # function.addParameter( # 'index_of_the_star', dtype='int32', direction=function.IN, # description="The index of the star to get the type of") # function.addParameter('type', dtype='int32', direction=function.OUT # , description="The type. ") # function.result_type = 'i' # function.result_doc = """ # 0 - OK # The value has been set. # -1 - ERROR # A star with the given index was not found. # """ # return function @legacy_function def get_stellar_type(): """ Retrieve the stellar type of the star. The meaning of the stellar type is defined by the code. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the stellar type of") function.addParameter( 'stellar_type', dtype='int32', direction=function.OUT, description="The stellar type. ") function.result_type = 'i' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def new_particle(): """ Define a new star in the code. The star will start with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.OUT, description=( "The new index for the star. This index can be used to refer " "to this star in other functions" ) ) function.addParameter( 'mass', dtype='float64', direction=function.IN, description="The initial mass of the star") # function.addParameter( # 'age_tag', dtype='float64', direction=function.IN, # description="Starting age of the star *to be specified exactly*") function.result_type = 'int32' function.result_doc = """ 0 - OK New star was loaded and the index_of_the_star parameter set. -1 - ERROR New star could not be created. """ return function @legacy_function def get_number_of_particles(): """ Retrieve the total number of particles define d in the code """ function = LegacyFunctionSpecification() function.addParameter( 'number_of_particles', dtype='int32', direction=function.OUT, description="Count of the particles in the code") function.result_type = 'int32' function.result_doc = """ 0 - OK Count could be determined -1 - ERROR Unable to determine the count """ return function @legacy_function def evolve_one_step(): """ Evolve the star with the given index one step. The code determines how far in time the star will be evolved after this function is finished. See the ``get_age`` function for retrieving the current age of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description=( "The index of the star, as returned by the new_zams_star " "function" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The star was evolved. -1 - ERROR The evolution could not complete, solution did not converge. """ return function @legacy_function def evolve_for(): """ Evolve the star for exactly the given time period. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to evolve") function.addParameter( 'delta_t', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_metallicity(): """ Retrieve the current value of the metallicity. The range of metallicities one can simulate will be dependent on the code. """ function = LegacyFunctionSpecification() function.addParameter( 'metallicity', dtype='float64', direction=function.OUT, description="The current value of the metallicity") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the metallicity was retrieved -1 - ERROR The code does not have support for retrieving the metallicity """ return function @legacy_function def set_metallicity(): """ Update the value of the metallicity. """ function = LegacyFunctionSpecification() function.addParameter( 'metallicity', dtype='float64', direction=function.IN, description="The new value of the metallicity.") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the metallicity was set -1 - ERROR The code does not have support for updating the metallicity """ return function @legacy_function def commit_particles(): """ Let the code perform initialization actions after all particles have been created. Called before the first evolve call and after the last new_particle call. Not every code needs this functionality. And it may be possible to create stars after this function has been called """ 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(): """ Let the code perform reinitialization actions after additional particles have been added or removed. Not every code needs this functionality, and it may be possible to create stars after this function has been called. """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function class StellarEvolution(common.CommonCode): def evolve_model(self, end_time=None, keep_synchronous=True): if not keep_synchronous: for particle in self.particles: particle.evolve_one_step() return delta_time = ( end_time-self.model_time if end_time else 0.99*min(self.particles.time_step) ) for particle in self.particles: particle.evolve_for(delta_time) self.model_time += delta_time def define_state(self, handler): common.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('EDIT', 'new_particle') handler.add_method('EDIT', 'delete_star') handler.add_method('UPDATE', 'new_particle') handler.add_method('UPDATE', 'delete_star') handler.add_transition('EDIT', 'RUN', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_particle', False) handler.add_transition( 'RUN', 'UPDATE', 'finalize_stellar_model', False) handler.add_transition('RUN', 'UPDATE', 'delete_star', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') handler.add_method('RUN', 'evolve_model') handler.add_method('RUN', 'evolve_for') handler.add_method('RUN', 'evolve_one_step') handler.add_method('RUN', 'get_age') handler.add_method('RUN', 'get_mass') handler.add_method('RUN', 'get_luminosity') handler.add_method('RUN', 'get_radius') handler.add_method('RUN', 'get_stellar_type') handler.add_method('RUN', 'get_temperature') def define_methods(self, handler): common.CommonCode.define_methods(self, handler) handler.add_method( "evolve_one_step", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "evolve_for", (handler.INDEX, units.yr), (handler.ERROR_CODE,) ) handler.add_method( "new_particle", (units.MSun), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "delete_star", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "get_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_radius", (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) handler.add_method( "get_stellar_type", (handler.INDEX,), (units.stellar_type, handler.ERROR_CODE,) ) handler.add_method( "get_age", (handler.INDEX,), (units.yr, handler.ERROR_CODE,) ) handler.add_method( "get_luminosity", (handler.INDEX,), (units.LSun, handler.ERROR_CODE,) ) handler.add_method( "get_temperature", (handler.INDEX,), (units.K, handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (handler.INDEX,), (units.yr, handler.ERROR_CODE,) ) handler.add_method( "get_metallicity", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_metallicity", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) class InternalStellarStructureInterface(object): @legacy_function def get_number_of_zones(): """ Retrieve the current number of zones/mesh-cells of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'n_zones', dtype='int32', direction=function.OUT, description="The current number of zones/mesh-cells of the star." ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_temperature_at_zone(): """ Retrieve the temperature at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of") function.addParameter( 'T_i', dtype='float64', direction=function.OUT, description=( "The temperature at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def set_temperature_at_zone(): """ Set the temperature at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to set the value of" ) function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to set the value of" ) function.addParameter( 'T_i', dtype='float64', direction=function.IN, description=( "The temperature at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was set. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def get_density_at_zone(): """ Retrieve the density at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of") function.addParameter( 'rho_i', dtype='float64', direction=function.OUT, description=( "The density at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def set_density_at_zone(): """ Set the density at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to set the value of" ) function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to set the value of" ) function.addParameter( 'rho_i', dtype='float64', direction=function.IN, description=( "The density at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was set. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def set_mass(): """ Set the current mass of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to set the value of" ) function.addParameter( 'mass', dtype='float64', direction=function.IN, description="The current mass of the star." ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_radius_at_zone(): """ Retrieve the radius at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of") function.addParameter( 'R_i', dtype='float64', direction=function.OUT, description=( "The radius at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def set_radius_at_zone(): """ Set the radius at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to set the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to set the value of") function.addParameter( 'R_i', dtype='float64', direction=function.IN, description=( "The radius at the specified zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was set. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def get_pressure_at_zone(): """ Retrieve the total pressure at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of") function.addParameter( 'P_i', dtype='float64', direction=function.OUT, description=( "The total pressure at the specified zone/mesh-cell of the " "star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def get_mu_at_zone(): """ Retrieve the mean molecular weight per particle (ions + free electrons) at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of" ) function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of" ) function.addParameter( 'mu_i', dtype='float64', direction=function.OUT, description=( "The mean molecular weight at the specified zone/mesh-cell " "of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR A zone with the given index was not found. """ return function @legacy_function def get_number_of_species(): """ Retrieve the current number of chemical abundance variables per zone of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'n_species', dtype='int32', direction=function.OUT, description=( "The current number of chemical abundance variables per zone " "of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_name_of_species(): """ Retrieve the name of the chemical abundance variable of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'species', dtype='int32', direction=function.IN, description="The species of the star to get the name of") function.addParameter( 'species_name', dtype='string', direction=function.OUT, description=( "The name of the chemical abundance variable of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_mass_fraction_of_species_at_zone(): """ Retrieve the fractional chemical abundance variable at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the value of") function.addParameter( 'species', dtype='int32', direction=function.IN, description="The species of the star to get the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to get the value of") function.addParameter( 'Xj_i', dtype='float64', direction=function.OUT, description=( "The fractional chemical abundance variable at the specified " "zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def set_mass_fraction_of_species_at_zone(): """ Set the fractional chemical abundance variable at the specified zone/mesh-cell of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to set the value of") function.addParameter( 'species', dtype='int32', direction=function.IN, description="The species of the star to set the value of") function.addParameter( 'zone', dtype='int32', direction=function.IN, description="The zone/mesh-cell of the star to set the value of") function.addParameter( 'Xj_i', dtype='float64', direction=function.IN, description=( "The fractional chemical abundance variable at the specified " "zone/mesh-cell of the star." ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK The value was set. -1 - ERROR A star with the given index was not found. """ return function class InternalStellarStructure(object): def define_particle_sets(self, handler, set_name='particles'): handler.add_method(set_name, 'get_number_of_zones') handler.add_method(set_name, 'get_density_profile') handler.add_method(set_name, 'set_density_profile') handler.add_method(set_name, 'get_radius_profile') handler.add_method(set_name, 'set_radius_profile') handler.add_method(set_name, 'get_temperature_profile') handler.add_method(set_name, 'set_temperature_profile') handler.add_method(set_name, 'get_pressure_profile') handler.add_method(set_name, 'get_mu_profile') handler.add_method(set_name, 'get_number_of_species') handler.add_method(set_name, 'get_names_of_species') handler.add_method(set_name, 'get_chemical_abundance_profiles') handler.add_method(set_name, 'set_chemical_abundance_profiles') handler.add_method(set_name, 'calculate_core_mass') handler.add_method(set_name, 'calculate_helium_exhausted_core_mass') handler.add_getter( set_name, 'get_central_temperature', names=('central_temperature',) ) handler.add_getter( set_name, 'get_central_density', names=('central_density',) ) def define_errorcodes(self, handler): handler.add_errorcode(-21, 'Specified particle does not exist.') handler.add_errorcode( -22, 'Specified zone is undefined for this particle.' ) handler.add_errorcode( -23, 'Specified chemical species is undefined for this particle.' ) def define_methods(self, handler): handler.add_method( "set_mass", (handler.INDEX, units.MSun,), (handler.ERROR_CODE,) ) handler.add_method( "get_number_of_zones", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_temperature_at_zone", (handler.INDEX, handler.NO_UNIT,), (units.K, handler.ERROR_CODE,) ) handler.add_method( "set_temperature_at_zone", (handler.INDEX, handler.NO_UNIT, units.K,), (handler.ERROR_CODE,) ) handler.add_method( "get_density_at_zone", (handler.INDEX, handler.NO_UNIT,), (units.g/units.cm**3, handler.ERROR_CODE,) ) handler.add_method( "set_density_at_zone", (handler.INDEX, handler.NO_UNIT, units.g/units.cm**3,), (handler.ERROR_CODE,) ) handler.add_method( "get_radius_at_zone", (handler.INDEX, handler.NO_UNIT,), (units.cm, handler.ERROR_CODE,) ) handler.add_method( "set_radius_at_zone", (handler.INDEX, handler.NO_UNIT, units.cm,), (handler.ERROR_CODE,) ) handler.add_method( "get_pressure_at_zone", (handler.INDEX, handler.NO_UNIT,), (units.barye, handler.ERROR_CODE,) ) handler.add_method( "get_mu_at_zone", (handler.INDEX, handler.NO_UNIT,), (units.amu, handler.ERROR_CODE,) ) handler.add_method( "get_number_of_species", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_name_of_species", (handler.INDEX, handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_mass_fraction_of_species_at_zone", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mass_fraction_of_species_at_zone", ( handler.INDEX, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, ), (handler.ERROR_CODE,) ) def _check_supplied_values( self, number_of_values, expected_number, type_string="mesh zones" ): if number_of_values != expected_number: raise exceptions.CodeException( ( "The length of the supplied vector ({0}) does not match " "the number of " + type_string + " of the star ({1})." ).format(number_of_values, expected_number) ) def _check_number_of_indices( self, indices_of_the_stars, action_string="Querying/setting profiles" ): if hasattr(indices_of_the_stars, '__iter__'): if len(indices_of_the_stars) > 1: raise exceptions.CodeException( action_string + " of more than one particle at a time is not supported." ) return indices_of_the_stars[0] return indices_of_the_stars def get_density_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying density profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_density_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none ) def get_central_density(self, indices_of_the_stars): return self.get_density_at_zone(indices_of_the_stars, 0) def set_density_profile( self, indices_of_the_stars, values, number_of_zones=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Setting density profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) self._check_supplied_values(len(values), number_of_zones) self.set_density_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values ) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) def get_radius_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying radius profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_radius_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none ) def set_radius_profile( self, indices_of_the_stars, values, number_of_zones=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Setting radius profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) self._check_supplied_values(len(values), number_of_zones) self.set_radius_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values ) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) def get_temperature_profile( self, indices_of_the_stars, number_of_zones=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying temperature profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_temperature_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none ) def get_central_temperature(self, indices_of_the_stars): return self.get_temperature_at_zone(indices_of_the_stars, 0) def set_temperature_profile( self, indices_of_the_stars, values, number_of_zones=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Setting temperature profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) self._check_supplied_values(len(values), number_of_zones) self.set_temperature_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values ) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) def get_pressure_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying pressure profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_pressure_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none ) def get_mu_profile( self, indices_of_the_stars, number_of_zones=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying mean-molecular-weight profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_mu_at_zone( [indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none ) def get_names_of_species( self, indices_of_the_stars, number_of_species=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying chemical abundance names" ) if number_of_species is None: number_of_species = self.get_number_of_species( indices_of_the_stars) return list(self.get_name_of_species( [indices_of_the_stars]*number_of_species, list(range(1, number_of_species+1)) | units.none )) def get_chemical_abundance_profiles( self, indices_of_the_stars, number_of_zones=None, number_of_species=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying chemical abundance profiles" ) if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) if number_of_species is None: number_of_species = self.get_number_of_species( indices_of_the_stars) grid = numpy.indices((number_of_species, number_of_zones)) return self.get_mass_fraction_of_species_at_zone( [indices_of_the_stars] * number_of_zones * number_of_species, grid[0].flatten()+1, grid[1].flatten() ).reshape((number_of_species, number_of_zones)) def set_chemical_abundance_profiles( self, indices_of_the_stars, values, number_of_zones=None, number_of_species=None ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Setting chemical abundance profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) if number_of_species is None: number_of_species = self.get_number_of_species( indices_of_the_stars) self._check_supplied_values( len(values), number_of_species, type_string="chemical species") self._check_supplied_values(len(values[0]), number_of_zones) grid = numpy.indices((number_of_species, number_of_zones)) self.set_mass_fraction_of_species_at_zone( [indices_of_the_stars] * number_of_zones * number_of_species, grid[0].flatten()+1, grid[1].flatten(), values.reshape((number_of_species*number_of_zones, )) ) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) def calculate_core_mass( self, indices_of_the_stars, species=None, core_H_abundance_limit=1.0e-4, split_species=False ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying the core mass") chemical_abundance_profiles = self.get_chemical_abundance_profiles( indices_of_the_stars) index_core = numpy.searchsorted( chemical_abundance_profiles[0], core_H_abundance_limit) densities, radii_cubed = self._get_densities_radii_cubed( indices_of_the_stars, index_core, split_species, species, chemical_abundance_profiles) sum_axis = 1 if split_species else None return ( numpy.pi * 4.0/3.0 * ( densities * (radii_cubed[1:] - radii_cubed[:-1]) ).sum(axis=sum_axis) ).as_quantity_in(units.MSun) def _get_index_helium_exhausted_core( self, indices_of_the_stars, chemical_abundance_profiles, core_He_abundance_limit ): helium_abundance_profile = 0 * chemical_abundance_profiles[0] for i, species_name in enumerate( self.get_names_of_species(indices_of_the_stars) ): if "he" in species_name or "He" in species_name: helium_abundance_profile += chemical_abundance_profiles[i] return numpy.searchsorted( helium_abundance_profile, core_He_abundance_limit) def _get_densities_radii_cubed( self, indices_of_the_stars, index_core, split_species, species, chemical_abundance_profiles ): densities = self.get_density_profile(indices_of_the_stars)[:index_core] if split_species: if species is None: species_profiles = chemical_abundance_profiles[ ..., :index_core ] else: species_profiles = [] for i, species_name in enumerate( self.get_names_of_species(indices_of_the_stars) ): if species_name in species: species_profiles.append( chemical_abundance_profiles[i, :index_core]) densities = densities * species_profiles else: if species is not None: fraction = 0 * chemical_abundance_profiles[0, :index_core] for i, species_name in enumerate( self.get_names_of_species(indices_of_the_stars) ): if species_name in species: fraction += chemical_abundance_profiles[i, :index_core] densities = densities * fraction radii = self.get_radius_profile(indices_of_the_stars)[:index_core] radii.prepend(0 | units.m) radii_cubed = radii**3 return densities, radii_cubed def calculate_helium_exhausted_core_mass( self, indices_of_the_stars, species=None, core_He_abundance_limit=1.0e-4, split_species=False ): indices_of_the_stars = self._check_number_of_indices( indices_of_the_stars, action_string="Querying the core mass") chemical_abundance_profiles = self.get_chemical_abundance_profiles( indices_of_the_stars) index_core = self._get_index_helium_exhausted_core( indices_of_the_stars, chemical_abundance_profiles, core_He_abundance_limit) densities, radii_cubed = self._get_densities_radii_cubed( indices_of_the_stars, index_core, split_species, species, chemical_abundance_profiles) sum_axis = 1 if split_species else None return ( numpy.pi * 4.0/3.0 * ( densities * (radii_cubed[1:] - radii_cubed[:-1]) ).sum(axis=sum_axis) ).as_quantity_in(units.MSun) def merge_colliding( self, primaries, secondaries, collision_code, code_options=dict(), code_parameters=dict(), return_merge_products=["se", "gd"], create_new_key=True ): return merge_colliding_in_stellar_evolution_code( self, primaries, secondaries, collision_code, code_options=code_options, code_parameters=code_parameters, return_merge_products=return_merge_products, create_new_key=create_new_key ) def merge_colliding_in_stellar_evolution_code( stellar_evolution_code, primaries, secondaries, collision_code, code_options=dict(), code_parameters=dict(), return_merge_products=["se", "gd"], create_new_key=True): primaries = primaries.as_set() secondaries = secondaries.as_set() star_collider = collision_code(**code_options) for (par_name, value) in code_parameters.items(): setattr(star_collider.parameters, par_name, value) star_collider.commit_parameters() star_collider.particles.add_particles(primaries) star_collider.particles.add_particles(secondaries) se_colliders = star_collider.particles.get_intersecting_subset_in( stellar_evolution_code.particles ) for col_particle, se_particle in zip( star_collider.particles, se_colliders ): number_of_zones = se_particle.get_number_of_zones() mm1 = se_particle.get_mass_profile( number_of_zones=number_of_zones) * se_particle.mass mass_profile = se_particle.get_cumulative_mass_profile( number_of_zones=number_of_zones) * se_particle.mass density_profile = se_particle.get_density_profile( number_of_zones=number_of_zones) radius_profile = se_particle.get_radius_profile( number_of_zones=number_of_zones) temperature_profile = se_particle.get_temperature_profile( number_of_zones=number_of_zones) lum = se_particle.get_luminosity_profile( number_of_zones=number_of_zones) pressure_profile = se_particle.get_pressure_profile( number_of_zones=number_of_zones) mu_profile = se_particle.get_mu_profile( number_of_zones=number_of_zones) composition_profile = se_particle.get_chemical_abundance_profiles( number_of_zones=number_of_zones) col_particle.add_shell( mm1, 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) stellar_evolution_code.particles.remove_particles( star_collider.native_stars) gd_merge_products = Particles() for primary, secondary in zip(primaries, secondaries): merge_product = Particle() merge_product.primary = primary merge_product.secondary = secondary new_particle = star_collider.merge_products.add_particle(merge_product) stellar_model = new_particle.get_internal_structure() if create_new_key: new_key = merge_product.key else: new_key = primary.key if ( primary.mass > secondary.mass ) else secondary.key stellar_evolution_code.new_particle_from_model( stellar_model, 0.0 | units.Myr, key=new_key) if "gd" in return_merge_products: merge_product = Particle(key=new_key) merge_product.mass = stellar_model.mass[-1] merge_product.radius = stellar_model.radius[-1] gd_colliders = (primary + secondary) merge_product.position = gd_colliders.center_of_mass() merge_product.velocity = gd_colliders.center_of_mass_velocity() gd_merge_products.add_particle(merge_product) star_collider.stop() result = [] for particle_type in return_merge_products: if particle_type == "se": result.append( gd_merge_products.get_intersecting_subset_in( stellar_evolution_code.particles ) ) elif particle_type == "gd": result.append(gd_merge_products) else: print( "Unexpected value in return_merge_products, must be 'gd' " "(gravity particles) or 'se' (stellar evolution particles):", particle_type ) return result
54,169
36.801814
79
py
amuse
amuse-main/src/amuse/community/aarsethzare/__init__.py
# generated file from .interface import Aarsethzare
52
16.666667
34
py
amuse
amuse-main/src/amuse/community/aarsethzare/interface.py
from amuse.community import * from amuse.units import units class AarsethZareInterface(CodeInterface, LiteratureReferencesMixIn): """ Interface to the regularized Burlish-Stoer integrator of Aarseth & Zare The relevant references are: .. [#] ADS:1974CeMec..10..185A (Aarseth, S. & Zare, K., 1974, Celestial Mechanics 10, 185) .. [#] ADS:1974CeMec..10..516A (Aarseth, S. & Zare, K., 1974, Celestial Mechanics 10, 516) """ #include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker = 'aarsethzare_worker', **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @legacy_function def evolve_triple(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.INOUT) function.addParameter('masses', dtype='float64', direction=function.IN) function.addParameter('x', dtype='float64', direction=function.INOUT) function.addParameter('y', dtype='float64', direction=function.INOUT) function.addParameter('z', dtype='float64', direction=function.INOUT) function.addParameter('vx', dtype='float64', direction=function.INOUT) function.addParameter('vy', dtype='float64', direction=function.INOUT) function.addParameter('vz', dtype='float64', direction=function.INOUT) function.addParameter('tend', dtype='float64', direction=function.IN) function.addParameter('nl', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def construct_orbital_elements() : function = LegacyFunctionSpecification() function.addParameter('m', dtype='float64', direction=function.IN) function.addParameter('r', dtype='float64', direction=function.IN) function.addParameter('v', dtype='float64', direction=function.IN) function.addParameter('e1', dtype='float64', direction=function.OUT) function.addParameter('e2', dtype='float64', direction=function.OUT) function.addParameter('nl', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def construct_orbital_coordinates() : function = LegacyFunctionSpecification() function.addParameter('m', dtype='float64', direction=function.IN) function.addParameter('e1', dtype='float64', direction=function.IN) function.addParameter('e2', dtype='float64', direction=function.IN) function.addParameter('r', dtype='float64', direction=function.OUT) function.addParameter('v', dtype='float64', direction=function.OUT) function.addParameter('nl', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function class AarsethZare(InCodeComponentImplementation): def __init__(self, unit_converter=None,**keyword_arguments): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, AarsethZareInterface(**keyword_arguments)) 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_inmemory_set('particles') def define_methods(self, handler): handler.add_method( "evolve_triple", ( nbody_system.time, nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.time ), ( nbody_system.time, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, handler.ERROR_CODE ) ) handler.add_method( "construct_orbital_elements", ( nbody_system.mass, nbody_system.length, nbody_system.speed ), ( units.none, units.none, handler.ERROR_CODE ) ) handler.add_method( "construct_orbital_coordinates", ( nbody_system.mass, handler.NO_UNIT, handler.NO_UNIT ), ( nbody_system.length, nbody_system.speed, handler.ERROR_CODE ) ) def evolve_model(self, tend): mass = self.particles.mass x = self.particles.x y = self.particles.y z = self.particles.z vx = self.particles.vx vy = self.particles.vy vz = self.particles.vz if hasattr(self.particles,"time"): time = self.particles.time else: time = tend.as_vector_with_length(len(self.particles)).aszeros() time, x, y, z, vx, vy, vz = self.evolve_triple(time,mass,x,y,z,vx,vy,vz,tend.as_vector_with_length(len(self.particles))) self.particles.time = time self.particles.x= x self.particles.y= y self.particles.z=z self.particles.vx=vx self.particles.vy=vy self.particles.vz=vz Aarsethzare = AarsethZare
5,892
36.062893
128
py
amuse
amuse-main/src/amuse/community/seba/download.py
#!/usr/bin/env python import subprocess import os import urllib.request import urllib.parse import urllib.error from shutil import which from optparse import OptionParser class GetCodeFromHttp: filename_template = "{version}.tar.gz" name = ["SeBa"] url_template = [ "https://github.com/amusecode/SeBa/archive/{version}.tar.gz", ] version = [ "", ] def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename, name, version): print(f"unpacking {filename}") arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( [ 'mv', f'{name}-{version}', name ], cwd=os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists(f'src.{counter}'): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', f'src.{counter}') os.mkdir('src') for i, url_template in enumerate(self.url_template): url = url_template.format(version=self.version[i]) filename = self.filename_template.format(version=self.version[i]) filepath = os.path.join(self.src_directory(), filename) print(f"downloading version {self.version[i]} from {url} to {filename}") if which('wget') is not None: arguments = ['wget', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) elif which('curl') is not None: arguments = ['curl', '-L', '-O', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) else: urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file( filename, self.name[i], self.version[i] ) def main(seba_version=''): version = [ seba_version, ] instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--seba-version", default='2f6e7f37a53167b4b0dcd6c723dff7b5ee1aecba', dest="seba_version", help="SeBa commit hash to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
3,014
27.17757
84
py
amuse
amuse-main/src/amuse/community/seba/__init__.py
from .interface import Seba
28
13.5
27
py
amuse
amuse-main/src/amuse/community/seba/interface.py
from amuse.community import * from amuse.datamodel import Particles from amuse.datamodel import ParticlesSubset from amuse.community.interface import se from amuse.support import code class SeBaInterface(CodeInterface, se.StellarEvolutionInterface, LiteratureReferencesMixIn, StoppingConditionInterface): """ Stellar evolution is performed by the rapid single-star evolution and binary evolution using SeBa.This is a package of semi-analytical formulae which covers all phases of evolution from the zero-age main-sequence up to and including remnant phases. It is valid for masses in the range 0.01-1000 Msun with variable metallicity. SeBa includes prescriptions for mass loss by stellar winds, supernova and supports binary evolution. .. [#] ADS:1996A&A...309..179P (Portegies Zwart S.F. & Verbunt F., 1996, A&A, 309, 179: .. [#] ... "Population synthesis of high-mass binaries") .. [#] ADS:2012A&A...546A..70T (Toonen, S., Nelemans, G., Portegies Zwart S.F., 2012, A&A, 546A, 70T .. [#] ... "Supernova Type Ia progenitors from merging double white dwarfs. Using a new population synthesis model") """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="seba_worker", **options) LiteratureReferencesMixIn.__init__(self) @legacy_function def evolve_star(): function = LegacyFunctionSpecification() function.addParameter('mass', dtype='float64', direction=function.IN) function.addParameter('endtime', dtype='float64', direction=function.IN) function.addParameter('metal', dtype='float64', direction=function.IN) function.addParameter('resulttime', dtype='float64', direction=function.OUT) function.addParameter('end_mass', dtype='float64', direction=function.OUT) function.addParameter('end_radius', dtype='float64', direction=function.OUT) function.addParameter('end_luminosity', dtype='float64', direction=function.OUT) function.addParameter('end_temperature', dtype='float64', direction=function.OUT) function.addParameter('time_step', dtype='float64', direction=function.OUT) function.addParameter('stellar_type', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def new_binary(): """ Define a new star in the code. The star will start with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('semi_major_axis', dtype='float64', direction=function.IN , description="The eccentricity of the orbit") function.addParameter('eccentricity', dtype='float64', direction=function.IN , description="The eccentricity of the orbit") function.addParameter('child1', dtype='int32', direction=function.IN , description="The index of the first child, as returned by new_particle") function.addParameter('child2', dtype='int32', direction=function.IN , description="The index of the second child, as returned by new_particle") function.result_type = 'int32' function.result_doc = """ 0 - OK New star was loaded and the index_of_the_star parameter set. -1 - ERROR New star could not be created. """ return function @legacy_function def delete_binary(): """ Remove the definition of binary from the code. After calling this function the particle is no longer part of the model evolution. It's children are still a part of particles model. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the binary to be removed. This index must have been returned by an earlier call to :meth:`new_binary`") function.result_type = 'int32' function.result_doc = """ 0 - OK binary was removed from the model -1 - ERROR binary could not be found -2 - ERROR not yet implemented """ return function @legacy_function def evolve_system(): """ Evolve the model until the given time, or until a stopping condition is set. Need to call this evolve_system as evolve_model is overriden in se.StellarEvolution """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.IN, description = "Model time to evolve the code to. The model will be " "evolved until this time is reached exactly or just after.") function.result_type = 'int32' return function @legacy_function def get_eccentricity(): """ Retrieve the current eccentricity of the binary star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current eccentricity.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_semi_major_axis(): """ Retrieve the current semi major axis of the elliptical orbit of the parts in the binary star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current semi major axis.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_core_mass(): """ Retrieve the current core mass of a star """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current core_mass.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_COcore_mass(): """ Retrieve the current CO core mass of a star """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current core_mass.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def change_mass(): """ Set the add_mass increase (positive) or decrease (negative) of a star """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('value', dtype='float64', direction=function.IN , description="The current change_mass.") function.addParameter('dt', dtype='float64', direction=function.IN , description="The time in which the mass was changed.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def merge_the_binary(): """ Merges the stars in the binary, creates a 'merged' binary. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_binary', dtype='int32', direction=function.IN , description="The index of the binary to set the value of") function.addParameter('child1', dtype='int32', direction=function.IN , description="The index of the consumer") function.addParameter('child2', dtype='int32', direction=function.IN , description="The index of the dinner") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def merge_with_other_star(): """ Merges the star with another star, companion star remains unaltered """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('child1', dtype='int32', direction=function.IN , description="The index of the consumer") function.addParameter('child2', dtype='int32', direction=function.IN , description="The index of the dinner") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def refresh_memory(): """ Refresh the memory of SeBa. Update previous parameters in SeBa to current values. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def recall_memory_one_step(): """ Recall the memory of SeBa one time_step ago. Update current parameters in SeBa to previous values. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_envelope_mass(): """ Retrieve the current envelope mass of a star """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current envelope_mass.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_core_radius(): """ Retrieve the current radius of the core """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.OUT , description="The current core_radius.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def set_semi_major_axis(): """ Update the current semi major axis of the elliptical orbit of the parts in the binary star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.IN , description="The new semi major axis.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def set_eccentricity(): """ Update the current eccentricity of the elliptical orbit of the parts in the binary star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.IN , description="The new eccentricity.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_children_of_binary(): """ Return the indices of both children """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN, description = 'index of the parent particle', unit = INDEX) function.addParameter('child1', dtype='int32', direction=function.OUT, description = 'index of the first child particle, -1 if none', unit = LINK('particles') ) function.addParameter('child2', dtype='int32', direction=function.OUT, unit = LINK('particles')) function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def get_is_logging_of_evolve_enabled(): """ If True log the star state before and after evolve in starev.data """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_is_logging_of_evolve_enabled(): """ If True log the star state before and after evolve in starev.data """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_supernova_kick_velocity(): """ Retrieve the current value of the supernova kick velocity (in kms). """ function = LegacyFunctionSpecification() function.addParameter('v_disp', dtype='float64', direction=function.OUT, description = "The current value of the kick velocity dispersion") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the supernova kick velocity was retrieved -1 - ERROR The code does not have support for retrieving the supernova kick velocity """ return function @legacy_function def set_supernova_kick_velocity(): """ Update the value of the kick velocity dispersion. """ function = LegacyFunctionSpecification() function.addParameter('v_disp', dtype='float64', direction=function.IN, description = "The new value of the supernova kick velocity dispersion.") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the supernova kick velocity was set -1 - ERROR The code does not have support for updating the supernova kick velocity """ return function @legacy_function def get_gyration_radius(): """ Retrieve the current value of the gyration radius (no units). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('gyration_radius', dtype='float64', direction=function.OUT, description = "The current value of the gyration radius") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the gyration radius was retrieved -1 - ERROR The code does not have support for retrieving the gyration radius """ return function @legacy_function def get_apsidal_motion_constant(): """ Retrieve the current value of the apsidal motion constant (no units). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('apsidal_motion_constant', dtype='float64', direction=function.OUT, description = "The current value of the apsidal motion constant") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the apsidal motion constant was retrieved -1 - ERROR The code does not have support for retrieving the apsidal motion constant """ return function @legacy_function def get_zeta_thermal(): """ Retrieve the current value of the zeta thermal (no units). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('zeta_thermal', dtype='float64', direction=function.OUT, description = "The current value of the zeta thermal") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the zeta thermal constant was retrieved -1 - ERROR The code does not have support for retrieving the zeta thermal constant """ return function @legacy_function def get_zeta_adiabatic(): """ Retrieve the current value of the zeta adiabatic (no units). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('zeta_adiabatic', dtype='float64', direction=function.OUT, description = "The current value of the zeta adiabatic") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the zeta adiabatic constant was retrieved -1 - ERROR The code does not have support for retrieving the zeta adiabatic constant """ return function @legacy_function def get_rotation_period(): """ Retrieve the current value of the rotation period (sec). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('rotation_period', dtype='float64', direction=function.OUT, description = "The current value of the rotation period") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the rotation period was retrieved -1 - ERROR The code does not have support for retrieving the rotation period """ return function @legacy_function def set_rotation_period(): """ Update the current rotation period of a star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('value', dtype='float64', direction=function.IN , description="The new rotation period.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR A binary with the given index was not found. """ return function @legacy_function def get_fallback(): """ Retrieve the value of fallback fraction during the SN. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('rotation_period', dtype='float64', direction=function.OUT, description = "The current value of the rotation period") function.result_type = 'int32' function.result_doc = """ 0 - OK Value of the fallback fraction was retrieved -1 - ERROR The code does not have support for retrieving the fallback fraction """ return function @legacy_function def get_relative_age(): """ Retrieve the current value of the square of the relative age (Myr). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('relative_age', dtype='float64', direction=function.OUT, description = "The current value of the square of the relative age") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the square of the relative age was retrieved -1 - ERROR The code does not have support for retrieving the square of the relative age """ return function @legacy_function def get_natal_kick_velocity(): """ Retrieve the current value of the square of the natal kick velocity (Myr). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('natal_kick_velocity_x', dtype='float64', direction=function.OUT) function.addParameter('natal_kick_velocity_y', dtype='float64', direction=function.OUT) function.addParameter('natal_kick_velocity_z', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the natal_kick_velocity was retrieved -1 - ERROR The code does not have support for retrieving the square of the natal_kick_velocity """ return function @legacy_function def get_relative_mass(): """ Retrieve the current value of the square of the relative mass (MSun). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('relative_mass', dtype='float64', direction=function.OUT, description = "The current value of the square of the relative mass") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the square of the relative mass was retrieved -1 - ERROR The code does not have support for retrieving the square of the relative mass """ return function @legacy_function def get_effective_radius(): """ Retrieve the current value of the effective radius (Rsun). This can be different from the (equilibrium) radius due to accretion or mass loss. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('effective_radius', dtype='float64', direction=function.OUT, description = "The current value of the effective radius") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the effective_radius was retrieved -1 - ERROR The code does not have support for retrieving the effective_radius """ return function @legacy_function def get_convective_envelope_mass(): """ Retrieve the current value of the mass of the part of the envelope that is convective (MSun). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('convective_envelope_mass', dtype='float64', direction=function.OUT, description = "The current value of the mass of the part of the envelope that is convective") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the convective envelope mass was retrieved -1 - ERROR The code does not have support for retrieving the square of the relative mass """ return function @legacy_function def get_convective_envelope_radius(): """ Retrieve the current value of the radius of the part of the envelope that is convective (RSun). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('convective_envelope_radius', dtype='float64', direction=function.OUT, description = "The current value of the radius of the part of the envelope that is convective") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the convective envelope radius was retrieved -1 - ERROR The code does not have support for retrieving the square of the relative mass """ return function @legacy_function def get_time(): """ Retrieve the model time. This time should be close to the end time specified in the evolve code. Or, when a collision was detected, it will be the model time of the collision. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT, description = "The current model time") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the time was retrieved -1 - ERROR The code does not have support for querying the time """ return function @legacy_function def get_wind_mass_loss_rate(): """ Retrieve the current value of the wind_mass_loss_rate (Msun/yr). """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to set the value of") function.addParameter('wind_mass_loss_rate', dtype='float64', direction=function.OUT, description = "The current value of the wind_mass_loss_rate") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of the wind_mass_loss_rate was retrieved -1 - ERROR The code does not have support for retrieving the wind_mass_loss_rate """ return function # SPZ&SLWMcM # No stopping conditions in this version for now. def evolve_model(self, end_time=None, keep_synchronous=True): if not keep_synchronous: raise Exception("non_synchronous evolution not implemented") if end_time is None: end_time = self.model_time + min(self.particles.time_step) return self.evolve_system(end_time) class SeBa(se.StellarEvolution): __interface__ = SeBaInterface def __init__(self, **options): self.stopping_conditions = StoppingConditions(self) self.stopping_conditions.supernova_detection = code.StoppingCondition('supernova_detection') se.StellarEvolution.__init__(self, SeBaInterface(**options), **options) def evolve_model(self, end_time=None, keep_synchronous=True): self.stopping_conditions.supernova_detection.unset() if not keep_synchronous: raise Exception("non_synchronous evolution not implemented") evolve_a_success = 0 if end_time is None: end_time = self.model_time + min(self.particles.time_step) # print "t=", self.model_time, end_time if not self.stopping_conditions.supernova_detection.is_enabled(): evolve_a_success = self.evolve_system(end_time) else: new_end_time = min(end_time, self.model_time + min(self.particles.time_step)) while self.model_time<new_end_time: old_particles = self.particles.copy() evolve_a_success = self.evolve_system(new_end_time) psn = self.particles[numpy.logical_and(self.particles.stellar_type >= 13|units.stellar_type, self.particles.stellar_type <= 15|units.stellar_type)] psn -= self.particles[numpy.logical_and(old_particles.stellar_type >= 13|units.stellar_type, old_particles.stellar_type <= 15|units.stellar_type)] if len(psn)>0: # print "Supernova at time:", psn self.stopping_conditions.supernova_detection.set(psn) break new_end_time = min(end_time, self.model_time + min(self.particles.time_step)) """ to be used if stopping condition is implemented in c old_particles = self.particles.copy() evolve_a_success = self.evolve_system(end_time) if self.stopping_conditions.supernova_detection.is_set(): print "XXStellar supernova stopping condition is set" print self.particles print "age=", self.particles.age, self.particles.relative_age self.reset_all_stars(old_particles) evolve_a_success = self.evolve_system(new_end_time) """ return evolve_a_success def reset_all_stars(self, old_particles): psn = self.particles[self.particles.stellar_type==14|units.stellar_type] psn -= self.particles[old_particles.stellar_type==14|units.stellar_type] # print "t=", psn.relative_age[0] tsn = self.model_time - psn.get_relative_age()[0] # channel_from_old_to_new_star = old_particles.new_channel_to(self.particles) # channel_from_old_to_new_star.copy_attributes(["relative_age", "relative_mass"]) # self.evolve_model(tsn) self.particles.remove_particles(self.particles) self.particles.add_particles(old_particles) self.model_time = tsn self.evolve_model(tsn) def define_properties(self, handler): se.StellarEvolution.define_properties(self, handler) handler.add_property('get_time', public_name = "model_time") def define_methods(self, handler): se.StellarEvolution.define_methods(self, handler) handler.add_method( "evolve_for", (handler.INDEX, units.Myr), (handler.ERROR_CODE,) ) handler.add_method( "evolve_star", (units.MSun, units.Myr, units.none), (units.Myr, units.MSun, units.RSun, units.LSun, units.K, units.Myr,units.stellar_type, handler.ERROR_CODE) ) handler.add_method( "evolve_system", (units.Myr,), (handler.ERROR_CODE,) ) handler.add_method( "new_binary", (units.RSun, handler.NO_UNIT, handler.LINK('particles'), handler.LINK('particles')), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "delete_binary", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "get_eccentricity", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_semi_major_axis", (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) handler.add_method( "get_core_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_COcore_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "change_mass", (handler.INDEX,units.MSun,units.Myr), (handler.ERROR_CODE,) ) handler.add_method( "merge_the_binary", (handler.INDEX,handler.LINK('particles'),handler.LINK('particles')), (handler.ERROR_CODE,) ) handler.add_method( "merge_with_other_star", (handler.INDEX,handler.LINK('particles')), (handler.ERROR_CODE,) ) handler.add_method( "refresh_memory", (handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( "recall_memory_one_step", (handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( "get_envelope_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_core_radius", (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) handler.add_method( "set_semi_major_axis", (handler.INDEX, units.RSun,), (handler.ERROR_CODE,) ) handler.add_method( "get_age", (handler.INDEX,), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (handler.INDEX,), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "get_supernova_kick_velocity", (), (units.kms, handler.ERROR_CODE,) ) handler.add_method( "set_supernova_kick_velocity", (units.kms,), (handler.ERROR_CODE,) ) handler.add_method( "get_gyration_radius", (handler.INDEX,), (units.none, handler.ERROR_CODE,) ) handler.add_method( "get_apsidal_motion_constant", (handler.INDEX,), (units.none, handler.ERROR_CODE,) ) handler.add_method( "get_zeta_thermal", (handler.INDEX,), (units.none, handler.ERROR_CODE,) ) handler.add_method( "get_zeta_adiabatic", (handler.INDEX,), (units.none, handler.ERROR_CODE,) ) handler.add_method( "get_rotation_period", (handler.INDEX,), (units.s, handler.ERROR_CODE,) ) handler.add_method( "set_rotation_period", (handler.INDEX, units.s,), (handler.ERROR_CODE,) ) handler.add_method( "get_fallback", (handler.INDEX,), (units.none, handler.ERROR_CODE,) ) handler.add_method( "get_relative_age", (handler.INDEX,), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "get_natal_kick_velocity", (handler.INDEX,), (units.kms, units.kms, units.kms, handler.ERROR_CODE,) ) handler.add_method( "get_relative_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_effective_radius", (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) handler.add_method( "get_convective_envelope_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_convective_envelope_radius", (handler.INDEX,), (units.RSun, handler.ERROR_CODE,) ) handler.add_method( "get_time", (), (units.Myr,handler.ERROR_CODE,) ) handler.add_method( "get_wind_mass_loss_rate", (handler.INDEX,), (units.MSun/units.yr, handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def update_time_steps(self): pass def define_parameters(self, handler): handler.add_method_parameter( "get_metallicity", "set_metallicity", "metallicity", "Metallicity of all stats", default_value = 0.02 ) handler.add_method_parameter( "get_supernova_kick_velocity", "set_supernova_kick_velocity", "supernova_kick_velocity", "Kick velocity to compact handler formed in supernova", default_value = 600 | units.kms ) handler.add_method_parameter( "get_is_logging_of_evolve_enabled", "set_is_logging_of_evolve_enabled", "is_logging_of_evolve_enabled", "if True will log star state before and after evolve in starev.data", default_value = False ) self.stopping_conditions.define_parameters(handler) def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_star') handler.set_new('particles', 'new_particle') handler.set_delete('particles', 'delete_star') handler.add_getter('particles', 'get_radius', names = ('radius',)) handler.add_getter('particles', 'get_stellar_type', names = ('stellar_type',)) handler.add_getter('particles', 'get_mass', names = ('mass',)) handler.add_getter('particles', 'get_core_mass', names = ('core_mass',)) handler.add_getter('particles', 'get_COcore_mass', names = ('CO_core_mass',)) handler.add_getter('particles', 'get_envelope_mass', names = ('envelope_mass',)) handler.add_getter('particles', 'get_core_radius', names = ('core_radius',)) handler.add_getter('particles', 'get_age', names = ('age',)) handler.add_getter('particles', 'get_time_step', names = ('time_step',)) #handler.add_getter('particles', 'get_spin', names = ('spin',)) handler.add_getter('particles', 'get_luminosity', names = ('luminosity',)) handler.add_getter('particles', 'get_temperature', names = ('temperature',)) handler.add_getter('particles', 'get_natal_kick_velocity', names = ('natal_kick_x','natal_kick_y','natal_kick_z')) handler.add_getter('particles', 'get_convective_envelope_mass', names = ('convective_envelope_mass',)) handler.add_getter('particles', 'get_convective_envelope_radius', names = ('convective_envelope_radius',)) handler.add_getter('particles', 'get_gyration_radius', names = ('gyration_radius',)) handler.add_getter('particles', 'get_apsidal_motion_constant', names = ('apsidal_motion_constant',)) handler.add_getter('particles', 'get_zeta_thermal', names = ('zeta_thermal',)) handler.add_getter('particles', 'get_zeta_adiabatic', names = ('zeta_adiabatic',)) handler.add_getter('particles', 'get_rotation_period', names = ('rotation_period',)) handler.add_setter('particles', 'set_rotation_period', names = ('rotation_period',)) handler.add_getter('particles', 'get_relative_age', names = ('relative_age',)) handler.add_getter('particles', 'get_relative_mass', names = ('relative_mass',)) handler.add_getter('particles', 'get_wind_mass_loss_rate', names = ('wind_mass_loss_rate',)) handler.add_getter('particles', 'get_effective_radius', names = ('effective_radius',)) handler.add_method('particles', 'evolve_one_step') handler.add_method('particles', 'evolve_for') handler.add_method('particles', 'change_mass') handler.add_method('particles', 'refresh_memory') handler.add_method('particles', 'recall_memory_one_step') handler.add_method('particles', 'merge_with_other_star') handler.add_method('particles', 'get_fallback') handler.add_method('particles', 'get_time_step') handler.define_set('binaries', 'index_of_the_star') handler.set_new('binaries', 'new_binary') handler.set_delete('binaries', 'delete_binary') handler.add_getter('binaries', 'get_semi_major_axis', names = ('semi_major_axis',)) handler.add_getter('binaries', 'get_eccentricity', names = ('eccentricity',)) handler.add_getter('binaries', 'get_mass', names = ('mass',)) handler.add_getter('binaries', 'get_time_step', names = ('time_step',)) handler.add_getter('binaries', 'get_age', names = ('age',)) handler.add_getter("binaries", 'get_children_of_binary') handler.add_setter('binaries', 'set_semi_major_axis', names = ('semi_major_axis',)) handler.add_setter('binaries', 'set_eccentricity', names = ('eccentricity',)) handler.add_method('binaries', 'merge_the_binary') def define_state(self, handler): se.StellarEvolution.define_state(self, handler) self.stopping_conditions.define_state(handler) Seba = SeBa
45,633
38.95972
163
py
amuse
amuse-main/src/amuse/community/tupan/__init__.py
from .interface import Tupan
29
14
28
py
amuse
amuse-main/src/amuse/community/tupan/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 SinglePointGravityFieldInterface from amuse.community.interface.gd import GravityFieldCode from amuse.rfi.core import PythonCodeInterface import sys import os.path dirname=os.path.dirname(__file__) sys.path.append(os.path.join(dirname,"install","lib","python"+sys.version[:3],"site-packages")) try: from tupan.integrator import Integrator from tupan.particles.allparticles import ParticleSystem MODULES_MISSING = False except ImportError as ex: print(ex) MODULES_MISSING = True """ MyCodeImplementation is what needs to be adapted to each specific community code, MyCodeInterface and MyCode do not need to be changed for standard dynamics codes (except for changing the name). """ class TupanImplementation(object): def __init__(self): self.eta = 0.03125 self.current_time = 0.0 self.eps2 = 0.0 self.time_begin = 0.0 self.integrator_method = "sia21h.dkd" self.pn_order = 0 self.clight = None self.particles = [] self.particles_initialized = False def initialize_code(self): return 0 def cleanup_code(self): return 0 def commit_parameters(self): if not self.integrator_method in Integrator.PROVIDED_METHODS: msg = "Unknown integrator: {0}. Provided methods are: {1}." print(msg.format(self.integrator_method, Integrator.PROVIDED_METHODS)) return -1 if self.pn_order > 0 and self.clight is None: print("'clight' is None. Please set the speed of light " "parameter 'clight' when using 'pn_order' > 0.") return -1 return 0 def commit_particles(self): num = len(self.particles) ps = ParticleSystem(nstars=num) for (i, p) in enumerate(self.particles): ps.id[i] = i ps.mass[i] = p.mass ps.radius[i] = p.radius # XXX: 'radius' is not yet used in Tupan. ps.eps2[i] = self.eps2/2 ps.rx[i] = p.rx ps.ry[i] = p.ry ps.rz[i] = p.rz ps.vx[i] = p.vx ps.vy[i] = p.vy ps.vz[i] = p.vz self.integrator = Integrator(self.eta, self.time_begin, ps, method=self.integrator_method, pn_order=self.pn_order, clight=self.clight) return 0 def synchronize_model(self): return 0 def new_particle(self, index_of_the_particle, mass, radius, x, y, z, vx, vy, vz): ps = ParticleSystem(nstars=1) ps.mass[0] = mass ps.radius[0] = radius ps.rx[0] = x ps.ry[0] = y ps.rz[0] = z ps.vx[0] = vx ps.vy[0] = vy ps.vz[0] = vz self.particles.append(ps) index_of_the_particle.value = len(self.particles)-1 return 0 def set_state(self, index_of_the_particle, mass, radius, x, y, z, vx, vy, vz): try: i = index_of_the_particle ps = self.integrator.particle_system ps.mass[i] = mass ps.radius[i] = radius ps.rx[i] = x ps.ry[i] = y ps.rz[i] = z ps.vx[i] = vx ps.vy[i] = vy ps.vz[i] = vz return 0 except Exception as exc: print(str(exc)) return -1 def set_mass(self, index_of_the_particle, mass): try: i = index_of_the_particle ps = self.integrator.particle_system ps.mass[i] = mass return 0 except Exception as exc: print(str(exc)) return -1 def set_radius(self, index_of_the_particle, radius): try: i = index_of_the_particle ps = self.integrator.particle_system ps.radius[i] = radius return 0 except Exception as exc: print(str(exc)) return -1 def set_position(self, index_of_the_particle, x, y, z): try: i = index_of_the_particle ps = self.integrator.particle_system ps.rx[i] = x ps.ry[i] = y ps.rz[i] = z return 0 except: return -1 def set_velocity(self, index_of_the_particle, vx, vy, vz): try: i = index_of_the_particle ps = self.integrator.particle_system ps.vx[i] = vx ps.vy[i] = vy ps.vz[i] = vz return 0 except: return -1 def get_state(self, index_of_the_particle, mass, radius, x, y, z, vx, vy, vz): try: i = index_of_the_particle ps = self.integrator.particle_system mass.value = ps.mass[i] radius.value = ps.radius[i] x.value, y.value, z.value = ps.rx[i], ps.ry[i], ps.rz[i] vx.value, vy.value, vz.value = ps.vx[i], ps.vy[i], ps.vz[i] return 0 except: return -1 def get_mass(self, index_of_the_particle, mass): try: i = index_of_the_particle ps = self.integrator.particle_system mass.value = ps.mass[i] return 0 except: return -1 def get_radius(self, index_of_the_particle, radius): try: i = index_of_the_particle ps = self.integrator.particle_system radius.value = ps.radius[i] return 0 except: return -1 def get_position(self, index_of_the_particle, x, y, z): try: i = index_of_the_particle ps = self.integrator.particle_system x.value, y.value, z.value = ps.rx[i], ps.ry[i], ps.rz[i] return 0 except: return -1 def get_velocity(self, index_of_the_particle, vx, vy, vz): try: i = index_of_the_particle ps = self.integrator.particle_system vx.value, vy.value, vz.value = ps.vx[i], ps.vy[i], ps.vz[i] return 0 except: return -1 def get_kinetic_energy(self, kinetic_energy): ps = self.integrator.particle_system ke = ps.kinetic_energy kinetic_energy.value = ke return 0 def get_potential_energy(self, potential_energy): ps = self.integrator.particle_system pe = ps.potential_energy potential_energy.value = pe return 0 def get_total_mass(self, total_mass): ps = self.integrator.particle_system mtot = ps.total_mass total_mass.value = mtot return 0 def get_center_of_mass_position(self, x, y, z): ps = self.integrator.particle_system com_r = ps.com_r x.value, y.value, z.value = com_r return 0 def get_center_of_mass_velocity(self, vx, vy, vz): ps = self.integrator.particle_system com_v = ps.com_v vx.value, vy.value, vz.value = com_v return 0 def get_gravity_at_point(self, eps, x, y, z, ax, ay, az, length): ax.value = 0.0 ay.value = 0.0 az.value = 0.0 return -2 # Not implemented def get_potential_at_point(self, eps, x, y, z, phi, length): phi.value = 0.0 return -2 # Not implemented def evolve_model(self, t_end): while (abs(self.integrator.time) < abs(t_end)): self.integrator.evolve_step(t_end) self.current_time = self.integrator.time return 0 def set_eta(self, eta): self.eta = eta return 0 def get_eta(self, eta): eta.value = self.eta return 0 def set_time(self, time): self.current_time = time return 0 def get_time(self, time): time.value = self.current_time return 0 def set_eps2(self, epsilon_squared): self.eps2 = epsilon_squared return 0 def get_eps2(self, epsilon_squared): epsilon_squared.value = self.eps2 return 0 def set_begin_time(self, time_begin): self.time_begin = time_begin return 0 def get_begin_time(self, time_begin): time_begin.value = self.time_begin return 0 def set_integrator_method(self, integrator_method): self.integrator_method = integrator_method return 0 def get_integrator_method(self, integrator_method): integrator_method.value = self.integrator_method return 0 def set_pn_order(self, pn_order): self.pn_order = pn_order return 0 def get_pn_order(self, pn_order): pn_order.value = self.pn_order return 0 def set_clight(self, clight): self.clight = clight return 0 def get_clight(self, clight): clight.value = self.clight return 0 class TupanInterface(PythonCodeInterface, GravitationalDynamicsInterface, SinglePointGravityFieldInterface): def __init__(self, **options): PythonCodeInterface.__init__( self, TupanImplementation, 'tupan_worker', **options) @legacy_function def new_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, 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( 'vx', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'vy', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'vz', dtype='float64', direction=function.IN, description="The initial velocity vector of the particle") function.addParameter( 'radius', dtype='float64', direction=function.IN, description="The radius of the particle", default=0) function.result_type = 'int32' return function @legacy_function def set_eta(): function = LegacyFunctionSpecification() function.addParameter( 'eta', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta(): function = LegacyFunctionSpecification() function.addParameter( 'eta', 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_eps2(): function = LegacyFunctionSpecification() function.addParameter( 'epsilon_squared', dtype='float64', direction=function.IN) 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_integrator_method(): function = LegacyFunctionSpecification() function.addParameter( 'integrator_method', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_integrator_method(): function = LegacyFunctionSpecification() function.addParameter( 'integrator_method', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_pn_order(): function = LegacyFunctionSpecification() function.addParameter( 'pn_order', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_pn_order(): function = LegacyFunctionSpecification() function.addParameter( 'pn_order', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_clight(): function = LegacyFunctionSpecification() function.addParameter( 'clight', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_clight(): function = LegacyFunctionSpecification() function.addParameter( 'clight', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function class Tupan(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody=None, **options): nbody_interface = TupanInterface(**options) GravitationalDynamics.__init__( self, nbody_interface, convert_nbody, **options ) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) def define_parameters(self, handler): handler.add_method_parameter( "get_eta", "set_eta", "timestep_parameter", "timestep parameter", default_value=0.01 ) 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_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_integrator_method", "set_integrator_method", "integrator_method", "The method to use to integrate the evolution of the system", default_value="sia21h.dkd" ) handler.add_method_parameter( "get_pn_order", "set_pn_order", "pn_order", "Order of the Post-Newtonian corrections \ (choices: [0, 2, 4, 5, 6, 7])", default_value=0 ) handler.add_method_parameter( "get_clight", "set_clight", "clight", "Speed of light to use in post-Newtonian corrections", ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eta", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_eta", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_time", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_begin_time", (nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "get_begin_time", (), (nbody_system.time, 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_clight", (nbody_system.speed,), (handler.ERROR_CODE,) ) handler.add_method( "get_clight", (), (nbody_system.speed, handler.ERROR_CODE,) ) ### end of file ###
17,947
27.948387
95
py
amuse
amuse-main/src/amuse/community/krome/__init__.py
from .interface import Krome
29
14
28
py
amuse
amuse-main/src/amuse/community/krome/interface.py
import os.path from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community import * from amuse.support.options import option #(Grevesse & Sauval, 1998, Space Sci. Rev. 85, 161) solar_abundances= dict(H=1., HE=.085, C=3.31e-4, N=8.3e-5, O=6.76e-4, Ne=1.2e-4, SI=3.55e-5, Fe=3.2e-5) class KromeInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn): """ KROME - a package to embed chemistry in astrophysical simulations .. [#] Grassi, T.; Bovino, S.; Schleicher, D. R. G.; Prieto, J.; Seifried, D.; Simoncini, E.; Gianturco, F. A., MNRAS, 439, 3, p.2386-2419 [2014MNRAS.439.2386G] """ def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker = self.name_of_the_worker(), **options) LiteratureReferencesMixIn.__init__(self) def name_of_the_worker(self): return 'krome_worker' @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def commit_parameters(): function = LegacyFunctionSpecification() function.result_type = 'i' return function def recommit_parameters(): return self.commit_parameters() @legacy_function def recommit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.OUT) for x in ['number_density','temperature','ionrate']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['number_density','temperature','ionrate']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['number_density','temperature','ionrate']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('aid', dtype='i', direction=function.IN) function.addParameter('abundance', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('aid', dtype='i', direction=function.IN) function.addParameter('abundance', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_firstlast_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('first', dtype='i', direction=function.OUT) function.addParameter('last', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_index_of_species(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('name', dtype='s', direction=function.IN) function.addParameter('index', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_name_of_species(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index', dtype='i', direction=function.IN) function.addParameter('name', dtype='s', direction=function.OUT) 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_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.result_type = 'i' return function class Krome(CommonCode): def __init__(self,unit_converter = None, **options): if unit_converter is not None: raise Exception("krome uses predefined units") InCodeComponentImplementation.__init__(self, KromeInterface(**options)) first,last=self.get_firstlast_abundance() self.species=dict() for i in range(first,last+1): self.species[self.get_name_of_species(i)]=i-1 # self.set_data_directory(self.data_directory()) # self.set_output_directory(self.output_directory()) def define_properties(self, handler): handler.add_property('get_time', public_name = "model_time") def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method( 'evolve_model', ( units.s, ), ( handler.ERROR_CODE, ) ) handler.add_method( "new_particle", ( units.cm**-3, units.K, units.s**-1, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "set_state", ( handler.NO_UNIT, units.cm**-3, units.K, units.s**-1, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state", ( handler.INDEX, ), ( units.cm**-3, units.K, units.s**-1, handler.ERROR_CODE, ) ) handler.add_method( "get_abundance", ( handler.INDEX, handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "set_abundance", ( handler.INDEX, handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "delete_particle", ( handler.INDEX, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_firstlast_abundance", ( ), ( handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_time", ( ), ( units.s, handler.ERROR_CODE, ) ) def define_particle_sets(self, handler): handler.define_set('particles', 'id') 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_gridded_getter('particles', 'get_abundance','get_firstlast_abundance', names = ('abundances',)) handler.add_gridded_setter('particles', 'set_abundance','get_firstlast_abundance', names = ('abundances',)) def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','PARAMETER_CHANGE_A','invoke_state_change2') handler.add_transition('EDIT','PARAMETER_CHANGE_B','invoke_state_change2') handler.add_transition('PARAMETER_CHANGE_A','RUN','recommit_parameters') handler.add_transition('PARAMETER_CHANGE_B','EDIT','recommit_parameters') 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_method('RUN', 'evolve_model') handler.add_method('RUN', 'get_state') handler.add_method('RUN', 'get_abundance')
9,905
32.693878
164
py
amuse
amuse-main/src/amuse/community/mesa_r15140/patch_files.py
#!/usr/bin/env python3 import os import sys import subprocess import re PATCHESDIR = os.path.abspath("patches") QUILT_PC = ".pc" def execute_command_line(arguments, cwd=None): process = subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, text=True, ) stdoutstring, stderrstring = process.communicate() returncode = process.poll() return stdoutstring, stderrstring, returncode def which(executablename): stdoutstring, stderrstring, returncode = execute_command_line( ['which', executablename] ) if returncode != 0: return None return stdoutstring def is_quilt_installed(): return False path = which('quilt') if path is None: return False stdoutstring, stderrstring, returncode = execute_command_line( ['quilt', '--version'] ) if returncode != 0: return False version_re = re.compile(r'(\d).(\d\d)') match = version_re.match(stdoutstring) if not match: return False return True def apply_patches_using_quilt(): returncode = subprocess.call(['quilt', 'push', '-a']) if returncode != 0: raise Exception( "error in applying the patches, please apply by hand using" " quilt push" ) def undo_patches_using_quilt(): returncode = subprocess.call(['quilt', 'pop', '-a']) if returncode != 0: raise Exception( "error in undoing the patches, please undo by hand using" " quilt pop -a" ) def run_patch(patchname, patchfile, wd): arguments = ['patch', '-p1', '-i', patchfile] returncode = subprocess.call(arguments, cwd=wd) if returncode != 0: raise Exception(f"could not apply patch {patchname}") def apply_patches_using_patch(): with open("patches/series_mesa", "r") as f: lines = f.readlines() patches = [x.strip() for x in lines] patches = [x for x in patches if len(x) > 0] for patch in patches: path = os.path.join(PATCHESDIR, patch) print(patch, path, os.environ['MESA_DIR']) run_patch(patch, path, os.environ['MESA_DIR']) with open("patches/series_deps", "r") as f: lines = f.readlines() patches = [x.strip() for x in lines] patches = [x for x in patches if len(x) > 0] for patch in patches: path = os.path.join(PATCHESDIR, patch) run_patch( patch, path, os.path.join(os.environ['MESA_DIR'], '../') ) def main(undo_patches=False): print("checking if quilt is installed ... ", end=' ') if not is_quilt_installed(): print("no") if undo_patches: print("quilt is not installed, cannot undo the patches") sys.exit(1) else: print("applying patches to source code") apply_patches_using_patch() else: print("yes") if undo_patches: print("quilt is install, will try to undo the patches") undo_patches_using_quilt() else: print("applying patches to source code") apply_patches_using_quilt() print("all patches applied") if __name__ == '__main__': main()
3,233
25.508197
75
py
amuse
amuse-main/src/amuse/community/mesa_r15140/download.py
#!/usr/bin/env python import subprocess import os import urllib.request import urllib.parse import urllib.error from shutil import which from optparse import OptionParser import stat class GetCodeFromHttp: filename_template = "mesa-r{version}.zip" url_template = '' version = "" zip=True unpack=True def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename): print(f"unpacking {filename}") if self.unpack: if self.zip: arguments = ['unzip'] else: arguments = ['tar', 'xvf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) print("done") def start(self): if not os.path.exists('src'): os.mkdir('src') url = self.url_template.format(version=self.version) filename = self.filename_template.format(version=self.version) filepath = os.path.join(self.src_directory(), filename) print(f"downloading version {self.version} from {url} to {filename}") if which('wget') is not None: arguments = ['wget', '--user-agent="Mozilla"', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) elif which('curl') is not None: arguments = ['curl', '-L', '-O', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) else: urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file(filename) def make_exectuable(filename): st = os.stat(filename) os.chmod(filename, st.st_mode | stat.S_IEXEC) def get_crmath(): instance = GetCodeFromHttp() instance.url_template = 'https://github.com/rhdtownsend/crmath/archive/{version}.zip' instance.filename_template='{version}.zip' instance.version = 'v1.2' instance.start() def get_crlibm(): instance = GetCodeFromHttp() instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/crlibm-{version}.tar.gz' instance.filename_template='crlibm-{version}.tar.gz' instance.version = '1.0beta4' instance.zip = False instance.start() def get_fpx3deps(): instance = GetCodeFromHttp() instance.url_template = 'https://raw.githubusercontent.com/rhdtownsend/sdk2/master/profile/common/fpx3/fpx3_deps' instance.filename_template='fpx3_deps' instance.version = '' instance.zip = False instance.unpack = False instance.start() def get_fpx3(): instance = GetCodeFromHttp() instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/fpx3.tar.gz' instance.filename_template='fpx3.tar.gz' instance.version = '' instance.zip = False instance.start() def get_lapack95(): instance = GetCodeFromHttp() instance.url_template = 'http://www.astro.wisc.edu/~townsend/resource/download/sdk2/src/lapack95.tgz' instance.filename_template='lapack95.tgz' instance.version = '' instance.zip = False instance.start() def get_mesa(): instance = GetCodeFromHttp() if 'AMUSE_LOCAL_COPY_MESA' in os.environ: instance.url_template = os.environ['AMUSE_LOCAL_COPY_MESA'] else: instance.url_template = "https://zenodo.org/record/4311514/files/mesa-r{version}.zip" instance.version = '15140' instance.start() def get_hdf5(): instance = GetCodeFromHttp() instance.url_template = "https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-1.12/hdf5-{version}/src/hdf5-{version}.tar.bz2" instance.filename_template='hdf5-{version}.tar.bz2' instance.version = '1.12.0' instance.zip = False instance.start() def main(): get_lapack95() get_crmath() get_crlibm() get_fpx3() get_fpx3deps() get_hdf5() get_mesa() if __name__ == "__main__": main()
4,221
28.319444
128
py
amuse
amuse-main/src/amuse/community/mesa_r15140/interface.py
import os import numpy import tempfile from amuse.units import units from amuse.community import * from amuse.community import ( CodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories, LegacyFunctionSpecification, legacy_function, remote_function ) from amuse.community.interface.se import ( StellarEvolution, StellarEvolutionInterface, InternalStellarStructure, InternalStellarStructureInterface ) from amuse.support.interface import InCodeComponentImplementation from amuse.support.options import option class MESAInterface( CodeInterface, LiteratureReferencesMixIn, StellarEvolutionInterface, InternalStellarStructureInterface, CodeWithDataDirectories ): """ The software project MESA (Modules for Experiments in Stellar Astrophysics, http://mesa.sourceforge.net/) version 15140, aims to provide state-of-the-art, robust, and efficient open source modules, usable singly or in combination for a wide range of applications in stellar astrophysics. The AMUSE interface to MESA can create and evolve stars using the MESA/STAR module. All metallicities are supported, even the interesting case of Z=0. The supported stellar mass range is from about 1M_jupiter to >100 Msun. References: .. [#] ADS:2011ApJS..192....3P (Paxton, Bildsten, Dotter, Herwig, Lesaffre & Timmes 2011, ApJS) .. [#] ADS:2013ApJS..208....4P (Paxton, Cantiello, Arras, Bildsten, Brown, Dotter, Mankovich, Montgomery, Stello, Timmes, Townsend, 2013, ApJS) .. [#] ADS:2015ApJS..220...15P (Paxton, Marchant, Schwab, Bauer, Bildsten, Cantiello, Dessart, Farmer, Hu, Langer, Townsend, Townsley, Timmes, 2015, ApJS) .. [#] ADS:2018ApJS..234...34P (Paxton, Schwab, Bauer, Bildsten, Blinnikov, Duffell, Farmer, Goldberg, Marchant, Sorokina, Thoul, Townsend, Timmes, 2018, ApJS) .. [#] ADS:2019ApJS..243...10P (Paxton, Smolec, Schwab, Gautschy, Bildsten, Cantiello, Dotter, Farmer, Goldberg, Jermyn, Kanbur, Marchant, Thoul, Townsend, Wolf, Zhang, Timmes, 2019, ApJS) .. [#] http://mesa.sourceforge.net/ .. [#] https://docs.mesastar.org/en/latest/reference.html """ use_modules = ['amuse_mesa'] # Needs to keep sync with interface.f90 _CONTROL_NML = 0 _STAR_JOB_NML = 1 _EOS_NML = 2 _KAP_NML = 3 # Set in mesa_interface.f90 _M_CENTER = 0 _R_CENTER = 1 _L_CENTER = 2 _V_CENTER = 3 def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="mesa_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) self.mesa_version = "15140" @property def default_path_to_inlist(self): return '' @option(type="string", sections=('data')) def default_path_to_MESA(self): return os.path.join(self.amuse_root_directory, 'src', 'amuse', 'community', 'mesa_r15140', 'src', 'mesa-r15140') @option(type="string", sections=('data')) def default_path_to_MESA_data(self): return os.path.join(self.amuse_root_directory, 'src', 'amuse', 'community', 'mesa_r15140', 'src', 'mesa-r15140', 'data') @property def default_tmp_dir(self): """ This must be unique for each MESA star being run a time, as a place MESA can write temporay files to. It does not need persistance """ return tempfile.mkdtemp() @legacy_function def set_MESA_paths(): """ Set the paths to the MESA inlist and data directories. """ function = LegacyFunctionSpecification() function.addParameter( 'inlist_path', dtype='string', direction=function.IN, description="Path to the inlist file.") function.addParameter( 'mesa_dir', dtype='string', direction=function.IN, description="Path to the MESA directory.") function.addParameter( 'mesa_data_dir', dtype='string', direction=function.IN, description="Path to the MESA data directory. Normally this would be mesa_dir/data") function.addParameter( 'local_data_path', dtype='string', direction=function.IN, description="Path to the data directory.") function.addParameter( 'gyre_in_filename', dtype='string', direction=function.IN, description="Path to the gyre.in file.") function.addParameter( 'temp_dir', dtype='string', direction=function.IN, description="Unique per-MESA temporary folder") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @remote_function def get_maximum_number_of_stars(): """ Retrieve the maximum number of stars that can be handled by this instance. """ returns (maximum_number_of_stars='i') @legacy_function def new_pre_ms_particle(): """ Define a new pre-main-sequence star in the code. The star will start with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('mass', dtype='float64', direction=function.IN , description="The initial mass of the star") function.addParameter('num_steps', dtype='int32', direction=function.IN, default=-1 , description="Number of steps to take during pre-MS relaxation process. If negative uses MESA's default choice") function.result_type = 'int32' return function @legacy_function def new_pure_he_particle(): """ Define a new pure He star in the code. The star will start with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('mass', dtype='float64', direction=function.IN , description="The initial mass of the star") function.result_type = 'int32' return function @legacy_function def new_zams_particle(): """ Define a new ZAMS model with Z=0.02. The star will start with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('mass', dtype='float64', direction=function.IN , description="The initial mass of the star") function.result_type = 'int32' return function @legacy_function def load_model(): """ Load a pre-built MESA model (.mod file) """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('filename', dtype='string', direction=function.IN , description="The filename of the model to load") function.result_type = 'int32' return function @legacy_function def load_photo(): """ Load a MESA snapshot (photo file) """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT , description="The new index for the star. This index can be used to refer to this star in other functions") function.addParameter('filename', dtype='string', direction=function.IN , description="The filename of the photo to load") function.result_type = 'int32' return function @remote_function def save_photo(index_of_the_star='i', filename='s' ): returns () @remote_function def save_model(index_of_the_star='i', filename='s'): returns () @remote_function def set_time_step(index_of_the_star='i', time_step='d' | units.s): returns () @legacy_function def get_time_step(): """ Retrieve the current time step """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('time_step', dtype='float64', direction=function.OUT , description="Current timestep") function.result_type = 'int32' return function @legacy_function def get_core_mass(): """ Retrieve the current core mass of the star, where hydrogen abundance is <= h1_boundary_limit """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('core_mass', dtype='float64', direction=function.OUT , description="The current core mass of the star, where hydrogen abundance is <= h1_boundary_limit") function.result_type = 'int32' return function @remote_function(can_handle_array=True) def get_mass_loss_rate(index_of_the_star='i'): """ Retrieve the current mass loss rate of the star. (positive for winds, negative for accretion) """ returns (mass_change='d' | units.MSun/units.julianyr) @remote_function(can_handle_array=True) def get_manual_mass_transfer_rate(index_of_the_star='i'): """ Retrieve the current user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ returns (mass_change='d' | units.MSun/units.julianyr) @remote_function def set_manual_mass_transfer_rate(index_of_the_star='i', mass_change='d' | units.MSun/units.julianyr): """ Set a new user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ return () @legacy_function def get_id_of_species(): """ Retrieve the net_id of the chemical abundance variable of the star. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('species', dtype='string', direction=function.IN , description="The name of the isotope to get the name id of") function.addParameter('species_id', dtype='int32', direction=function.OUT , description="The net_id of the chemical abundance variable of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR The isotope was not found. """ return function @legacy_function def get_mass_of_species(): """ Retrieve the mass number of the species. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('species', dtype='int32', direction=function.IN , description="The species of the star to get the mass number of") function.addParameter('species_mass', dtype='float64', direction=function.OUT , description="The mass number of the chemical abundance variable of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR The species was not found """ return function @legacy_function def get_mass_fraction_of_species_at_zone(): """ Retrieve the mass number of the chemical abundance variable of the star at zone. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('species', dtype='int32', direction=function.IN , description="The species of the star to get the mass number of") function.addParameter('zone', dtype='int32', direction=function.IN , description="The zone of the star to get the mass number of") function.addParameter('species_mass', dtype='float64', direction=function.OUT , description="The mass number of the chemical abundance variable of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR The zone was not found -3 - ERROR The species was not found """ return function @legacy_function def get_name_of_species(): """ Retrieve the name of the species given by the species id """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('species', dtype='int32', direction=function.IN , description="The species of the star to get the mass number of") function.addParameter('species_name', dtype='string', direction=function.OUT , description="The name of the species.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value was retrieved. -1 - ERROR A star with the given index was not found. -2 - ERROR The species was not found """ return function @legacy_function def get_max_age_stop_condition(): """ Retrieve the current maximum age stop condition of this instance (in years). Evolution will stop once the star has reached this maximum age. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('max_age_stop_condition', dtype='float64', direction=function.OUT , description="The current maximum age stop condition of this instance (in years).") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was retrieved -1 - ERROR The code could not retrieve the value. """ return function @legacy_function def set_max_age_stop_condition(): """ Set the new maximum age stop condition of this instance (in years). Evolution will stop once the star has reached this maximum age. """ function = LegacyFunctionSpecification() function.addParameter('max_age_stop_condition', dtype='float64', direction=function.IN , description="The new maximum age stop condition of this instance (in years).") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR The code could not set the value. """ return function @legacy_function def get_min_timestep_stop_condition(): """ Retrieve the current minimum timestep stop condition of this instance (in years). Evolution will stop if the timestep required by the solver in order to converge has decreased below this minimum timestep. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('min_timestep_stop_condition', dtype='float64', direction=function.OUT , description="The current minimum timestep stop condition of this instance (in years).") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was retrieved -1 - ERROR The code could not retrieve the value. """ return function @legacy_function def set_min_timestep_stop_condition(): """ Set the new minimum timestep stop condition of this instance (in years). Evolution will stop if the timestep required by the solver in order to converge has decreased below this minimum timestep. """ function = LegacyFunctionSpecification() function.addParameter('min_timestep_stop_condition', dtype='float64', direction=function.IN , description="The new minimum timestep stop condition of this instance (in years).") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR The code could not set the value. """ return function @legacy_function def get_max_iter_stop_condition(): """ Retrieve the current maximum number of iterations of this instance. (Negative means no maximum) Evolution will stop after this number of iterations. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('max_iter_stop_condition', dtype='int32', direction=function.OUT , description="The current maximum number of iterations of this instance.") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was retrieved -1 - ERROR The code could not retrieve the value. """ return function @legacy_function def set_max_iter_stop_condition(): """ Set the new maximum number of iterations of this instance. (Negative means no maximum) Evolution will stop after this number of iterations. """ function = LegacyFunctionSpecification() function.addParameter('max_iter_stop_condition', dtype='int32', direction=function.IN , description="The new maximum number of iterations of this instance.") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR The code could not set the value. """ return function @legacy_function def _get_opt(): """ Users should not call this directly """ function = LegacyFunctionSpecification() function.name = 'get_opt' function.can_handle_array=True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('type', dtype='int32', direction=function.IN , description="Flag for which type of option to get") function.addParameter('name', dtype='string', direction=function.IN , description="Name of control parameter to get") function.addParameter('value', dtype='string', direction=function.OUT , description="The value of the parameter") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR The code could not set the value. """ return function @legacy_function def _set_opt(): """ Users should not call this directly """ function = LegacyFunctionSpecification() function.name = 'set_opt' function.can_handle_array=True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('type', dtype='int32', direction=function.IN , description="Flag for which type of option to get") function.addParameter('name', dtype='string', direction=function.IN , description="Name of control parameter to get") function.addParameter('value', dtype='string', direction=function.IN , description="The value of the parameter") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR The code could not set the value. """ return function def set_control(self, index_of_the_star, name, value): """ Sets a MESA control namelist value. """ v = self._val2str(value) return self._set_opt(index_of_the_star, self._CONTROL_NML, name, v) def get_control(self, index_of_the_star, name): """ Gets a MESA control namelist value. """ v = self._get_opt(index_of_the_star, self._CONTROL_NML, name) v['value'] = self._str2val(v['value']) return v def set_star_job(self, index_of_the_star, name, value): """ Sets a MESA star_job namelist value. """ v = self._val2str(value) return self._set_opt(index_of_the_star, self._STAR_JOB_NML, name, v) def get_star_job(self, index_of_the_star, name): """ Gets a MESA star_job namelist value. """ v = self._get_opt(index_of_the_star, self._STAR_JOB_NML, name) v['value'] = self._str2val(v['value']) return v def set_eos(self, index_of_the_star, name, value): """ Sets a MESA eos namelist value. """ v = self._val2str(value) return self._set_opt(index_of_the_star, self._EOS_NML, name, v) def get_eos(self, index_of_the_star, name): """ Gets a MESA eos namelist value. """ v = self._get_opt(index_of_the_star, self._EOS_NML, name) v['value'] = self._str2val(v['value']) return v def set_kap(self, index_of_the_star, name, value): """ Sets a MESA kap namelist value. """ v = self._val2str(value) return self._set_opt(index_of_the_star, self._KAP_NML, name, v) def get_kap(self, index_of_the_star, name): """ Gets a MESA kap namelist value. """ v = self._get_opt(index_of_the_star, self._KAP_NML, name) v['value'] = self._str2val(v['value']) return v def _val2str(self, value): if isinstance(value, bool): if value: return '.true.' else: return '.false.' elif isinstance(value, (int, float)): return str(value) else: if '"' not in value and "'" not in value: return '"'+str(value)+'"' else: return value def _str2val(self, value): def process(val): val = val.strip() if '.true.' in val.lower() or val == 'T': return True elif '.false.' in val.lower() or val == 'F': return False try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass return val if isinstance(value, (list, numpy.ndarray)): result = numpy.array([process(i) for i in value]) else: result = process(value) return result @legacy_function def set_mesa_value(): """ Sets a MESA variable given by name. If the variable is not an array then set zone=1 Not all variables are supported, addtional ones can be added to set_value() in mesa_interface.f90 """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('name', dtype='string', direction=function.IN , description="Name of the variable to set") function.addParameter('value', dtype='float64', direction=function.IN , description="Value to set to") function.addParameter('zone', dtype='int32', direction=function.IN , description="Zone if setting array ( must between 1 and s%nz)") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been set. -1 - ERROR An error occured -2 - ERROR The zone is out of bounds -3 - ERROR The named variable does not exist """ return function @legacy_function def get_mesa_value(): """ Gets a MESA variable given by name. If the variable is not an array then set zone=1 Not all variables are supported, addtional ones can be added to get_value() in mesa_interface.f90 """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('name', dtype='string', direction=function.IN , description="Name of the variable to get") function.addParameter('value', dtype='float64', direction=function.OUT , description="Value which has be gotten") function.addParameter('zone', dtype='int32', direction=function.IN , description="Zone if getting from an array (must between 1 and s%nz)") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been gotten. -1 - ERROR An error occured -2 - ERROR The zone is out of bounds -3 - ERROR The named variable does not exist """ return function @legacy_function def _get_center_value(): """ Gets one of the inner boundry conditions of mesa """ function = LegacyFunctionSpecification() function.name = 'get_center_value' function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('name', dtype='int32', direction=function.IN , description="Flag for which variable to get") function.addParameter('value', dtype='float64', direction=function.OUT , description="Value which has to be get") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been gotten. -1 - ERROR An error occured -3 - ERROR The named variable does not exist """ return function @legacy_function def _set_center_value(): """ Sets one of the inner boundry conditions of mesa """ function = LegacyFunctionSpecification() function.name = 'set_center_value' function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('name', dtype='int32', direction=function.IN , description="Flag for which variable to set") function.addParameter('value', dtype='float64', direction=function.IN , description="Value which has to be set") function.result_type = 'int32' function.result_doc = """ 0 - OK The value has been gotten. -1 - ERROR An error occured -3 - ERROR The named variable does not exist """ return function def set_m_center(self, index_of_the_star, value): """ Sets the inner mass boundary """ return self._set_center_value(index_of_the_star, self._M_CENTER, value) def get_m_center(self, index_of_the_star): """ Gets the inner mass boundary """ return self._get_center_value(index_of_the_star, self._M_CENTER) def set_r_center(self, index_of_the_star, value): """ Sets the inner radius boundary """ return self._set_center_value(index_of_the_star, self._R_CENTER, value) def get_r_center(self, index_of_the_star): """ Gets the inner radius boundary """ return self._get_center_value(index_of_the_star, self._R_CENTER) def set_l_center(self, index_of_the_star, value ): """ Sets the inner luminosity boundary """ return self._set_center_value(index_of_the_star, self._L_CENTER, value) def get_l_center(self, index_of_the_star): """ Gets the inner luminosity boundary """ return self._get_center_value(index_of_the_star, self._L_CENTER) def set_v_center(self, index_of_the_star, value ): """ Sets the inner velocity boundary """ return self._set_center_value(index_of_the_star, self._V_CENTER, value) def get_v_center(self, index_of_the_star): """ Sets the inner velocity boundary """ return self._get_center_value(index_of_the_star, self._V_CENTER) @legacy_function def new_stellar_model(): """ Define a new star model in the code. Arrays should be in MESA order (surface =1 center=n) """ function = LegacyFunctionSpecification() function.must_handle_array = True for par in ['star_mass', 'dq', 'rho', 'temperature', 'XH1', 'XHe3', 'XHe4', 'XC12', 'XN14', 'XO16', 'XNe20', 'XMg24', 'XSi28', 'XS32', 'XAr36', 'XCa40', 'XTi44', 'XCr48', 'XFe52', 'XFe54', 'XFe56', 'XCr56', 'XNi56', 'prot', 'neut']: function.addParameter(par, dtype='float64', direction=function.IN) function.addParameter('n', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def finalize_stellar_model(): """ Finalize the new star model defined by 'new_stellar_model'. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT, description="The new index for the star. " "This index can be used to refer to this star in other functions") function.addParameter('age_tag', dtype='float64', direction=function.IN, description="The initial age of the star") function.result_type = 'int32' return function @remote_function(can_handle_array=True) def get_profile_at_zone(index_of_the_star='i', zone='i', name='s'): """ Retrieve arbitary profile column at the specified zone/mesh-cell of the star. """ returns (value='d') @remote_function(can_handle_array=True) def get_history(index_of_the_star='i', name='s'): """ Retrieve arbitary history column of the star. """ returns (value='d') @remote_function def star_job_update(index_of_the_star='i'): """ After changing options in star_job this function must be called to make the changes to the star """ returns () @remote_function def get_nuclear_network(index_of_the_star='i'): """ Retrieve the current nuclear network of the star. """ returns (net_name='s') @remote_function def set_nuclear_network(index_of_the_star='i', net_name='s'): """ Set the current nuclear network of the star. """ returns () @remote_function(can_handle_array=True) def get_age(index_of_the_star='i'): """ Retrieve the current age of the star """ returns (age='d' | units.julianyr) @remote_function def set_age(index_of_the_star='i', new_age='d' | units.julianyr): """ Set the current age of the star """ returns () def get_radius_at_zone(self, index_of_the_star, zone): return self.get_profile_at_zone(index_of_the_star, zone, 'radius') def get_temperature_at_zone(self, index_of_the_star, zone): return self.get_profile_at_zone(index_of_the_star, zone, 'temperature') def get_density_at_zone(self, index_of_the_star, zone): return self.get_profile_at_zone(index_of_the_star, zone, 'density') def get_pressure_at_zone(self, index_of_the_star, zone): return self.get_profile_at_zone(index_of_the_star, zone, 'pressure') def get_mu_at_zone(self, index_of_the_star, zone): return self.get_profile_at_zone(index_of_the_star, zone, 'mu') def get_mass_fraction_of_species_at_zone(self, index_of_the_star, species, zone): res = self.get_name_of_species(index_of_the_star, species) if all(numpy.atleast_1d(res['__result'])) == 0: return self.get_profile_at_zone(index_of_the_star, zone, res['species_name']) else: return res['__result'] def get_accrete_same_as_surface(self, index_of_the_star): return self.get_control(index_of_the_star,'accrete_same_as_surface') def set_accrete_same_as_surface(self, index_of_the_star, value): return self.set_control(index_of_the_star,'accrete_same_as_surface', value) @legacy_function def _get_gyre(): """ Get gyre data. Dont call this directly use get_gyre() """ function = LegacyFunctionSpecification() function.name = 'get_gyre' function.addParameter('index_of_the_star', dtype='int32', direction=function.IN, description="The index for the star. ") function.addParameter('mode_l', dtype='int32', direction=function.IN, description="L mode to find (must match that in gyre.in) ") function.addParameter('add_center_point', dtype='bool', direction=function.IN, description="Whether to add center point") function.addParameter('keep_surface_pointt', dtype='bool', direction=function.IN, description="Whether to keep surface point") function.addParameter('add_atmosphere', dtype='bool', direction=function.IN, description="Whether to add atmosphere") function.addParameter('fileout', dtype='string', direction=function.IN, description="Filename to store data at each radial point") function.result_type = 'int32' return function def get_gyre(self, index_of_the_star, mode_l=0, add_center_point=False, keep_surface_point=False, add_atmosphere=False): """ Get gyre data. This returns a list of dicts where each element of the list corresponds to one mode Each dict contains the pg,p,g and complex frequency for the mode as well as arrays of r/R, xi_r, xi_h, and dwdx for the mode """ _, filename = tempfile.mkstemp() res = self._get_gyre(index_of_the_star, mode_l, add_center_point, keep_surface_point, add_atmosphere, filename) if res != 0: os.remove(filename) return res res = [] with open(filename, 'r') as f: while True: line = f.readline() if len(line) == 0: break pg, p, g, nk, fr, fi = line.split() nk = int(nk) data = numpy.zeros((nk, 7)) for i in range(nk): data[i, :] = [float(j) for j in f.readline().split()] # Repack data into arrays with complex quantities k = data[:, 0].astype('int') r = data[:, 1] xi_r = data[:, 2] + 1j*data[:, 3] xi_h = data[:, 4] + 1j*data[:, 5] dwdx = data[:, 6] res.append({'pg': int(pg), 'p': int(p), 'g': int(g), 'freq': complex(float(fr), float(fi)), 'r/R': r, 'xi_r': xi_r, 'xi_h': xi_h, 'dwdx': dwdx}) os.remove(filename) return res def get_mixing_length_ratio(self,index_of_the_star): """ Retrieve the current mixing_length_ratio of the star. """ return self.get_control(index_of_the_star,'mixing_length_alpha') def set_mixing_length_ratio(self,index_of_the_star, mixing_length_ratio): """ Sets the current mixing_length_ratio of the star. """ return self.set_control(index_of_the_star,'mixing_length_alpha',mixing_length_ratio) def get_semi_convection_efficiency(self,index_of_the_star): """ Retrieve the current semi_convection_efficiency of the star. """ return self.get_control(index_of_the_star,'alpha_semiconvection') def set_semi_convection_efficiency(self,index_of_the_star, semi_convection_efficiency): """ Sets the current semi_convection_efficiency of the star and turns on semiconvection. """ self.set_control(index_of_the_star,'use_Ledoux_criterion',True) return self.set_control(index_of_the_star,'alpha_semiconvection',semi_convection_efficiency) def get_RGB_wind_scheme(self, index_of_the_star): """ Retrieve the current RGB wind scheme """ return self.get_control(index_of_the_star,'cool_wind_RGB_scheme') def set_RGB_wind_scheme(self, index_of_the_star, cool_wind_RGB_scheme): """ Set the current RGB wind scheme """ return self.set_control(index_of_the_star,'cool_wind_RGB_scheme',cool_wind_RGB_scheme) def get_AGB_wind_scheme(self, index_of_the_star): """ Retrieve the current AGB wind scheme """ return self.get_control(index_of_the_star,'cool_wind_AGB_scheme') def set_AGB_wind_scheme(self, index_of_the_star, cool_wind_AGB_scheme): """ Set the current RGB wind scheme """ return self.set_control(index_of_the_star,'cool_wind_AGB_scheme',cool_wind_AGB_scheme) def get_reimers_wind_efficiency(self, index_of_the_star): """ Retrieve the current reimers_wind_efficiency """ return self.get_control(index_of_the_star,'reimers_scaling_factor') def set_reimers_wind_efficiency(self, index_of_the_star, reimers_wind_efficiency): """ Set the current reimers_wind_efficiency """ return self.set_control(index_of_the_star,'reimers_scaling_factor',reimers_wind_efficiency) def get_blocker_wind_efficiency(self, index_of_the_star): """ Retrieve the current blocker_wind_efficiency """ return self.get_control(index_of_the_star,'blocker_scaling_factor') def set_blocker_wind_efficiency(self, index_of_the_star, blocker_wind_efficiency): """ Set the current blocker_wind_efficiency """ return self.set_control(index_of_the_star,'blocker_scaling_factor',blocker_wind_efficiency) def get_de_jager_wind_efficiency(self, index_of_the_star): """ Retrieve the current de_jager_wind_efficiency """ return self.get_control(index_of_the_star,'de_jager_scaling_factor') def set_de_jager_wind_efficiency(self, index_of_the_star, de_jager_wind_efficiency): """ Set the current de_jager_wind_efficiency """ return self.set_control(index_of_the_star,'de_jager_scaling_factor',de_jager_wind_efficiency) def get_dutch_wind_efficiency(self, index_of_the_star): """ Retrieve the current dutch_wind_efficiency """ return self.get_control(index_of_the_star,'dutch_scaling_factor') def set_dutch_wind_efficiency(self, index_of_the_star, dutch_wind_efficiency): """ Set the current dutch_wind_efficiency """ return self.set_control(index_of_the_star,'dutch_scaling_factor',dutch_wind_efficiency) def get_accrete_composition_non_metals(self, index_of_the_star): h1 = self.get_control(index_of_the_star,'accretion_h1') h2 = self.get_control(index_of_the_star,'accretion_h2') he3 = self.get_control(index_of_the_star,'accretion_he3') he4 = self.get_control(index_of_the_star,'accretion_he4') return [{'h1':h1['value'], 'h2': h2['value'], 'he3': he3['value'], 'he4': he4['value'], }] def set_accrete_composition_non_metals(self,index_of_the_star,h1=0.0,h2=0.0,he3=0.0,he4=0.0): self.set_control(index_of_the_star,'accretion_h1',h1) self.set_control(index_of_the_star,'accretion_h2',h2) self.set_control(index_of_the_star,'accretion_he3',he3) return self.set_control(index_of_the_star,'accretion_he4',he4) def get_accrete_composition_metals_identifier(self, index_of_the_star): return self.get_control(index_of_the_star,'accretion_zfracs') def set_accrete_composition_metals_identifier(self, index_of_the_star, zfracs): return self.set_control(index_of_the_star,'accretion_zfracs',zfracs) def get_accrete_composition_metals(self, index_of_the_star): result = {} for element in ['li','be','b','c','n','o','f','ne','na','mg','al','si','p', 's','cl','ar','k','ca','sc','ti','v','cr','mn','fe', 'co','ni','cu','zn']: r = self.get_control(index_of_the_star,f'z_fraction_{element}') result[element] = r['value'] return result def set_accrete_composition_metals(self, index_of_the_star, **kwargs): ''' Sets the accretion composition based on the following elements: 'li','be','b','c','n','o','f','ne','na','mg','al','si','p' 's','cl','ar','k','ca','sc','ti','v','cr','mn','fe', 'co','ni','cu','zn' Thus to set the li accretion fraction to 1/2 then pass li=0.5 If an element is not set then its left with its current value These must sum to 1.0 (the total z fraction is set by setting the non_metals to the 1-Z value) ''' result = {} for element,value in kwargs.items(): if element not in ['li','be','b','c','n','o','f','ne','na','mg','al','si','p', 's','cl','ar','k','ca','sc','ti','v','cr','mn','fe', 'co','ni','cu','zn']: raise ValueError(f"Bad element {element}") r = self.set_control(index_of_the_star,f'z_fraction_{element}',value) return r @legacy_function def solve_one_step(): """ Takes one step forward, but does not handle retries or redo's. Must call solve_one_step_pre first and solve_one_step_post afterwards """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('first_try', dtype='bool', direction=function.IN , description="If this is the first attempt at taking this timestep") function.addParameter('result', dtype='int32', direction=function.OUT , description="What the star should do next (keep going, redo, retry, terminate)") function.result_type = 'int32' return function @legacy_function def solve_one_step_pre(): """ Prepares to takes one step forward, but does not handle retries or redo's. Called before solve_one_step """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('result', dtype='int32', direction=function.OUT , description="What the star should do next (keep going, redo, retry, terminate)") function.result_type = 'int32' return function @legacy_function def solve_one_step_post(): """ After taking one step forward cleanup the model, but does not handle retries or redo's. Called after solve_one_step """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('result', dtype='int32', direction=function.OUT , description="What the star should do next (keep going, redo, retry, terminate)") function.result_type = 'int32' return function @legacy_function def prepare_retry_step(): """ Prepares to retry a step with a new dt. Does not actually take the step """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('dt_next', dtype='float64', direction=function.IN , description="New timestep to try") function.addParameter('result', dtype='int32', direction=function.OUT , description="What the star should do next (keep going, redo, retry, terminate)") function.result_type = 'int32' return function @legacy_function def prepare_redo_step(): """ Prepares to redo a step (a step with the same dt but where you have changed other options like the mdot) Does not actually take the step """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_star', dtype='int32', direction=function.IN , description="The index of the star to get the value of") function.addParameter('result', dtype='int32', direction=function.OUT , description="What the star should do next (keep going, redo, retry, terminate)") function.result_type = 'int32' return function class MESA(StellarEvolution, InternalStellarStructure): def __init__(self, **options): InCodeComponentImplementation.__init__(self, MESAInterface(**options), **options) output_dir = self.get_output_directory() if 'inlist' in options: inlist = options['inlist'] if not os.path.exists(inlist): raise ValueError('Named inlist does not exist, maybe its in a different folder?') else: inlist = self.default_path_to_inlist if 'gyre_in' in options: gyre_in = options['gyre_in'] else: gyre_in = '' self.set_MESA_paths( inlist, self.default_path_to_MESA, self.default_path_to_MESA_data, output_dir, gyre_in, self.default_tmp_dir ) self.model_time = 0.0 | units.julianyr self.mesa_version = "15140" def define_parameters(self, handler): handler.add_method_parameter( "get_metallicity", "set_metallicity", "metallicity", "Metallicity of all stars", default_value=0.02 ) handler.add_method_parameter( "get_max_age_stop_condition", "set_max_age_stop_condition", "max_age_stop_condition", "The maximum age stop condition of this instance.", default_value=1.0e36 | units.julianyr ) handler.add_method_parameter( "get_min_timestep_stop_condition", "set_min_timestep_stop_condition", "min_timestep_stop_condition", "The minimum timestep stop condition of this instance.", default_value=1.0e-6 | units.s ) handler.add_method_parameter( "get_max_iter_stop_condition", "set_max_iter_stop_condition", "max_iter_stop_condition", "The maximum number of iterations of this instance. (Negative means no maximum)", default_value=-1111 ) def define_particle_sets(self, handler): star_types = ['native_stars', 'pre_ms_stars', 'pre_built_stars', 'pure_he_stars', 'imported_stars','photo_stars', ] handler.define_super_set('particles', star_types, index_to_default_set=0) handler.define_set('imported_stars', 'index_of_the_star') handler.set_new('imported_stars', 'finalize_stellar_model') handler.set_delete('imported_stars', 'delete_star') handler.define_set('native_stars', 'index_of_the_star') handler.set_new('native_stars', 'new_zams_particle') handler.set_delete('native_stars', 'delete_star') handler.define_set('pre_ms_stars', 'index_of_the_star') handler.set_new('pre_ms_stars', 'new_pre_ms_particle') handler.set_delete('pre_ms_stars', 'delete_star') handler.define_set('pre_built_stars', 'index_of_the_star') handler.set_new('pre_built_stars', 'load_model') handler.set_delete('pre_built_stars', 'delete_star') handler.define_set('photo_stars', 'index_of_the_star') handler.set_new('photo_stars', 'load_photo') handler.set_delete('photo_stars', 'delete_star') handler.define_set('pure_he_stars', 'index_of_the_star') handler.set_new('pure_he_stars', 'new_pure_he_particle') handler.set_delete('pure_he_stars', 'delete_star') for particle_set_name in star_types: handler.add_getter(particle_set_name, 'get_radius', names=('radius',)) handler.add_getter(particle_set_name, 'get_stellar_type', names=('stellar_type',)) handler.add_getter(particle_set_name, 'get_mass', names=('mass',)) handler.add_setter(particle_set_name, 'set_mass', names=('mass',)) handler.add_getter(particle_set_name, 'get_core_mass', names=('core_mass',)) handler.add_getter(particle_set_name, 'get_mass_loss_rate', names=('wind',)) handler.add_getter(particle_set_name, 'get_age', names=('age',)) handler.add_setter(particle_set_name, 'set_age', names=('age',)) handler.add_getter(particle_set_name, 'get_time_step', names=('time_step',)) handler.add_setter(particle_set_name, 'set_time_step', names=('time_step',)) handler.add_getter(particle_set_name, 'get_luminosity', names=('luminosity',)) handler.add_getter(particle_set_name, 'get_temperature', names=('temperature',)) handler.add_getter(particle_set_name, 'get_manual_mass_transfer_rate', names=('mass_change',)) handler.add_setter(particle_set_name, 'set_manual_mass_transfer_rate', names=('mass_change',)) handler.add_getter(particle_set_name, 'get_m_center', names=('m_center',)) handler.add_setter(particle_set_name, 'set_m_center', names=('m_center',)) handler.add_getter(particle_set_name, 'get_r_center', names=('r_center',)) handler.add_setter(particle_set_name, 'set_r_center', names=('r_center',)) handler.add_getter(particle_set_name, 'get_l_center', names=('l_center',)) handler.add_setter(particle_set_name, 'set_l_center', names=('l_center',)) handler.add_getter(particle_set_name, 'get_v_center', names=('v_center',)) handler.add_setter(particle_set_name, 'set_v_center', names=('v_center',)) handler.add_method(particle_set_name, 'get_control') handler.add_method(particle_set_name, 'set_control') handler.add_method(particle_set_name, 'get_star_job') handler.add_method(particle_set_name, 'set_star_job') handler.add_method(particle_set_name, 'star_job_update') handler.add_method(particle_set_name, 'get_eos') handler.add_method(particle_set_name, 'set_eos') handler.add_method(particle_set_name, 'get_kap') handler.add_method(particle_set_name, 'set_kap') handler.add_method(particle_set_name, 'get_mesa_value') handler.add_method(particle_set_name, 'set_mesa_value') handler.add_method(particle_set_name, 'get_extra_heat') handler.add_method(particle_set_name, 'set_extra_heat') handler.add_method(particle_set_name, 'get_nuclear_network') handler.add_method(particle_set_name, 'set_nuclear_network') handler.add_method(particle_set_name, 'evolve_one_step') handler.add_method(particle_set_name, 'evolve_for') InternalStellarStructure.define_particle_sets( self, handler, set_name=particle_set_name ) handler.add_method(particle_set_name, 'get_mass_profile') handler.add_method(particle_set_name, 'set_mass_profile') handler.add_method(particle_set_name, 'get_cumulative_mass_profile') handler.add_method(particle_set_name, 'get_luminosity_profile') handler.add_method(particle_set_name, 'set_luminosity_profile') handler.add_method(particle_set_name, 'get_entropy_profile') handler.add_method(particle_set_name, 'get_thermal_energy_profile') handler.add_method(particle_set_name, 'get_brunt_vaisala_frequency_squared_profile') handler.add_method(particle_set_name, 'get_profile') handler.add_method(particle_set_name, 'get_history') handler.add_method(particle_set_name, 'get_mesa_value_profile') handler.add_method(particle_set_name, 'set_mesa_value_profile') handler.add_method(particle_set_name, 'get_name_of_species') handler.add_method(particle_set_name, 'get_mass_of_species') handler.add_method(particle_set_name, 'get_masses_of_species') handler.add_method(particle_set_name, 'get_mass_fraction_of_species_at_zone') handler.add_method(particle_set_name, 'get_id_of_species') handler.add_method(particle_set_name, 'get_IDs_of_species') handler.add_method(particle_set_name, 'get_gyre') handler.add_method(particle_set_name, 'get_accrete_same_as_surface') handler.add_method(particle_set_name, 'set_accrete_same_as_surface') handler.add_method(particle_set_name, 'get_accrete_composition_non_metals') handler.add_method(particle_set_name, 'set_accrete_composition_non_metals') handler.add_method(particle_set_name, 'get_accrete_composition_metals_identifier') handler.add_method(particle_set_name, 'set_accrete_composition_metals_identifier') handler.add_method(particle_set_name, 'get_accrete_composition_metals') handler.add_method(particle_set_name, 'set_accrete_composition_metals') handler.add_method(particle_set_name, 'save_photo') handler.add_method(particle_set_name, 'save_model') handler.add_method(particle_set_name, 'get_RGB_wind_scheme') handler.add_method(particle_set_name, 'set_RGB_wind_scheme') handler.add_method(particle_set_name, 'get_AGB_wind_scheme') handler.add_method(particle_set_name, 'set_AGB_wind_scheme') handler.add_method(particle_set_name, 'get_reimers_wind_efficiency') handler.add_method(particle_set_name, 'set_reimers_wind_efficiency') handler.add_method(particle_set_name, 'get_de_jager_wind_efficiency') handler.add_method(particle_set_name, 'set_de_jager_wind_efficiency') handler.add_method(particle_set_name, 'get_dutch_wind_efficiency') handler.add_method(particle_set_name, 'set_dutch_wind_efficiency') handler.add_method(particle_set_name, 'get_blocker_wind_efficiency') handler.add_method(particle_set_name, 'set_blocker_wind_efficiency') handler.add_method(particle_set_name, 'solve_one_step') handler.add_method(particle_set_name, 'solve_one_step_pre') handler.add_method(particle_set_name, 'solve_one_step_post') handler.add_method(particle_set_name, 'prepare_retry_step') handler.add_method(particle_set_name, 'prepare_redo_step') def define_state(self, handler): StellarEvolution.define_state(self, handler) handler.add_method('EDIT', 'new_pre_ms_particle') handler.add_method('UPDATE', 'new_pre_ms_particle') handler.add_transition('RUN', 'UPDATE', 'new_pre_ms_particle', False) handler.add_transition('RUN', 'UPDATE', 'load_photo', False) handler.add_method('EDIT', 'finalize_stellar_model') handler.add_method('UPDATE', 'finalize_stellar_model') handler.add_transition('RUN', 'UPDATE', 'finalize_stellar_model', False) def define_errorcodes(self, handler): InternalStellarStructure.define_errorcodes(self, handler) handler.add_errorcode(-1, 'Something went wrong...') handler.add_errorcode(-4, 'Not implemented.') handler.add_errorcode(-11, 'Evolve terminated: Unspecified stop condition reached.') handler.add_errorcode(-12, 'Evolve terminated: Maximum age reached.') handler.add_errorcode(-13, 'Evolve terminated: Maximum number of iterations reached.') handler.add_errorcode(-15, 'Evolve terminated: Minimum timestep limit reached.') handler.add_errorcode(-99, 'GYRE not configured for use') def define_methods(self, handler): InternalStellarStructure.define_methods(self, handler) StellarEvolution.define_methods(self, handler) handler.add_method( "new_pre_ms_particle", (units.MSun, units.none), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "new_zams_particle", (units.MSun), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "new_pure_he_particle", (units.MSun), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "load_model", (handler.NO_UNIT), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "load_photo", (handler.NO_UNIT), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "save_model", (handler.INDEX,handler.NO_UNIT), (handler.ERROR_CODE) ) handler.add_method( "save_photo", (handler.INDEX,handler.NO_UNIT), (handler.ERROR_CODE) ) handler.add_method( "set_time_step", (handler.INDEX, units.s), (handler.ERROR_CODE,) ) handler.add_method( "get_time_step", (handler.INDEX,), (units.s, handler.ERROR_CODE,) ) handler.add_method( "get_core_mass", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "get_mass_loss_rate", (handler.INDEX,), (units.MSun / units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "get_manual_mass_transfer_rate", (handler.INDEX,), (units.MSun / units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "set_manual_mass_transfer_rate", (handler.INDEX, units.MSun / units.julianyr), (handler.ERROR_CODE,) ) handler.add_method( "get_profile_at_zone", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_history", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_id_of_species", (handler.INDEX, handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_mass_of_species", (handler.INDEX, handler.NO_UNIT,), (units.amu, handler.ERROR_CODE,) ) handler.add_method( "new_stellar_model", (units.MSun, handler.NO_UNIT, units.g / units.cm**3, units.K, 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.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.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_star_age", (handler.INDEX,), (units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "set_star_age", (handler.INDEX, units.julianyr), (handler.ERROR_CODE,) ) handler.add_method( "get_age", (handler.INDEX,), (units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "evolve_for", (handler.INDEX, units.julianyr), (handler.ERROR_CODE,) ) handler.add_method( "get_max_age_stop_condition", (), (units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "set_max_age_stop_condition", (units.julianyr, ), (handler.ERROR_CODE,) ) handler.add_method( "get_min_timestep_stop_condition", (), (units.s, handler.ERROR_CODE,) ) handler.add_method( "set_min_timestep_stop_condition", (units.s, ), (handler.ERROR_CODE,) ) handler.add_method( "get_max_iter_stop_condition", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_max_iter_stop_condition", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_accrete_same_as_surface", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_accrete_same_as_surface", (handler.INDEX,handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_name_of_species", (handler.INDEX, handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_kap", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_kap", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_eos", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_eos", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_control", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_control", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_star_job", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_star_job", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "star_job_update", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "get_mesa_value", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mesa_value", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "set_age", (handler.INDEX,), (units.julianyr, handler.ERROR_CODE,) ) handler.add_method( "set_age", (handler.INDEX, units.julianyr), (handler.ERROR_CODE,) ) handler.add_method( "get_nuclear_network", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_nuclear_network", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "finalize_stellar_model", (units.julianyr,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "get_m_center", (handler.INDEX,), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "set_m_center", (handler.INDEX, units.MSun), (handler.ERROR_CODE,) ) handler.add_method( "get_r_center", (handler.INDEX,), (units.cm, handler.ERROR_CODE,) ) handler.add_method( "set_r_center", (handler.INDEX, units.cm), (handler.ERROR_CODE,) ) handler.add_method( "get_l_center", (handler.INDEX,), (units.erg/units.s, handler.ERROR_CODE,) ) handler.add_method( "set_l_center", (handler.INDEX, units.erg/units.s), (handler.ERROR_CODE,) ) handler.add_method( "get_v_center", (handler.INDEX,), (units.cm/units.s, handler.ERROR_CODE,) ) handler.add_method( "set_v_center", (handler.INDEX, units.cm/units.s), (handler.ERROR_CODE,) ) handler.add_method( "get_gyre", (handler.INDEX, 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.add_method( "get_mixing_length_ratio", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_mixing_length_ratio", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_semi_convection_efficiency", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_semi_convection_efficiency", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_reimers_wind_efficiency", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_reimers_wind_efficiency", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_dutch_wind_efficiency", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_dutch_wind_efficiency", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_de_jager_wind_efficiency", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_de_jager_wind_efficiency", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "get_blocker_wind_efficiency", (handler.INDEX,), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "set_blocker_wind_efficiency", (handler.INDEX, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( "set_MESA_paths", (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_accrete_composition_non_metals", (handler.INDEX,), (handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT) ) handler.add_method( "set_accrete_composition_non_metals", (handler.INDEX,handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT), (handler.ERROR_CODE) ) handler.add_method( "get_accrete_composition_metals_identifier", (handler.INDEX,), (handler.NO_UNIT,) ) handler.add_method( "set_accrete_composition_metals_identifier", (handler.INDEX,handler.NO_UNIT), (handler.ERROR_CODE) ) handler.add_method( "solve_one_step", (handler.INDEX, handler.NO_UNIT), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "solve_one_step_pre", (handler.INDEX), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "solve_one_step_post", (handler.INDEX), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "prepare_retry_step", (handler.INDEX, units.s), (handler.NO_UNIT,handler.ERROR_CODE) ) handler.add_method( "prepare_redo_step", (handler.INDEX), (handler.NO_UNIT,handler.ERROR_CODE) ) def initialize_module_with_default_parameters(self): self.parameters.set_defaults() self.initialize_code() def initialize_module_with_current_parameters(self): self.initialize_code() def commit_parameters(self): self.parameters.send_not_set_parameters_to_code() self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def get_mass_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying mass profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'dq', number_of_zones) def get_cumulative_mass_profile(self, indices_of_the_stars, number_of_zones=None): frac_profile = self.get_mass_profile(indices_of_the_stars, number_of_zones=number_of_zones) return frac_profile.cumsum() def set_mass_profile(self, indices_of_the_stars, values, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Setting mass profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) self._check_supplied_values(len(values), number_of_zones) self.set_mass_fraction_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values) def get_luminosity_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying luminosity profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'luminosity', number_of_zones) | units.LSun def set_luminosity_profile(self, indices_of_the_stars, values, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Setting luminosity profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) self._check_supplied_values(len(values), number_of_zones) self.set_luminosity_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, values) def get_entropy_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying entropy profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'entropy', number_of_zones) | units.erg/units.K def get_thermal_energy_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying thermal energy profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'energy', number_of_zones) | units.erg/units.s/units.g def get_temperature_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying temperature profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'temperature', number_of_zones) | units.K def get_density_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying density profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'density', number_of_zones) | units.g/(units.cm*units.cm*units.cm) def get_radius_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying radius profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'radius', number_of_zones) | units.RSun def get_pressure_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying pressure profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'pressure', number_of_zones) | units.g/(units.cm * units.s * units.s) def get_pressure_scale_height_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying pressure scale height profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'pressure_scale_height', number_of_zones) | units.RSun def get_mu_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying mu profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'mu', number_of_zones) | units.amu def get_brunt_vaisala_frequency_squared_profile(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying brunt-vaisala-frequency-squared profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile(indices_of_the_stars, 'brunt_N2', number_of_zones) | units.none def get_IDs_of_species(self, indices_of_the_stars, number_of_species=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying chemical abundance IDs") if number_of_species is None: number_of_species = self.get_number_of_species(indices_of_the_stars) return list(range(1, number_of_species+1)) def get_profile(self, indices_of_the_stars, name, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying profiles") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_profile_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none, [name]*number_of_zones) def get_masses_of_species(self, indices_of_the_stars, number_of_species=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying chemical abundance mass numbers") if number_of_species is None: number_of_species = self.get_number_of_species(indices_of_the_stars) return self.get_mass_of_species( [indices_of_the_stars]*number_of_species, list(range(1, number_of_species+1)) ) def get_extra_heat(self, indices_of_the_stars, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying extra_heat ") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_mesa_value([indices_of_the_stars]*number_of_zones, ['extra_heat']*number_of_zones, list(range(1, number_of_zones+1))) | units.erg/units.g/units.s def set_extra_heat(self, indices_of_the_stars, values , number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Setting extra_heat ") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.set_mesa_value([indices_of_the_stars]*number_of_zones, ['extra_heat']*number_of_zones, values, list(range(1, number_of_zones+1))) def get_mesa_value_profile(self, indices_of_the_stars, name, number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Querying generic mesa_get_value") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.get_mesa_value([indices_of_the_stars]*number_of_zones, [name]*number_of_zones, list(range(1, number_of_zones+1))) def set_mesa_value_profile(self, indices_of_the_stars, name, values , number_of_zones=None): indices_of_the_stars = self._check_number_of_indices(indices_of_the_stars, action_string="Setting generic mesa_get_value") if number_of_zones is None: number_of_zones = self.get_number_of_zones(indices_of_the_stars) return self.set_mesa_value([indices_of_the_stars]*number_of_zones, [name]*number_of_zones, values, list(range(1, number_of_zones+1))) def new_particle_from_model(self, internal_structure, current_age=0|units.julianyr, key=None): if hasattr(internal_structure, 'get_profile'): mm = internal_structure xqs = 10**mm.get_profile('logxq') # log(1-q) temperature = mm.get_profile('temperature') | units.K rho = mm.get_profile('rho') | units.g / units.cm**3 empty_comp = numpy.zeros(numpy.size(xqs)) empty_comp[:] = 10**-50 # If you dont have anything in that isotope sm = mm.get_history('star_mass') star_mass = [sm]*len(xqs) | units.MSun species = [mm.get_name_of_species(i) for i in range(1, mm.get_number_of_species()+1)] xH1 = mm.get_profile('h1') if 'h1' in species else empty_comp xHe3 = mm.get_profile('he3') if 'he3' in species else empty_comp xHe4 = mm.get_profile('he4') if 'he4' in species else empty_comp xC12 = mm.get_profile('c12') if 'c12' in species else empty_comp xN14 = mm.get_profile('n14') if 'n14' in species else empty_comp xO16 = mm.get_profile('o16') if 'o16' in species else empty_comp xNe20 = mm.get_profile('ne20') if 'ne20' in species else empty_comp xMg24 = mm.get_profile('mg24') if 'mg24' in species else empty_comp xSi28 = mm.get_profile('si28') if 'si28' in species else empty_comp xS32 = mm.get_profile('s32') if 's32' in species else empty_comp xAr36 = mm.get_profile('ar36') if 'ar36' in species else empty_comp xCa40 = mm.get_profile('ca40') if 'ca40' in species else empty_comp xTi44 = mm.get_profile('ti44') if 'ti44' in species else empty_comp xCr48 = mm.get_profile('cr48') if 'cr48' in species else empty_comp xFe52 = mm.get_profile('fe52') if 'fe52' in species else empty_comp xFe54 = mm.get_profile('fe54') if 'fe54' in species else empty_comp xFe56 = mm.get_profile('fe56') if 'fe56' in species else empty_comp xCr56 = mm.get_profile('cr56') if 'cr56' in species else empty_comp xNi56 = mm.get_profile('ni56') if 'ni56' in species else empty_comp self.new_stellar_model( star_mass, xqs[::-1], rho[::-1], temperature[::-1], xH1[::-1], xHe3[::-1], xHe4[::-1], xC12[::-1], xN14[::-1], xO16[::-1], xNe20[::-1], xMg24[::-1], xSi28[::-1], xS32[::-1], xAr36[::-1], xCa40[::-1], xTi44[::-1], xCr48[::-1], xFe52[::-1], xFe54[::-1], xFe56[::-1], xCr56[::-1], xNi56[::-1], empty_comp[::-1], empty_comp[::-1], ) elif isinstance(internal_structure, dict): cumulative_mass_profile = internal_structure['mass'].value_in(units.MSun) mass_profile = cumulative_mass_profile/cumulative_mass_profile.max() xqs = 1.0 - mass_profile # 1-q star_mass = numpy.zeros(numpy.size(internal_structure['temperature'])) star_mass[:] = internal_structure['mass'].max().value_in(units.MSun) star_mass = star_mass | units.MSun empty_comp = numpy.zeros(numpy.size(internal_structure['temperature'])) empty_comp[:] = 10**-50 self.new_stellar_model( star_mass, xqs[::-1], internal_structure['rho'][::-1], internal_structure['temperature'][::-1], internal_structure['X_H'][::-1], empty_comp, internal_structure['X_He'][::-1], internal_structure['X_C'][::-1], internal_structure['X_N'][::-1], internal_structure['X_O'][::-1], internal_structure['X_Ne'][::-1], internal_structure['X_Mg'][::-1], internal_structure['X_Si'][::-1], empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, internal_structure['X_Fe'][::-1], empty_comp, empty_comp, empty_comp[::-1], empty_comp[::-1], ) else: cumulative_mass_profile = internal_structure.mass.value_in(units.MSun) mass_profile = cumulative_mass_profile/cumulative_mass_profile.max() xqs = 1.0 - mass_profile # 1-q star_mass = numpy.zeros(numpy.size(internal_structure.temperature)) star_mass[:] = internal_structure.mass.max().value_in(units.MSun) star_mass = star_mass | units.MSun empty_comp = numpy.zeros(numpy.size(internal_structure.temperature)) empty_comp[:] = 10**-50 self.new_stellar_model( star_mass, xqs[::-1], internal_structure.rho[::-1], internal_structure.temperature[::-1], internal_structure.X_H[::-1], empty_comp, internal_structure.X_He[::-1], internal_structure.X_C[::-1], internal_structure.X_N[::-1], internal_structure.X_O[::-1], internal_structure.X_Ne[::-1], internal_structure.X_Mg[::-1], internal_structure.X_Si[::-1], empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, empty_comp, internal_structure.X_Fe[::-1], empty_comp, empty_comp, empty_comp[::-1], empty_comp[::-1], ) tmp_star = datamodel.Particle(key=key) tmp_star.age_tag = current_age return self.imported_stars.add_particle(tmp_star) Mesa = MESA
88,033
39.179827
196
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/purehe.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') # Set Z for all stars? stellar_evolution.parameters.metallicity = 0.0142 masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.pure_he_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.time_step) star.time_step = 1. | units.yr star.evolve_one_step() print(star.time_step) h1 = star.get_profile('h1') print(h1[0],h1[-1]) he4 = star.get_profile('he4') print(he4[0],he4[-1])
662
18.5
60
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/inlist.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140',inlist='./inlist') masses=[10.0] | units.MSun # Masses must be set here not in inlist stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.time_step) print(star.get_history('time_step')) # Previous step print(star.get_control('mesh_delta_coeff')) # Should be 1.5
581
23.25
66
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/new_model.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[5.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) # Show how to make a star based on an importted model # For convenience we just use another star made with MESA # but this could be from another code # Lets evolve a star first stars[0].evolve_for(0.05 | units.Gyr) # Make new one based on what we just created new_star = stellar_evolution.new_particle_from_model(stars[0], 0.0|units.Myr) # Check they look similiar, they wont be identical as mesa attemtps to find a matching solution # within some tolerances (even when importing an exisiting mesa model), this will be worse # the more the EOSs and oither microphysics differs between models. print(new_star.mass,stars[0].mass) print(new_star.temperature,stars[0].temperature) print(new_star.get_profile('h1')[0],stars[0].get_profile('h1')[0]) #print(new_star.age,stars[0].age) new_star.evolve_one_step() #print(new_star.age)
1,182
27.166667
95
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/save_and_load.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[2.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.time_step) star.time_step = 1. | units.yr star.evolve_one_step() star.save_photo('photo') star.save_model('model.mod') star.evolve_one_step() age = star.age model_number = star.get_history('model_number') masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses,filename=['photo']) stars = stellar_evolution.photo_stars.add_particles(stars) star = stars[0] star.evolve_one_step() # Photos will give exactly the same answer compared to a run without a save/load print(star.age, star.get_history('model_number'), star.mass) masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses,filename=['model.mod']) stars = stellar_evolution.pre_built_stars.add_particles(stars) star = stars[0] star.evolve_one_step() # Models do not give exactly the same answer as a photo print(star.age, star.get_history('model_number'), star.mass)
1,277
22.666667
103
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/basic2.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[2.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.get_number_of_species()) print(star.get_name_of_species(1)) print(star.get_masses_of_species()) print(star.get_mass_fraction_of_species_at_zone(1,1)) print(star.get_id_of_species('h1'))
584
21.5
59
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/multi.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel ###BOOKLISTSTART### def evolve_with_different_stellar_model(): times = [10, 100, 1000] | units.Myr stars = datamodel.Particles(mass=[1, 2, 4]|units.MSun) stellars = [MESA(version='15140')] channels = [] for star, stellar in zip(stars, stellars): stellar.particles.add_particle(star) channels.append(stellar.particles.new_channel_to(stars)) for time, channel, stellar in zip(times, channels, stellars): stellar.evolve_model(time) channel.copy() for time, star in zip(times, stars): print("Time=", time, "M=", star.mass) stellar.stop() ###BOOKLISTSTOP### evolve_with_different_stellar_model()
829
28.642857
65
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/prems.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') # Set Z for all stars? stellar_evolution.parameters.metallicity = 0.0142 masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.pre_ms_stars.add_particles(stars) star = stars[0] star.evolve_for(4.6 | units.Gyr) print(star.temperature,star.mass,star.radius,star.luminosity) star.evolve_one_step() print(star.temperature,star.get_history('Teff'),star.get_history('log_Teff')) h1 = star.get_profile('h1') print(h1[0],h1[-1])
682
22.551724
77
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/gyre.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140',gyre_in='./gyre.in') masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.time_step = 100. | units.yr star.evolve_one_step() print(star.get_history('time_step')) # Previous step star.get_gyre()
507
22.090909
61
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/rotation.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] # Turn on rotation star.set_star_job('change_rotation_flag',True) star.set_star_job('new_rotation_flag',True) # Many options for initialising the rotation rate star.set_star_job('set_surface_rotation_v',True) star.set_star_job('new_surface_rotation_v',100.0) # sets surface velocity in km/sec # Now change the model to turn on rotation star.star_job_update() # Turn options back off star.set_star_job_logical('change_rotation_flag',False) # Evovle star until? star.evolve_for(1.0 | units.Gyr) irot = star.get_profile('irot') # ! specific moment of inertia at cell boundary mass = star.get_profile('mass') # m/Msun. mass coordinate of outer boundary of cell.
1,026
26.026316
84
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/plot.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[2.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() age = star.get_history('star_age') # Years fig=plt.figure(figsize=(12*4,9*4)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) logL= [] logT =[] logTc=[] logRhoc=[] while age < 4.6*10**9: star.evolve_one_step() age = star.get_history('star_age') # Years logL.append(star.get_history('log_L')) logT.append(star.get_history('log_Teff')) logTc.append(star.get_history('log_center_T')) logRhoc.append(star.get_history('log_center_Rho')) ax1.cla() ax2.cla() ax3.cla() ax4.cla() ax1.plot(logT,logL) ax1.scatter(logT[-1],logL[-1],s=50) ax1.set_xlim(ax1.get_xlim()[::-1]) ax1.set_xlabel(r'$\log \left(T_{eff}/K\right)$') ax1.set_ylabel(r'$\log \left(L/L_{\odot}\right)$') ax1.set_title('Model Number='+str(int(star.get_history('model_number')))) ax2.set_title('Star age='+str(star.get_history('star_age'))) ax2.plot(logRhoc,logTc) ax2.scatter(logRhoc[-1],logTc[-1],s=50) ax2.set_ylabel(r'$\log \left(T_{c}/K\right)$') ax2.set_xlabel(r'$\log \left(\rho_{c}/\left(g\ cm^{-3}\right)\right)$') lgt = star.get_profile('logT') lgr = star.get_profile('logRho') ax3.set_xlabel(r'$\log \left(\rho/\left(g\ cm^{-3}\right)\right)$') ax3.set_ylabel(r'$\log \left(T/K\right)$') ax3.plot(lgr,lgt) m = star.get_profile('mass') ax4.set_yscale('log') for i in range(1,star.get_number_of_species()+1): name = star.get_name_of_species(i) species = star.get_profile(name) ax4.plot(m,species,label=name) ax4.legend(loc=0) ax4.set_ylim(10**-5,1.0) ax4.set_xlabel(r'$m/M_{\odot}$') ax4.set_ylabel('Abundance') plt.pause(0.01)
2,118
24.53012
77
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/__init__.py
""" The Astrophysical Multipurpose Software Environment AMUSE contains a lot of functionality to execute astrophysical experiments. Look into the interface packages for the interfacing to physical model simulation software. You can also use AMUSE to convert common data formats. """
285
30.777778
91
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/sun.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') stellar_evolution.parameters.metallicity = 0.0142 masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.pre_ms_stars.add_particles(stars) star = stars[0] star.evolve_one_step() star.evolve_for(4.6 | units.Gyr) print(star.temperature,star.mass,star.radius,star.luminosity) star.evolve_one_step() print(star.temperature,star.get_history('Teff'),star.get_history('log_Teff')) h1 = star.get_profile('h1') print(h1[0],h1[-1]) # Note use the name from the history_columns.list file 'center h1' not the hsitory output 'center_h1' print(star.get_history('center h1'))
824
24
101
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/controls.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[5.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] print(star.get_control('mesh_delta_coeff')) star.set_control('mesh_delta_coeff',0.8) print(star.get_control('mesh_delta_coeff')) print(star.get_control('merge_if_dr_div_cs_too_small')) star.set_control('merge_if_dr_div_cs_too_small',False) print(star.get_control('merge_if_dr_div_cs_too_small')) print(star.get_control('terminal_show_age_units')) star.set_control('terminal_show_age_units','seconds') print(star.get_control('terminal_show_age_units')) print(star.get_control('solver_save_photo_call_number')) star.set_control('solver_save_photo_call_number',3) print(star.get_control('solver_save_photo_call_number')) print(star.get_control('max_num_subcells')) star.set_control('max_num_subcells',3) print(star.get_control('max_num_subcells')) # On their own changing an option in star_job does not do anything # Once you've set all the star_job options you then want then call star_job_update() print(star.get_star_job('min_x_for_keep')) star.set_star_job('min_x_for_keep',10**-4) print(star.get_star_job('min_x_for_keep')) print(star.get_star_job('change_net')) star.set_star_job('change_net',True) print(star.get_star_job('change_net')) print(star.get_star_job('new_net_name')) star.set_star_job('new_net_name','approx21.net') print(star.get_star_job('new_net_name')) print(star.get_star_job('new_rates_preference')) star.set_star_job('new_rates_preference',1) print(star.get_star_job('new_rates_preference')) star.star_job_update() # EOS and KAP options print(star.get_eos('mass_fraction_limit_for_PC')) star.set_eos('mass_fraction_limit_for_PC',0.0) print(star.get_eos('mass_fraction_limit_for_PC')) print(star.get_kap('zbase')) star.set_kap('zbase',0.001) print(star.get_kap('zbase')) print(star.get_history('species')) # Should be 21 now # Change the mass of the tar star.mass=10| units.MSun print(star.mass) print(star.get_history('star_mass')) #Add extra energy to satr print(star.get_extra_heat()) print(star.set_extra_heat(1.0,1)) print(star.get_mesa_value('extra_heat',1)) eng = np.zeros(star.get_number_of_zones()) eng[:] = 2.0 print(star.set_mesa_value_profile('extra_heat',eng)) print(star.get_mesa_value_profile('extra_heat'))
2,531
26.225806
84
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/basic.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[2.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.time_step) star.time_step = 1. | units.yr star.evolve_one_step() print(star.get_history('time_step')) # Previous step print(star.time_step) # Next step
552
18.75
59
py
amuse
amuse-main/src/amuse/community/mesa_r15140/examples/photo_load.py
import matplotlib.pyplot as plt import numpy as np from amuse.units import units from amuse.community.mesa.interface import MESA from amuse import datamodel stellar_evolution = MESA(version='15140') masses=[2.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses) stars = stellar_evolution.native_stars.add_particles(stars) star = stars[0] star.evolve_one_step() print(star.time_step) star.time_step = 1. | units.yr star.evolve_one_step() star.save_photo('photo') star.save_model('model.mod') star.evolve_one_step() age = star.age model_number = star.get_history('model_number') masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses,filename=['photo']) stars = stellar_evolution.photo_stars.add_particles(stars) star = stars[0] star.evolve_one_step() # Photos will give exactly the same answer compared to a run without a save/load print(star.age, star.get_history('model_number'), star.mass) masses=[1.0] | units.MSun stars = datamodel.Particles(len(masses), mass=masses,filename=['model.mod']) stars = stellar_evolution.pre_built_stars.add_particles(stars) star = stars[0] star.evolve_one_step() # Models do not give exactly the same answer as a photo print(star.age, star.get_history('model_number'), star.mass)
1,277
22.666667
103
py
amuse
amuse-main/src/amuse/community/vader/download.py
#!/usr/bin/env python import subprocess import os import urllib.request from shutil import which from optparse import OptionParser class GetCodeFromHttp: filename_template = "{version}.tar.gz" name = ["MJCWilhelm-vader"] url_template = [ "https://bitbucket.org/MJCWilhelm/vader/get/{version}.tar.gz", ] version = [ "", ] def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename, name, version): print ("unpacking", filename) arguments = ['mkdir', 'vader_src'] subprocess.call( arguments, cwd=os.path.join(self.directory()) ) arguments = ['tar', '-xf', filename, '-C', 'vader_src', '--strip-components=1'] subprocess.call( arguments, cwd=os.path.join(self.directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) #os.mkdir('src') for i, url_template in enumerate(self.url_template): url = url_template.format(version=self.version[i]) filename = self.filename_template.format(version=self.version[i]) filepath = os.path.join(self.directory(), filename) print( "downloading version", self.version[i], "from", url, "to", filename ) if which('wget') is not None: arguments = ['wget', url] subprocess.call( arguments, cwd=os.path.join(self.directory()) ) elif which('curl') is not None: arguments = ['curl', '-L', '-O', url] subprocess.call( arguments, cwd=os.path.join(self.directory()) ) else: urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file( filename, self.name[i], self.version[i] ) def main(vader_version=''): version = [ vader_version, ] instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--vader-version", default='0e6357b451e6', dest="vader_version", help="VADER commit hash to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
2,985
27.711538
87
py
amuse
amuse-main/src/amuse/community/vader/__init__.py
# generated file from .interface import Vader
46
14.666667
28
py
amuse
amuse-main/src/amuse/community/vader/interface.py
from amuse.community import * from amuse.community.interface import common class VaderInterface(CodeInterface, LiteratureReferencesMixIn, common.CommonCodeInterface): """ VADER is a code simulating the evolution of viscous thin accretion disks. It is developed by Mark Krumholz and John Forbes [1]. .. [#] ADS:2015A&C....11....1K (Krumholz, M. R. and Forbes, J. C., Astronomy and Computing, Vol. 11 (2015): .. [#] ... VADER: A Flexible, Robust, Open-Source Code for Simulating Viscous Thin Accretion Disks) """ include_headers = ['worker_code.h'] def __init__(self, mode = 'none', **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="vader_worker_" + mode, **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @legacy_function def initialize_code(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('tlim', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def initialize_keplerian_grid(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('linear', dtype='bool', direction=function.IN) function.addParameter('rmin', dtype='float64', direction=function.IN) function.addParameter('rmax', dtype='float64', direction=function.IN) function.addParameter('m', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def update_keplerian_grid(): function = LegacyFunctionSpecification() function.addParameter('m', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def initialize_flat_grid(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('linear', dtype='bool', direction=function.IN) function.addParameter('rmin', dtype='float64', direction=function.IN) function.addParameter('rmax', dtype='float64', direction=function.IN) function.addParameter('vphi', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def update_flat_grid(): function = LegacyFunctionSpecification() function.addParameter('vphi', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def initialize_tabulated_grid(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('linear', dtype='int32', direction=function.IN) function.addParameter('rmin', dtype='float64', direction=function.IN) function.addParameter('rmax', dtype='float64', direction=function.IN) function.addParameter('bspline_degree', dtype='int32', direction=function.IN) function.addParameter('bspline_breakpoints', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def update_tabulated_grid(): function = LegacyFunctionSpecification() function.addParameter('bspline_degree', dtype='int32', direction=function.IN) function.addParameter('bspline_breakpoints', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tabulated_size(): function = LegacyFunctionSpecification() function.addParameter('nTab', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tabulated_size(): function = LegacyFunctionSpecification() function.addParameter('nTab', dtype='int32', direction=function.IN) function.result_type = 'int32' return function def get_table_range(self): nTab = self.get_tabulated_size()['nTab'] return (0, nTab-1) @legacy_function def get_tabulated_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('rTab', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tabulated_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('rTab', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tabulated_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('vTab', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tabulated_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('vTab', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #grid getters&setters @legacy_function def get_position_of_index(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('r', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_index_of_position(): function = LegacyFunctionSpecification() function.addParameter('r', dtype='float64', direction=function.IN) function.addParameter('i', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_grid_column_density(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('sigma', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_grid_pressure(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('pressure', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_grid_internal_energy(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('internal_energy', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) for x in ['sigma', 'pressure', 'internal_energy']: function.addParameter(x, dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_grid_user_output(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('user_output', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_grid_column_density(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('sigma', dtype='float64', direction=function.IN) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_grid_pressure(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('pressure', dtype='float64', direction=function.IN) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_grid_internal_energy(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('internal_energy', dtype='float64', direction=function.IN) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) for x in ['sigma', 'pressure', 'internal_energy']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def set_grid_user_output(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('user_output', dtype='float64', direction=function.IN) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function #viscous parameters getters&setters @legacy_function def get_alpha_function(): function = LegacyFunctionSpecification() function.addParameter('alpha_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_alpha_function(): function = LegacyFunctionSpecification() function.addParameter('alpha_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_alpha(): function = LegacyFunctionSpecification() function.addParameter('alpha', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_alpha(): function = LegacyFunctionSpecification() function.addParameter('alpha', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eos_function(): function = LegacyFunctionSpecification() function.addParameter('eos_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eos_function(): function = LegacyFunctionSpecification() function.addParameter('eos_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gamma(): function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_gamma(): function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_delta(): function = LegacyFunctionSpecification() function.addParameter('delta', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_delta(): function = LegacyFunctionSpecification() function.addParameter('delta', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #source getters&setters @legacy_function def get_mass_source_function(): function = LegacyFunctionSpecification() function.addParameter('mass_source_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_mass_source_function(): function = LegacyFunctionSpecification() function.addParameter('mass_source_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_internal_energy_source_function(): function = LegacyFunctionSpecification() function.addParameter('internal_energy_source_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_internal_energy_source_function(): function = LegacyFunctionSpecification() function.addParameter('internal_energy_source_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_mass_source_value(): function = LegacyFunctionSpecification() function.addParameter('mass_source_value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_mass_source_value(): function = LegacyFunctionSpecification() function.addParameter('mass_source_value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_internal_energy_source_value(): function = LegacyFunctionSpecification() function.addParameter('internal_energy_source_value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_internal_energy_source_value(): function = LegacyFunctionSpecification() function.addParameter('internal_energy_source_value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function #boundary getters&setters @legacy_function def get_inner_pressure_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_inner_pressure_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_inner_pressure_boundary_mass_flux(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_inner_pressure_boundary_torque_flux(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_inner_pressure_boundary_torque(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_inner_pressure_boundary_mass_flux(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_inner_pressure_boundary_torque_flux(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_inner_pressure_boundary_torque(): function = LegacyFunctionSpecification() function.addParameter('ibc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_inner_enthalpy_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_inner_enthalpy_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_inner_enthalpy_boundary_enthalpy(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_inner_enthalpy_boundary_enthalpy_gradient(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_inner_enthalpy_boundary_enthalpy(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_inner_enthalpy_boundary_enthalpy_gradient(): function = LegacyFunctionSpecification() function.addParameter('ibc_enth_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_inner_boundary_function(): function = LegacyFunctionSpecification() function.addParameter('ibc_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_inner_boundary_function(): function = LegacyFunctionSpecification() function.addParameter('ibc_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outer_pressure_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('obc_pres', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outer_pressure_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('obc_pres', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outer_pressure_boundary_mass_flux(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_outer_pressure_boundary_torque_flux(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_outer_pressure_boundary_torque(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outer_pressure_boundary_mass_flux(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_outer_pressure_boundary_torque_flux(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_outer_pressure_boundary_torque(): function = LegacyFunctionSpecification() function.addParameter('obc_pres_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outer_enthalpy_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('obc_enth', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outer_enthalpy_boundary_type(): function = LegacyFunctionSpecification() function.addParameter('obc_enth', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outer_enthalpy_boundary_enthalpy(): function = LegacyFunctionSpecification() function.addParameter('obc_enth_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_outer_enthalpy_boundary_enthalpy_gradient(): function = LegacyFunctionSpecification() function.addParameter('obc_enth_val', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outer_enthalpy_boundary_enthalpy(): function = LegacyFunctionSpecification() function.addParameter('obc_enth_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_outer_enthalpy_boundary_enthalpy_gradient(): function = LegacyFunctionSpecification() function.addParameter('obc_enth_val', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_outer_boundary_function(): function = LegacyFunctionSpecification() function.addParameter('obc_func', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_outer_boundary_function(): function = LegacyFunctionSpecification() function.addParameter('obc_func', dtype='bool', direction=function.IN) function.result_type = 'int32' return function #various @legacy_function def get_number_of_cells(): function = LegacyFunctionSpecification() function.addParameter('i', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function def get_index_range_for_grid(self): i, error = self.get_number_of_cells() return (0, i-1) def get_index_range_for_user_outputs(self): i, error = self.get_number_of_cells() j, error = self.get_nUserOut() return (0, j-1, 0, i-1) @legacy_function def get_area_of_index(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('area', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_rotational_velocity_of_index(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('vphi', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_effective_potential_of_index(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('psiEff', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_gravitational_potential_of_index(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('psi_grav', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_number_of_user_parameters(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_number_of_user_parameters(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_parameter(): function = LegacyFunctionSpecification() function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('param', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_parameter(): function = LegacyFunctionSpecification() function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('param', 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 get_inner_boundary_mass_out(): function = LegacyFunctionSpecification() function.addParameter('mSrcOut', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_outer_boundary_mass_out(): function = LegacyFunctionSpecification() function.addParameter('mSrcOut', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_inner_boundary_energy_out(): function = LegacyFunctionSpecification() function.addParameter('eSrcOut', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_outer_boundary_energy_out(): function = LegacyFunctionSpecification() function.addParameter('eSrcOut', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_mass_source_out(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('mSrcOut', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_energy_source_out(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('i', dtype='int32', direction=function.IN) function.addParameter('eSrcOut', dtype='float64', direction=function.OUT) function.addParameter('number_of_points', 'int32', function.LENGTH) function.result_type = 'int32' return function @legacy_function def get_dtStart(): function = LegacyFunctionSpecification() function.addParameter('dtStart', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtStart(): function = LegacyFunctionSpecification() function.addParameter('dtStart', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtMin(): function = LegacyFunctionSpecification() function.addParameter('dtMin', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtMin(): function = LegacyFunctionSpecification() function.addParameter('dtMin', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtTol(): function = LegacyFunctionSpecification() function.addParameter('dtTol', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtTol(): function = LegacyFunctionSpecification() function.addParameter('dtTol', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_errTol(): function = LegacyFunctionSpecification() function.addParameter('errTol', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_errTol(): function = LegacyFunctionSpecification() function.addParameter('errTol', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_maxDtIncrease(): function = LegacyFunctionSpecification() function.addParameter('maxDtIncrease', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_maxDtIncrease(): function = LegacyFunctionSpecification() function.addParameter('maxDtIncrease', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_maxIter(): function = LegacyFunctionSpecification() function.addParameter('maxIter', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_maxIter(): function = LegacyFunctionSpecification() function.addParameter('maxIter', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_interpOrder(): function = LegacyFunctionSpecification() function.addParameter('interpOrder', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_interpOrder(): function = LegacyFunctionSpecification() function.addParameter('interpOrder', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_maxStep(): function = LegacyFunctionSpecification() function.addParameter('maxStep', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_maxStep(): function = LegacyFunctionSpecification() function.addParameter('maxStep', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_useBE(): function = LegacyFunctionSpecification() function.addParameter('useBE', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_useBE(): function = LegacyFunctionSpecification() function.addParameter('useBE', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_verbosity(): function = LegacyFunctionSpecification() function.addParameter('verbosity', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_verbosity(): function = LegacyFunctionSpecification() function.addParameter('verbosity', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_PreTimestep(): function = LegacyFunctionSpecification() function.addParameter('PreTimestep', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_PreTimestep(): function = LegacyFunctionSpecification() function.addParameter('PreTimestep', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_PostTimestep(): function = LegacyFunctionSpecification() function.addParameter('PostTimestep', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_PostTimestep(): function = LegacyFunctionSpecification() function.addParameter('PostTimestep', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nUserOut(): function = LegacyFunctionSpecification() function.addParameter('nUserOut', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nUserOut(): function = LegacyFunctionSpecification() function.addParameter('nUserOut', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_begin_time(): function = LegacyFunctionSpecification() function.addParameter('begin_time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_begin_time(): function = LegacyFunctionSpecification() function.addParameter('begin_time', dtype='float64', direction=function.IN) function.result_type = 'int32' return function ''' @legacy_function def get_nFail(): function = LegacyFunctionSpecification() function.addParameter('nFail', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function ''' @legacy_function def cleanup_code(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function class Vader(common.CommonCode): def __init__(self, unit_converter = None, mode = 'none', **options): self.mode = mode self.unit_converter = unit_converter common.CommonCode.__init__(self, VaderInterface(mode = mode, **options), **options) def define_state(self, handler): common.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('CHANGE_PARAMETERS_RUN', 'RUN', 'recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT', 'EDIT', '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_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_transition('EDIT', 'RUN', 'initialize_keplerian_grid', False) handler.add_transition('EDIT', 'RUN', 'initialize_flat_grid', False) handler.add_transition('EDIT', 'RUN', 'initialize_tabulated_grid', False) handler.add_method('RUN', 'update_keplerian_grid') handler.add_method('RUN', 'update_flat_grid') handler.add_method('RUN', 'update_tabulated_grid') grid_write_properties = ['state', 'column_density', 'pressure', 'internal_energy', 'user_output'] for prop in grid_write_properties: handler.add_method('RUN', 'set_grid_'+prop) handler.add_method('RUN', 'get_grid_'+prop) handler.add_method('EDIT', 'set_grid_'+prop) handler.add_method('EDIT', 'get_grid_'+prop) grid_read_properties = ['mass_source_out', 'energy_source_out', 'position_of_index', 'area_of_index', 'effective_potential_of_index', 'gravitational_potential_of_index', 'index_range_for_grid', 'rotational_velocity_of_index'] for prop in grid_read_properties: handler.add_method('RUN', 'get_'+prop) handler.add_method('EDIT', 'get_'+prop) code_properties = ['inner_boundary_mass_out', 'outer_boundary_mass_out', 'inner_boundary_energy_out', 'outer_boundary_energy_out'] for prop in code_properties: handler.add_method('RUN', 'get_'+prop) handler.add_method('EDIT', 'get_'+prop) handler.add_method('RUN', 'evolve_model') handler.add_method('EDIT', 'get_time') handler.add_method('RUN', 'get_time') def commit_parameters(self): self.parameters.send_not_set_parameters_to_code() self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def define_methods(self, builder): length = units.cm time = units.s mass = units.g velocity = length / time energy = mass * velocity**2. pressure = mass / length / time**2. force = mass * velocity / time col_density = mass / length**2. Eint_density = energy / length**2. builder.add_method( "evolve_model", (time,), (builder.ERROR_CODE,) ) builder.add_method( "initialize_code", (), (builder.ERROR_CODE,) ) builder.add_method( "initialize_keplerian_grid", (builder.NO_UNIT, builder.NO_UNIT, length, length, mass,), (builder.ERROR_CODE,) ) builder.add_method( "update_keplerian_grid", (mass,), (builder.ERROR_CODE,) ) builder.add_method( "initialize_flat_grid", (builder.NO_UNIT, builder.NO_UNIT, length, length, velocity,), (builder.ERROR_CODE) ) builder.add_method( "update_flat_grid", (velocity,), (builder.ERROR_CODE,) ) builder.add_method( "initialize_tabulated_grid", (builder.NO_UNIT, builder.NO_UNIT, length, length, builder.NO_UNIT, builder.NO_UNIT,), (builder.ERROR_CODE) ) builder.add_method( "update_tabulated_grid", (builder.NO_UNIT, builder.NO_UNIT), (builder.ERROR_CODE,) ) builder.add_method( "get_tabulated_size", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_tabulated_size", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_tabulated_radius", (builder.INDEX,), (length, builder.ERROR_CODE) ) builder.add_method( "set_tabulated_radius", (builder.INDEX, length), (builder.ERROR_CODE,) ) builder.add_method( "get_tabulated_velocity", (builder.INDEX,), (velocity, builder.ERROR_CODE) ) builder.add_method( "set_tabulated_velocity", (builder.INDEX, velocity), (builder.ERROR_CODE,) ) ''' builder.add_method( "initialize_grid", (builder.NO_UNIT, builder.NO_UNIT, length, length, velocity, velocity #beta units #beta units energy/mass, energy/mass, #whatever the hell g_h is ,), (builder.ERROR_CODE) ) ''' #grid getters&setters builder.add_method( "get_position_of_index", (builder.INDEX,), (length, builder.ERROR_CODE) ) builder.add_method( "get_index_of_position", (length,), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( "get_area_of_index", (builder.INDEX,), (length**2., builder.ERROR_CODE) ) builder.add_method( "get_rotational_velocity_of_index", (builder.INDEX,), (length / time, builder.ERROR_CODE) ) builder.add_method( "get_effective_potential_of_index", (builder.INDEX,), (energy / mass, builder.ERROR_CODE) ) builder.add_method( "get_gravitational_potential_of_index", (builder.INDEX,), (energy / mass, builder.ERROR_CODE) ) builder.add_method( "get_grid_column_density", (builder.INDEX,), (col_density, builder.ERROR_CODE) ) builder.add_method( "get_grid_pressure", (builder.INDEX,), (pressure * length, builder.ERROR_CODE) ) builder.add_method( "get_grid_internal_energy", (builder.INDEX,), (Eint_density, builder.ERROR_CODE) ) builder.add_method( "get_grid_state", (builder.INDEX,), (col_density, pressure * length, Eint_density, builder.ERROR_CODE) ) builder.add_method( "get_grid_user_output", (builder.INDEX, builder.INDEX), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_grid_column_density", (builder.INDEX, col_density), (builder.ERROR_CODE,) ) builder.add_method( "set_grid_pressure", (builder.INDEX, pressure * length), (builder.ERROR_CODE,) ) builder.add_method( "set_grid_internal_energy", (builder.INDEX, Eint_density), (builder.ERROR_CODE,) ) builder.add_method( "set_grid_state", (builder.INDEX, col_density, pressure * length, Eint_density), (builder.ERROR_CODE,) ) builder.add_method( "set_grid_user_output", (builder.INDEX, builder.INDEX, builder.NO_UNIT), (builder.ERROR_CODE,) ) #viscous parameters getters&setters builder.add_method( "get_alpha_function", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_alpha_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_alpha", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_alpha", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_eos_function", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_eos_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_gamma", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_gamma", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_delta", (), (velocity**2, builder.ERROR_CODE,) ) builder.add_method( "set_delta", (velocity**2,), (builder.ERROR_CODE,) ) #source getters&setters builder.add_method( "get_mass_source_function", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_mass_source_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_internal_energy_source_function", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_internal_energy_source_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_mass_source_value", (), (col_density / time, builder.ERROR_CODE,) ) builder.add_method( "set_mass_source_value", (col_density / time,), (builder.ERROR_CODE,) ) builder.add_method( "get_internal_energy_source_value", (), (Eint_density / time, builder.ERROR_CODE,) ) builder.add_method( "set_internal_energy_source_value", (Eint_density / time,), (builder.ERROR_CODE,) ) #boundary condition getters&setters builder.add_method( "get_inner_pressure_boundary_type", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_inner_pressure_boundary_type", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_inner_pressure_boundary_mass_flux", (), (mass / time, builder.ERROR_CODE) ) builder.add_method( "get_inner_pressure_boundary_torque_flux", (), (force * length / time, builder.ERROR_CODE) ) builder.add_method( "get_inner_pressure_boundary_torque", (), (force * length, builder.ERROR_CODE) ) builder.add_method( "set_inner_pressure_boundary_mass_flux", (mass / time,), (builder.ERROR_CODE,) ) builder.add_method( "set_inner_pressure_boundary_torque_flux", (force * length / time,), (builder.ERROR_CODE,) ) builder.add_method( "set_inner_pressure_boundary_torque", (force * length,), (builder.ERROR_CODE,) ) builder.add_method( "get_inner_enthalpy_boundary_type", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_inner_enthalpy_boundary_type", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_inner_enthalpy_boundary_enthalpy", (), (energy / mass, builder.ERROR_CODE) ) builder.add_method( "get_inner_enthalpy_boundary_enthalpy_gradient", (), (energy / length / mass, builder.ERROR_CODE) ) builder.add_method( "set_inner_enthalpy_boundary_enthalpy", (energy / mass,), (builder.ERROR_CODE,) ) builder.add_method( "set_inner_enthalpy_boundary_enthalpy_gradient", (energy / length / mass,), (builder.ERROR_CODE,) ) builder.add_method( "get_inner_boundary_function", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_inner_boundary_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_outer_pressure_boundary_type", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_outer_pressure_boundary_type", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_outer_pressure_boundary_mass_flux", (), (mass / time, builder.ERROR_CODE) ) builder.add_method( "get_outer_pressure_boundary_torque_flux", (), (force * length / time, builder.ERROR_CODE) ) builder.add_method( "get_outer_pressure_boundary_torque", (), (force * length, builder.ERROR_CODE) ) builder.add_method( "set_outer_pressure_boundary_mass_flux", (mass / time,), (builder.ERROR_CODE,) ) builder.add_method( "set_outer_pressure_boundary_torque_flux", (force * length / time,), (builder.ERROR_CODE,) ) builder.add_method( "set_outer_pressure_boundary_torque", (force * length,), (builder.ERROR_CODE,) ) builder.add_method( "get_outer_enthalpy_boundary_type", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_outer_enthalpy_boundary_type", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_outer_enthalpy_boundary_enthalpy", (), (energy / mass, builder.ERROR_CODE) ) builder.add_method( "get_outer_enthalpy_boundary_enthalpy_gradient", (), (energy / length / mass, builder.ERROR_CODE) ) builder.add_method( "set_outer_enthalpy_boundary_enthalpy", (energy / mass,), (builder.ERROR_CODE,) ) builder.add_method( "set_outer_enthalpy_boundary_enthalpy_gradient", (energy / length / mass,), (builder.ERROR_CODE,) ) builder.add_method( "get_outer_boundary_function", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_outer_boundary_function", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) #other outputs builder.add_method( "get_inner_boundary_mass_out", (), (mass, builder.ERROR_CODE) ) builder.add_method( "get_outer_boundary_mass_out", (), (mass, builder.ERROR_CODE) ) builder.add_method( "get_inner_boundary_energy_out", (), (energy, builder.ERROR_CODE) ) builder.add_method( "get_outer_boundary_energy_out", (), (energy, builder.ERROR_CODE) ) builder.add_method( "get_mass_source_out", (builder.INDEX,), (col_density, builder.ERROR_CODE) ) builder.add_method( "get_energy_source_out", (builder.INDEX,), (Eint_density, builder.ERROR_CODE) ) #control parameters builder.add_method( "get_dtStart", (), (time, builder.ERROR_CODE) ) builder.add_method( "set_dtStart", (time,), (builder.ERROR_CODE,) ) builder.add_method( "get_dtMin", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_dtMin", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_dtTol", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_dtTol", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_errTol", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_errTol", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_maxDtIncrease", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_maxDtIncrease", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_maxIter", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_maxIter", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_interpOrder", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_interpOrder", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_maxStep", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_maxStep", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_useBE", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_useBE", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_verbosity", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_verbosity", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_PreTimestep", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_PreTimestep", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_PostTimestep", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_PostTimestep", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) #various builder.add_method( "get_time", (), (time, builder.ERROR_CODE,) ) builder.add_method( "get_number_of_user_parameters", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_number_of_user_parameters", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_max_index", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "get_nUserOut", (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( "set_nUserOut", (builder.NO_UNIT,), (builder.ERROR_CODE,) ) builder.add_method( "get_begin_time", (), (time, builder.ERROR_CODE,) ) builder.add_method( "set_begin_time", (time,), (builder.ERROR_CODE,) ) ''' builder.add_method( "get_nFail", (), (builder.NO_UNIT, builder.ERROR_CODE) ) ''' def define_parameters(self, builder): length = units.cm time = units.s mass = units.g velocity = length / time energy = mass * velocity**2. pressure = mass / length / time**2. force = mass * velocity / time col_density = mass / length**2. Eint_density = energy / length**2. builder.add_method_parameter( "get_alpha_function", "set_alpha_function", "alpha_function", "True if user-defined function is to be used for the viscosity parameter", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_alpha", "set_alpha", "alpha", "viscosity parameter, see Krumholz 2015", default_value = 1., must_set_before_get = True ) builder.add_method_parameter( "get_eos_function", "set_eos_function", "equation_of_state_function", "nonzero if user-defined function is to be used for the equation of state", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_gamma", "set_gamma", "gamma", "equation of state parameter, see Krumholz 2015", default_value = 1.000001, must_set_before_get = True ) builder.add_method_parameter( "get_delta", "set_delta", "delta", "equation of state parameter, see Krumholz 2015", default_value = 0. | velocity**2, must_set_before_get = True ) builder.add_method_parameter( "get_inner_pressure_boundary_type", "set_inner_pressure_boundary_type", "inner_pressure_boundary_type", "type for pressure inner boundary condition \n1: fixed mass flux \n2: fixed torque flux \n3: fixed torque", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_inner_pressure_boundary_mass_flux", "set_inner_pressure_boundary_mass_flux", "inner_pressure_boundary_mass_flux", "constant value for pressure inner boundary condition, ignored if inner boundary function is nonzero", default_value = 0. | mass / time, must_set_before_get = True ) builder.add_method_parameter( "get_inner_pressure_boundary_torque_flux", "set_inner_pressure_boundary_torque_flux", "inner_pressure_boundary_torque_flux", "constant value for pressure inner boundary condition, ignored if inner boundary function is nonzero", default_value = 0. | force * length / time, must_set_before_get = True ) builder.add_method_parameter( "get_inner_pressure_boundary_torque", "set_inner_pressure_boundary_torque", "inner_pressure_boundary_torque", "constant value for pressure inner boundary condition, ignored if inner boundary function is nonzero", default_value = 0. | force * length, must_set_before_get = True ) builder.add_method_parameter( "get_inner_enthalpy_boundary_type", "set_inner_enthalpy_boundary_type", "inner_enthalpy_boundary_type", "type for enthalpy inner boundary condition \n1: fixed enthalpy value \n2: fixed enthalpy gradient", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_inner_enthalpy_boundary_enthalpy", "set_inner_enthalpy_boundary_enthalpy", "inner_enthalpy_boundary_enthalpy", "constant value for enthalpy inner boundary condition, ignored if inner boundary function is nonzero", default_value = 0. | energy / mass, must_set_before_get = True ) builder.add_method_parameter( "get_inner_enthalpy_boundary_enthalpy_gradient", "set_inner_enthalpy_boundary_enthalpy_gradient", "inner_enthalpy_boundary_enthalpy_gradient", "constant value for enthalpy inner boundary condition, ignored if inner boundary function is nonzero", default_value = 0. | energy / length / mass, must_set_before_get = True ) builder.add_method_parameter( "get_inner_boundary_function", "set_inner_boundary_function", "inner_boundary_function", "nonzero if user-defined function is to be used for the inner boundary", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_outer_pressure_boundary_type", "set_outer_pressure_boundary_type", "outer_pressure_boundary_type", "type for pressure outer boundary condition \n1: fixed mass flux \n2: fixed torque flux \n3: fixed torque", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_outer_pressure_boundary_mass_flux", "set_outer_pressure_boundary_mass_flux", "outer_pressure_boundary_mass_flux", "constant value for pressure outer boundary condition, ignored if outer boundary function is nonzero", default_value = 0. | mass / time, must_set_before_get = True ) builder.add_method_parameter( "get_outer_pressure_boundary_torque_flux", "set_outer_pressure_boundary_torque_flux", "outer_pressure_boundary_torque_flux", "constant value for pressure outer boundary condition, ignored if outer boundary function is nonzero", default_value = 0. | force * length / time, must_set_before_get = True ) builder.add_method_parameter( "get_outer_pressure_boundary_torque", "set_outer_pressure_boundary_torque", "outer_pressure_boundary_torque", "constant value for pressure outer boundary condition, ignored if outer boundary function is nonzero", default_value = 0. | force * length, must_set_before_get = True ) builder.add_method_parameter( "get_outer_enthalpy_boundary_type", "set_outer_enthalpy_boundary_type", "outer_enthalpy_boundary_type", "type for enthalpy outer boundary condition \n1: fixed enthalpy value \n2: fixed enthalpy gradient", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_outer_enthalpy_boundary_enthalpy", "set_outer_enthalpy_boundary_enthalpy", "outer_enthalpy_boundary_enthalpy", "constant value for enthalpy outer boundary condition, ignored if outer boundary function is nonzero", default_value = 0. | energy / mass, must_set_before_get = True ) builder.add_method_parameter( "get_outer_enthalpy_boundary_enthalpy_gradient", "set_outer_enthalpy_boundary_enthalpy_gradient", "outer_enthalpy_boundary_enthalpy_gradient", "constant value for enthalpy outer boundary condition, ignored if outer boundary function is nonzero", default_value = 0. | energy / length / mass, must_set_before_get = True ) builder.add_method_parameter( "get_outer_boundary_function", "set_outer_boundary_function", "outer_boundary_function", "nonzero if user-defined function is to be used for the outer boundary", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_mass_source_function", "set_mass_source_function", "mass_source_function", "nonzero if user-defined function is to be used for mass source", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_mass_source_value", "set_mass_source_value", "mass_source_value", "constant mass source value, ignored if mass source function is nonzero", default_value = 0. | col_density / time, must_set_before_get = True ) builder.add_method_parameter( "get_internal_energy_source_function", "set_internal_energy_source_function", "internal_energy_source_function", "nonzero if user-defined function is to be used for internal energy source", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_internal_energy_source_value", "set_internal_energy_source_value", "internal_energy_source_value", "constant internal energy source value, ignored if energy source function is nonzero", default_value = 0. | Eint_density / time, must_set_before_get = True ) builder.add_method_parameter( "get_number_of_user_parameters", "set_number_of_user_parameters", "number_of_user_parameters", "the number of user-defined parameters for use in custom vader problems", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_dtStart", "set_dtStart", "initial_timestep", "the initial timestep of the simulation", default_value = 1. | time, must_set_before_get = True ) builder.add_method_parameter( "get_dtMin", "set_dtMin", "minimum_timestep", "the minimum timestep of the simulation", default_value = 1E-15, must_set_before_get = True ) builder.add_method_parameter( "get_dtTol", "set_dtTol", "maximum_tolerated_change", "the allowed relative change in column density/pressure/internal energy", default_value = 0.1, must_set_before_get = True ) builder.add_method_parameter( "get_errTol", "set_errTol", "error_tolerance", "implicit solver tolerance", default_value = 1E-6, must_set_before_get = True ) builder.add_method_parameter( "get_maxDtIncrease", "set_maxDtIncrease", "maximum_timestep_increase", "the maximum allowed relative time increase", default_value = 1.5, must_set_before_get = True ) builder.add_method_parameter( "get_maxIter", "set_maxIter", "maximum_iterations", "the maximum number of implicit iterations", default_value = 40, must_set_before_get = True ) builder.add_method_parameter( "get_interpOrder", "set_interpOrder", "interpolation_order", "the interpolation order; piecewise 1) constant 2) linear 3) parabolic", default_value = 2, must_set_before_get = True ) builder.add_method_parameter( "get_maxStep", "set_maxStep", "maximum_steps", "the maximum number of steps. negative indicates unbound", default_value = -1, must_set_before_get = True ) builder.add_method_parameter( "get_useBE", "set_useBE", "use_backwards_euler", "uses backwards Euler integration if true, Crank Nicolson if false", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_verbosity", "set_verbosity", "verbosity", "the verbosity of the simulation. 0 is silent, 3 very loud. note that this is only shown on console if redirection='none' is added to the vader initialization", default_value = 0, must_set_before_get = True ) builder.add_method_parameter( "get_PreTimestep", "set_PreTimestep", "pre_timestep_function", "if True, the user-defined PreTimestep function is used", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_PostTimestep", "set_PostTimestep", "post_timestep_function", "if True, the user-defined PostTimestep function is used", default_value = False, must_set_before_get = True ) builder.add_method_parameter( "get_nUserOut", "set_nUserOut", "number_of_user_outputs", "number of user-defined grid properties", default_value = 1, must_set_before_get = True ) builder.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "time to start integration at", default_value = 0.|time, must_set_before_get = True ) builder.add_method_parameter( "get_tabulated_size", "set_tabulated_size", "table_size", "length of the interpolation table", default_value = 1, must_set_before_get = True ) builder.add_array_parameter( "get_tabulated_radius", "set_tabulated_radius", "get_table_range", "radius_table", "radii of the velocity curve interpolation table" ) builder.add_array_parameter( "get_tabulated_velocity", "set_tabulated_velocity", "get_table_range", "velocity_table", "velocities of the velocity curve interpolation table" ) def define_properties(self, builder): builder.add_property('get_time', public_name = 'model_time') #builder.add_property('get_nFail', # public_name = 'failed_iterations') builder.add_property('get_inner_boundary_mass_out', public_name = 'inner_boundary_mass_out') builder.add_property('get_outer_boundary_mass_out', public_name = 'outer_boundary_mass_out') builder.add_property('get_inner_boundary_energy_out', public_name = 'inner_boundary_energy_out') builder.add_property('get_outer_boundary_energy_out', public_name = 'outer_boundary_energy_out') def define_particle_sets(self, builder): builder.define_grid('grid') builder.set_grid_range('grid', 'get_index_range_for_grid') builder.add_getter('grid', 'get_position_of_index', names=('r',)) builder.add_getter('grid', 'get_area_of_index', names=('area',)) builder.add_getter('grid', 'get_rotational_velocity_of_index', names=('rotational_velocity',)) builder.add_getter('grid', 'get_effective_potential_of_index', names=('effective_potential',)) builder.add_getter('grid', 'get_gravitational_potential_of_index', names=('gravitational_potential',)) builder.add_getter('grid', 'get_grid_column_density', names=('column_density',)) builder.add_setter('grid', 'set_grid_column_density', names=('column_density',)) builder.add_getter('grid', 'get_grid_pressure', names=('pressure',)) builder.add_setter('grid', 'set_grid_pressure', names=('pressure',)) builder.add_getter('grid', 'get_grid_internal_energy', names=('internal_energy',)) builder.add_setter('grid', 'set_grid_internal_energy', names=('internal_energy',)) builder.add_getter('grid', 'get_mass_source_out', names=('mass_source_difference',)) builder.add_getter('grid', 'get_energy_source_out', names=('internal_energy_source_difference',)) builder.define_grid('grid_user') builder.set_grid_range('grid_user', 'get_index_range_for_user_outputs') builder.add_getter('grid_user', 'get_grid_user_output', names=('value',)) builder.add_setter('grid_user', 'set_grid_user_output', names=('value',)) @property def mass(self): return (self.grid.area*self.grid.column_density).sum()
64,882
25.353777
163
py
amuse
amuse-main/src/amuse/community/mesa/__init__.py
try: from .interface import Mesa except: # fix for pip install error pass
83
11
29
py
amuse
amuse-main/src/amuse/community/mesa/interface.py
""" MESA chooser """ from amuse.community.mesa_r2208.interface import \ MESAInterface as MESAInterface_2208 from amuse.community.mesa_r15140.interface import \ MESAInterface as MESAInterface_15140 from amuse.community.mesa_r2208.interface import MESA as MESA_2208 from amuse.community.mesa_r15140.interface import MESA as MESA_15140 def MESAInterface(version="15140", **options): if str(version) == "2208": return MESAInterface_2208(**options) if str(version) == "15140": return MESAInterface_15140(**options) raise AttributeError( "This version of MESA is not (yet) supported by AMUSE" ) def MESA(version="15140", **options): if str(version) == "2208": return MESA_2208(**options) if str(version) == "15140": return MESA_15140(**options) raise AttributeError( "This version of MESA is not (yet) supported by AMUSE" ) Mesa = MESA
924
27.030303
68
py
amuse
amuse-main/src/amuse/community/hermite0/__init__.py
0
0
0
py
amuse
amuse-main/src/amuse/community/hermite0/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 SinglePointGravityFieldInterface from amuse.community.interface.gd import GravityFieldCode from amuse.community.hermite.interface import *
345
48.428571
73
py
amuse
amuse-main/src/amuse/community/petar/download.py
#!/usr/bin/env python import subprocess import os import urllib.request import urllib.parse import urllib.error from shutil import which from optparse import OptionParser class GetCodeFromHttp: filename_template = "{version}.tar.gz" name = ["PeTar", "SDAR", "FDPS"] url_template = [ "https://github.com/lwang-astro/PeTar/archive/{version}.tar.gz", "https://github.com/lwang-astro/SDAR/archive/{version}.tar.gz", "https://github.com/FDPS/FDPS/archive/{version}.tar.gz", ] version = [ "", "", "", ] def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename, name, version): print("unpacking", filename) arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( [ 'mv', '{name}-{version}'.format(name=name, version=version), name ], cwd=os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) os.mkdir('src') for i, url_template in enumerate(self.url_template): url = url_template.format(version=self.version[i]) filename = self.filename_template.format(version=self.version[i]) filepath = os.path.join(self.src_directory(), filename) print( "downloading version", self.version[i], "from", url, "to", filename ) if which('wget') is not None: arguments = ['wget', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) elif which('curl') is not None: arguments = ['curl', '-L', '-O', url] subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) else: urllib.request.urlretrieve(url, filepath) print("downloading finished") self.unpack_downloaded_file( filename, self.name[i], self.version[i] ) def main(petar_version='', sdar_version='', fdps_version=''): version = [ petar_version, sdar_version, fdps_version, ] instance = GetCodeFromHttp() instance.version = version instance.start() def new_option_parser(): result = OptionParser() result.add_option( "--petar-version", default='6ccac364e83ab05e4dad27e6eb6abdf7e5c89bcc', dest="petar_version", help="PeTar commit hash to download", type="string" ) result.add_option( "--sdar-version", default='a4ff4b3d076535684313a912ea31985c1431f827', dest="sdar_version", help="SDAR commit hash to download", type="string" ) result.add_option( "--fdps-version", default='55b2bafd316805bad22057cf4ee96217735279bf', dest="fdps_version", help="FDPS commit hash to download", type="string" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() main(**options.__dict__)
3,782
28.325581
77
py
amuse
amuse-main/src/amuse/community/petar/__init__.py
from .interface import Petar
29
14
28
py
amuse
amuse-main/src/amuse/community/petar/interface.py
from amuse.rfi.core import legacy_function, LegacyFunctionSpecification from amuse.community import ( CodeInterface, LiteratureReferencesMixIn, StoppingConditionInterface, StoppingConditions, ) from amuse.community.interface.gd import ( GravitationalDynamics, GravitationalDynamicsInterface, GravityFieldInterface, GravityFieldCode, ) from amuse.units import nbody_system class petarInterface( CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, GravityFieldInterface ): """ Parallel, Particle-Particle & Particle-Tree & Few-body integration module .. [#] ADS:2020MNRAS.497..536W (Wang, L., Iwasawa, M., Nitadori, K., Makino, J., 2020, MNRAS, 497, 536) .. [#] ADS:2020MNRAS.493.3398W (Wang, L., Nitadori, K., Makino, J., 2020, MNRAS, 493, 3398) .. [#] ADS:2018PASJ...70...70N (Namekata D., et al., 2018, PASJ, 70, 70) .. [#] ADS:2016PASJ...68...54I (Iwasawa M., Tanikawa A., Hosono N., Nitadori K., Muranushi T., Makino J., 2016, PASJ, 68, 54) .. [#] ADS:2015ComAC...2....6I (Iwasawa M., Portegies Zwart S., Makino J., 2015, ComAC, 2, 6) """ include_headers = ['interface.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__( self, name_of_the_worker="petar_worker", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @legacy_function def get_theta(): """ Get theta, the opening angle for building the tree """ function = LegacyFunctionSpecification() function.addParameter( 'theta_for_tree', dtype='float64', direction=function.OUT, description=( "theta, the opening angle for building the tree:" " between 0 and 1" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_theta(): """ Set theta, the opening angle for building the tree """ function = LegacyFunctionSpecification() function.addParameter( 'theta', dtype='float64', direction=function.IN, description=( "theta, the opening angle for building the tree:" " between 0 and 1" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function #@legacy_function #def get_gravitational_constant(): # """ # Get the value of gravitational constant # """ # function = LegacyFunctionSpecification() # function.addParameter( # 'gravitational_constant', dtype='float64', direction=function.OUT, # description=( # "gravitational constant:" # " positive" # ) # ) # function.result_type = 'int32' # function.result_doc = """ # 0 - OK # the parameter was retrieved # -1 - ERROR # could not retrieve parameter # """ # return function # #@legacy_function #def set_gravitational_constant(): # """ # Set gravitational constant # """ # function = LegacyFunctionSpecification() # function.addParameter( # 'gravitational_constant', dtype='float64', direction=function.IN, # description=( # "gravitational constant:" # " between 0 and 1" # ) # ) # function.result_type = 'int32' # function.result_doc = """ # 0 - OK # the parameter was set # -1 - ERROR # could not set parameter # """ # return function @legacy_function def get_changeover_rout(): """ Get r_out, the changeover radius outer boundary reference for switching long/short-range interactions (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_out', dtype='float64', direction=function.OUT, description=( "r_out, the changeover radius outer boundary reference" " for switching long/short-range interactions (if zero," " auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_changeover_rout(): """ Set r_out, the changeover radius outer boundary reference for switching long/short-range interactions (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_out', dtype='float64', direction=function.IN, description=( "r_out, the changeover radius outer boundary reference" " for switching long/short-range interactions (if zero," " auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_changeover_ratio(): """ Get ratio_r_cut, the changeover radius ratio between the inner and outer boundaries """ function = LegacyFunctionSpecification() function.addParameter( 'ratio_r_cut', dtype='float64', direction=function.OUT, description=( "ratio_r_cut, the changeover radius ratio between the inner" " and outer boundaries" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_changeover_ratio(): """ Set ratio_r_cut, the changeover radius ratio between the inner and outer boundaries """ function = LegacyFunctionSpecification() function.addParameter( 'ratio_r_cut', dtype='float64', direction=function.IN, description=( "ratio_r_cut, the changeover radius ratio between the inner" " and outer boundaries" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_group_radius(): """ Get r_bin, the group detection maximum radius to switch on AR (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_bin', dtype='float64', direction=function.OUT, description=( "r_bin, the group detection maximum radius to switch on AR" " (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_group_radius(): """ Set r_bin, the group detection maximum radius to switch on AR (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_bin', dtype='float64', direction=function.IN, description=( "r_bin, the group detection maximum radius to switch on AR" " (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_rsearch_min(): """ Get r_search_min, the minimum neighbor searching radius (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_search_min', dtype='float64', direction=function.OUT, description=( "r_search_min, the minimum neighbor searching radius" " (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_rsearch_min(): """ Set r_search_min, the minimum neighbor searching radius (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'r_search_min', dtype='float64', direction=function.IN, description=( "r_search_min, the minimum neighbor searching radius" " (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function @legacy_function def get_tree_step(): """ Get dt_soft, the tree time step (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'dt_soft', dtype='float64', direction=function.OUT, description=( "dt_soft, the tree time step (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def set_tree_step(): """ Set dt_soft, the minimum neighbor searching radius (if zero, auto-determine) """ function = LegacyFunctionSpecification() function.addParameter( 'dt_soft', dtype='float64', direction=function.IN, description=( "dt_soft, the tree time step (if zero, auto-determine)" ) ) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function class petar(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody=None, **keyword_arguments): self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, petarInterface(**keyword_arguments), convert_nbody, **keyword_arguments) 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_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_changeover_rout", "set_changeover_rout", "r_out", ("changeover radius outer boundary reference for switching" " long/short-range interactions (if zero, auto-determine)"), default_value=0.0 | nbody_system.length ) handler.add_method_parameter( "get_changeover_ratio", "set_changeover_ratio", "ratio_r_cut", "Changeover radius ratio between the inner and outer boundaries", default_value=0.1 ) handler.add_method_parameter( "get_group_radius", "set_group_radius", "r_bin", ("Group detection maximum radius to switch on AR (if zero," " auto-determine)"), default_value=0.0 | nbody_system.length ) handler.add_method_parameter( "get_rsearch_min", "set_rsearch_min", "r_search_min", "Minimum neighbor searching radius (if zero, auto-determine)", default_value=0.0 | nbody_system.length ) handler.add_method_parameter( "get_theta", "set_theta", "theta", "Tree opening angle", default_value=0.3 ) #handler.add_method_parameter( # "get_gravitational_constant", # "set_gravitational_constant", # "gravitational_constant", # "Gravitational constant", # default_value=0.3 #) handler.add_method_parameter( "get_tree_step", "set_tree_step", "dt_soft", "Tree time step (if zero, auto-determine)", default_value=0.0 | nbody_system.time ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) 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, ) ) handler.add_method( "set_changeover_rout", ( nbody_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_changeover_rout", (), ( nbody_system.length, handler.ERROR_CODE, ) ) handler.add_method( "set_group_radius", ( nbody_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_group_radius", (), ( nbody_system.length, handler.ERROR_CODE, ) ) handler.add_method( "set_rsearch_min", ( nbody_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_rsearch_min", (), ( nbody_system.length, handler.ERROR_CODE, ) ) handler.add_method( "set_tree_step", ( nbody_system.time, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_tree_step", (), ( nbody_system.time, handler.ERROR_CODE, ) ) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) PetarInterface = petarInterface Petar = petar
16,287
28.507246
129
py
amuse
amuse-main/src/amuse/community/capreole/__init__.py
from .interface import Capreole
32
15.5
31
py
amuse
amuse-main/src/amuse/community/capreole/interface.py
from amuse.community import * from amuse.community.interface.hydro import HydrodynamicsInterface from amuse.community.interface.common import CommonCode from amuse.units.generic_unit_system import * class CapreoleInterface( CodeInterface, HydrodynamicsInterface, StoppingConditionInterface, LiteratureReferencesMixIn ): """ Capreole is a grid-based astrophysical hydrodynamics code developed by Garrelt Mellema. It works in one, two dimensions, and three spatial dimensions and is programmed in Fortran 90. It is parallelized with MPI. For the hydrodynamics it relies on the Roe-Eulderink-Mellema (REM) solver, which is an approximate Riemann solver for arbitrary metrics. It can solve different hydrodynamics problems. Capreole has run on single processors, but also on massively parallel systems (e.g. 512 processors on a BlueGene/L). The reference for Capreole (original version): .. [#] ADS:1991A&A...252..718M (Mellema, Eulderink & Icke 1991, A&A 252, 718) """ def __init__(self, number_of_workers = 1, **options): CodeInterface.__init__(self, self.name_of_the_worker(number_of_workers),number_of_workers = number_of_workers, **options) LiteratureReferencesMixIn.__init__(self) def name_of_the_worker(self, number_of_workers): if number_of_workers > 1: return 'capreole_worker_mpi' else: return 'capreole_worker' @legacy_function def setup_mesh(): function = LegacyFunctionSpecification() function.addParameter('nmeshx', dtype='i', direction=function.IN) function.addParameter('nmeshy', dtype='i', direction=function.IN) function.addParameter('nmeshz', dtype='i', direction=function.IN) function.addParameter('xlength', dtype='d', direction=function.IN) function.addParameter('ylength', dtype='d', direction=function.IN) function.addParameter('zlength', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def initialize_grid(): function = LegacyFunctionSpecification() #function.addParameter('time', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary(): function = LegacyFunctionSpecification() for x in ["xbound1","xbound2","ybound1","ybound2","zbound1","zbound2"]: function.addParameter(x, dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_innerxstate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_outerxstate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_innerystate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_outerystate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_innerzstate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_boundary_outerzstate(): function = LegacyFunctionSpecification() for x in ["rho_in","rhvx_in","rhvy_in","rhvz_in","en_in"]: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_gravity_field(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['f_x','f_y','f_z']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_gravity_field(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['f_x','f_y','f_z']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' 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 get_time(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_position_of_index(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_index_of_position(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_mesh_size(): function = LegacyFunctionSpecification() function.addParameter('nmeshx', dtype='i', direction=function.OUT) function.addParameter('nmeshy', dtype='i', direction=function.OUT) function.addParameter('nmeshz', dtype='i', direction=function.OUT) function.result_type = 'i' return function def get_index_range_inclusive(self): ni,nj,nk,error = self.get_mesh_size() return (1, ni, 1, nj, 1, nk) @legacy_function def get_grid_momentum_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rhovx','rhovy','rhovz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho',]: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_grid_energy_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['energy']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function def get_number_of_grids(): return (0,1) set_grid_energy_density = None set_grid_density = None set_grid_momentum_density = None @legacy_function def get_boundary_index_range_inclusive(): function = LegacyFunctionSpecification() function.addParameter('index_of_boundary', dtype='i', direction=function.IN) function.addParameter('minx', dtype='i', direction=function.OUT) function.addParameter('maxx', dtype='i', direction=function.OUT) function.addParameter('miny', dtype='i', direction=function.OUT) function.addParameter('maxy', dtype='i', direction=function.OUT) function.addParameter('minz', dtype='i', direction=function.OUT) function.addParameter('maxz', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_boundary_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_boundary_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) for x in ['rho','rhovx','rhovy','rhovz','en']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def get_boundary_position_of_index(): """ Retrieves the x, y and z position of the center of the cell with coordinates i, j, k """ function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('index_of_boundary', dtype='i', direction=function.IN, default = 1) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function @legacy_function def set_parallel_decomposition(): """Set the number of processes per dimension, the total number of available processors must be nx * ny * nz """ function = LegacyFunctionSpecification() for x in ['nx','ny','nz']: function.addParameter(x, dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_parallel_decomposition(): """Retrieves the number of processes per dimension, the total number of available processors must be nx * ny * nz """ function = LegacyFunctionSpecification() for x in ['nx','ny','nz']: function.addParameter(x, dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_gamma(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gamma(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_hydro_state_at_point(): function = LegacyFunctionSpecification() for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN, default = 0) for x in ['rho','rhovx','rhovy','rhovz','rhoe']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('npoints', dtype='i', direction=function.LENGTH) function.result_type = 'i' function.must_handle_array = True return function class GLCapreoleInterface(CapreoleInterface): def __init__(self, **options): CodeInterface.__init__(self,name_of_the_worker = 'capreole_worker_gl', **options) @legacy_function def viewer(): function = LegacyFunctionSpecification() return function class Capreole(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter self.stopping_conditions = StoppingConditions(self) CommonCode.__init__(self, CapreoleInterface(**options), **options) 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_properties(self, handler): handler.add_property('get_time', public_name = "model_time") def define_methods(self, handler): handler.add_method('evolve_model', (time,), (handler.ERROR_CODE,)) handler.add_method( 'get_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX,), (length, length, length, handler.ERROR_CODE,) ) density = mass / (length**3) momentum_density = mass / (time * (length**2)) energy_density = mass / ((time**2) * length) acceleration = length / time ** 2 handler.add_method( 'set_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX, density, momentum_density, momentum_density, momentum_density, energy_density, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX), (density, momentum_density, momentum_density, momentum_density, energy_density, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX), (density, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_momentum_density', (handler.INDEX, handler.INDEX, handler.INDEX), (momentum_density, momentum_density, momentum_density, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX), (energy_density, handler.ERROR_CODE,) ) handler.add_method( 'get_gravity_field', (handler.INDEX, handler.INDEX, handler.INDEX), (acceleration, acceleration, acceleration, handler.ERROR_CODE,) ) handler.add_method( 'set_gravity_field', (handler.INDEX, handler.INDEX, handler.INDEX, acceleration, acceleration, acceleration,), (handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (time, handler.ERROR_CODE,) ) handler.add_method( 'setup_mesh', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, length, length, length,), (handler.ERROR_CODE,) ) handler.add_method( 'set_boundary', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( 'set_parallel_decomposition', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT), (handler.ERROR_CODE,) ) handler.add_method( 'set_boundary_state', (handler.INDEX, handler.INDEX, handler.INDEX, density, momentum_density, momentum_density, momentum_density, energy_density, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_state', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, momentum_density, momentum_density, momentum_density, energy_density, handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (length, length, length, handler.ERROR_CODE,) ) handler.add_method( 'get_boundary_index_range_inclusive', (handler.INDEX), (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_timestep", (), (time, handler.ERROR_CODE,) ) handler.add_method( "set_timestep", (time, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_hydro_state_at_point', (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed), (generic_unit_system.density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.momentum_density, generic_unit_system.energy_density, handler.ERROR_CODE) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): handler.define_grid('grid') handler.set_grid_range('grid', 'get_index_range_inclusive') handler.add_getter('grid', 'get_position_of_index', names=('x','y','z')) handler.add_getter('grid', 'get_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) handler.add_setter('grid', 'set_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) handler.add_getter('grid', 'get_grid_density', names=('rho',)) handler.add_getter('grid', 'get_grid_momentum_density', names=('rhovx','rhovy','rhovz')) handler.add_getter('grid', 'get_grid_energy_density', names=('energy',)) handler.define_grid('acceleration_grid') handler.set_grid_range('acceleration_grid', 'get_index_range_inclusive') handler.add_getter('acceleration_grid', 'get_position_of_index', names=('x','y','z')) handler.add_setter('acceleration_grid', 'set_gravity_field', names=('ax','ay','az')) handler.add_getter('acceleration_grid', 'get_gravity_field', names=('ax','ay','az')) #handler.add_setter('grid', 'set_momentum_density', names=('rhovx','rhovy','rhovz')) #handler.add_setter('grid', 'set_density', names=('rho',)) #handler.add_setter('grid', 'set_energy_density', names=('energy',)) def define_parameters(self, handler): handler.add_method_parameter( "get_gamma", "set_gamma", "gamma", "ratio of specific heats used in equation of state", default_value = 1.6666666666666667 ) handler.add_caching_parameter( "set_boundary", "xbound1", "xbound1", "boundary conditions on first (inner, left) X boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "xbound2", "xbound2", "boundary conditions on second (outer, right) X boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "ybound1", "ybound1", "boundary conditions on first (inner, front) Y boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "ybound2", "ybound2", "boundary conditions on second (outer, back) Y boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "zbound1", "zbound1", "boundary conditions on first (inner, bottom) Z boundary", "reflective", ) handler.add_caching_parameter( "set_boundary", "zbound2", "zbound2", "boundary conditions on second (outer, top) Z boundary", "reflective", ) handler.add_vector_parameter( "x_boundary_conditions", "boundary conditions for the X directorion", ("xbound1", "xbound2") ) handler.add_vector_parameter( "y_boundary_conditions", "boundary conditions for the Y directorion", ("ybound1", "ybound2") ) handler.add_vector_parameter( "z_boundary_conditions", "boundary conditions for the Z directorion", ("zbound1", "zbound2") ) handler.add_caching_parameter( "set_parallel_decomposition", "nx", "nproc_x", "number of processors for the x direction", 0, ) handler.add_caching_parameter( "set_parallel_decomposition", "ny", "nproc_y", "number of processors for the y direction", 0, ) handler.add_caching_parameter( "set_parallel_decomposition", "nz", "nproc_z", "number of processors for the z direction", 0, ) handler.add_vector_parameter( "parallel_decomposition", "number of processors for each dimensions", ("nproc_x", "nproc_y", "nproc_z") ) handler.add_caching_parameter( "setup_mesh", "nmeshx", "nx", "number of cells in the x direction", 10, ) handler.add_caching_parameter( "setup_mesh", "nmeshy", "ny", "number of cells in the y direction", 10, ) handler.add_caching_parameter( "setup_mesh", "nmeshz", "nz", "number of cells in the z direction", 10, ) handler.add_caching_parameter( "setup_mesh", "xlength", "length_x", "length of model in the x direction", 10 | length, ) handler.add_caching_parameter( "setup_mesh", "ylength", "length_y", "length of model in the x direction", 10 | length, ) handler.add_caching_parameter( "setup_mesh", "zlength", "length_z", "length of model in the z direction", 10 | length, ) handler.add_vector_parameter( "mesh_size", "number of cells in the x, y and z directions", ("nx", "ny", "nz") ) handler.add_vector_parameter( "mesh_length", "length of the model in the x, y and z directions", ("length_x", "length_y", "length_z") ) self.stopping_conditions.define_parameters(handler) def get_index_range_inclusive(self): """ Returns the min and max values of indices in each direction. The range is inclusive, the min index and max index both exist and can be queried. The total number of cells in one direction is max - min + 1. """ nx, ny, nz = self.get_mesh_size() return (1, nx, 1, ny, 1, nz) def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def itergrids(self): yield self.grid def define_state(self, handler): CommonCode.define_state(self, handler) #handler.add_transition('END', 'INITIALIZED', 'initialize_code', False) handler.add_method('INITIALIZED', 'set_parallel_decomposition') 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('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','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_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_transition('EDIT', 'RUN', 'initialize_grid') handler.add_method('RUN', 'evolve_model') handler.add_method('RUN', 'get_hydro_state_at_point') for state in ['EDIT', 'RUN']: for methodname in [ 'get_grid_state', 'set_grid_state', 'get_grid_density', 'set_grid_density', 'set_grid_energy_density', 'get_grid_energy_density', 'get_grid_momentum_density', 'set_grid_momentum_density', 'get_position_of_index', 'get_index_of_position', 'set_grid_scalar', 'get_grid_scalar', 'get_mesh_size', 'set_gravity_field', 'get_gravity_field', 'get_boundary_state', 'set_boundary_state', 'get_boundary_position_of_index', 'get_boundary_index_range_inclusive' ]: handler.add_method(state, methodname) self.stopping_conditions.define_state(handler) def specify_boundary_grid(self, definition, index_of_boundary, index_of_grid = 1): definition.set_grid_range('get_boundary_index_range_inclusive') definition.add_getter('get_boundary_position_of_index', names=('x','y','z')) definition.add_getter('get_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_setter('set_boundary_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.define_extra_keywords({'index_of_boundary': index_of_boundary}) BOUNDARY_NAME_TO_INDEX = { 'xbound1': 1, 'xbound2': 2, 'ybound1': 3, 'ybound2': 4, 'zbound1': 5, 'zbound2': 6, } def get_boundary_grid(self, name): if not name in self.BOUNDARY_NAME_TO_INDEX: raise Exception("boundary name is not known {0}".format(name)) index_of_boundary = self.BOUNDARY_NAME_TO_INDEX[name] return self._create_new_grid(self.specify_boundary_grid, index_of_boundary = index_of_boundary, index_of_grid = 1) def get_extended_grid(self, index_of_grid = 1): return self._create_new_grid(self.sepecify_extended_grid, index_of_grid = index_of_grid) def get_index_range_extended(self, index_of_grid = 1): i0,i1, j0,j1, k0,k1 = self.get_index_range_inclusive() dj = 2 if j1 > j0 else 0 dk = 2 if k1 > k0 else 0 return i0-2, i1+2, j0-dj, j0+dj, k0-dk, k1+dk def sepecify_extended_grid(self, definition, index_of_grid = 1): definition.set_grid_range('get_index_range_extended') definition.add_getter('get_position_of_index', names=('x','y','z')) definition.add_getter('get_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_setter('set_grid_state', names=('rho', 'rhovx','rhovy','rhovz','energy')) definition.add_getter('get_grid_density', names=('rho',)) definition.add_getter('get_grid_momentum_density', names=('rhovx','rhovy','rhovz')) definition.add_getter('get_grid_energy_density', names=('energy',))
32,009
36.134571
133
py
amuse
amuse-main/src/amuse/community/sei/example.py
import os import sys import numpy as np import math from .interface import SeiInterface OMEGA = 1.0 if __name__ == '__main__': instance = SeiInterface() instance.initialization() impactparameter = 8.0 * 0.69336127435063 #8 Hill radii instance.set_state(impactparameter, np.pi * 300.0/2.0*OMEGA*impactparameter, 0.0, 0.0, -3.0/2.0*OMEGA*impactparameter, 0.0) for t in np.arange(0, 6,1): print(instance.get_state()['x'],\ instance.get_state()['y'],\ instance.get_state()['z']) instance.evolve(t) instance.stop()
705
23.344828
63
py
amuse
amuse-main/src/amuse/community/sei/test_sei.py
from amuse.test.amusetest import TestWithMPI from amuse.units import nbody_system from amuse.units import units import os import sys import numpy import math from amuse.community.sei.interface import SeiInterface from amuse.community.sei.interface import Sei from amuse import datamodel class TestSeiInterface(TestWithMPI): def test0(self): instance = SeiInterface() instance.initialization() instance.set_state(0,1,0,0,0,0,0) for i in range(0,10): instance.evolve(i) print(instance.get_state(0)) instance.stop() class TestSei(TestWithMPI): def test0(self): convert_nbody = nbody_system.nbody_to_si(1.0 | units.MSun, 1 | units.AU) particle = datamodel.Particles(1) particle.position = [1.0, 0.0, 0.0,]|units.AU particle.velocity = [0.0, 2.0*3.1415926535*1.0/365, 0.0] | units.AUd sei = Sei(convert_nbody) sei.initialization() sei.particles.add_particles(particle) print(sei.particles.position.x.value_in(units.AU)) for i in range(365): sei.evolve_model(i|units.day) print(sei.particles.position.x.value_in(units.AU))
1,213
28.609756
80
py
amuse
amuse-main/src/amuse/community/sei/__init__.py
from .interface import Sei
27
13
26
py
amuse
amuse-main/src/amuse/community/sei/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics from amuse.units import nbody_system from amuse.community.interface import common class SeiInterface(CodeInterface): include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="sei_worker", **keyword_arguments) @legacy_function def initialization(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def select_integrator(): function = LegacyFunctionSpecification() function.addParameter('i', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.OUT, description = """ An index assigned to the newly created particle. This index is supposed to be a local index for the code (and not valid in other instances of the code or in other codes) """ ) function.addParameter('x', dtype='float64', direction=function.IN) function.addParameter('y', dtype='float64', direction=function.IN) function.addParameter('z', dtype='float64', direction=function.IN) function.addParameter('vx', dtype='float64', direction=function.IN) function.addParameter('vy', dtype='float64', direction=function.IN) function.addParameter('vz', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('dt', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', 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('t', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', 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('x', dtype='float64', direction=function.IN) function.addParameter('y', dtype='float64', direction=function.IN) function.addParameter('z', dtype='float64', direction=function.IN) function.addParameter('vx', dtype='float64', direction=function.IN) function.addParameter('vy', dtype='float64', direction=function.IN) function.addParameter('vz', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', 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('x', dtype='float64', direction=function.OUT) function.addParameter('y', dtype='float64', direction=function.OUT) function.addParameter('z', dtype='float64', direction=function.OUT) function.addParameter('vx', dtype='float64', direction=function.OUT) function.addParameter('vy', dtype='float64', direction=function.OUT) function.addParameter('vz', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def evolve(): function = LegacyFunctionSpecification() function.addParameter('t_end', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', 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.result_type = 'int32' return function class Sei(common.CommonCode): def __init__(self, unit_converter=None, **options): legacy_interface = SeiInterface(**options) self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, legacy_interface, **options) 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') def define_methods(self, handler): #GravitationalDynamics.define_methods(self, handler) common.CommonCode.define_methods(self, handler) handler.add_method( 'evolve', (nbody_system.time,), public_name = 'evolve_model' ) handler.add_method( "new_particle", ( nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "delete_particle", ( handler.INDEX ), ( handler.ERROR_CODE ) ) handler.add_method( "get_state", ( handler.INDEX, ), ( nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, handler.ERROR_CODE ) ) handler.add_method( "set_state", ( handler.INDEX, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, ), ( 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())
7,494
38.447368
228
py
amuse
amuse-main/src/amuse/community/galactics/gas_interface.py
import os import sys import os.path import pickle import random import numpy import hashlib from subprocess import Popen, PIPE from amuse.units.core import * from amuse.community import * from amuse.community.interface.common import CommonCode, CommonCodeInterface from amuse.support.options import option from amuse.rfi.core import PythonCodeInterface # KD95 = 1995MNRAS.277.1341K parameters={ "halo_type_parameter": dict(dtype="int32", default=3 ,description="type of halo 0=no,1=KD95,2=fixed (file),3=spherical df"), "halo_scale_radius": dict(dtype="float64", default=13.7 | nbody_system.length ,description="halo scale parameter"), "halo_virial_radius": dict(dtype="float64", default=40. | nbody_system.length ,description="halo 'virial' radius, beyond this the density is tapered smoothly"), "halo_density_parameter": dict(dtype="float64", default=0.01 | nbody_system.density ,description="halo density parameter"), "halo_einasto_nindex": dict(dtype="float64", default=5. ,description="einasto profile n-index"), "halo_einasto_mass": dict(dtype="float64", default=400. ,description="einasto profile total mass"), "halo_central_potential": dict(dtype="float64", default=-28. | nbody_system.potential ,description="KD95 central potential"), "halo_v0": dict(dtype="float64", default=2.5 | nbody_system.speed ,description="KD95 v0 parameter"), "halo_q": dict(dtype="float64", default=1. ,description="KD95 q parameter"), "halo_coreparam": dict(dtype="float64", default=0.0 ,description="KD95 core parameter"), "halo_Ra": dict(dtype="float64", default=4.| nbody_system.length ,description="KD95 Ra parameter"), "disk_type_parameter": dict(dtype="int32", default=3 ,description="type of disk (0=no,1=KD95,2=gas disk,3=KD95 + gas)"), "disk_mass": dict(dtype="float64", default=50. ,description="(approx) stellar disk mass"), "disk_scale_length": dict(dtype="float64", default=3. | nbody_system.length,description="stellar disk exponential scale length"), "disk_outer_radius": dict(dtype="float64", default=13. | nbody_system.length,description="stellar disk outer radius"), "disk_scale_height": dict(dtype="float64", default=0.6 | nbody_system.length,description="stellar disk scale height"), "disk_truncation_dr": dict(dtype="float64", default=1. | nbody_system.length,description="stellar disk truncation width"), "gas_disk_mass": dict(dtype="float64", default=5. ,description="gas disk mass"), "gas_disk_scale_length": dict(dtype="float64", default=3. | nbody_system.length,description="gas disk scale length (1/r profile)"), "gas_disk_outer_radius": dict(dtype="float64", default=26. | nbody_system.length,description="gas disk outer radius"), "gas_disk_truncation_dr": dict(dtype="float64", default=1. | nbody_system.length,description="gas disk truncation width"), "gas_disk_sound_speed": dict(dtype="float64", default=0.12 | nbody_system.speed ,description="gas disk sound speed"), "gas_disk_gamma": dict(dtype="float64", default=1. ,description="gas disk polytropic index"), "gas_disk_number_of_radial_bins": dict(dtype="int32", default=50 ,description="gas disk nr of radial bins"), "gas_disk_max_z": dict(dtype="float64", default=5. | nbody_system.length,description="gas disk max z of grid"), "bulge_type_parameter": dict(dtype="int32", default=3 ,description="type of bulge (0=no, 1=KD95 (untested), 3=spherical df)"), "bulge_cutoff_potential": dict(dtype="float64", default= -20 | nbody_system.potential ,description="KD95 cutoff potential"), "bulge_velocity_dispersion": dict(dtype="float64", default= 1. | nbody_system.speed ,description="KD95 velocity dispersion"), "bulge_scale_radius": dict(dtype="float64", default=0.8 | nbody_system.length,description="bulge scale radius"), "bulge_cutoff_radius": dict(dtype="float64", default=7. | nbody_system.length,description="bulge cutoff radius"), "bulge_density_parameter": dict(dtype="float64", default=5.5 | nbody_system.density,description="bulge density parameter"), "radial_grid_delta_r": dict(dtype="float64", default=0.025 | nbody_system.length,description="radial grid cell size"), "number_of_grid_intervals": dict(dtype="int32", default=20000 ,description="number of radial grid points"), "order_of_multipole_expansion": dict(dtype="int32", default=12 ,description="order of multipole expansion"), "disk_central_radial_vdisp_over_z_vdisp": dict(dtype="float64", default=1. ,description="disk central rdial velocity dispersion in units of z dispersion"), "disk_scale_length_of_radial_vdisp": dict(dtype="float64", default=3. | nbody_system.length ,description="scale length of radial vel dispersion"), "number_of_radial_steps_correction_fns": dict(dtype="int32", default=200 ,description="number of radial steps correction functions"), "number_of_iterations": dict(dtype="int32", default=12 ,description="number of diskdf iterations"), "halo_streaming_fraction": dict(dtype="float64", default=0.5 ,description="halo streaming factor (to impose rotation, 0.5 is no rotation)"), "halo_number_of_particles": dict(dtype="int32", default=10000 ,description="number of particles in halo"), "halo_random_seed": dict(dtype="int64", default=0 ,description="halo random seed"), "halo_do_center_flag": dict(dtype="bool", default=False ,description="whether to independently center halo"), "bulge_streaming_fraction": dict(dtype="float64", default=0.5 ,description="bulge streaming fraction (to impose rotation)"), "bulge_number_of_particles": dict(dtype="int32", default=1000 ,description="number of bulge particles"), "bulge_random_seed": dict(dtype="int64", default=12345678 ,description="bulge random seed"), "bulge_do_center_flag": dict(dtype="bool", default=False ,description="whether to independently center bulge "), "disk_number_of_particles": dict(dtype="int32", default=1000 ,description="stellar disk number of particles"), "disk_random_seed": dict(dtype="int64", default=98765432 ,description="stellar disk random seed"), "disk_do_center_flag": dict(dtype="bool", default=False ,description="whether to independently center the stellar disk"), "gas_disk_number_of_particles": dict(dtype="int32", default=1000 ,description="number of gas particles"), "gas_disk_velocity_dispersion": dict(dtype="float64", default=0. ,description="velocity dispersion of gas particles"), "gas_disk_random_seed": dict(dtype="int64", default=543212345 ,description="random seed for gas disk"), "reuse_cached_model" : dict(dtype="bool", default=True, description="if True reuse cached preexisting model with the same parameters"), } class GaslactICsImplementation(object): def __init__(self): self._output_directory = "./" self._particles_generated = False self._particle_data = numpy.array([]) self._bin_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "gbin") def get_output_path(self, output_directory): output_directory.value = self._output_directory return 0 def set_output_path(self, output_directory): self._output_directory = output_directory return 0 def set_src_bin_path(self, src_bin_path): self._bin_path = src_bin_path return 0 def initialize_code(self): self.set_default_parameter_values() return 0 #parameter getters & setters for par in parameters: exec("def get_"+par+"(self, value): value.value = self._"+par+"; return 0") exec("def set_"+par+"(self, value): self._"+par+" = value; return 0") def set_default_parameter_values(self): for par in parameters: if hasattr(parameters[par]["default"],"unit"): exec("self._"+par+"=parameters[par]['default'].number") else: exec("self._"+par+"=parameters[par]['default']") def cleanup_code(self): return 0 def generate_in_dbh_string(self): in_dbh=[] in_dbh.append( str(self._halo_type_parameter) ) if self._halo_type_parameter==1: in_dbh.append( str(self._halo_central_potential)+" "+ str(self._halo_v0)+" "+ str(self._halo_q)+" "+ str(self._halo_coreparam)+" "+ str(self._halo_Ra) ) if self._halo_type_parameter==3: in_dbh.append( str(self._halo_scale_radius)+" "+str(self._halo_virial_radius)+" "+str(self._halo_density_parameter) ) in_dbh.append(str(self._disk_type_parameter)) if self._disk_type_parameter in [1,3]: in_dbh.append( str(self._disk_mass)+" "+ str(self._disk_scale_length)+" "+ str(self._disk_outer_radius)+" "+ str(self._disk_scale_height)+" "+ str(self._disk_truncation_dr) ) if self._disk_type_parameter in [2,3]: in_dbh.append( str(self._gas_disk_mass)+" "+ str(self._gas_disk_scale_length)+" "+ str(self._gas_disk_outer_radius)+" "+ str(self._gas_disk_truncation_dr) ) in_dbh.append( str(self._gas_disk_sound_speed)+" "+ str(self._gas_disk_gamma)+" "+ str(self._gas_disk_number_of_radial_bins)+" "+ str(self._gas_disk_max_z) ) in_dbh.append(str(self._bulge_type_parameter)) if self._bulge_type_parameter==1: in_dbh.append( str(self._bulge_density_parameter)+" "+ str(self._bulge_cutoff_potential)+" "+ str(self._bulge_velocity_dispersion) ) if self._bulge_type_parameter==3: in_dbh.append( str(self._bulge_scale_radius)+" "+ str(self._bulge_cutoff_radius)+" "+ str(self._bulge_density_parameter) ) in_dbh.append( str(self._radial_grid_delta_r)+" "+ str(self._number_of_grid_intervals) ) in_dbh.append( str(self._order_of_multipole_expansion)) in_dbh.append( "") in_dbh="\n".join(in_dbh) # print "in_dbh:\n", in_dbh return in_dbh def generate_in_diskdf_string(self): in_diskdf=[] in_diskdf.append( str(self._disk_central_radial_vdisp_over_z_vdisp)+" "+str(self._disk_scale_length_of_radial_vdisp)) in_diskdf.append( str(self._number_of_radial_steps_correction_fns)) in_diskdf.append( str(self._number_of_iterations)) in_diskdf.append("diskdf.ps/ps") in_diskdf="\n".join(in_diskdf) # print "in_diskdf:\n", in_diskdf return in_diskdf def generate_in_halo_string(self): in_halo = "{0:.15}\n".format(self._halo_streaming_fraction) in_halo += "{0}\n".format(self._halo_number_of_particles) in_halo += "{0}\n".format(self._halo_random_seed) in_halo += "{0}\n".format(1 if self._halo_do_center_flag else 0) in_halo += "dbh.dat\n" # print "in_halo:\n", in_halo return in_halo def generate_in_bulge_string(self): in_bulge = "{0:.15}\n".format(self._bulge_streaming_fraction) in_bulge += "{0}\n".format(self._bulge_number_of_particles) in_bulge += "{0}\n".format(self._bulge_random_seed) in_bulge += "{0}\n".format(1 if self._bulge_do_center_flag else 0) in_bulge += "dbh.dat\n" # print "in_bulge:\n", in_bulge return in_bulge def generate_in_disk_string(self): in_disk = "{0}\n".format(self._disk_number_of_particles) in_disk += "{0}\n".format(self._disk_random_seed) in_disk += "{0}\n".format(1 if self._disk_do_center_flag else 0) in_disk += "dbh.dat\n" # print "in_disk:\n", in_disk return in_disk def generate_in_gas_string(self): in_gas = "{0}\n".format(self._gas_disk_number_of_particles) in_gas += "{0}\n0.\n".format(self._gas_disk_velocity_dispersion) in_gas += "{0}\n".format(self._gas_disk_random_seed) # print "in_gas:\n", in_gas return in_gas def _new_dbh_dir(self, data_directory,in_dbh,in_diskdf): if not os.path.exists(data_directory): os.makedirs(data_directory) # with open(os.path.join(data_directory, "in.gendenspsi"), "w") as f: # f.write("2000 40\n") # for clarity, also store the used input parameters in this directory: with open(os.path.join(data_directory, "in.dbh"), "w") as f: f.write(in_dbh) with open(os.path.join(data_directory, "in.diskdf"), "w") as f: f.write(in_diskdf) # remove finished-step files for f in ['dbh.finished','getfreqs.finished','diskdf.finished']: try: os.remove(os.path.join( data_directory, f)) except: pass def _data_directory(self,in_dbh,in_diskdf): modelhash=hashlib.sha1((in_dbh+in_diskdf).encode()).hexdigest() return os.path.join(self._output_directory, "model_"+modelhash) def model_present(self,model_present): in_dbh = self.generate_in_dbh_string() in_diskdf = self.generate_in_diskdf_string() data_directory=self._data_directory(in_dbh,in_diskdf) model_present.value=self._directory_contains_valid_model(data_directory) return 0 def _directory_contains_valid_model(self,data_directory): if os.path.exists(os.path.join( data_directory)) and \ os.path.exists(os.path.join( data_directory, 'dbh.dat')) and \ os.path.exists(os.path.join( data_directory, 'dbh.finished')) and \ os.path.exists(os.path.join( data_directory, 'getfreqs.finished')) and \ (os.path.exists(os.path.join( data_directory, 'diskdf.finished')) or self._disk_type_parameter in [0,2]): return True else: return False def _location_dbh_dat(self, in_dbh,in_diskdf): data_directory=self._data_directory(in_dbh,in_diskdf) if self._directory_contains_valid_model(data_directory) and self._reuse_cached_model: is_new = False else: is_new = True self._new_dbh_dir(data_directory,in_dbh,in_diskdf) return data_directory, is_new def commit_parameters(self): try: in_dbh = self.generate_in_dbh_string() in_diskdf = self.generate_in_diskdf_string() dbh_dir, is_new = self._location_dbh_dat(in_dbh, in_diskdf) self._cwd = dbh_dir if not is_new: return 0 print("Writing output to:", self._cwd) print("\n running dbh \n\n") proc=Popen([os.path.join(self._bin_path, "dbh")], cwd = self._cwd, stdin = PIPE, stdout = sys.stdout, stderr = sys.stderr) proc.communicate(in_dbh.encode()) if proc.returncode==0: open(os.path.join(dbh_dir,"dbh.finished"),'a').close() else: raise Exception("dbh fail") print("\n running getfreqs \n\n") proc=Popen([os.path.join(self._bin_path, "getfreqs")], cwd = self._cwd, stdin = PIPE, stdout = sys.stdout, stderr = sys.stderr) proc.communicate() if proc.returncode==0: open(os.path.join(dbh_dir,"getfreqs.finished"),'a').close() else: raise Exception("getfreqs fail") print("\n running diskdf \n\n") if self._disk_type_parameter in [1,3]: proc=Popen([os.path.join(self._bin_path, "diskdf")], cwd = self._cwd, stdin = PIPE, stdout = sys.stdout, stderr = sys.stderr) proc.communicate(in_diskdf.encode()) if proc.returncode==0: open(os.path.join(dbh_dir,"diskdf.finished"),'a').close() else: raise Exception("diskdf fail") return 0 except Exception as ex: print("Exception occurred in commit_parameters:", ex) return -1 def recommit_parameters(self): return self.commit_parameters() def get_number_of_particles_updated(self, number_of_particles_updated,number_of_gas_particles_updated): if self._particles_generated: number_of_particles_updated.value = self._number_of_particles_updated number_of_gas_particles_updated.value = self._number_of_gas_particles_updated self._particles_generated = False else: number_of_particles_updated.value = 0 return 0 def generate_particles(self): try: if self._disk_type_parameter in [1,3] and self._disk_number_of_particles>0: in_disk = self.generate_in_disk_string() process = Popen([os.path.join(self._bin_path, "gendisk")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out,err=process.communicate(in_disk.encode()) if process.returncode != 0: print("error:", err) return -2 print(err ," ****") disk_data=numpy.frombuffer(out,dtype="float32") else: disk_data=numpy.array([]) if self._disk_type_parameter in [2,3] and self._gas_disk_number_of_particles>0: in_gas = self.generate_in_gas_string() process = Popen([os.path.join(self._bin_path, "gengas")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out,err=process.communicate(in_gas.encode()) if process.returncode != 0: print("error:", err) return -2 gas_data=numpy.frombuffer(out,dtype="float32") else: gas_data=numpy.array([]) if self._bulge_type_parameter in [1,3] and self._bulge_number_of_particles>0: in_bulge = self.generate_in_bulge_string() process = Popen([os.path.join(self._bin_path, "genbulge")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out,err=process.communicate(in_bulge.encode()) if process.returncode != 0: print("error:", err) return -3 bulge_data=numpy.frombuffer(out,dtype="float32") else: bulge_data=numpy.array([]) if self._halo_type_parameter in [1,3] and self._halo_number_of_particles>0: in_halo = self.generate_in_halo_string() process = Popen([os.path.join(self._bin_path, "genhalo")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out, err = process.communicate(in_halo.encode()) if process.returncode != 0: print("error:", err) return -4 halo_data=numpy.frombuffer(out,dtype="float32") else: halo_data=numpy.array([]) self._number_of_particles_updated = len(gas_data)//8+(len(halo_data)+len(bulge_data)+len(disk_data))//7 self._number_of_gas_particles_updated = len(gas_data)//8 self._number_of_halo_particles=len(halo_data)//7 self._number_of_bulge_particles=len(bulge_data)//7 self._number_of_disk_particles=len(disk_data)//7 self._number_of_gas_particles=len(gas_data)//8 gas_posdata=gas_data[8*numpy.arange(self._number_of_gas_particles*7)//7] gammafactor=1. if self._gas_disk_gamma==1 else 1/self._gas_disk_gamma/(self._gas_disk_gamma-1) self._gas_internal_energy=gammafactor*gas_data[8*numpy.arange(self._number_of_gas_particles)+7]**2 data=numpy.concatenate((gas_posdata,disk_data,bulge_data,halo_data)) self._particle_data = numpy.reshape(data,( self._number_of_particles_updated,7)) self._particles_generated = True return 0 except Exception as ex: print("Exception occurred in generate_particles:", ex) return -1 def get_number_of_particles(self,nhalo,nbulge,ndisk,ngas): try: nhalo.value=self._number_of_halo_particles nbulge.value=self._number_of_bulge_particles ndisk.value=self._number_of_disk_particles ngas.value=self._number_of_gas_particles return 0 except: return -1 def get_mass(self, index_of_the_particle, mass, length): try: mass.value = self._particle_data[index_of_the_particle, 0] return 0 except: return -1 def get_position(self, index_of_the_particle, x, y, z, length): try: x.value = self._particle_data[index_of_the_particle, 1] y.value = self._particle_data[index_of_the_particle, 2] z.value = self._particle_data[index_of_the_particle, 3] return 0 except: return -1 def get_velocity(self, index_of_the_particle, vx, vy, vz, length): try: vx.value = self._particle_data[index_of_the_particle, 4] vy.value = self._particle_data[index_of_the_particle, 5] vz.value = self._particle_data[index_of_the_particle, 6] return 0 except: return -1 def get_internal_energy(self, index_of_the_particle, u, length): try: u.value = self._gas_internal_energy[index_of_the_particle] return 0 except: return -1 class GaslactICsInterface(PythonCodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ GaslactICs is a variant of GalactICs which allows for the inclusion of a gas disk. It generates self-consistent disc-bulge-halo-gas galaxy models. The bulge and halo distribution functions (DFs) are functions of E and L_z only. The halo's flattening and rotation can be specified. The disc DF is a function of E and L_z and a third 'integral', E_z, the vertical energy, which is approximately conserved in a warm disc with vertical extent. A simulation of a sample model shows that in practice the models are very close to equilibrium, making them ideal for experiments on instabilities in galactic discs. Relevant references: .. [#] Kuijken K., Dubinski J., 1995, MNRAS, 277, 1341 (original version) .. [#] Widrow L.M., Dubinski J., 2005, ApJ, 631, 838 (2nd version) .. [#] Widrow L.M., Pym B., Dubinski J., 2008, ApJ, 679, 1239 (current version) .. [#] Pelupessy, F. I. et al., 2013, The Astrophysical Multipurpose Software Environment, Astronomy and Astrophysics 557, 84 [2013A&A...557A..84P] (gas version) """ def __init__(self, **options): PythonCodeInterface.__init__(self, GaslactICsImplementation, **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) def _check_if_worker_is_up_to_date(self): if not os.path.exists(os.path.join(GaslactICsImplementation()._bin_path, "dbh")): raise exceptions.CodeException( "The worker code of the '{0}' interface class is not up to date.\n" "Please do a 'make clean; make' in the root directory.".format(type(self).__name__)) @option(type="string", sections=('data',)) def output_data_root_directory(self): """ The root directory of the output data, read - write directory """ return os.path.join(get_amuse_root_dir(), 'data') def get_output_directory(self): """ Returns the root name of the directory to use by the application to store it's output / temporary files in. """ return os.path.join(self.output_data_root_directory, 'gaslactics', 'output') new_particle = None def delete_particle(self, index_of_the_particle): return 0 @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 #parameter getters & setters # boolean parameters for par in parameters: dtype=parameters[par]["dtype"] if hasattr(parameters[par]["default"],"unit"): unit=parameters[par]["default"].unit.reference_string() else: unit="None" exec("@legacy_function\ndef get_"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='"+dtype+"', direction=function.OUT, unit="+unit+")\n" " function.result_type = 'int32'\n return function") exec("@legacy_function\ndef set_"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='"+dtype+"', direction=function.IN, unit="+unit+")\n" " function.result_type = 'int32'\n return function") def invoke_state_change2(self): pass def invoke_state_change_updated(self): pass @legacy_function def generate_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def get_number_of_particles_updated(): """ Return the number of particles added during the last generate_particles. """ function = LegacyFunctionSpecification() function.addParameter('number_of_particles_updated', dtype='int32', direction=function.OUT) function.addParameter('number_of_gas_particles_updated', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_number_of_particles(): """ Return the number of halo/bulge/disk particles of the last generate_particles. """ function = LegacyFunctionSpecification() function.addParameter('number_of_halo_particles', dtype='int32', direction=function.OUT) function.addParameter('number_of_bulge_particles', dtype='int32', direction=function.OUT) function.addParameter('number_of_disk_particles', dtype='int32', direction=function.OUT) function.addParameter('number_of_gas_particles', 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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_internal_energy(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('u', dtype='float64', direction=function.OUT, description = "internal energy of gas particle", unit=nbody_system.speed**2) function.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def model_present(): """ Return whether a valid galaxy model is present. """ function = LegacyFunctionSpecification() function.addParameter('model_present', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function class GaslactICs(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, GaslactICsInterface(**options), **options) def initialize_code(self): result = self.overridden().initialize_code() self.parameters.set_defaults() self.ensure_data_directory_exists(self.get_output_directory()) self.parameters.output_directory = self.get_output_directory() def define_parameters(self, handler): handler.add_method_parameter( "get_output_path", "set_output_path", "output_directory", "The path to the output directory", default_value = "./" ) # boolean parameters for par in parameters: if parameters[par]["dtype"]=="bool": handler.add_boolean_parameter( "get_"+par, "set_"+par, par, parameters[par]["description"], default_value=parameters[par]["default"] ) else: handler.add_method_parameter( "get_"+par, "set_"+par, par, parameters[par]["description"], default_value=parameters[par]["default"] ) 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.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_output_path", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_output_path", (handler.NO_UNIT,), (handler.ERROR_CODE,)) for par in parameters: if hasattr(parameters[par]["default"],"unit"): unit=parameters[par]["default"].unit else: unit=handler.NO_UNIT handler.add_method("get_"+par, (), (unit, handler.ERROR_CODE,)) handler.add_method("set_"+par, (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') handler.define_set('gas_particles', 'index_of_the_particle') handler.set_new('gas_particles', 'new_particle') handler.set_delete('gas_particles', 'delete_particle') handler.add_getter('gas_particles', 'get_mass') handler.add_getter('gas_particles', 'get_position') handler.add_getter('gas_particles', 'get_velocity') handler.add_getter('gas_particles', 'get_internal_energy') def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','PARAMETER_CHANGE_A','invoke_state_change2') handler.add_transition('EDIT','PARAMETER_CHANGE_B','invoke_state_change2') handler.add_transition('PARAMETER_CHANGE_A','RUN','recommit_parameters') handler.add_transition('PARAMETER_CHANGE_B','EDIT','recommit_parameters') 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 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', 'model_present') handler.add_method('CHANGE_PARAMETERS_EDIT', 'model_present') handler.add_method('CHANGE_PARAMETERS_UPDATE','model_present') handler.add_method('INITIALIZED','model_present') 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_number_of_particles') handler.add_method('RUN', 'get_mass') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_velocity') handler.add_method('RUN', 'get_internal_energy') def commit_parameters(self): if not self.model_present(): print("generating galaxy model, this may take a while...") self.overridden().commit_parameters() def recommit_parameters(self): if not self.model_present(): print("(re)generating galaxy model, this may take a while...") self.overridden().recommit_parameters() 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,number_of_updated_gas_particles = self.get_number_of_particles_updated() if number_of_updated_particles: self.particles._private.attribute_storage._add_indices( list(range(number_of_updated_gas_particles,number_of_updated_particles)) ) # this should generate disjoint sets (gas_particles not in particles) if number_of_updated_gas_particles: self.gas_particles._private.attribute_storage._add_indices( list(range(number_of_updated_gas_particles)) ) def clear_particle_set(self): if len(self.particles): self.particles.remove_particles(self.particles) if len(self.gas_particles): self.gas_particles.remove_particles(self.gas_particles) @property def halo_particles(self): nhalo,nbulge,ndisk,ngas=self.get_number_of_particles() return self.particles[ngas+ndisk+nbulge:] @property def bulge_particles(self): nhalo,nbulge,ndisk,ngas=self.get_number_of_particles() return self.particles[ngas+ndisk:ngas+ndisk+nbulge] @property def disk_particles(self): nhalo,nbulge,ndisk,ngas=self.get_number_of_particles() return self.particles[ngas:ngas+ndisk]
40,300
49.629397
173
py
amuse
amuse-main/src/amuse/community/galactics/__init__.py
# generated file from .interface import Galactics
50
16
32
py
amuse
amuse-main/src/amuse/community/galactics/interface.py
import os import os.path import pickle import random import numpy import hashlib from amuse.community import * from amuse.community.interface.common import CommonCode, CommonCodeInterface from amuse.support.options import option from subprocess import Popen, PIPE from amuse.rfi.core import PythonCodeInterface class GalactICsImplementation(object): def __init__(self): self._output_directory = "./" self._particles_generated = False self._particle_data = numpy.array([]) self._bin_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data", "bin") def get_output_path(self, output_directory): output_directory.value = self._output_directory return 0 def set_output_path(self, output_directory): self._output_directory = output_directory return 0 def set_src_bin_path(self, src_bin_path): self._bin_path = src_bin_path return 0 def initialize_code(self): self.set_default_parameter_values() return 0 #parameter getters & setters for par in ["_generate_halo_flag", "_halo_outer_radius", "_scale_velocity", "_scale_radius", "_truncation_delta_r", "_inner_cusp_slope", "_outer_slope", "_generate_disk_flag", "_disk_mass", "_disk_scale_length", "_disk_outer_radius", "_disk_scale_height_sech2", "_disk_truncation_dr", "_generate_bulge_flag", "_Sersic_index_n", "_bulge_velocity", "_bulge_scale_radius", "_radial_grid_delta_r", "_number_of_grid_intervals", "_order_of_multipole_expansion", "_central_radial_vel_dispersion", "_scale_length_of_sigR2", "_number_of_radial_steps_correction_fns", "_number_of_iterations", "_halo_streaming_fraction", "_halo_number_of_particles", "_halo_random_seed", "_halo_do_center_flag", "_bulge_streaming_fraction", "_bulge_number_of_particles", "_bulge_random_seed", "_bulge_do_center_flag", "_disk_number_of_particles", "_disk_random_seed", "_disk_do_center_flag"]: exec("def get"+par+"(self, value): value.value = self."+par+"; return 0") exec("def set"+par+"(self, value): self."+par+" = value; return 0") def set_default_parameter_values(self): # Halo parameters: # do you want a halo (y or n) self._generate_halo_flag = True self._halo_outer_radius = 300.0 self._scale_velocity = 3.26331115 self._scale_radius = 6.06699419 self._truncation_delta_r = 100.0 self._inner_cusp_slope = 1.0 self._outer_slope = 2.3 # Disk parameters: # do you want a disk (y or n) self._generate_disk_flag = True self._disk_mass = 25.0 self._disk_scale_length = 5.8097949 self._disk_outer_radius = 40.5 self._disk_scale_height_sech2 = 0.5 self._disk_truncation_dr = 1.5 # Bulge parameters: # do you want a Sersic bulge (y or n) self._generate_bulge_flag = True self._Sersic_index_n = 0.937324703 self._ppp_ = -1.0 self._bulge_velocity = 3.21182013 self._bulge_scale_radius = 1.50395405 # do you want a blackhole (y or n) (NOT SUPPORTED IN THIS VERSION) #n self._radial_grid_delta_r = 0.01 self._number_of_grid_intervals = 90000 self._order_of_multipole_expansion = 10 # order of multipole expansion - even number - should be l=10 for models # with disks - l=0 for purely spherical models without a disk # parameters for in.diskdf self._central_radial_vel_dispersion = 0.73 # central radial vel dispersion (in vzdisp) self._scale_length_of_sigR2 = 5.8097949 # scale length of sig_r^2 self._number_of_radial_steps_correction_fns = 10 # number of intervals for correction functions (min. 6) self._number_of_iterations = 50 #self._psfile = "psfile" # doesn't seem to be used... # parameters for in.halo self._halo_streaming_fraction = 0.50 # [0.0, 1.0]; 0.5 means no net rotation self._halo_number_of_particles = 200000 self._halo_random_seed = -1 self._halo_do_center_flag = True # parameters for in.bulge self._bulge_streaming_fraction = 0.80 # [0.0, 1.0]; 0.5 means no net rotation self._bulge_number_of_particles = 50000 self._bulge_random_seed = -1 self._bulge_do_center_flag = True # parameters for in.disk self._disk_number_of_particles = 100000 self._disk_random_seed = -1 self._disk_do_center_flag = True def cleanup_code(self): return 0 def generate_in_dbh_string(self): if self._generate_halo_flag: in_dbh = "y\n" in_dbh += "{0:.15} ".format(self._halo_outer_radius) in_dbh += "{0:.15} ".format(self._scale_velocity) in_dbh += "{0:.15} ".format(self._scale_radius) in_dbh += "{0:.15} ".format(self._truncation_delta_r) in_dbh += "{0:.15} ".format(self._inner_cusp_slope) in_dbh += "{0:.15}\n".format(self._outer_slope) else: in_dbh = "n\n" if self._generate_disk_flag: in_dbh += "y\n" in_dbh += "{0:.15} ".format(self._disk_mass) in_dbh += "{0:.15} ".format(self._disk_scale_length) in_dbh += "{0:.15} ".format(self._disk_outer_radius) in_dbh += "{0:.15} ".format(self._disk_scale_height_sech2) in_dbh += "{0:.15}\n".format(self._disk_truncation_dr) else: in_dbh += "n\n" if self._generate_bulge_flag: in_dbh += "y\n" in_dbh += "{0:.15} ".format(self._Sersic_index_n) in_dbh += "{0:.15} ".format(self._ppp_) in_dbh += "{0:.15} ".format(self._bulge_velocity) in_dbh += "{0:.15}\n".format(self._bulge_scale_radius) else: in_dbh += "n\n" in_dbh += "n\n" in_dbh += "{0:.15} ".format(self._radial_grid_delta_r) in_dbh += "{0}\n".format(self._number_of_grid_intervals) in_dbh += "{0}\n".format(self._order_of_multipole_expansion) return in_dbh def generate_in_diskdf_string(self): in_diskdf = "{0:.15} ".format(self._central_radial_vel_dispersion) # central radial vel dispersion (in vzdisp) in_diskdf += "{0:.15}\n".format(self._scale_length_of_sigR2) # scale length of sig_r^2 in_diskdf += "{0}\n".format(self._number_of_radial_steps_correction_fns) # number of intervals for correction functions (min. 6) in_diskdf += "{0}\n".format(self._number_of_iterations) #in_diskdf += "{0}\n".format(self._psfile) # doesn't seem to be used... return in_diskdf def generate_in_halo_string(self): in_halo = "{0:.15}\n".format(self._halo_streaming_fraction) in_halo += "{0}\n".format(self._halo_number_of_particles) in_halo += "{0}\n".format(self._halo_random_seed) in_halo += "{0}\n".format(1 if self._halo_do_center_flag else 0) return in_halo def generate_in_bulge_string(self): in_bulge = "{0:.15}\n".format(self._bulge_streaming_fraction) in_bulge += "{0}\n".format(self._bulge_number_of_particles) in_bulge += "{0}\n".format(self._bulge_random_seed) in_bulge += "{0}\n".format(1 if self._bulge_do_center_flag else 0) return in_bulge def generate_in_disk_string(self): in_disk = "{0}\n".format(self._disk_number_of_particles) in_disk += "{0}\n".format(self._disk_random_seed) in_disk += "{0}\n".format(1 if self._disk_do_center_flag else 0) return in_disk def _new_dbh_dir(self, data_directory,in_dbh,in_diskdf): if not os.path.exists(data_directory): os.makedirs(data_directory) with open(os.path.join(data_directory, "in.gendenspsi"), "w") as f: f.write("2000 40\n") # for clarity, also store the used input parameters in this directory: with open(os.path.join(data_directory, "in.dbh"), "w") as f: f.write(in_dbh) with open(os.path.join(data_directory, "in.diskdf"), "w") as f: f.write(in_diskdf) # remove finished-step files for f in ['dbh.finished','getfreqs.finished','diskdf.finished']: try: os.remove(os.path.join( data_directory, f)) except: pass def _data_directory(self,in_dbh,in_diskdf): modelhash=hashlib.sha1((in_dbh+in_diskdf).encode()).hexdigest() return os.path.join(self._output_directory, "model_"+modelhash) def model_present(self,x): in_dbh = self.generate_in_dbh_string() in_diskdf = self.generate_in_diskdf_string() data_directory=self._data_directory(in_dbh,in_diskdf) x.value=self._directory_contains_valid_model(data_directory) return 0 def _directory_contains_valid_model(self,data_directory): if os.path.exists(os.path.join( data_directory)) and \ os.path.exists(os.path.join( data_directory, 'dbh.dat')) and \ os.path.exists(os.path.join( data_directory, 'dbh.finished')) and \ os.path.exists(os.path.join( data_directory, 'getfreqs.finished')) and \ (os.path.exists(os.path.join( data_directory, 'diskdf.finished')) or not self._generate_disk_flag): return True else: return False def _location_dbh_dat(self, in_dbh,in_diskdf): data_directory=self._data_directory(in_dbh,in_diskdf) if self._directory_contains_valid_model(data_directory): is_new = False else: is_new = True self._new_dbh_dir(data_directory,in_dbh,in_diskdf) return data_directory, is_new def commit_parameters(self): try: in_dbh = self.generate_in_dbh_string() in_diskdf = self.generate_in_diskdf_string() dbh_dir, is_new = self._location_dbh_dat(in_dbh, in_diskdf) self._cwd = dbh_dir print(dbh_dir) if not is_new: return 0 print("Writing output to:", self._cwd) proc=Popen([os.path.join(self._bin_path, "dbh")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) stdout,stderr=proc.communicate(in_dbh.encode('UTF-8')) print("(stdout, stderr) =", stdout,stderr) if proc.returncode==0: open(os.path.join(dbh_dir,"dbh.finished"),'a').close() proc=Popen([os.path.join(self._bin_path, "getfreqs")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) stdout,stderr=proc.communicate() print("(stdout, stderr) =", stdout,stderr) if proc.returncode==0: open(os.path.join(dbh_dir,"getfreqs.finished"),'a').close() if self._generate_disk_flag: proc=Popen([os.path.join(self._bin_path, "diskdf")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) stdout,stderr=proc.communicate(in_diskdf.encode('UTF-8')) print("(stdout, stderr) =", stdout,stderr) if proc.returncode==0: open(os.path.join(dbh_dir,"diskdf.finished"),'a').close() return 0 except Exception as ex: print("Exception occurred in commit_parameters:", ex) raise def recommit_parameters(self): return self.commit_parameters() def get_number_of_particles_updated(self, number_of_particles_updated): if self._particles_generated: number_of_particles_updated.value = self._number_of_particles_updated self._particles_generated = False else: number_of_particles_updated.value = 0 return 0 def generate_particles(self): try: if self._generate_disk_flag: in_disk = self.generate_in_disk_string() process = Popen([os.path.join(self._bin_path, "gendisk")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out,err=process.communicate(in_disk.encode('UTF-8')) if process.returncode != 0: print("error:", err) return -2 disk_data=numpy.frombuffer(out,dtype="float32") else: disk_data=numpy.array([]) if self._generate_bulge_flag: in_bulge = self.generate_in_bulge_string() process = Popen([os.path.join(self._bin_path, "genbulge")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out,err=process.communicate(in_bulge.encode('UTF-8')) if process.returncode != 0: print("error:", err) return -3 bulge_data=numpy.frombuffer(out,dtype="float32") else: bulge_data=numpy.array([]) if self._generate_halo_flag: in_halo = self.generate_in_halo_string() process = Popen([os.path.join(self._bin_path, "genhalo")], cwd = self._cwd, stdin = PIPE, stdout = PIPE, stderr = PIPE) out, err = process.communicate(in_halo.encode('UTF-8')) if process.returncode != 0: print("error:", err) return -4 halo_data=numpy.frombuffer(out,dtype="float32") else: halo_data=numpy.array([]) self._number_of_particles_updated = (len(halo_data)+len(bulge_data)+len(disk_data))//7 self._number_of_halo_particles=len(halo_data)//7 self._number_of_bulge_particles=len(bulge_data)//7 self._number_of_disk_particles=len(disk_data)//7 data=numpy.concatenate((disk_data,bulge_data,halo_data)) self._particle_data = numpy.reshape(data,( self._number_of_particles_updated,7)) self._particles_generated = True return 0 except Exception as ex: print("Exception occurred in generate_particles:", ex) return -1 def get_number_of_particles(self,nhalo,nbulge,ndisk): try: nhalo.value=self._number_of_halo_particles nbulge.value=self._number_of_bulge_particles ndisk.value=self._number_of_disk_particles return 0 except: return -1 def get_mass(self, index_of_the_particle, mass, length): try: mass.value = self._particle_data[index_of_the_particle, 0] return 0 except: return -1 def get_position(self, index_of_the_particle, x, y, z, length): try: x.value = self._particle_data[index_of_the_particle, 1] y.value = self._particle_data[index_of_the_particle, 2] z.value = self._particle_data[index_of_the_particle, 3] return 0 except: return -1 def get_velocity(self, index_of_the_particle, vx, vy, vz, length): try: vx.value = self._particle_data[index_of_the_particle, 4] vy.value = self._particle_data[index_of_the_particle, 5] vz.value = self._particle_data[index_of_the_particle, 6] return 0 except: return -1 class GalactICsInterface(PythonCodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ GalactICs allows to generate self-consistent disc-bulge-halo galaxy models. The bulge and halo distribution functions (DFs) are functions of E and L_z only. The halo's flattening and rotation can be specified. The disc DF is a function of E and L_z and a third 'integral', E_z, the vertical energy, which is approximately conserved in a warm disc with vertical extent. A simulation of a sample model shows that in practice the models are very close to equilibrium, making them ideal for experiments on instabilities in galactic discs. Relevant references: .. [#] Kuijken K., Dubinski J., 1995, MNRAS, 277, 1341 (original version) .. [#] Widrow L.M., Dubinski J., 2005, ApJ, 631, 838 (2nd version) .. [#] Widrow L.M., Pym B., Dubinski J., 2008, ApJ, 679, 1239 (current version) """ def __init__(self, **options): PythonCodeInterface.__init__(self, GalactICsImplementation, **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) def _check_if_worker_is_up_to_date(self): if not os.path.exists(os.path.join(GalactICsImplementation()._bin_path, "dbh")): raise exceptions.CodeException( "The worker code of the '{0}' interface class is not up to date.\n" "Please do a 'make clean; make' in the root directory.".format(type(self).__name__)) new_particle = None def delete_particle(self, index_of_the_particle): return 0 @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 set_src_bin_path(): function = LegacyFunctionSpecification() function.addParameter('src_bin_path', dtype='string', direction=function.IN, description = "The path to the Galactics binaries.") function.result_type = 'int32' return function #parameter getters & setters # boolean parameters for par in ["_generate_halo_flag", "_generate_disk_flag", "_generate_bulge_flag", "_halo_do_center_flag", "_bulge_do_center_flag", "_disk_do_center_flag"]: exec("@legacy_function\ndef get"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='bool', direction=function.OUT)\n" " function.result_type = 'int32'\n return function") exec("@legacy_function\ndef set"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='bool', direction=function.IN)\n" " function.result_type = 'int32'\n return function") # integer parameters for par in [ "_number_of_grid_intervals", "_order_of_multipole_expansion", "_number_of_radial_steps_correction_fns", "_number_of_iterations", "_halo_number_of_particles", "_halo_random_seed", "_bulge_number_of_particles", "_bulge_random_seed", "_disk_number_of_particles", "_disk_random_seed"]: exec("@legacy_function\ndef get"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='int32', direction=function.OUT)\n" " function.result_type = 'int32'\n return function") exec("@legacy_function\ndef set"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='int32', direction=function.IN)\n" " function.result_type = 'int32'\n return function") # float parameters for par in ["_halo_outer_radius", "_scale_velocity", "_scale_radius", "_truncation_delta_r", "_inner_cusp_slope", "_outer_slope", "_disk_mass", "_disk_scale_length", "_disk_outer_radius", "_disk_scale_height_sech2", "_disk_truncation_dr", "_Sersic_index_n", "_bulge_velocity", "_bulge_scale_radius", "_radial_grid_delta_r", "_central_radial_vel_dispersion", "_scale_length_of_sigR2", "_halo_streaming_fraction", "_bulge_streaming_fraction"]: exec("@legacy_function\ndef get"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='float64', direction=function.OUT)\n" " function.result_type = 'int32'\n return function") exec("@legacy_function\ndef set"+par+"():\n function = LegacyFunctionSpecification()\n" " function.addParameter('value', dtype='float64', direction=function.IN)\n" " function.result_type = 'int32'\n return function") def invoke_state_change2(self): pass def invoke_state_change_updated(self): pass @legacy_function def generate_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def get_number_of_particles_updated(): """ Return the number of particles added during the last generate_particles. """ function = LegacyFunctionSpecification() function.addParameter('number_of_particles_updated', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_number_of_particles(): """ Return the number of halo/bulge/disk particles of the last generate_particles. """ function = LegacyFunctionSpecification() function.addParameter('number_of_halo_particles', dtype='int32', direction=function.OUT) function.addParameter('number_of_bulge_particles', dtype='int32', direction=function.OUT) function.addParameter('number_of_disk_particles', 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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_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.addParameter('length', 'int32', function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def model_present(): """ Return whether a valid galaxy model is present. """ function = LegacyFunctionSpecification() function.addParameter('model_present', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function def get_code_src_directory(self): return os.path.join(os.path.dirname(os.path.normpath(os.path.abspath(__file__))),'src') class GalactICs(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, GalactICsInterface(**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_output_path", "set_output_path", "output_directory", "The path to the output directory", default_value = "./" ) # boolean parameters for par in ["generate_halo_flag", "generate_disk_flag", "generate_bulge_flag"]: handler.add_boolean_parameter( "get_"+par, "set_"+par, par, "Flag specifying whether to generate a "+par[9:-5], True ) for par in ["halo_do_center_flag", "bulge_do_center_flag", "disk_do_center_flag"]: handler.add_boolean_parameter( "get_"+par, "set_"+par, par, "Flag specifying whether to center the "+par[:-15]+" at the origin", True ) # integer parameters handler.add_method_parameter( "get_number_of_grid_intervals", "set_number_of_grid_intervals", "number_of_grid_intervals", "Number of gridpoints in the radial direction", default_value = 90000 ) handler.add_method_parameter( "get_order_of_multipole_expansion", "set_order_of_multipole_expansion", "order_of_multipole_expansion", "order of multipole expansion - even number - should be l=10 for models with disks - l=0 for purely spherical models without a disk", default_value = 10 ) handler.add_method_parameter( "get_number_of_radial_steps_correction_fns", "set_number_of_radial_steps_correction_fns", "number_of_radial_steps_correction_fns_disk_df", "The number of intervals for correction functions (min. 6); used in calculation of the DF of the disk", default_value = 10 ) handler.add_method_parameter( "get_number_of_iterations", "set_number_of_iterations", "number_of_iterations_disk_df", "The number of iterations in calculation of the DF of the disk", default_value = 50 ) handler.add_method_parameter( "get_halo_number_of_particles", "set_halo_number_of_particles", "halo_number_of_particles", "The number of halo particles to generate", default_value = 200000 ) handler.add_method_parameter( "get_bulge_number_of_particles", "set_bulge_number_of_particles", "bulge_number_of_particles", "The number of bulge particles to generate", default_value = 50000 ) handler.add_method_parameter( "get_disk_number_of_particles", "set_disk_number_of_particles", "disk_number_of_particles", "The number of disk particles to generate", default_value = 100000 ) handler.add_method_parameter( "get_halo_random_seed", "set_halo_random_seed", "halo_random_seed", "The seed to the random number generator used to generate the halo particles", default_value = -1 ) handler.add_method_parameter( "get_bulge_random_seed", "set_bulge_random_seed", "bulge_random_seed", "The seed to the random number generator used to generate the bulge particles", default_value = -1 ) handler.add_method_parameter( "get_disk_random_seed", "set_disk_random_seed", "disk_random_seed", "The seed to the random number generator used to generate the disk particles", default_value = -1 ) # float parameters handler.add_method_parameter( "get_halo_outer_radius", "set_halo_outer_radius", "halo_outer_radius", "The halo is smoothly truncated at this radius", default_value = 300.0 | nbody_system.length ) handler.add_method_parameter( "get_scale_velocity", "set_scale_velocity", "halo_scale_velocity", "The velocity scale of the halo", default_value = 3.26331115 | nbody_system.speed ) handler.add_method_parameter( "get_scale_radius", "set_scale_radius", "halo_scale_radius", "The length scale of the halo", default_value = 6.06699419 | nbody_system.length ) handler.add_method_parameter( "get_truncation_delta_r", "set_truncation_delta_r", "halo_truncation_width", "The width of the smooth truncation at halo_outer_radius", default_value = 100.0 | nbody_system.length ) handler.add_method_parameter( "get_inner_cusp_slope", "set_inner_cusp_slope", "halo_inner_cusp_slope", "The slope of inner cusp of the halo density profile", default_value = 1.0 ) handler.add_method_parameter( "get_outer_slope", "set_outer_slope", "halo_outer_slope", "The outer slope of the halo density profile", default_value = 2.3 ) handler.add_method_parameter( "get_disk_mass", "set_disk_mass", "disk_mass", "The mass of the disk", default_value = 25.0 | nbody_system.mass ) handler.add_method_parameter( "get_disk_scale_length", "set_disk_scale_length", "disk_scale_length", "The length scale of the disk", default_value = 5.8097949 | nbody_system.length ) handler.add_method_parameter( "get_disk_outer_radius", "set_disk_outer_radius", "disk_outer_radius", "The disk is smoothly truncated at this radius", default_value = 40.5 | nbody_system.length ) handler.add_method_parameter( "get_disk_scale_height_sech2", "set_disk_scale_height_sech2", "disk_scale_height_sech2", "The vertical scale length of the disk. The disk falls off as sech^2 in the z-direction.", default_value = 0.5 | nbody_system.length ) handler.add_method_parameter( "get_disk_truncation_dr", "set_disk_truncation_dr", "disk_truncation_width", "The width of the smooth truncation at disk_outer_radius", default_value = 1.5 | nbody_system.length ) handler.add_method_parameter( "get_Sersic_index_n", "set_Sersic_index_n", "Sersic_index", "The Sersic index of the bulge (1.0 for a classical bulge)", default_value = 0.937324703 ) handler.add_method_parameter( "get_bulge_velocity", "set_bulge_velocity", "bulge_scale_velocity", "The velocity scale of the bulge", default_value = 3.21182013 | nbody_system.speed ) handler.add_method_parameter( "get_bulge_scale_radius", "set_bulge_scale_radius", "bulge_scale_radius", "The length scale of the bulge", default_value = 1.50395405 | nbody_system.length ) handler.add_method_parameter( "get_radial_grid_delta_r", "set_radial_grid_delta_r", "radial_grid_delta_r", "Spacing of the grid in the radial direction", default_value = 0.01 | nbody_system.length ) handler.add_method_parameter( "get_central_radial_vel_dispersion", "set_central_radial_vel_dispersion", "disk_central_radial_velocity_dispersion", "The velocity dispersion of the disk in the radial direction at the center (in units of vertical velocity dispersion)", default_value = 0.73 ) handler.add_method_parameter( "get_scale_length_of_sigR2", "set_scale_length_of_sigR2", "disk_scale_length_of_sigR2", "The length scale of the exponential decline of the velocity dispersion of the disk in the radial direction.", default_value = 5.8097949 | nbody_system.length ) handler.add_method_parameter( "get_halo_streaming_fraction", "set_halo_streaming_fraction", "halo_streaming_fraction", "Control for rotating halo: distribution function is split in positive and negative angular momentum, and recombined with this parameter (F = aF+ + (1-a)F-); 0.5 means no rotation", default_value = 0.50 ) handler.add_method_parameter( "get_bulge_streaming_fraction", "set_bulge_streaming_fraction", "bulge_streaming_fraction", "Control for rotating bulge: distribution function is split in positive and negative angular momentum, and recombined with this parameter (F = aF+ + (1-a)F-); 0.5 means no rotation", default_value = 0.80 ) 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_output_path", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_output_path", (handler.NO_UNIT,), (handler.ERROR_CODE,)) for par in ["_number_of_grid_intervals", "_order_of_multipole_expansion", "_number_of_radial_steps_correction_fns", "_number_of_iterations", "_halo_number_of_particles", "_halo_random_seed", "_bulge_number_of_particles", "_bulge_random_seed", "_disk_number_of_particles", "_disk_random_seed", "_inner_cusp_slope", "_outer_slope", "_Sersic_index_n", "_central_radial_vel_dispersion", "_halo_streaming_fraction", "_bulge_streaming_fraction"]: handler.add_method("get"+par, (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set"+par, (handler.NO_UNIT, ), (handler.ERROR_CODE,)) for par in ["_halo_outer_radius", "_scale_radius", "_truncation_delta_r", "_disk_scale_length", "_disk_outer_radius", "_disk_scale_height_sech2", "_disk_truncation_dr", "_bulge_scale_radius", "_radial_grid_delta_r", "_scale_length_of_sigR2"]: handler.add_method("get"+par, (), (nbody_system.length, handler.ERROR_CODE,)) handler.add_method("set"+par, (nbody_system.length, ), (handler.ERROR_CODE,)) for par in ["_scale_velocity", "_bulge_velocity"]: handler.add_method("get"+par, (), (nbody_system.speed, handler.ERROR_CODE,)) handler.add_method("set"+par, (nbody_system.speed, ), (handler.ERROR_CODE,)) handler.add_method("get_disk_mass", (), (nbody_system.mass, handler.ERROR_CODE,)) handler.add_method("set_disk_mass", (nbody_system.mass, ), (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', 'model_present') handler.add_method('CHANGE_PARAMETERS_EDIT', 'model_present') handler.add_method('CHANGE_PARAMETERS_UPDATE','model_present') handler.add_method('INITIALIZED','model_present') 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_number_of_particles') 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) @property def halo_particles(self): nhalo,nbulge,ndisk=self.get_number_of_particles() return self.particles[ndisk+nbulge:] @property def bulge_particles(self): nhalo,nbulge,ndisk=self.get_number_of_particles() return self.particles[ndisk:ndisk+nbulge] @property def disk_particles(self): nhalo,nbulge,ndisk=self.get_number_of_particles() return self.particles[:ndisk] Galactics = GalactICs
41,672
44.149512
194
py
amuse
amuse-main/src/amuse/community/evtwin2sse/__init__.py
from .interface import Evtwin2sse
34
16.5
33
py
amuse
amuse-main/src/amuse/community/evtwin2sse/interface.py
import os import sys import math import traceback from amuse.units import units from amuse.units import constants from amuse.community.sse.interface import SSE from amuse.community.evtwin.interface import EVtwin from amuse.community.cachedse.interface import CachedStellarEvolution, ParticlesTimeseries from amuse import datamodel class EVtwin2SSE: """ EVtwin2SSE is a modification of the EVtwin stellar evolution code that hands over execution to SSE when EVtwin crashes. The handover algorithm performs a RMS search on the relative differences of mass, radius and luminosity between the last point known EVtwin state and the entire stellar history of SSE until the first state of a stellar remnant type. Note that although the code allows running several stars simultaneously the timepoint where EVtwin crashes is strongly dependant on the inital mass of the stars. It is advisable to run the EVtwin2SSE code for single initial masses at a time. """ class ParticleCache: pass def __init__(self, pEVtwin = None, pSSE = None): # specifying the stellar evolution objects as parameters in the constructor # allows setting up caching in a convenient way if pEVtwin is None: self._EVtwin = EVtwin() else: self._EVtwin = pEVtwin if pSSE is None: self._SSE = SSE() else: self._SSE = pSSE # initialize member variables self.particles = datamodel.Particles() self.EVtwinAgeAtSwitch = float("nan") | units.Myr self.EVtwinException = None self.ActiveModel = self._EVtwin # self.ActiveModel.__class__.__name__ contains name of active model self._EVtwin_particlesh = None self._SSE_particlesh = None def cache_underlying_models(self, cacheDir): self._EVtwin = CachedStellarEvolution(self._EVtwin, cacheDir) self._SSE = CachedStellarEvolution(self._SSE, cacheDir) def commit_paremeters(self): self._EVtwin.commit_paremeters() self._SSE.commit_paremeters() def commit_particles(self): self.ActiveModel = self._EVtwin # self.ActiveModel.__class__.__name__ contains name of active model # remove all particles from underlying models if not (self._EVtwin_particlesh is None): self._EVtwin.particles.remove_particles(self._EVtwin_particlesh) if not (self._SSE_particlesh is None): self._SSE.particles.remove_particles(self._SSE_particlesh) # initialize EVtwin, transfer state self._EVtwin_particlesh = self._EVtwin.particles.add_particles(self.particles) self._EVtwin.commit_particles() self._transfer_state_EVtwin() # initialize SSE self._SSE_particlesh = self._SSE.particles.add_particles(self.particles) self._SSE.commit_particles() self._SSETimeseries = ParticlesTimeseries(self._SSE.particles) self._SSETimeseries.add_timepoint() # copy current state from underlying <active model>.particles to self.particles def _transfer_state_EVtwin(self): for particle, ActiveModelParticle in zip(self.particles, self.ActiveModel.particles): particle.mass = ActiveModelParticle.mass particle.age = ActiveModelParticle.age particle.luminosity = ActiveModelParticle.luminosity particle.temperature = ActiveModelParticle.temperature particle.stellar_type = ActiveModelParticle.stellar_type particle.radius = ActiveModelParticle.radius def evolve_model(self): # TODO add evolve_until argument # EVtwin is working so far #if math.isnan(self.EVtwinAgeAtSwitch.value_in(units.Myr)): if self.ActiveModel == self._EVtwin: #print "evolve_model() EVtwin" # try advancing a timestep with EVtwin try: prev_age = self._EVtwin.particles.age self._EVtwin.evolve_model() if (prev_age == self._EVtwin.particles.age): raise Exception("Evtwin model timestep is zero.") self._transfer_state_EVtwin() # EVtwin crashed; switch to SSE except Exception as ex: self.EVtwinAgeAtSwitch = self._EVtwin.particles.age self.EVtwinException = ex self.ActiveModel = self._SSE print("Evtwin2SSE switching models, EVtwin (age = %s) threw exception: %s" % (self._EVtwin.particles.age, self.EVtwinException)) # run SSE for just long enough to get data for the RMS search while not _sse_search_endpoint_reached(self._SSE.particles): self._SSE.evolve_model() self._SSETimeseries.add_timepoint() print("Evtwin2SSE switch: evolved SSE to: %s " % (self._SSE.particles.age,)) for evtwin_star, sse_track in zip(self._EVtwin.particles, self._SSETimeseries.particles): self._SSE_rms_search(evtwin_star, sse_track) # TODO: Add ModelSwitchFailed exception when RMS statistics is above some threshold? print(("Evtwin2SSE switch parameters: %s %s %s %s" % (sse_track.SSEIndexAtSwitch, sse_track.SSENextStateIndex, sse_track.SSEAgeAtSwitch, sse_track.RMSErrorAtSwitch))) self._evolve_model_SSE() # model has been switched to SSE else: #print "evolve_model() SSE" self._evolve_model_SSE() # def _plausible_stellar_type_transition(evt_state, sse_state): # # return ( \ # # no change / advancement in stellar type # (evt_state <= sse_state) or \ # # # no differentiation between MS star and convective low-mass star # (evt_state <= 1 and sse_state <= 1) # ) # returns the optimal index for SSE rms def _SSE_rms_search(self, evtwin_star, sse_track): sse_track.SSEIndexAtSwitch = float("nan") sse_track.SSEAgeAtSwitch = float("nan") sse_track.RMSErrorAtSwitch = float("inf") # TODO heuristic for fixing non-physical stellar type transitions #evtwin_final_known_state = -1 #for i in range(len(evt_raw['stellar_types'])): # if evt_raw['stellar_types'][i] != 16: # evtwin_final_known_state = evt_raw['stellar_types'][i] for i in range(len(sse_track.age)): # TODO #if not plausible_stellar_type_transition(evtwin_final_known_state, sse_raw['stellar_types'][i]): # continue rel_diff_mass = (sse_track.mass[i] - evtwin_star.mass) / evtwin_star.mass rel_diff_radius = (sse_track.radius[i] - evtwin_star.radius) / evtwin_star.radius rel_diff_luminosity = (sse_track.luminosity[i] - evtwin_star.luminosity) / evtwin_star.luminosity rms = ((rel_diff_mass)**2 \ + (rel_diff_radius)**2 \ + (rel_diff_luminosity)**2) if (rms < sse_track.RMSErrorAtSwitch): sse_track.SSEIndexAtSwitch = i sse_track.SSENextStateIndex = i sse_track.SSEAgeAtSwitch = sse_track.age[i] - (10E-3 | units.Myr) # ugly way to "cheat the convergence check" sse_track.RMSErrorAtSwitch = rms # TODO calculate fudge factors for m, r, L, T? #self._transfer_state_SSE() def _evolve_model_SSE(self): #print "evolve_model_SSE()" for evtwin_star, star, sse_track in zip(self._EVtwin.particles, self.particles, self._SSETimeseries.particles): # advance SSE if necessary while (sse_track.SSENextStateIndex >= len(sse_track.age)): self._SSE.evolve_model() self._SSETimeseries.add_timepoint() # update state state star.age = sse_track.age[ sse_track.SSENextStateIndex ] - sse_track.SSEAgeAtSwitch + self.EVtwinAgeAtSwitch star.mass = sse_track.mass[ sse_track.SSENextStateIndex ] star.radius = sse_track.radius[ sse_track.SSENextStateIndex ] star.luminosity = sse_track.luminosity[ sse_track.SSENextStateIndex ] star.temperature = sse_track.temperature[ sse_track.SSENextStateIndex ] star.stellar_type = sse_track.stellar_type[ sse_track.SSENextStateIndex ] # advance index sse_track.SSENextStateIndex = sse_track.SSENextStateIndex + 1 def stop(self): self._EVtwin.stop() self._SSE.stop() def _sse_search_endpoint_reached(stars): for star in stars: if (0 <= star.stellar_type.value_in(units.stellar_type) and \ star.stellar_type.value_in(units.stellar_type) <= 9) or \ star.stellar_type.value_in(units.stellar_type) == 16: return False return True Evtwin2sse = EVtwin2SSE
9,063
40.2
144
py
amuse
amuse-main/src/amuse/community/mesa_r2208/build_mesa.py
#!/usr/bin/env python import subprocess import os import sys import time import urllib.request, urllib.parse, urllib.error class MyFancyUrlopener(urllib.request.FancyURLopener): def retrieve(self, url, filename=None, reporthook=None, data=None): """retrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.""" url = urllib.unwrap(urllib.toBytes(url)) if self.tempcache and url in self.tempcache: return self.tempcache[url] type, url1 = urllib.parse.splittype(url) if filename is None and (not type or type == 'file'): try: fp = self.open_local_file(url1) hdrs = fp.info() del fp return urllib.request.url2pathname(urllib.parse.splithost(url1)[1]), hdrs except IOError as msg: pass fp = self.open(url, data) try: headers = fp.info() code = fp.code if filename: tfp = open(filename, 'wb') else: import tempfile garbage, path = urllib.parse.splittype(url) garbage, path = urllib.parse.splithost(path or "") path, garbage = urllib.parse.splitquery(path or "") path, garbage = urllib.parse.splitattr(path or "") suffix = os.path.splitext(path)[1] (fd, filename) = tempfile.mkstemp(suffix) self.__tempfiles.append(filename) tfp = os.fdopen(fd, 'wb') try: result = filename, headers, code if self.tempcache is not None: self.tempcache[url] = result bs = 1024*8 size = -1 read = 0 blocknum = 0 if reporthook: if "content-length" in headers: size = int(headers["Content-Length"]) reporthook(blocknum, bs, size) while 1: block = fp.read(bs) if block == "": break read += len(block) tfp.write(block) blocknum += 1 if reporthook: reporthook(blocknum, bs, size) finally: tfp.close() finally: fp.close() del fp del tfp # raise exception if actual size does not match content-length header if size >= 0 and read < size: raise urllib.error.ContentTooShortError("retrieval incomplete: got only %i out " "of %i bytes" % (read, size), result) return result class GetCodeFromHttp(object): url_template = "http://www.amusecode.org/codes/mesa-r{version}.tgz" filename_template = "mesa-r{version}.tgz" version = "2208" def directory(self): return os.path.abspath(os.path.dirname(__file__)) def src_directory(self): return os.path.join(self.directory(), 'src') def unpack_downloaded_file(self, filename): print("unpacking", filename) arguments = ['tar', '-xf'] arguments.append(filename) subprocess.call( arguments, cwd = os.path.join(self.src_directory()) ) print("done") def start(self): if os.path.exists('src'): counter = 0 while os.path.exists('src.{0}'.format(counter)): counter += 1 if counter > 100: print("too many backup directories") break os.rename('src', 'src.{0}'.format(counter)) os.mkdir('src') url = self.url_template.format(version = self.version) filename = self.filename_template.format(version = self.version) print("downloading version",self.version,"from", url, "to", filename) opener = MyFancyUrlopener() filename, httpmessage, code = opener.retrieve(url, filename = os.path.join(self.src_directory(),filename)) if code == 404: os.remove(filename) url = self.backup_url_template.format(version = self.version) filename, httpmessage, code = opener.retrieve(url, filename = os.path.join(self.src_directory(),filename)) print("downloading finished") self.unpack_downloaded_file(filename) class BuildMesa(object): def mesa_directory(self): return os.path.abspath(os.path.dirname(__file__)) def get_mesa_source_from_svn(self): mesa_url = "http://mesa.svn.sourceforge.net/svnroot/mesa/trunk" revision = "2208" subprocess.call(['svn', 'export', '-r', revision, mesa_url, os.path.join('src','mesa')], cwd = self.mesa_directory()) self.patch_mesa_source() def get_mesa_source_from_http(self): revision = "2208" instance = GetCodeFromHttp() instance.version = "2208" instance.start() #self.patch_mesa_source() def patch_mesa_source(self): if 1: # no longer copy these files # the patch system will do this return subprocess.call(['cp','-f','./mesa_reqs/makefile_header', './src/mesa/utils/makefile_header'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/create_zams.f', './src/mesa/star/test/src/create_zams.f'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/eos_def.f', './src/mesa/eos/public/eos_def.f'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/jina_def.f', './src/mesa/jina/public/jina_def.f'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/kap_def.f', './src/mesa/kap/public/kap_def.f'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/net_def.f', './src/mesa/net/public/net_def.f'], cwd = self.mesa_directory()) subprocess.call(['cp','-f','./mesa_reqs/star_def.f', './src/mesa/star/public/star_def.f'], cwd = self.mesa_directory()) def build_mesa(self): self.get_mesa_source_from_http() subprocess.call(['./install'], cwd = os.path.join(self.mesa_directory(), 'src', 'mesa')) def clean_mesa(self): subprocess.call(['./clean'], cwd = os.path.join(self.mesa_directory(), 'src', 'mesa')) print("Finished cleaning.\n") def very_clean_mesa(self): self.clean_mesa() print("Also emptying the EOS, KAP, and NET caches.") subprocess.call(['./empty_caches'], cwd = os.path.join(self.mesa_directory(), 'src', 'mesa')) if __name__ == '__main__': instance = BuildMesa() if len(sys.argv) == 1: instance.build_mesa() elif sys.argv[1] == "download": instance.get_mesa_source_from_http() elif sys.argv[1] == "patch": instance.patch_mesa_source() elif sys.argv[1] == "build": instance.build_mesa() elif sys.argv[1] == "rebuild": instance.clean_mesa() instance.build_mesa() elif sys.argv[1] == "clean": instance.clean_mesa() elif sys.argv[1] == "veryclean": instance.very_clean_mesa() else: print("I'm confused: unknown argument: ", sys.argv[1]) print("Known arguments: 'download', 'build', 'rebuild', 'clean', 'veryclean'")
7,648
38.02551
118
py