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/mesa_r2208/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): with subprocess.Popen( arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd ) as process: 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(): 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): arguments = [ 'patch', '-p1', f'--prefix={QUILT_PC}/{patchname}/', '-E', '-i', patchfile ] print(arguments) returncode = subprocess.call(arguments) if returncode != 0: raise Exception(f"could not apply patch {patchname}") def apply_patches_using_patch(): with open("patches/series", "r", encoding="utf-8") as file: lines = file.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,861
24.783784
74
py
amuse
amuse-main/src/amuse/community/mesa_r2208/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://zenodo.org/record/2603017/files/mesa-r{version}.zip" filename_template = "mesa-r{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(f"unpacking {filename}") arguments = ['unzip', ] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) os.rename( f"{self.src_directory()}/mesa-r{self.version}", f"{self.src_directory()}/mesa" ) 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') 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}") 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='2208', 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,152
25.9125
80
py
amuse
amuse-main/src/amuse/community/mesa_r2208/__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_r2208/interface.py
import os import numpy import shutil from operator import itemgetter from amuse.community import * from amuse.community.interface.se import StellarEvolution, StellarEvolutionInterface, \ InternalStellarStructure, InternalStellarStructureInterface from amuse.units.quantities import VectorQuantity 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/), 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. If you order a metallicity you haven't used before, starting models will be computed automatically and saved in the `mesa/src/data/star_data/starting_models` directory (please be patient...). All metallicities are supported, even the interesting case of Z=0. The supported stellar mass range is from about 0.1 to 100 Msun. References: .. [#] ADS:2011ApJS..192....3P (Paxton, Bildsten, Dotter, Herwig, Lesaffre & Timmes 2011, ApJS, .. [#] http://mesa.sourceforge.net/) """ def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="mesa_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) self.mesa_version = "2208" @property def default_path_to_inlist(self): return os.path.join(self.get_data_directory(), 'AMUSE_inlist') @option(type="string", sections=('data')) def default_path_to_MESA_data(self): return os.path.join(os.path.dirname(__file__), 'data', 'data') @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_data_path', dtype='string', direction=function.IN, description = "Path to the data directory.") function.addParameter('local_data_path', dtype='string', direction=function.IN, description = "Path to the data directory.") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_maximum_number_of_stars(): """ Retrieve the maximum number of stars that can be handled by this instance. """ function = LegacyFunctionSpecification() function.addParameter('maximum_number_of_stars', dtype='int32', direction=function.OUT, description = "The current value of the maximum number of stars") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of was retrieved """ return function @legacy_function def new_zams_model(): function = LegacyFunctionSpecification() function.addParameter('status', dtype='int32', direction=function.OUT) return function @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.result_type = 'int32' return function @legacy_function def set_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.IN , 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_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 @legacy_function def get_mass_loss_rate(): """ Retrieve the current mass loss rate of the star. (positive for winds, negative for accretion) """ 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_loss_rate', dtype='float64', direction=function.OUT , description="The current mass loss rate of the star. (positive for winds, negative for accretion)") function.result_type = 'int32' return function @legacy_function def get_manual_mass_transfer_rate(): """ Retrieve the current user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ 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_change', dtype='float64', direction=function.OUT , description="The current user-specified mass transfer rate of the star. (negative for winds, positive for accretion)") function.result_type = 'int32' return function @legacy_function def set_manual_mass_transfer_rate(): """ Set a new user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ 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_change', dtype='float64', direction=function.IN , description="The new user-specified mass transfer rate of the star. (negative for winds, positive for accretion)") function.result_type = 'int32' return function @legacy_function def get_accrete_same_as_surface(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('accrete_same_as_surface_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_accrete_same_as_surface(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('accrete_same_as_surface_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_accrete_composition_non_metals(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('h1', dtype='float64', direction=function.OUT) function.addParameter('h2', dtype='float64', direction=function.OUT) function.addParameter('he3', dtype='float64', direction=function.OUT) function.addParameter('he4', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_accrete_composition_non_metals(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('h1', dtype='float64', direction=function.IN) function.addParameter('h2', dtype='float64', direction=function.IN) function.addParameter('he3', dtype='float64', direction=function.IN) function.addParameter('he4', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_accrete_composition_metals_identifier(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('accrete_composition_metals_identifier', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_accrete_composition_metals_identifier(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('accrete_composition_metals_identifier', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_accrete_composition_metals(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('li', dtype='float64', direction=function.OUT) function.addParameter('be', dtype='float64', direction=function.OUT) function.addParameter('b', dtype='float64', direction=function.OUT) function.addParameter('c', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='float64', direction=function.OUT) function.addParameter('o', dtype='float64', direction=function.OUT) function.addParameter('f', dtype='float64', direction=function.OUT) function.addParameter('ne', dtype='float64', direction=function.OUT) function.addParameter('na', dtype='float64', direction=function.OUT) function.addParameter('mg', dtype='float64', direction=function.OUT) function.addParameter('al', dtype='float64', direction=function.OUT) function.addParameter('si', dtype='float64', direction=function.OUT) function.addParameter('p', dtype='float64', direction=function.OUT) function.addParameter('s', dtype='float64', direction=function.OUT) function.addParameter('cl', dtype='float64', direction=function.OUT) function.addParameter('ar', dtype='float64', direction=function.OUT) function.addParameter('k', dtype='float64', direction=function.OUT) function.addParameter('ca', dtype='float64', direction=function.OUT) function.addParameter('sc', dtype='float64', direction=function.OUT) function.addParameter('ti', dtype='float64', direction=function.OUT) function.addParameter('v', dtype='float64', direction=function.OUT) function.addParameter('cr', dtype='float64', direction=function.OUT) function.addParameter('mn', dtype='float64', direction=function.OUT) function.addParameter('fe', dtype='float64', direction=function.OUT) function.addParameter('co', dtype='float64', direction=function.OUT) function.addParameter('ni', dtype='float64', direction=function.OUT) function.addParameter('cu', dtype='float64', direction=function.OUT) function.addParameter('zn', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_accrete_composition_metals(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('li', dtype='float64', direction=function.IN) function.addParameter('be', dtype='float64', direction=function.IN) function.addParameter('b', dtype='float64', direction=function.IN) function.addParameter('c', dtype='float64', direction=function.IN) function.addParameter('n', dtype='float64', direction=function.IN) function.addParameter('o', dtype='float64', direction=function.IN) function.addParameter('f', dtype='float64', direction=function.IN) function.addParameter('ne', dtype='float64', direction=function.IN) function.addParameter('na', dtype='float64', direction=function.IN) function.addParameter('mg', dtype='float64', direction=function.IN) function.addParameter('al', dtype='float64', direction=function.IN) function.addParameter('si', dtype='float64', direction=function.IN) function.addParameter('p', dtype='float64', direction=function.IN) function.addParameter('s', dtype='float64', direction=function.IN) function.addParameter('cl', dtype='float64', direction=function.IN) function.addParameter('ar', dtype='float64', direction=function.IN) function.addParameter('k', dtype='float64', direction=function.IN) function.addParameter('ca', dtype='float64', direction=function.IN) function.addParameter('sc', dtype='float64', direction=function.IN) function.addParameter('ti', dtype='float64', direction=function.IN) function.addParameter('v', dtype='float64', direction=function.IN) function.addParameter('cr', dtype='float64', direction=function.IN) function.addParameter('mn', dtype='float64', direction=function.IN) function.addParameter('fe', dtype='float64', direction=function.IN) function.addParameter('co', dtype='float64', direction=function.IN) function.addParameter('ni', dtype='float64', direction=function.IN) function.addParameter('cu', dtype='float64', direction=function.IN) function.addParameter('zn', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_number_of_backups_in_a_row(): """ Retrieve the number_of_backups_in_a_row 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 number_of_backups_in_a_row") function.addParameter('n_backup', dtype='int32', direction=function.OUT , description="The current number_of_backups_in_a_row of the star.") function.result_type = 'int32' function.result_doc = """ 0 - OK The number_of_backups_in_a_row was retrieved. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def reset_number_of_backups_in_a_row(): """ Reset number_of_backups_in_a_row 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 reset the value of number_of_backups_in_a_row") function.result_type = 'int32' function.result_doc = """ 0 - OK The number_of_backups_in_a_row was reset. -1 - ERROR A star with the given index was not found. """ return function @legacy_function def get_mass_fraction_at_zone(): """ Retrieve the mass fraction 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('dq_i', dtype='float64', direction=function.OUT , description="The mass fraction 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_mass_fraction_at_zone(): """ Set the mass fraction 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('dq_i', dtype='float64', direction=function.IN , description="The mass fraction 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_luminosity_at_zone(): """ Retrieve the luminosity 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('lum_i', dtype='float64', direction=function.OUT , description="The luminosity 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_luminosity_at_zone(): """ Set the luminosity 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('lum_i', dtype='float64', direction=function.IN , description="The luminosity 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_entropy_at_zone(): """ Retrieve the entropy 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('S_i', dtype='float64', direction=function.OUT , description="The specific entropy 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_thermal_energy_at_zone(): """ Retrieve the entropy 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('E_i', dtype='float64', direction=function.OUT , description="The specific thermal energy 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_brunt_vaisala_frequency_squared_at_zone(): """ Retrieve the Brunt-Vaisala frequency squared 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, unit=INDEX) function.addParameter('zone', dtype='int32', direction=function.IN, unit=NO_UNIT) function.addParameter('brunt_N2', dtype='float64', direction=function.OUT, unit=units.s**-2) function.result_type = 'int32' return function @legacy_function def get_id_of_species(): """ Retrieve the chem_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='int32', direction=function.IN , description="The species of the star to get the name of") function.addParameter('species_id', dtype='int32', direction=function.OUT , description="The chem_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. """ return function @legacy_function def get_mass_of_species(): """ Retrieve the mass number 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 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. """ return function @legacy_function def erase_memory(): """ Erase memory of the star, i.e. copy the current structure over the memory of the structure of the previous steps. Useful after setting the stucture of the star, to prevent backup steps to undo changes """ 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.result_type = 'int32' 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.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.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.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_convective_overshoot_parameter(): function = LegacyFunctionSpecification() function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.OUT, description="The current value of the convective overshoot parameter.") function.result_type = 'int32' return function @legacy_function def set_convective_overshoot_parameter(): function = LegacyFunctionSpecification() function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.IN, description="The new value of the convective overshoot parameter.") function.result_type = 'int32' return function @legacy_function def get_mixing_length_ratio(): """ Retrieve the current value of the mixing length ratio. """ function = LegacyFunctionSpecification() function.addParameter('mixing_length_ratio', dtype='float64', direction=function.OUT , description="The current value of the mixing length ratio.") 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_mixing_length_ratio(): """ Set the value of the mixing length ratio. """ function = LegacyFunctionSpecification() function.addParameter('mixing_length_ratio', dtype='float64', direction=function.IN , description="The new value of the mixing length ratio.") 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_semi_convection_efficiency(): """ Retrieve the current value of the efficiency of semi-convection, after Heger, Langer, & Woosley 2000 (ApJ), which goes back to Langer, Sugimoto & Fricke 1983 (A&A). """ function = LegacyFunctionSpecification() function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.OUT , description="The current value of the efficiency of semi-convection.") 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_semi_convection_efficiency(): """ Set the value of the efficiency of semi-convection, after Heger, Langer, & Woosley 2000 (ApJ), which goes back to Langer, Sugimoto & Fricke 1983 (A&A). """ function = LegacyFunctionSpecification() function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.IN , description="The new value of the efficiency of semi-convection.") 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_RGB_wind_scheme(): """ Retrieve the current wind (mass loss) scheme for RGB stars: No automatic wind (0) Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229. Blocker (2): T. Blocker, A&A 297, 727-738 (1995) de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259 Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990 Mattsson (5) """ function = LegacyFunctionSpecification() function.addParameter('RGB_wind_scheme', dtype='int32', direction=function.OUT , description="The current wind (mass loss) scheme for RGB stars 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_RGB_wind_scheme(): """ Set the new wind (mass loss) scheme for RGB stars: No automatic wind (0) Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229. Blocker (2): T. Blocker, A&A 297, 727-738 (1995) de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259 Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990 Mattsson (5) """ function = LegacyFunctionSpecification() function.addParameter('RGB_wind_scheme', dtype='int32', direction=function.IN , description="The new wind (mass loss) scheme for RGB stars 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_AGB_wind_scheme(): """ Retrieve the current wind (mass loss) scheme for AGB stars: No automatic wind (0) Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229. Blocker (2): T. Blocker, A&A 297, 727-738 (1995) de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259 Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990 Mattsson (5) """ function = LegacyFunctionSpecification() function.addParameter('AGB_wind_scheme', dtype='int32', direction=function.OUT , description="The current wind (mass loss) scheme for AGB stars 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_AGB_wind_scheme(): """ Set the new wind (mass loss) scheme for AGB stars: No automatic wind (0) Reimers (1): e.g. see: Baschek, Kegel, Traving (eds), Springer, Berlin, 1975, p. 229. Blocker (2): T. Blocker, A&A 297, 727-738 (1995) de Jager (3): de Jager, C., Nieuwenhuijzen, H., & van der Hucht, K. A. 1988, A&AS, 72, 259 Dutch (4): Glebbeek et al 2009, Vink et al 2001, Nugis & Lamers 2000, de Jager 1990 Mattsson (5) """ function = LegacyFunctionSpecification() function.addParameter('AGB_wind_scheme', dtype='int32', direction=function.IN , description="The new wind (mass loss) scheme for AGB stars 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_reimers_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('reimers_wind_efficiency', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_reimers_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('reimers_wind_efficiency', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_blocker_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('blocker_wind_efficiency', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_blocker_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('blocker_wind_efficiency', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_de_jager_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('de_jager_wind_efficiency', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_de_jager_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('de_jager_wind_efficiency', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dutch_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('dutch_wind_efficiency', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dutch_wind_efficiency(): function = LegacyFunctionSpecification() function.addParameter('dutch_wind_efficiency', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stabilize_new_stellar_model_flag(): function = LegacyFunctionSpecification() function.addParameter('stabilize_new_stellar_model_flag', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_stabilize_new_stellar_model_flag(): function = LegacyFunctionSpecification() function.addParameter('stabilize_new_stellar_model_flag', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_stellar_model(): """ Define a new star model in the code. The star needs to be finalized before it can evolve, see 'finalize_stellar_model'. """ function = LegacyFunctionSpecification() function.must_handle_array = True for par in ['d_mass', 'radius', 'rho', 'temperature', 'luminosity', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']: 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 class MESA(StellarEvolution, InternalStellarStructure): def __init__(self, **options): InCodeComponentImplementation.__init__(self, MESAInterface(**options), **options) output_dir = self.get_output_directory() model_path = os.path.join(output_dir, 'star_data', 'starting_models') if not self.channel_type == 'distributed': self.ensure_data_directory_exists(model_path) if not os.path.isfile(os.path.join(model_path, 'zams_z20m3.data')): model_file=os.path.join(self.get_data_directory(), 'star_data', 'starting_models', 'zams_z20m3.data') shutil.copy(model_file, model_path) if 'inlist' in options: inlist_path = options['inlist'] if not os.path.exists(inlist_path): raise ValueError('Named inlist does not exist, maybe its in a different folder?') else: inlist_path = self.default_path_to_inlist self.set_MESA_paths( inlist_path, self.default_path_to_MESA_data, output_dir ) self.model_time = 0.0 | units.yr self.mesa_version = "2208" self.inlist = inlist_path 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.yr ) 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 ) handler.add_method_parameter( "get_convective_overshoot_parameter", "set_convective_overshoot_parameter", "herwig_convective_overshoot_parameter", "The convective overshoot parameter (Herwig 2000), f=0.016 is argued to be a reasonable value.", default_value = 0.0 ) handler.add_method_parameter( "get_mixing_length_ratio", "set_mixing_length_ratio", "mixing_length_ratio", "The mixing-length ratio (alpha).", default_value = 2.0 ) handler.add_method_parameter( "get_semi_convection_efficiency", "set_semi_convection_efficiency", "semi_convection_efficiency", "The efficiency of semi-convection, after Heger, Langer, & Woosley 2000 (ApJ), " "which goes back to Langer, Sugimoto & Fricke 1983 (A&A).", default_value = 0.0 ) handler.add_method_parameter( "get_RGB_wind_scheme", "set_RGB_wind_scheme", "RGB_wind_scheme", "The mass loss scheme for RGB stars: none (0), Reimers (1), " "Blocker (2), de Jager (3), Dutch (4), Mattsson (5)", default_value = 1 ) handler.add_method_parameter( "get_AGB_wind_scheme", "set_AGB_wind_scheme", "AGB_wind_scheme", "The mass loss scheme for AGB stars: none (0), Reimers (1), " "Blocker (2), de Jager (3), Dutch (4), Mattsson (5)", default_value = 1 ) handler.add_method_parameter( "get_reimers_wind_efficiency", "set_reimers_wind_efficiency", "reimers_wind_efficiency", "The Reimers mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 1).", default_value = 0.5 ) handler.add_method_parameter( "get_blocker_wind_efficiency", "set_blocker_wind_efficiency", "blocker_wind_efficiency", "The Blocker mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 2).", default_value = 0.1 ) handler.add_method_parameter( "get_de_jager_wind_efficiency", "set_de_jager_wind_efficiency", "de_jager_wind_efficiency", "The de Jager mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 3).", default_value = 0.8 ) handler.add_method_parameter( "get_dutch_wind_efficiency", "set_dutch_wind_efficiency", "dutch_wind_efficiency", "The Dutch mass loss efficiency. Only used if (RGB/AGB_wind_scheme == 4).", default_value = 0.8 ) handler.add_boolean_parameter( "get_stabilize_new_stellar_model_flag", "set_stabilize_new_stellar_model_flag", "stabilize_new_stellar_model_flag", "Flag specifying whether to stabilize any loaded stellar models first.", default_value = True ) def define_particle_sets(self, handler): handler.define_super_set('particles', ['native_stars', 'imported_stars', 'pre_ms_stars'], 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_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') for particle_set_name in ['native_stars', 'imported_stars', 'pre_ms_stars']: 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_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_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, '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_IDs_of_species') handler.add_method(particle_set_name, 'get_masses_of_species') handler.add_method(particle_set_name, 'get_number_of_backups_in_a_row') handler.add_method(particle_set_name, 'reset_number_of_backups_in_a_row') 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_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(-14, 'Evolve terminated: Maximum number of backups reached.') handler.add_errorcode(-15, 'Evolve terminated: Minimum timestep limit reached.') def define_methods(self, handler): InternalStellarStructure.define_methods(self, handler) StellarEvolution.define_methods(self, handler) handler.add_method( "evolve_for", (handler.INDEX, units.julianyr), (handler.ERROR_CODE,) ) handler.add_method( "new_pre_ms_particle", (units.MSun), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "set_time_step", (handler.INDEX, units.yr), (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.g / units.s, handler.ERROR_CODE,) ) handler.add_method( "get_manual_mass_transfer_rate", (handler.INDEX,), (units.MSun / units.yr, handler.ERROR_CODE,) ) handler.add_method( "set_manual_mass_transfer_rate", (handler.INDEX, units.MSun / units.yr), (handler.ERROR_CODE,) ) handler.add_method( "get_number_of_backups_in_a_row", (handler.INDEX,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "reset_number_of_backups_in_a_row", (handler.INDEX,), (handler.ERROR_CODE,) ) handler.add_method( "get_mass_fraction_at_zone", (handler.INDEX,handler.NO_UNIT,), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mass_fraction_at_zone", (handler.INDEX, handler.NO_UNIT, handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_luminosity_at_zone", (handler.INDEX,handler.NO_UNIT,), (units.erg/units.s, handler.ERROR_CODE,) ) handler.add_method( "set_luminosity_at_zone", (handler.INDEX, handler.NO_UNIT, units.erg/units.s,), (handler.ERROR_CODE,) ) handler.add_method( "get_entropy_at_zone", (handler.INDEX,handler.NO_UNIT,), (units.erg/units.K, handler.ERROR_CODE,) ) handler.add_method( "get_thermal_energy_at_zone", (handler.INDEX,handler.NO_UNIT,), (units.erg/units.g, 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( "erase_memory", (handler.INDEX,), (handler.ERROR_CODE,), public_name = "_erase_memory" ) handler.add_method( "new_stellar_model", (units.MSun, units.cm, units.g / units.cm**3, units.K, units.erg / units.s, 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( "finalize_stellar_model", (units.yr,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "get_max_age_stop_condition", (), (units.yr, handler.ERROR_CODE,) ) handler.add_method( "set_max_age_stop_condition", (units.yr, ), (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_mixing_length_ratio", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mixing_length_ratio", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_semi_convection_efficiency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_semi_convection_efficiency", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_RGB_wind_scheme", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_RGB_wind_scheme", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_AGB_wind_scheme", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_AGB_wind_scheme", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_reimers_wind_efficiency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_reimers_wind_efficiency", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_blocker_wind_efficiency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_blocker_wind_efficiency", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_de_jager_wind_efficiency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_de_jager_wind_efficiency", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_dutch_wind_efficiency", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_dutch_wind_efficiency", (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_mass_fraction_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none) 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) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) 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_luminosity_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none) 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) if hasattr(self, "_erase_memory"): self._erase_memory(indices_of_the_stars) 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_entropy_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none) 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_thermal_energy_at_zone([indices_of_the_stars]*number_of_zones, list(range(number_of_zones)) | units.none) 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_brunt_vaisala_frequency_squared_at_zone([indices_of_the_stars]*number_of_zones, list(range(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(self.get_id_of_species( [indices_of_the_stars]*number_of_species, list(range(1,number_of_species+1)) )) 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 new_particle_from_model(self, internal_structure, current_age=0|units.Myr, key=None): if isinstance(internal_structure, dict): if "dmass" in internal_structure: mass_profile = internal_structure['dmass'][::-1] else: cumulative_mass_profile = [0.0] | units.MSun cumulative_mass_profile.extend(internal_structure['mass']) mass_profile = (cumulative_mass_profile[1:] - cumulative_mass_profile[:-1])[::-1] self.new_stellar_model( mass_profile, internal_structure['radius'][::-1], internal_structure['rho'][::-1], internal_structure['temperature'][::-1], internal_structure['luminosity'][::-1], internal_structure['X_H'][::-1], 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], internal_structure['X_Fe'][::-1] ) else: if hasattr(internal_structure, "dmass"): mass_profile = internal_structure.dmass[::-1] else: cumulative_mass_profile = [0.0] | units.MSun cumulative_mass_profile.extend(internal_structure.mass) mass_profile = (cumulative_mass_profile[1:] - cumulative_mass_profile[:-1])[::-1] self.new_stellar_model( mass_profile, internal_structure.radius[::-1], internal_structure.rho[::-1], internal_structure.temperature[::-1], internal_structure.luminosity[::-1], internal_structure.X_H[::-1], 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], internal_structure.X_Fe[::-1] ) tmp_star = datamodel.Particle(key=key) tmp_star.age_tag = current_age return self.imported_stars.add_particle(tmp_star) Mesa = MESA
68,390
42.644544
152
py
amuse
amuse-main/src/amuse/community/kepler/test_kepler.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.kepler.interface import Kepler from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.rfi.core import is_mpd_running def test1(): mass = 1 | nbody_system.mass semi = 1 | nbody_system.length ecc = 0.5 time = 5.0 | nbody_system.time run_kepler(mass, semi, ecc, time) def run_kepler(mass, semi, ecc, time): kep = Kepler(redirection='none') kep.initialize_code() kep.set_longitudinal_unit_vector(1.0, 1.0, 0.0) kep.initialize_from_elements(mass, semi, ecc) a,e = kep.get_elements() p = kep.get_periastron() print("elements:", a, e, p) kep.transform_to_time(time) x,y,z = kep.get_separation_vector() print("separation:", x,y,z) x,y,z = kep.get_longitudinal_unit_vector() print("longitudinal:", x,y,z) pos = [1, 0, 0] | nbody_system.length vel = [0, 0.5, 0] | nbody_system.speed kep.initialize_from_dyn(mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a,e = kep.get_elements() p = kep.get_periastron() print("elements:", a, e, p) kep.transform_to_time(time) x,y,z = kep.get_separation_vector() print("separation:", x,y,z) x,y,z = kep.get_velocity_vector() print("velocity:", x,y,z) x,y,z = kep.get_longitudinal_unit_vector() print("longitudinal:", x,y,z) kep.set_random(42) kep.make_binary_scattering(0.5 | nbody_system.mass, 0.5, 0.5 | nbody_system.mass, 0.0 | nbody_system.speed, 0.0 | nbody_system.length, 1.e-6, 0) kep.stop() if __name__ == '__main__': mass = 1 | nbody_system.mass semi = 1 | nbody_system.length ecc = 0.5 time = 5.0 | nbody_system.time try: opts, args = getopt.getopt(sys.argv[1:], "a:e:m:t:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) for o, a in opts: if o == "-a": semi = float(a) | nbody_system.length elif o == "-e": ecc = float(a) elif o == "-m": time = float(a) | nbody_system.mass elif o == "-t": time = float(a) | nbody_system.time else: print("unexpected argument", o) assert is_mpd_running() run_kepler(mass, semi, ecc, time)
2,657
27.580645
60
py
amuse
amuse-main/src/amuse/community/kepler/__init__.py
from .interface import Kepler
30
14.5
29
py
amuse
amuse-main/src/amuse/community/kepler/interface.py
from amuse.community import * from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.support.options import option from amuse.units import units import os.path class KeplerInterface(CodeInterface, CommonCodeInterface): """ Kepler orbit manipulation functions, imported from Starlab. Initialize an orbit from mass, pos, and vel, or mass, semi-major axis and eccentricity, and allow the user to manipulate the resulting structure. Most Starlab functionality is currently exposed. """ # Interface specification. include_headers = ['interface.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker = "kepler_worker", **options) @legacy_function def initialize_from_dyn(): """ Initialize a new kepler system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('mass', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.addParameter('x', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('vx', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('time', dtype='float64', direction=function.IN, default = 0, unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK new kepler was created -1 - ERROR kepler could not be created""" return function @legacy_function def initialize_from_elements(): """ Initialize a new kepler system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('mass', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.addParameter('semi', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('ecc', dtype='float64', direction=function.IN, unit = NO_UNIT) function.addParameter('mean_anomaly', dtype='float64', direction=function.IN, default = 0, unit = NO_UNIT) function.addParameter('time', dtype='float64', direction=function.IN, default = 0, unit = nbody_system.time) function.addParameter('periastron', dtype='float64', direction=function.IN, default = 0, unit = nbody_system.length) function.addParameter('random_orientation', dtype='int32', direction=function.IN, default = 0, unit = NO_UNIT) function.result_type = 'int32' function.result_doc = """ 0 - OK new kepler was created -1 - ERROR kepler could not be created""" return function @legacy_function def transform_to_time(): """ Transform the kepler system to the specified time. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('time', dtype='float64', direction=function.IN, unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK transform to time OK -1 - ERROR could not transform to time""" return function @legacy_function def advance_to_radius(): """ Evolve the kepler system forward in time to the specified radius. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('radius', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK advance to radius OK -1 - ERROR could not advance to radius""" return function @legacy_function def return_to_radius(): """ Evolve the kepler system backward in time to the specified radius. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('radius', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK return to radius OK -1 - ERROR could not return to radius""" return function @legacy_function def advance_to_periastron(): """ Evolve the kepler system forward in time to the next periastron. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.result_type = 'int32' function.result_doc = """ 0 - OK advance to periastron OK -1 - ERROR could not advance to periastron""" return function @legacy_function def advance_to_apastron(): """ Evolve the kepler system forward in time to the next apastron. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.result_type = 'int32' function.result_doc = """ 0 - OK advance to apastron OK -1 - ERROR could not advance to apastron""" return function @legacy_function def return_to_periastron(): """ Evolve the kepler system backward in time to the previous periastron. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.result_type = 'int32' function.result_doc = """ 0 - OK return to periastron OK -1 - ERROR could not return to periastron""" return function @legacy_function def return_to_apastron(): """ Evolve the kepler system backward in time to the previous apastron. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.result_type = 'int32' function.result_doc = """ 0 - OK return to apastron OK -1 - ERROR could not return to apastron""" return function @legacy_function def get_total_mass(): """ Return the total mass (remind the user) of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('mass', dtype='float64', direction=function.OUT, unit = nbody_system.mass) function.result_type = 'int32' function.result_doc = """ 0 - OK get mass OK -1 - ERROR could not get mass""" return function @legacy_function def get_time(): """ Return the current time of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('time', dtype='float64', direction=function.OUT, unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK get time OK -1 - ERROR could not get time""" return function @legacy_function def get_period(): """ Return the periodof the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('period', dtype='float64', direction=function.OUT, unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK get period OK -1 - ERROR could not get period""" return function @legacy_function def get_elements(): """ Return the orbital elements (a,e) of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('semi', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('ecc', dtype='float64', direction=function.OUT, unit = NO_UNIT) function.result_type = 'int32' function.result_doc = """ 0 - OK get elements OK -1 - ERROR could not get elements""" return function @legacy_function def get_integrals(): """ Return the total energy and angular momentum of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('energy', dtype='float64', direction=function.OUT, unit = nbody_system.speed*nbody_system.speed) function.addParameter('angular_momentum', dtype='float64', direction=function.OUT, unit = nbody_system.length*nbody_system.speed) function.result_type = 'int32' function.result_doc = """ 0 - OK get integrals OK -1 - ERROR could not get integrals""" return function @legacy_function def get_separation_vector(): """ Return the current separation vector (x,y,z) of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('x', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK get separation vector OK -1 - ERROR could not get separation vector""" return function @legacy_function def get_separation(): """ Return the current separation r of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('r', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK get separation OK -1 - ERROR could not get separation""" return function @legacy_function def set_periastron(): """ Set the current periastron of the system (initialization only). """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('peri', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK set periastron OK -1 - ERROR could not set periastron""" return function @legacy_function def get_periastron(): """ Return the current periastron of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('peri', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK get periastron OK -1 - ERROR could not get periastron""" return function @legacy_function def get_apastron(): """ Return the current apastron of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('apo', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' function.result_doc = """ 0 - OK get apastron OK -1 - ERROR could not get apastron""" return function @legacy_function def get_velocity_vector(): """ Return the current relative velocity vector (x,y,z) of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('vx', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.result_type = 'int32' function.result_doc = """ 0 - OK get velocity vector OK -1 - ERROR could not get velocity vector""" return function @legacy_function def get_angles(): """ Return the current mean and true anomalies of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('true_anomaly', dtype='float64', direction=function.OUT) function.addParameter('mean_anomaly', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK get angles OK -1 - ERROR could not get angles""" return function @legacy_function def set_longitudinal_unit_vector(): """ Set the longitudinal unit vector of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK set vector OK -1 - ERROR could not set vector""" return function @legacy_function def set_normal_unit_vector(): """ Set the normal unit vector of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK set vector OK -1 - ERROR could not set vector""" return function @legacy_function def get_longitudinal_unit_vector(): """ Return the longitudinal unit vector of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK get vector OK -1 - ERROR could not get vector""" return function @legacy_function def get_transverse_unit_vector(): """ Return the transverse unit vector of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK get vector OK -1 - ERROR could not get vector""" return function @legacy_function def set_transverse_unit_vector(): """ Set the transverse unit vector of the system (tangent on longitudal uv). """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK set vector OK -1 - ERROR could not set vector""" return function @legacy_function def get_normal_unit_vector(): """ Return the normal unit vector of the system. """ function = LegacyFunctionSpecification() function.can_handle_array = False 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' function.result_doc = """ 0 - OK get vector OK -1 - ERROR could not get vector""" return function @legacy_function def print_all(): """ Print a kepler system. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.result_type = 'int32' function.result_doc = """ 0 - OK kepler was printed -1 - ERROR kepler could not be printed""" return function @legacy_function def set_random(): """ Set the random seed for kepler functions. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('seed', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK seed was initialized -1 - ERROR error occurred""" return function @legacy_function def get_random(): """ Return the random seed for kepler functions. """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('seed', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK seed was returned -1 - ERROR error occurred""" return function @legacy_function def make_binary_scattering(): """ Return a three-body scattering configuration (much faster than python). """ function = LegacyFunctionSpecification() function.can_handle_array = False function.addParameter('m', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.addParameter('ecc', dtype='float64', direction=function.IN, unit = NO_UNIT) function.addParameter('M', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.addParameter('v_inf', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('impact_parameter', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('gamma', dtype='float64', direction=function.IN, unit = NO_UNIT) function.addParameter('planar', dtype='int32', direction=function.IN, unit = NO_UNIT) function.addParameter('time', dtype='float64', direction=function.OUT, unit = nbody_system.time) function.addParameter('m1', dtype='float64', direction=function.OUT, unit = nbody_system.mass) function.addParameter('m2', dtype='float64', direction=function.OUT, unit = nbody_system.mass) function.addParameter('m3', dtype='float64', direction=function.OUT, unit = nbody_system.mass) function.addParameter('x1', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('x2', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('x3', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('y1', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('y2', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('y3', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('z1', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('z2', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('z3', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('vx1', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vx2', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vx3', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vy1', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vy2', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vy3', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vz1', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vz2', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vz3', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.result_type = 'int32' function.result_doc = """ 0 - OK legal scattering configuration -1 - ERROR problem""" return function class Kepler(CommonCode): __interface__ = KeplerInterface def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter CommonCode.__init__(self, self.__interface__(**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_methods(self, handler): CommonCode.define_methods(self, handler) def initialize_from_particles(self, particles): if not len(particles) == 2: raise Exception('The kepler code can only be initialized from a particle set with 2 particles') total_mass = particles[0].mass + particles[1].mass rel_position = particles[0].position - particles[1].position rel_velocity = particles[0].velocity - particles[1].velocity self.center_of_mass_position = particles.center_of_mass() self.center_of_mass_velocity = particles.center_of_mass_velocity() self.initialize_from_dyn( total_mass, rel_position[0],rel_position[1],rel_position[2], rel_velocity[0],rel_velocity[1],rel_velocity[2] ) self.particles = particles.copy() def define_state(self, handler): CommonCode.define_state(self, handler) for method_name in [ 'initialize_from_dyn', 'initialize_from_elements', 'transform_to_time', 'advance_to_radius', 'return_to_radius', 'advance_to_periastron', 'advance_to_apastron', 'return_to_periastron', 'return_to_apastron', 'get_total_mass', 'get_time', 'get_period', 'get_elements', 'get_integrals', 'get_separation_vector', 'get_separation', 'set_periastron', 'get_periastron', 'get_apastron', 'get_velocity_vector', 'get_angles', 'set_longitudinal_unit_vector', 'set_normal_unit_vector', 'get_longitudinal_unit_vector', 'get_transverse_unit_vector', 'set_transverse_unit_vector', 'get_normal_unit_vector', 'print_all', 'set_random', 'get_random', 'make_binary_scattering']: handler.add_method('!UNINITIALIZED!END', method_name)
27,362
36.742069
107
py
amuse
amuse-main/src/amuse/community/symple/test.py
from amuse.lab import * from interface import symple from matplotlib import pyplot as plt import sys, math n = 2 # Select a gravity code. g = symple(redirection='none') g.initialize_code() g.parameters.set_defaults() # Make a binary. p = new_plummer_model(n) r = 0.5|nbody_system.length vcirc = (0.25*nbody_system.G*p[0].mass/r).sqrt() v = 0.5*vcirc p[0].position = [r, zero, zero] p[1].position = -p[0].position p[0].velocity = [zero, v, zero] p[1].velocity = -p[0].velocity g.particles.add_particles(p) g.commit_particles() E0 = g.kinetic_energy + g.potential_energy M = p[0].mass+p[1].mass GM = (nbody_system.G)*M a = -0.5*nbody_system.G*p[0].mass*p[1].mass/E0 P = 2*math.pi*(a**3/GM).sqrt() L = 2*p[0].mass*(p[0].x*p[0].vy) mu = p[0].mass*p[1].mass/M ee = E0/mu h = L/mu e = math.sqrt(1+2*ee*h**2/GM**2) print('E =', E0) print('a =', a) print('P =', P) print('e =', e) # Include mass loss. mdotfac = 0. for i in range(n): g.set_dmdt(i, -mdotfac*p[i].mass/(1.e3|nbody_system.time)) g.parameters.integrator = 10 # 10th order symplectic g.parameters.timestep = P/128 # power of 2 seems to work best #g.parameters.timestep_parameter = 0.2 # timestep and timestep_parameter are # mutually exclusive -- no longer # symplectic if timestep_parameter > 0 print(g.parameters) time = 0.|nbody_system.time dt = P/64 t_end = 100*P t = [time.number] x = [(g.particles[0].x-g.particles[1].x).number] y = [(g.particles[0].y-g.particles[1].y).number] e = [0.] while time < t_end: time += dt g.evolve_model(time) t.append(time.number) x.append((g.particles[0].x-g.particles[1].x).number) y.append((g.particles[0].y-g.particles[1].y).number) E1 = g.kinetic_energy + g.potential_energy dE = E1/E0 - 1 e.append(dE) print('dE/E =', dE) if 0: plt.figure(figsize=(6,6)) plt.plot(x, y) plt.xlim(-1.2, 1.2) plt.ylim(-1.2, 1.2) plt.axes().set_aspect('equal') else: plt.plot(t, e) plt.show() g.stop()
2,007
22.08046
78
py
amuse
amuse-main/src/amuse/community/symple/test_si.py
from amuse.lab import * from .interface import symple n = 10 total_mass = n|units.MSun length = 1|units.parsec converter = nbody_system.nbody_to_si(total_mass, length) # Select a gravity code. g = symple(convert_nbody=converter, redirection='none') g.initialize_code() g.parameters.set_defaults() # Make an N-body system. p = new_plummer_model(n, convert_nbody=converter) g.particles.add_particles(p) g.commit_particles() E0 = g.kinetic_energy + g.potential_energy print('E0 =', E0) # Include mass loss. mdotfac = 0. for i in range(n): g.set_dmdt(i, -mdotfac*p[i].mass/(1000|units.Myr)) g.parameters.epsilon_squared = (0.01|units.parsec)**2 g.parameters.integrator = 5 # 5th order symplectic g.parameters.timestep = 0.005|units.Myr g.parameters.timestep_parameter = 0.02 # timestep and timestep_parameter are # mutually exclusive -- no longer # symplectic if timestep_parameter > 0 print(g.parameters) g.evolve_model(100.|units.Myr) print('time =', g.model_time.in_(units.Myr)) #print g.particles E1 = g.kinetic_energy + g.potential_energy print('dE/E =', E1/E0 - 1) g.stop()
1,143
23.340426
78
py
amuse
amuse-main/src/amuse/community/symple/__init__.py
# generated file from .interface import Symple
47
15
29
py
amuse
amuse-main/src/amuse/community/symple/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 sympleInterface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, SinglePointGravityFieldInterface): """ N-body integration module with shared but variable time step (the same for all particles but with size changing in time), using the symple integration scheme. Code is symplectic for fixed time steps. .. [#] McMillan, S., 2017 """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="symple_worker", **options) LiteratureReferencesMixIn.__init__(self) def reinitialize_particles(self): self.recommit_particles() @legacy_function def get_dmdt(): """ Retrieve the mass loss rate of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle") function.addParameter('dmdt', dtype='float64', direction=function.OUT, description = "Current mdot 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 retrieved -1 - ERROR - particle could not be found """ return function @legacy_function def set_dmdt(): """ Set the mass loss rate of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle") function.addParameter('dmdt', dtype='float64', direction=function.IN, description = "New mdot 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 """ return function @legacy_function def get_timestep(): """ Get the fixed timestep. """ function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.OUT, description = "fixed timestep") 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_timestep(): """ Set the fixed timestep. """ function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.IN, description = "fixed timestep") 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_integrator(): """ Get the integration scheme. """ function = LegacyFunctionSpecification() function.addParameter('integrator', dtype='int32', direction=function.OUT, description = "the integration scheme") 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_integrator(): """ Set the integration scheme. """ function = LegacyFunctionSpecification() function.addParameter('integrator', dtype='int32', direction=function.IN, description = "the integration scheme") 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_timestep_parameter(): """ Get the time step scaling factor. """ function = LegacyFunctionSpecification() function.addParameter('timestep_parameter', dtype='float64', direction=function.OUT, description = "the timestep scaling factor") 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_timestep_parameter(): """ Set the time step scaling factor. """ function = LegacyFunctionSpecification() function.addParameter('timestep_parameter', dtype='float64', direction=function.IN, description = "the timestep scaling factor") 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_time(): """ Get the current simulation time. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT, description = "the current simulation time") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function class sympleDoc(object): def __get__(self, instance, owner): return instance.legacy_doc+"\n\n"+instance.parameters.__doc__ class symple(GravitationalDynamics, GravityFieldCode): __doc__ = sympleDoc() __interface__ = sympleInterface 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) def define_parameters(self, handler): handler.add_method_parameter( "get_integrator", "set_integrator", "integrator", "integrator for gravity calculations", default_value = 2 ) handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_timestep", "set_timestep", "timestep", "fixed timestep", default_value = 0.01 | nbody_system.time ) handler.add_method_parameter( "get_timestep_parameter", "set_timestep_parameter", "timestep_parameter", "timestep scaling parameter", default_value = 0.05 ) 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_integrator", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length,), (handler.ERROR_CODE,) ) handler.add_method( "set_timestep_parameter", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "set_time", (nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "set_timestep", (nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "set_dmdt", (handler.NO_UNIT, nbody_system.mass / nbody_system.time,), (handler.ERROR_CODE,) ) handler.add_method( "get_integrator", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "get_timestep_parameter", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "get_time", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "get_timestep", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "get_dmdt", (handler.NO_UNIT,), (nbody_system.mass / nbody_system.time, handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) handler.add_setter('particles', 'set_dmdt') handler.add_getter('particles', 'get_dmdt') self.stopping_conditions.define_particle_set(handler) Symple = symple
11,124
29.988858
82
py
amuse
amuse-main/src/amuse/community/sphray/__init__.py
from .interface import Sphray
30
14.5
29
py
amuse
amuse-main/src/amuse/community/sphray/interface.py
import os.path from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community import * from amuse.support.options import option class SPHRayInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn, CodeWithDataDirectories): """ SPHRAY is a smoothed particle hydrodynamics (SPH) ray tracer designed to solve the 3D, time-dependent, radiative transfer equation. SPHRAY relies on a Monte Carlo (MC) ray-tracing scheme that does not interpolate the SPH particles on to a grid but instead integrates directly through the SPH kernels. A quick Axis Aligned Bounding Box (AABB) test taken from computer graphics applications allows for the acceleration of the ray-tracing component. The relevant references are: .. [#] ADS:2008MNRAS.386.1931A (Altay, Gabriel; Croft, Rupert A. C.; Pelupessy, Inti, 2008, MNRAS 386) """ def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker = self.name_of_the_worker(), **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) def name_of_the_worker(self): return 'sphray_worker' def new_particle(self, mass, radius, x, y, z, vx, vy, vz): pass @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def recommit_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def new_gas_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.OUT) for x in ['mass','h_smooth','x','y','z','rho','xion','u']: function.addParameter(x, dtype='float64', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='float64', direction=function.IN,default=0) function.result_type = 'i' return function @legacy_function def new_src_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.OUT) for x in ['luminosity','x','y','z']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter("SpcType", dtype='float64', direction=function.IN,default=0) function.result_type = 'i' return function @legacy_function def get_state_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','h_smooth','x','y','z','rho','xion','u']: function.addParameter(x, dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_state_src(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) for x in ['luminosity','x','y','z','SpcType']: function.addParameter(x, dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_state_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','h_smooth','x','y','z','rho','xion','u']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_pos_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['x','y','z']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_hsml_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['h_smooth']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_rho_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['rho']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_u_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['u']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_dudt_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['du_dt']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_vel_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_vel_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_dudt_gas(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['du_dt']: function.addParameter(x, dtype='float64', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_state_src(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) for x in ['luminosity','x','y','z']: function.addParameter(x, dtype='float64', direction=function.IN) function.addParameter("SpcType", dtype='float64', direction=function.IN,default=0.) function.result_type = 'i' return function @legacy_function def set_luminosity_src(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) for x in ['luminosity']: function.addParameter(x, dtype='float64', direction=function.IN) function.result_type = 'i' return function @legacy_function def remove_src_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def remove_gas_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_isothermal(): """ set_isothermal([0,1]): isothermal if 1, Temperature evolution if 0 """ function = LegacyFunctionSpecification() function.addParameter('isothermal_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_isothermal(): """ get_isothermal(): isothermal if 1, Temperature evolution if 0 """ function = LegacyFunctionSpecification() function.addParameter('isothermal_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_H_caseA(): """ set_H_caseA([0,1]): use case A for H if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('H_caseA_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_H_caseA(): """ get_H_caseA(): use case A for H if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('H_caseA_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_He_caseA(): """ set_He_caseA([0,1]): use case A for H if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('He_caseA_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_He_caseA(): """ get_He_caseA(): use case A for H if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('He_caseA_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_raynumber(): """ set number of rays per unit time """ function = LegacyFunctionSpecification() function.addParameter('number_rays', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_raynumber(): """ get number of rays per unit time """ function = LegacyFunctionSpecification() function.addParameter('number_rays', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_defaultspectype(): """ set default specType (negative in units of rydbergs, or positive integer) """ function = LegacyFunctionSpecification() function.addParameter('defaultspectype', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_defaultspectype(): """ get default specType (negative in units of rydbergs, or positive integer) """ function = LegacyFunctionSpecification() function.addParameter('defaultspectype', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_iontempsolver(): """ set solver to use (1,2 = euler, bdf) """ function = LegacyFunctionSpecification() function.addParameter('iontempsolver', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_iontempsolver(): """ get solver to use (1,2 = euler, bdf) """ function = LegacyFunctionSpecification() function.addParameter('iontempsolver', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_boundary(): """ set boundary condition to use (-1,0,1 = reflective, vacuum, periodic) """ function = LegacyFunctionSpecification() function.addParameter('boundary', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_boundary(): """ get boundary condition to use (-1,0,1 = reflective, vacuum, periodic) """ function = LegacyFunctionSpecification() function.addParameter('boundary', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_boxsize(): """ set box size in kpc """ function = LegacyFunctionSpecification() function.addParameter('boxsize', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_boxsize(): """ get box size in kpc """ function = LegacyFunctionSpecification() function.addParameter('boxsize', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_globalHefraction(): """ set He mass fraction (f_H+f_He=1 ) """ function = LegacyFunctionSpecification() function.addParameter('globalHefraction', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_globalHefraction(): """ get He mass fraction (f_H+f_He=1 ) """ function = LegacyFunctionSpecification() function.addParameter('globalHefraction', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_momentum_kicks(): """ set_momentume_kicks([0,1]): calc momentum kicks if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('momentum_kicks', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_momentum_kicks(): """ set_momentume_kicks([0,1]): calc momentum kicks if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('momentum_kicks', dtype='i', 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 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_sphray_data_directory(): """ Update the path to the sphray database. """ function = LegacyFunctionSpecification() function.addParameter('data_directory', dtype='string', direction=function.IN, description = "Name of the data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_sphray_data_directory(): """ Retrieve the path to the database currently used. """ function = LegacyFunctionSpecification() function.addParameter('data_directory', dtype='string', direction=function.OUT, description = "Name of the data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Value was retrieved -1 - ERROR Could not retrieve value """ return function @legacy_function def set_spectra_file(): """ set the spectrafile to use(relative to data directory) """ function = LegacyFunctionSpecification() function.addParameter('spectra_file', dtype='string', direction=function.IN, description = "Name of the file") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_spectra_file(): """ get the spectrafile to use(relative to data directory) """ function = LegacyFunctionSpecification() function.addParameter('spectra_file', dtype='string', direction=function.OUT, description = "Name of the file") function.result_type = 'int32' function.result_doc = """ 0 - OK Value was retrieved -1 - ERROR Could not retrieve value """ return function @legacy_function def set_sphray_output_directory(): """ Update the output path. """ function = LegacyFunctionSpecification() function.addParameter('output_directory', dtype='string', direction=function.IN, description = "Name of the output directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_sphray_output_directory(): """ Retrieve the output path. """ function = LegacyFunctionSpecification() function.addParameter('output_directory', dtype='string', direction=function.OUT, description = "Name of the output directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Value was retrieved -1 - ERROR Could not retrieve value """ return function class SPHRay(CommonCode): def __init__(self,unit_converter = None, **options): if unit_converter is not None: raise Exception("atm SPHRay uses predefined units converter") self.unit_converter = ConvertBetweenGenericAndSiUnits( 1. | units.kpc, 1.e10 | units.MSun, 1. | units.kms) InCodeComponentImplementation.__init__(self, SPHRayInterface(**options)) self.set_sphray_data_directory(self.data_directory) self.set_sphray_output_directory(self.output_directory) def define_converter(self, handler): if self.unit_converter is None: raise Exception("something seriously wrong") 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_parameters(self, handler): handler.add_boolean_parameter( "get_isothermal", "set_isothermal", "isothermal_flag", "whether to evolve temperature (0) or keep isothermal (1)", False ) handler.add_boolean_parameter( "get_momentum_kicks", "set_momentum_kicks", "momentum_kicks_flag", "whether to use momentum kicks (1) not (0)", False ) handler.add_method_parameter( "get_raynumber", "set_raynumber", "number_of_rays", "number of rays per unit time", default_value = 1000 | generic_unit_system.time**-1 ) handler.add_method_parameter( "get_iontempsolver", "set_iontempsolver", "ionization_temperature_solver", "solver to use (1: euler, 2: bdf)", default_value = 2 ) handler.add_method_parameter( "get_globalHefraction", "set_globalHefraction", "global_helium_mass_Fraction", "global helium mass fraction (f_H+f_He=1)", default_value = 0. ) handler.add_method_parameter( "get_boxsize", "set_boxsize", "box_size", "simulation box size", default_value = 13.2 | units.kpc ) handler.add_method_parameter( "get_defaultspectype", "set_defaultspectype", "default_spectral_type", "default src spectral type", default_value = -1. ) handler.add_method_parameter( "get_boundary", "set_boundary", "boundary_condition", "simulation bundary condition (-1,0,1 = reflective, vacuum, periodic", default_value = 0 ) handler.add_boolean_parameter( "get_H_caseA", "set_H_caseA", "hydrogen_case_A_flag", "flag for hydrogen case A recombination (1)", True ) handler.add_boolean_parameter( "get_He_caseA", "set_He_caseA", "helium_case_A_flag", "flag for helium case A recombination (1)", True ) handler.add_method_parameter( "get_spectra_file", "set_spectra_file", "spectra_file", "spectra file to use", default_value = "./spectra/thermal30k.cdf" ) def define_methods(self, handler): CommonCode.define_methods(self, handler) handler.add_method('evolve_model', (generic_unit_system.time,), ( handler.ERROR_CODE, )) handler.add_method( "new_gas_particle", ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.density, handler.NO_UNIT, generic_unit_system.speed**2, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "set_state_gas", ( handler.NO_UNIT, generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.density, handler.NO_UNIT, generic_unit_system.speed**2 ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_vel_gas", ( handler.NO_UNIT, generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_pos_gas", ( handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_rho_gas", ( handler.NO_UNIT, generic_unit_system.density, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_hsml_gas", ( handler.NO_UNIT, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_u_gas", ( handler.NO_UNIT, generic_unit_system.speed**2 ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_dudt_gas", ( handler.NO_UNIT, generic_unit_system.length**2/generic_unit_system.time**3 ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_dudt_gas", ( handler.INDEX, ), ( generic_unit_system.length**2/generic_unit_system.time**3, handler.ERROR_CODE, ) ) handler.add_method( "get_state_gas", ( handler.INDEX, ), ( generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, generic_unit_system.density, handler.NO_UNIT, generic_unit_system.speed**2, handler.ERROR_CODE, ) ) handler.add_method( "get_vel_gas", ( handler.INDEX, ), ( generic_unit_system.speed, generic_unit_system.speed, generic_unit_system.speed, handler.ERROR_CODE, ) ) handler.add_method( "new_src_particle", ( 1.e50 * units.s**-1, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "set_state_src", ( handler.NO_UNIT, 1.e50 * units.s**-1, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_luminosity_src", ( handler.NO_UNIT, 1.e50 * units.s**-1, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state_src", ( handler.INDEX, ), ( 1.e50 * units.s**-1, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "remove_src_particle", ( handler.INDEX, ), ( handler.ERROR_CODE, ) ) handler.add_method( "remove_gas_particle", ( handler.INDEX, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_boxsize", ( generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_defaultspectype", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_globalHefraction", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_boxsize", ( ), ( generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( "get_globalHefraction", ( ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_defaultspectype", ( ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "set_raynumber", ( generic_unit_system.time**-1, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_raynumber", ( ), ( generic_unit_system.time**-1, handler.ERROR_CODE, ) ) handler.add_method( "set_iontempsolver", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_iontempsolver", ( ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "set_boundary", ( handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_boundary", ( ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_time", ( ), ( generic_unit_system.time, handler.ERROR_CODE, ) ) def define_particle_sets(self, handler): handler.define_set('gas_particles', 'id') handler.set_new('gas_particles', 'new_gas_particle') handler.set_delete('gas_particles', 'remove_gas_particle') handler.add_setter('gas_particles', 'set_state_gas') handler.add_getter('gas_particles', 'get_state_gas') handler.add_setter('gas_particles', 'set_pos_gas') handler.add_setter('gas_particles', 'set_vel_gas') handler.add_getter('gas_particles', 'get_vel_gas') handler.add_setter('gas_particles', 'set_hsml_gas') handler.add_setter('gas_particles', 'set_rho_gas') handler.add_setter('gas_particles', 'set_u_gas') handler.add_setter('gas_particles', 'set_dudt_gas') handler.add_getter('gas_particles', 'get_dudt_gas') handler.define_set('src_particles', 'id') handler.set_new('src_particles', 'new_src_particle') handler.set_delete('src_particles', 'remove_src_particle') handler.add_setter('src_particles', 'set_state_src') handler.add_setter('src_particles', 'set_luminosity_src') handler.add_getter('src_particles', 'get_state_src') def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False) handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False) handler.add_transition('UPDATE','CHANGE_PARAMETERS_UPDATE','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE','UPDATE','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_method('EVOLVED','before_get_parameter') handler.add_method('EDIT', 'new_gas_particle') handler.add_method('EDIT', 'remove_gas_particle') handler.add_method('EDIT', 'new_src_particle') handler.add_method('EDIT', 'remove_src_particle') handler.add_transition('EDIT', 'RUN', 'commit_particles') handler.add_transition('RUN', 'UPDATE', 'new_gas_particle', False) handler.add_transition('RUN', 'UPDATE', 'remove_gas_particle', False) handler.add_transition('RUN', 'UPDATE', 'new_src_particle', False) handler.add_transition('RUN', 'UPDATE', 'remove_src_particle', False) handler.add_transition('RUN', 'UPDATE', 'set_pos_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_rho_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_hsml_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_u_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_dudt_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_state_gas', False) handler.add_transition('RUN', 'UPDATE', 'set_state_src', False) handler.add_transition('RUN', 'UPDATE', 'set_luminosity_src', False) handler.add_transition('UPDATE', 'RUN', 'recommit_particles') handler.add_method('RUN', 'evolve_model') handler.add_method('RUN', 'get_state_gas') handler.add_method('RUN', 'get_state_src') handler.add_method('INITIALIZED', 'set_momentum_kicks') handler.add_method('INITIALIZED', 'set_isothermal') handler.add_method('INITIALIZED', 'set_boxsize') handler.add_method('INITIALIZED', 'set_globalHefraction') handler.add_method('INITIALIZED', 'set_raynumber') handler.add_method('INITIALIZED', 'set_iontempsolver') handler.add_method('INITIALIZED', 'set_boundary') handler.add_method('INITIALIZED', 'set_H_caseA') handler.add_method('INITIALIZED', 'set_He_caseA') Sphray = SPHRay
35,232
33.67815
110
py
amuse
amuse-main/src/amuse/community/sse/__init__.py
# -*- mode: python; coding: utf-8 -*- __author__ = 'Steve McMillan' __author_email__ = '<Steve@physics.drexel.edu>' __date__ = '2007-12-06' # Dummy file to indicate that this directory is a package. from .interface import Sse
242
26
58
py
amuse
amuse-main/src/amuse/community/sse/interface.py
import numpy from operator import itemgetter from amuse.community import * from amuse.units import units from amuse.units import constants from amuse.support.interface import InCodeComponentImplementation from amuse.community.interface import common from amuse.datamodel import Particles from amuse.datamodel import ParticlesSubset class SSEInterface(CodeInterface, common.CommonCodeInterface , LiteratureReferencesMixIn): """ Stellar evolution is performed by the rapid single-star evolution (SSE) algorithm. This is a package of analytical formulae fitted to the detailed models of Pols et al. (1998) that 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.1-100 Msun and metallicity can be varied. The SSE package contains a prescription for mass loss by stellar winds. It also follows the evolution of rotational angular momentum for the star. Full details can be found in the SSE paper: .. [#] 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="sse_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('sigma_in', dtype='d', direction=function.IN, unit = units.km / units.s) 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('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('status', dtype='i', direction=function.OUT, unit = NO_UNIT) return function @legacy_function def evolve_star(): function = LegacyFunctionSpecification() function.name = 'evolve0' function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mt', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('r', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('lum', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('mc', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('rc', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('menv', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('renv', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('ospin', dtype='d', direction=function.INOUT, unit = units.yr**-1) function.addParameter('epoch', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tm', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tphys', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tphysf', 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('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('age', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('tm', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('dt', dtype='d', direction=function.OUT, unit = units.Myr) return function @legacy_function def get_mass_loss_wind(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('lum', dtype='d', direction=function.IN, unit = units.LSun) function.addParameter('r', dtype='d', direction=function.IN, unit = units.RSun) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mc', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mlout', dtype='d', direction=function.OUT, unit = units.MSun/units.yr) return function @legacy_function def get_gyration_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('r', dtype='d', direction=function.IN, unit = units.RSun) function.addParameter('lum', dtype='d', direction=function.IN, unit = units.LSun) function.addParameter('epoch', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('tm', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('tphys', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('rg', dtype='d', direction=function.OUT, unit = NO_UNIT) return function 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 SSEParticles(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"]) self.add_function_attribute("evolve_one_step", self.particleset_evolve_one_step, self.evolve_one_step) self.add_function_attribute("evolve_for", self.particleset_evolve_for, self.evolve_for) 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, "CO_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.yr**-1, "main_sequence_lifetime": 0 | units.Myr, "age": 0 | units.Myr } 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(SSEParticles, self).add_particles_to_store(keys, all_attributes, all_values) added_particles = ParticlesSubset(self, keys) self._private.code_interface._evolve_particles(added_particles, 0 | units.yr) def evolve_one_step(self, particles, subset): self._private.code_interface._evolve_particles(subset.as_set(), subset.age + subset.time_step) def particleset_evolve_one_step(self, particles): self._private.code_interface._evolve_particles(particles, particles.age + particles.time_step) def evolve_for(self, particles, subset, delta_time): self._private.code_interface._evolve_particles(subset.as_set(), subset.age + delta_time) def particleset_evolve_for(self, particles, delta_time): self._private.code_interface._evolve_particles(particles, particles.age + delta_time) def get_defined_attribute_names(self): return ["mass", "radius"] class SSE(common.CommonCode): def __init__(self, **options): InCodeComponentImplementation.__init__(self, SSEInterface(**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", 0.5 ) 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", "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", "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 ) def define_state(self, handler): common.CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','RUN','commit_parameters') handler.add_method('RUN', 'evolve_star') 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', SSEParticles) handler.add_attribute( 'particles', 'time_step', 'get_time_step', ('stellar_type', 'initial_mass', 'age', 'mass', 'main_sequence_lifetime', 'epoch') ) handler.add_attribute( 'particles', 'mass_loss_wind', 'get_mass_loss_wind', ('stellar_type', 'luminosity', 'radius', 'mass', 'CO_core_mass') ) handler.add_attribute( 'particles', 'gyration_radius', 'get_gyration_radius', ('stellar_type', 'initial_mass','mass','radius', 'luminosity','epoch','main_sequence_lifetime', 'age') ) def _evolve_particles(self, particles, end_time): attributes = ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "main_sequence_lifetime", "age", "end_time" ) result = self.evolve_star( particles.stellar_type, particles.initial_mass, particles.mass, particles.radius, particles.luminosity, particles.core_mass, particles.core_radius, particles.convective_envelope_mass, particles.convective_envelope_radius, particles.spin, particles.epoch, particles.main_sequence_lifetime, particles.age, end_time.as_vector_with_length(len(particles))) # For helium (and helium exhausted) stars, the core mass returned is actually the CO core mass type = result[0].value_in(units.stellar_type) helium_star_selection = (type > 6) & (type < 16) & (type != 10) helium_stars = particles[helium_star_selection] other_stars = particles - helium_stars if len(helium_stars): helium_stars_results = [sub[helium_star_selection] for sub in result] helium_stars_results.append(helium_stars_results[2]) helium_stars.set_values_in_store(helium_stars.get_all_indices_in_store(), ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "CO_core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "main_sequence_lifetime", "age", "end_time", "core_mass"), helium_stars_results) if len(other_stars): other_star_selection = numpy.logical_not(helium_star_selection) other_stars.set_values_in_store(other_stars.get_all_indices_in_store(), attributes, [sub[other_star_selection] for sub in result]) def evolve_model(self, end_time = None, keep_synchronous = True): if not keep_synchronous: self._evolve_particles(self.particles, self.particles.time_step + self.particles.age) return if end_time is None: end_time = self.model_time + min(self.particles.time_step) self._evolve_particles(self.particles, end_time - self.model_time + self.particles.age) self.model_time = end_time def _evolve_model_old(self, end_time = None, keep_synchronous = True): """ This is the old implementation of evolve_model. Even with (keep_synchronous = True) it is unable to evolve all stars to a common age, since it relies on the individual timesteps as determined by the community code. Furthermore, it is not suited to simulations with ongoing star formation, since it evolves newly created stars to the same age as the old stars. """ if end_time is None: if keep_synchronous: ages = self.particles.age index, min_age = min(enumerate(ages), key=itemgetter(1)) new_age = min_age + self.particles[index].time_step selection = self.particles.select(lambda x : x < new_age, ["age"]) self._evolve_particles(selection, selection.time_step + selection.age) return end_time = self.particles.time_step + self.particles.age self._evolve_particles(self.particles, end_time) def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def initialize_module_with_current_parameters(self): self.parameters.send_cached_parameters_to_code() def initialize_module_with_default_parameters(self): self.parameters.set_defaults() self.commit_parameters() def update_time_steps(self): pass Sse = SSE
19,473
41.334783
140
py
amuse
amuse-main/src/amuse/community/phantom/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/rieder/phantom/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 = ['unzip', '-x'] arguments.append(filename) subprocess.call( arguments, cwd=os.path.join(self.src_directory()) ) subprocess.call( [ 'mv', 'phantom-{version}'.format(version=self.version), 'phantom' ], 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="ca6907f5f9a95f866b1d7e520cc356ab8cec8dd0", 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,297
26.357143
79
py
amuse
amuse-main/src/amuse/community/phantom/__init__.py
# generated file from .interface import Phantom
48
15.333333
30
py
amuse
amuse-main/src/amuse/community/phantom/interface.py
"Interface to Phantom" from amuse.community import ( CodeInterface, LegacyFunctionSpecification, legacy_function, LiteratureReferencesMixIn, ) from amuse.community.interface.gd import ( GravitationalDynamicsInterface, GravitationalDynamics, # GravityFieldInterface, GravityFieldCode, ) from amuse.community.interface.stopping_conditions import ( StoppingConditionInterface, StoppingConditions, ) from amuse.units import units, generic_unit_system from amuse.units.generic_unit_converter import ConvertBetweenGenericAndSiUnits class PhantomInterface( CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, # SinglePointGravityFieldInterface, ): """ The Phantom Smoothed Particle Hydrodynamics code, by Daniel Price et al. References: .. [#] ADS:2018PASA...35...31P (Price et al., 2018, PASA, Volume 35, id.e031 82 pp) """ def __init__(self, **options): CodeInterface.__init__( self, name_of_the_worker="phantom_worker", **options) LiteratureReferencesMixIn.__init__(self) @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.addParameter( 'h_smooth', dtype='float64', direction=function.IN, default=0.01, ) function.result_type = 'int32' return function @legacy_function def new_sink_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.addParameter( 'radius', dtype='float64', direction=function.IN, default=0.01, # default should be h_acc ) function.addParameter( 'h_smooth', dtype='float64', direction=function.IN, default=0.01, # default should be h_smooth_sinksink? ) function.result_type = 'int32' return function @legacy_function def get_state_dm(): """ Retrieve the current state of a DM particle. The mass, position and velocity are 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.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_state_sink(): """ Retrieve the current state of a sink particle. The mass, position and velocity are 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 accretion radius of the particle") function.addParameter( 'h_smooth', dtype='float64', direction=function.OUT, description="The smoothing length 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 def get_state(self, index_of_the_particle): return self.get_state_dm(index_of_the_particle) @legacy_function def get_state_sph(): """ Retrieve the current state of an SPH particle. The mass, position, velocity, internal energy and smoothing length are 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( 'u', dtype='float64', direction=function.OUT, description="The current internal energy of the particle") function.addParameter( 'h_smooth', dtype='float64', direction=function.OUT, description="The current smoothing length 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_sph(): """ Update the current state of an SPH particle. The mass, position, velocity, internal energy and smoothing length are 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( 'u', dtype='float64', direction=function.IN, description="The new internal energy of the particle") function.addParameter( 'h_smooth', dtype='float64', direction=function.IN, description="The new smoothing length of the particle") 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 def set_state( self, index_of_the_particle, mass, x, y, z, vx, vy, vz, ): return self.set_state_dm( index_of_the_particle, mass, x, y, z, vx, vy, vz) @legacy_function def set_state_dm(): """ Update the current state of a DM particle. The mass, position and velocity are 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 softening length of the particle") 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 set_state_sink(): """ Update the current state of a sink particle. The mass, position and velocity are 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 accretion radius of the particle") function.addParameter( 'h_smooth', dtype='float64', direction=function.IN, description="The smoothing length of the particle") 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 set_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'u', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_h2ratio(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'h2ratio', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_hi_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'hi_abundance', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_proton_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'proton_abundance', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_electron_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'electron_abundance', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_co_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'co_abundance', dtype='float64', direction=function.IN, description='', ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_smoothing_length(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'h_smooth', dtype='float64', direction=function.IN, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='' ) function.addParameter( 'density', dtype='float64', direction=function.OUT, description="The current density of the particle" ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_pressure(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'pressure', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_h2ratio(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'h2ratio', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_hi_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'hi_abundance', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_proton_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'proton_abundance', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_electron_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'electron_abundance', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_co_abundance(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='', ) function.addParameter( 'co_abundance', dtype='float64', direction=function.OUT, description='' ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='' ) function.addParameter( 'u', dtype='float64', direction=function.OUT, description="The current internal energy of the particle", ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_smoothing_length(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter( 'index_of_the_particle', dtype='int32', direction=function.IN, description='' ) function.addParameter( 'h_smooth', dtype='float64', direction=function.OUT, description="The current smoothing length of the particle" ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_time_step(): function = LegacyFunctionSpecification() function.addParameter( 'time_step', dtype='float64', direction=function.OUT, unit=generic_unit_system.time, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_time_step(): function = LegacyFunctionSpecification() function.addParameter( 'time_step', dtype='float64', direction=function.IN, unit=generic_unit_system.time, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_c_courant(): function = LegacyFunctionSpecification() function.addParameter( 'c_courant', dtype='float64', direction=function.OUT, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_c_courant(): function = LegacyFunctionSpecification() function.addParameter( 'c_courant', dtype='float64', direction=function.IN, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_c_force(): function = LegacyFunctionSpecification() function.addParameter( 'C_force', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_c_force(): function = LegacyFunctionSpecification() function.addParameter( 'C_force', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_c_cool(): function = LegacyFunctionSpecification() function.addParameter( 'C_cool', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_c_cool(): function = LegacyFunctionSpecification() function.addParameter( 'C_cool', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_tolv(): function = LegacyFunctionSpecification() function.addParameter( 'tolv', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_tolv(): function = LegacyFunctionSpecification() function.addParameter( 'tolv', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_hfact(): function = LegacyFunctionSpecification() function.addParameter( 'hfact', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_hfact(): function = LegacyFunctionSpecification() function.addParameter( 'hfact', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_tolh(): function = LegacyFunctionSpecification() function.addParameter( 'tolh', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_tolh(): function = LegacyFunctionSpecification() function.addParameter( 'tolh', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_tree_accuracy(): function = LegacyFunctionSpecification() function.addParameter( 'tree_accuracy', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_tree_accuracy(): function = LegacyFunctionSpecification() function.addParameter( 'tree_accuracy', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_alpha(): function = LegacyFunctionSpecification() function.addParameter( 'alpha', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_alpha(): function = LegacyFunctionSpecification() function.addParameter( 'alpha', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_alphamax(): function = LegacyFunctionSpecification() function.addParameter( 'alphamax', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_alphamax(): function = LegacyFunctionSpecification() function.addParameter( 'alphamax', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_beta(): function = LegacyFunctionSpecification() function.addParameter( 'beta', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_beta(): function = LegacyFunctionSpecification() function.addParameter( 'beta', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_avdecayconst(): function = LegacyFunctionSpecification() function.addParameter( 'avdecayconst', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_avdecayconst(): function = LegacyFunctionSpecification() function.addParameter( 'avdecayconst', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_idamp(): function = LegacyFunctionSpecification() function.addParameter( 'idamp', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_idamp(): function = LegacyFunctionSpecification() function.addParameter( 'idamp', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_ieos(): function = LegacyFunctionSpecification() function.addParameter( 'ieos', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_ieos(): function = LegacyFunctionSpecification() function.addParameter( 'ieos', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_icooling(): function = LegacyFunctionSpecification() function.addParameter( 'icooling', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_icooling(): function = LegacyFunctionSpecification() function.addParameter( 'icooling', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_polyk(): function = LegacyFunctionSpecification() function.addParameter( 'polyk', dtype='float64', direction=function.OUT, unit=(generic_unit_system.speed**2) ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_polyk(): function = LegacyFunctionSpecification() function.addParameter( 'polyk', dtype='float64', direction=function.IN, unit=(generic_unit_system.speed**2) ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_gamma(): function = LegacyFunctionSpecification() function.addParameter( 'gamma', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_gamma(): function = LegacyFunctionSpecification() function.addParameter( 'gamma', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_mu(): function = LegacyFunctionSpecification() function.addParameter( 'mu', dtype='float64', direction=function.OUT, unit=units.amu ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_mu(): function = LegacyFunctionSpecification() function.addParameter( 'mu', dtype='float64', direction=function.IN, unit=units.amu ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_rhofinal(): function = LegacyFunctionSpecification() function.addParameter( 'rhofinal', dtype='float64', direction=function.OUT, unit=(generic_unit_system.density), ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_rhofinal(): function = LegacyFunctionSpecification() function.addParameter( 'rhofinal', dtype='float64', direction=function.IN, unit=(generic_unit_system.density), ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_rho_crit(): function = LegacyFunctionSpecification() function.addParameter( 'rho_crit', dtype='float64', direction=function.OUT, unit=(generic_unit_system.density), ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_rho_crit(): function = LegacyFunctionSpecification() function.addParameter( 'rho_crit', dtype='float64', direction=function.IN, unit=(generic_unit_system.density), ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_r_crit(): function = LegacyFunctionSpecification() function.addParameter( 'r_crit', dtype='float64', direction=function.OUT, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_r_crit(): function = LegacyFunctionSpecification() function.addParameter( 'r_crit', dtype='float64', direction=function.IN, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_h_acc(): function = LegacyFunctionSpecification() function.addParameter( 'h_acc', dtype='float64', direction=function.OUT, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_h_acc(): function = LegacyFunctionSpecification() function.addParameter( 'h_acc', dtype='float64', direction=function.IN, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_h_soft_sinkgas(): function = LegacyFunctionSpecification() function.addParameter( 'h_soft_sinkgas', dtype='float64', direction=function.OUT, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_h_soft_sinkgas(): function = LegacyFunctionSpecification() function.addParameter( 'h_soft_sinkgas', dtype='float64', direction=function.IN, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_h_soft_sinksink(): function = LegacyFunctionSpecification() function.addParameter( 'h_soft_sinksink', dtype='float64', direction=function.OUT, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_h_soft_sinksink(): function = LegacyFunctionSpecification() function.addParameter( 'h_soft_sinksink', dtype='float64', direction=function.IN, unit=generic_unit_system.length, ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_f_acc(): function = LegacyFunctionSpecification() function.addParameter( 'f_acc', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_f_acc(): function = LegacyFunctionSpecification() function.addParameter( 'f_acc', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_iexternalforce(): function = LegacyFunctionSpecification() function.addParameter( 'iexternalforce', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_iexternalforce(): function = LegacyFunctionSpecification() function.addParameter( 'iexternalforce', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_irealvisc(): function = LegacyFunctionSpecification() function.addParameter( 'irealvisc', dtype='int32', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_irealvisc(): function = LegacyFunctionSpecification() function.addParameter( 'irealvisc', dtype='int32', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_shearparam(): function = LegacyFunctionSpecification() function.addParameter( 'shearparam', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_shearparam(): function = LegacyFunctionSpecification() function.addParameter( 'shearparam', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_bulkvisc(): function = LegacyFunctionSpecification() function.addParameter( 'bulkvisc', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_bulkvisc(): function = LegacyFunctionSpecification() function.addParameter( 'bulkvisc', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_unit_length(): function = LegacyFunctionSpecification() function.addParameter( 'unit_length', dtype='float64', direction=function.OUT, unit=units.cm # generic_unit_system.length ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_unit_length(): function = LegacyFunctionSpecification() function.addParameter( 'unit_length', dtype='float64', direction=function.IN, unit=units.cm # generic_unit_system.length ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_unit_mass(): function = LegacyFunctionSpecification() function.addParameter( 'unit_mass', dtype='float64', direction=function.OUT, unit=units.g # generic_unit_system.mass ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_unit_mass(): function = LegacyFunctionSpecification() function.addParameter( 'unit_mass', dtype='float64', direction=function.IN, unit=units.g # generic_unit_system.mass ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def get_unit_time(): function = LegacyFunctionSpecification() function.addParameter( 'unit_time', dtype='float64', direction=function.OUT, unit=units.s # generic_unit_system.time ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function @legacy_function def set_unit_time(): function = LegacyFunctionSpecification() function.addParameter( 'unit_time', dtype='float64', direction=function.IN, unit=units.s # generic_unit_system.time ) function.result_type = 'int32' function.result_doc = """ 0 - OK -1 - ERROR """ return function class Phantom(GravitationalDynamics, GravityFieldCode): __interface__ = PhantomInterface def __init__( self, convert_nbody=None, **options): # if convert_nbody is None: # NOTE we use a fixed converter here internally! # Not doing this *really* complicates things as we'd need to change the # internal units used in Phantom as well. phantom_solarm = 1.9891e33 | units.g phantom_pc = 3.086e18 | units.cm phantom_gg = 6.672041e-8 | units.cm**3 * units.g**-1 * units.s**-2 # phantom_mass = 1.0 | units.MSun # phantom_mass = 1.98892e33 | units.g # phantom_time = 60 * 60 * 24 * 365.25 * 1e6 | units.s # phantom_length = (phantom_time**2 * phantom_gg * phantom_mass)**(1/3) phantom_mass = 1.0 * phantom_solarm phantom_length = 0.1 * phantom_pc phantom_time = (phantom_length**3 / (phantom_gg*phantom_mass))**0.5 unit_converter = ConvertBetweenGenericAndSiUnits( # Phantom uses CGS units internally, scaled with G=1 # So we need to make sure we use those same units here... # Also, Phantom's value for G is not the same as AMUSE's... phantom_length, phantom_mass, # 1.0 MSun phantom_time, # 1 Julian Myr ) convert_nbody = unit_converter self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, PhantomInterface(**options), convert_nbody, **options ) def initialize_code(self): result = self.overridden().initialize_code() if self.unit_converter is not None: mass = self.unit_converter.to_si(generic_unit_system.mass) time = self.unit_converter.to_si(generic_unit_system.time) # self.parameters._original.unit_mass = mass # self.parameters._original.unit_time = time # 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 define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) # self.stopping_conditions.define_state(handler) handler.add_transition('END', 'INITIALIZED', 'initialize_code', False) handler.add_method('END', 'initialize_code') handler.add_transition('RUN', 'UPDATE', 'new_sph_particle', False) handler.add_method('EDIT', 'new_sph_particle') handler.add_method('UPDATE', 'new_sph_particle') handler.add_transition('RUN', 'UPDATE', 'new_dm_particle', False) handler.add_method('EDIT', 'new_dm_particle') handler.add_method('UPDATE', 'new_dm_particle') handler.add_transition('RUN', 'UPDATE', 'new_sink_particle', False) handler.add_method('EDIT', 'new_sink_particle') handler.add_method('UPDATE', 'new_sink_particle') self.stopping_conditions.define_state(handler) def define_parameters(self, handler): handler.add_method_parameter( "get_time_step", "set_time_step", "time_step", "Maximum internal time step", default_value=0.01 | generic_unit_system.time ) handler.add_method_parameter( "get_c_courant", "set_c_courant", "c_courant", "Courant number", default_value=0.3 ) handler.add_method_parameter( "get_c_force", "set_c_force", "c_force", "dt_force number", default_value=0.25 ) handler.add_method_parameter( "get_c_cool", "set_c_cool", "c_cool", "dt_cool number", default_value=0.25 ) handler.add_method_parameter( "get_tolv", "set_tolv", "tolv", "tolerance on v iterations in timestepping", default_value=1.0e-2 ) handler.add_method_parameter( "get_hfact", "set_hfact", "hfact", "h in units of particle spacing [h = hfact(m/rho)^(1/3)]", default_value=1.2 ) handler.add_method_parameter( "get_tolh", "set_tolh", "tolh", "tolerance on h-rho iterations", default_value=1.0e-4 ) handler.add_method_parameter( "get_tree_accuracy", "set_tree_accuracy", "tree_accuracy", "tree opening criterion (0.0-1.0)", default_value=0.5 ) handler.add_method_parameter( "get_alpha", "set_alpha", "alpha", "MINIMUM art. viscosity parameter", default_value=0. ) handler.add_method_parameter( "get_alphamax", "set_alphamax", "alphamax", "MAXIMUM art. viscosity parameter", default_value=1.0 ) handler.add_method_parameter( "get_beta", "set_beta", "beta", "beta viscosity", default_value=2.0 ) handler.add_method_parameter( "get_avdecayconst", "set_avdecayconst", "avdecayconst", "decay time constant for viscosity switches", default_value=0.1 ) handler.add_method_parameter( "get_idamp", "set_idamp", "idamp", "artificial damping of velocities (0=off, 1=constant, 2=star)", default_value=0 ) handler.add_method_parameter( "get_polyk", "set_polyk", "polyk", "polyk value", default_value=(0. | units.km**2 * units.s**-2) ) handler.add_method_parameter( "get_ieos", "set_ieos", "ieos", "eqn of state (1=isoth;2=adiab;3=locally iso;8=barotropic)", default_value=1 ) handler.add_method_parameter( "get_icooling", "set_icooling", "icooling", "Cooling (0=off 1=default 2/3 = other)", default_value=0 ) handler.add_method_parameter( "get_gamma", "set_gamma", "gamma", "gamma value ", default_value=1 ) handler.add_method_parameter( "get_mu", "set_mu", "mu", "mean molecular weight", default_value=(2.381 | units.amu) ) handler.add_method_parameter( "get_rhofinal", "set_rhofinal", "rhofinal", "maximum allowed density (<=0 to ignore)", default_value=(0 | generic_unit_system.density) ) handler.add_method_parameter( "get_rho_crit", "set_rho_crit", "rho_crit", "density above which sink particles are created", default_value=(1e-10 | units.g * units.cm**-3) ) handler.add_method_parameter( "get_r_crit", "set_r_crit", "r_crit", "critical radius for point mass creation" " (no new sinks < r_crit from existing sink)", default_value=(0.005 | generic_unit_system.length) ) handler.add_method_parameter( "get_h_acc", "set_h_acc", "h_acc", "accretion radius for new sink particles", default_value=(0.001 | generic_unit_system.length) ) handler.add_method_parameter( "get_h_soft_sinkgas", "set_h_soft_sinkgas", "h_soft_sinkgas", "softening length for new sink particles", default_value=(0. | generic_unit_system.length) ) handler.add_method_parameter( "get_h_soft_sinksink", "set_h_soft_sinksink", "h_soft_sinksink", "softening length between sink particles", default_value=(0. | generic_unit_system.length) ) handler.add_method_parameter( "get_f_acc", "set_f_acc", "f_acc", "particles < f_acc*h_acc accreted without checks", default_value=0.8 ) handler.add_method_parameter( "get_iexternalforce", "set_iexternalforce", "iexternalforce", "1=star,2=coro,3=bina,4=prdr,5=toru,6=toys,7=exte," "8=spir,9=Lens,10=neut,11=Eins", default_value=0 ) handler.add_method_parameter( "get_irealvisc", "set_irealvisc", "irealvisc", "physical viscosity type (0=none,1=const,2=Shakura/Sunyaev)", default_value=0 ) handler.add_method_parameter( "get_shearparam", "set_shearparam", "shearparam", "magnitude of shear viscosity (irealvisc=1) or alpha_SS" " (irealvisc=2)", default_value=0.1 ) handler.add_method_parameter( "get_bulkvisc", "set_bulkvisc", "bulkvisc", "magnitude of bulk viscosity", default_value=0.0 ) handler.add_method_parameter( "get_unit_length", "set_unit_length", "code_unit_length", "code unit length", default_value=( ((60 * 60 * 24 * 365.25 * 1e6) | units.s)**2 * (6.672041e-8 | units.cm**3 * units.g**-1 * units.s**-2) * (1.98892e33 | units.g) )**(1/3) ) handler.add_method_parameter( "get_unit_mass", "set_unit_mass", "code_unit_mass", "code unit mass", default_value=1.98892e33 | units.g ) handler.add_method_parameter( "get_unit_time", "set_unit_time", "code_unit_time", "code unit time", default_value=3.15576e13 | units.s ) self.stopping_conditions.define_parameters(handler) def define_particle_sets(self, handler): handler.define_super_set( 'particles', ['dm_particles', 'gas_particles', 'sink_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_getter('dm_particles', 'get_state_dm') handler.add_setter('dm_particles', 'set_state_dm') handler.add_getter('dm_particles', 'get_mass') handler.add_setter('dm_particles', 'set_mass') handler.add_getter('dm_particles', 'get_position') handler.add_setter('dm_particles', 'set_position') handler.add_getter('dm_particles', 'get_velocity') handler.add_setter('dm_particles', 'set_velocity') handler.add_getter('dm_particles', 'get_acceleration') handler.define_set('gas_particles', 'index_of_the_particle') handler.set_new('gas_particles', 'new_sph_particle') handler.set_delete('gas_particles', 'delete_particle') handler.add_getter('gas_particles', 'get_state_sph') handler.add_setter('gas_particles', 'set_state_sph') handler.add_getter('gas_particles', 'get_mass') handler.add_setter('gas_particles', 'set_mass') handler.add_getter('gas_particles', 'get_position') handler.add_setter('gas_particles', 'set_position') handler.add_getter('gas_particles', 'get_velocity') handler.add_setter('gas_particles', 'set_velocity') handler.add_getter('gas_particles', 'get_acceleration') handler.add_getter('gas_particles', 'get_internal_energy') handler.add_setter('gas_particles', 'set_internal_energy') handler.add_getter('gas_particles', 'get_smoothing_length') handler.add_setter('gas_particles', 'set_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_h2ratio') handler.add_getter('gas_particles', 'get_hi_abundance') handler.add_getter('gas_particles', 'get_proton_abundance') handler.add_getter('gas_particles', 'get_electron_abundance') handler.add_getter('gas_particles', 'get_co_abundance') handler.add_setter('gas_particles', 'set_h2ratio') handler.add_setter('gas_particles', 'set_hi_abundance') handler.add_setter('gas_particles', 'set_proton_abundance') handler.add_setter('gas_particles', 'set_electron_abundance') handler.add_setter('gas_particles', 'set_co_abundance') handler.define_set('sink_particles', 'index_of_the_particle') handler.set_new('sink_particles', 'new_sink_particle') handler.set_delete('sink_particles', 'delete_particle') handler.add_getter('sink_particles', 'get_state_sink') handler.add_setter('sink_particles', 'set_state_sink') handler.add_getter('sink_particles', 'get_mass') handler.add_setter('sink_particles', 'set_mass') handler.add_getter('sink_particles', 'get_position') handler.add_setter('sink_particles', 'set_position') handler.add_getter('sink_particles', 'get_velocity') handler.add_setter('sink_particles', 'set_velocity') handler.add_getter('sink_particles', 'get_acceleration') handler.add_getter('sink_particles', 'get_radius') handler.add_setter('sink_particles', 'set_radius') handler.add_getter('sink_particles', 'get_smoothing_length') handler.add_setter('sink_particles', 'set_smoothing_length') self.stopping_conditions.define_particle_set(handler, 'particles') def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) 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, generic_unit_system.length, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "new_sink_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.length, generic_unit_system.length, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "get_state_dm", ( 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, handler.ERROR_CODE, ) ) handler.add_method( "set_state_dm", ( 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.length, ), ( 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, generic_unit_system.length, 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, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_state_sink", ( 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.length, generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( "set_state_sink", ( 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.length, 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_smoothing_length", ( handler.INDEX, ), ( generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( "set_smoothing_length", ( handler.INDEX, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_pressure", ( handler.INDEX, ), ( generic_unit_system.pressure, handler.ERROR_CODE, ) ) handler.add_method( "get_h2ratio", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_hi_abundance", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_proton_abundance", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_electron_abundance", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_co_abundance", ( handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( "get_internal_energy", ( handler.INDEX, ), ( 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( "set_h2ratio", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_hi_abundance", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_proton_abundance", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_electron_abundance", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_co_abundance", ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_time_step", ( ), ( generic_unit_system.time, handler.ERROR_CODE, ) ) handler.add_method( "set_time_step", ( generic_unit_system.time, ), ( handler.ERROR_CODE, ) ) self.stopping_conditions.define_methods(handler)
72,402
30.479565
104
py
amuse
amuse-main/src/amuse/community/adaptb/functions.py
def read_log(filename): infile = open(filename, "r") # open file data = [] # declare data container while True: # while data to read line = infile.readline() # read data if not line: break line = line.split() # distinguish columns data.append(line) # put data in container infile.close() # close file data = list(zip(*data)) # inverse rows and columns return data[2] # return data def read_out(filename): infile = open(filename, "r") # open file data = [] # declare data container while True: # while data to read line = infile.readline() # read data if not line: break line = line.split() # distinguish columns data.append(line) # put data in container infile.close() # close file data_line = data[4001] x0 = float(data_line[1]) vx0 = float(data_line[4]) return [x0, vx0] # return data def read_xy(filename): infile = open(filename, "r") # open file data1 = [] # declare data container data2 = [] data3 = [] numLine = 0 p1line = 1 p2line = 2 p3line = 3 dp = 4 while True: # while data to read line = infile.readline() # read data if not line: break line = line.split() # distinguish columns if numLine == p1line: data1.append(line) # put data in container p1line += dp elif numLine == p2line: data2.append(line) p2line += dp elif numLine == p3line: data3.append(line) p3line += dp numLine += 1 infile.close() # close file data1 = list(zip(*data1)) data2 = list(zip(*data2)) data3 = list(zip(*data3)) x1 = data1[1] y1 = data1[2] x2 = data2[1] y2 = data2[2] x3 = data3[1] y3 = data3[2] x1 = [float(k) for k in x1] y1 = [float(k) for k in y1] x2 = [float(k) for k in x2] y2 = [float(k) for k in y2] x3 = [float(k) for k in x3] y3 = [float(k) for k in y3] return x1, y1, x2, y2, x3, y3 # return data
1,964
22.674699
54
py
amuse
amuse-main/src/amuse/community/adaptb/__init__.py
from .interface import Adaptb
30
14.5
29
py
amuse
amuse-main/src/amuse/community/adaptb/interface.py
import warnings from amuse.community import * from amuse.community.interface.gd import GravitationalDynamicsInterface, GravitationalDynamics class AdaptbInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, CodeWithDataDirectories): """ Adaptb (Accurate Dynamics with Arbitrary Precision by Tjarda Boekholt) """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="adaptb_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) warnings.warn("Adaptb is superseded by Brutus") @legacy_function def get_adaptb_output_directory(): function = LegacyFunctionSpecification() function.addParameter('adaptb_output_directory', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_adaptb_output_directory(): function = LegacyFunctionSpecification() function.addParameter('adaptb_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 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('bs_tolerance', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bs_tolerance_string(): function = LegacyFunctionSpecification() function.addParameter('bs_tolerance', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bs_tolerance_float64(): function = LegacyFunctionSpecification() function.addParameter('bs_tolerance', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bs_tolerance_float64(): function = LegacyFunctionSpecification() function.addParameter('bs_tolerance', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_word_length(): function = LegacyFunctionSpecification() function.addParameter('word_length', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_word_length(): function = LegacyFunctionSpecification() function.addParameter('word_length', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dt_print(): function = LegacyFunctionSpecification() function.addParameter('dt_print', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dt_print(): function = LegacyFunctionSpecification() function.addParameter('dt_print', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_max_cpu_time(): function = LegacyFunctionSpecification() function.addParameter('max_cpu_time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_max_cpu_time(): function = LegacyFunctionSpecification() function.addParameter('max_cpu_time', dtype='float64', direction=function.IN) function.result_type = 'int32' return function class Adaptb(GravitationalDynamics): def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = AdaptbInterface(**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.adaptb_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_bs_tolerance_float64", "set_bs_tolerance_float64", "bs_tolerance", "Error tolerance of the Bulirsch-Stoer integrator", default_value = 1.0e-6 ) handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations, usage is not recommended for Adaptb", default_value = 0.0 | nbody_system.length**2 ) handler.add_method_parameter( "get_dt_print", "set_dt_print", "dt_print", "dt_print, regular print interval to show status (% complete) of evolve_model", default_value = 0.1 | nbody_system.time ) handler.add_method_parameter( "get_word_length", "set_word_length", "word_length", "The word length, or number of bits, used for the arbitrary precision calculations", default_value = 64 ) handler.add_method_parameter( "get_adaptb_output_directory", "set_adaptb_output_directory", "adaptb_output_directory", "Path to the directory where Adaptb stores its output", default_value = "./" ) handler.add_method_parameter( "get_max_cpu_time", "set_max_cpu_time", "time_limit_cpu", "The cpu-time limit, the maximum amount of time Adaptb is allowed to run for.", default_value = 3600.0 | units.s ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) self.stopping_conditions.define_methods(handler) handler.add_method("get_bs_tolerance_float64", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_bs_tolerance_float64", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) 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_dt_print", (), (nbody_system.time, handler.ERROR_CODE,)) handler.add_method("set_dt_print", (nbody_system.time, ), (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_adaptb_output_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_adaptb_output_directory", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_max_cpu_time", (), (units.s, handler.ERROR_CODE,)) handler.add_method("set_max_cpu_time", (units.s, ), (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)
10,898
44.4125
136
py
amuse
amuse-main/src/amuse/community/mpiamrvac/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/mpiamrvac/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/mpiamrvac-r{version}.tgz" filename_template = "mpiamrvac-r{version}.tgz" 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()) ) 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='187', 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,048
25.960526
83
py
amuse
amuse-main/src/amuse/community/mpiamrvac/__init__.py
# generated file from .interface import Mpiamrvac
50
16
32
py
amuse
amuse-main/src/amuse/community/mpiamrvac/interface.py
from amuse.community import * from amuse.community.interface.hydro import HydrodynamicsInterface from amuse.support.options import OptionalAttributes, option from amuse.units import generic_unit_system from amuse.community.interface.common import CommonCode import os class MpiAmrVacInterface(CodeInterface, HydrodynamicsInterface, StoppingConditionInterface, CodeWithDataDirectories): use_modules = ['mpiamrvac_interface', 'StoppingConditions'] MODE_NORMAL = 'normal' MODE_3D = '3d' MODE_3D_ACC = '3d-acc' MODE_2D = '2d' MODE_2D_ACC = '2d-acc' MODE_1D = '1d' MODE_1D_ACC = '1d-acc' def __init__(self, mode = MODE_NORMAL, **options): CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **options) CodeWithDataDirectories.__init__(self) self._mode = mode def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL or mode == self.MODE_3D: return 'mpiamrvac_worker' elif mode == self.MODE_3D_ACC: return 'mpiamrvac_worker_acc' elif mode == self.MODE_2D: return 'mpiamrvac_worker_2d' elif mode == self.MODE_2D_ACC: return 'mpiamrvac_worker_2dacc' elif mode == self.MODE_1D: return 'mpiamrvac_worker_1d' elif mode == self.MODE_1D_ACC: return 'mpiamrvac_worker_1dacc' else: return 'mpiamrvac_worker' # # options # @option(type="string") def default_parameters_filename(self): """ Default parameter file for amrvac, has empty lists for all parameters. """ if self._mode == self.MODE_2D: return os.path.join(self.data_directory, 'amrvac_2d.par') elif self._mode == self.MODE_2D_ACC: return os.path.join(self.data_directory, 'amrvac_2d-acc.par') elif self._mode == self.MODE_1D: return os.path.join(self.data_directory, 'amrvac_1d.par') elif self._mode == self.MODE_1D_ACC: return os.path.join(self.data_directory, 'amrvac_1d-acc.par') elif self._mode == self.MODE_3D_ACC: return os.path.join(self.data_directory, 'amrvac-acc.par') else: return os.path.join(self.data_directory, 'amrvac.par') # # parameters # @legacy_function def set_typeentropy(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeentropy(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typefull1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typefull1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typepred1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typepred1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' 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 set_dt(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dt(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nbufferx1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nbufferx1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nbufferx2(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nbufferx2(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nbufferx3(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nbufferx3(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_mxnest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_mxnest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dixb(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dixb(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_levmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_levmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_levmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_levmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_skipfinestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_skipfinestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_time_advance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_time_advance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_courantpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_courantpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtdiffpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtdiffpar(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_t(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_t(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_residmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_residmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_residmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_residmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_residual(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_residual(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tfixgrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tfixgrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tvdlfeps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tvdlfeps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_mcbeta(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_mcbeta(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_divbdiff(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_divbdiff(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_smallp(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_smallp(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_smallrho(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_smallrho(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dmaxvel(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dmaxvel(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tolernr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tolernr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_absaccnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_absaccnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_cfrac(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_cfrac(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_x1ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_x1ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_x2ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_x2ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_x3ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_x3ptms(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ptmass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ptmass(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ratebdflux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ratebdflux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_normt(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_normt(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_time_bc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_time_bc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_it(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_it(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_itmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_itmax(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_itmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_itmin(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_slowsteps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_slowsteps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typepario(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typepario(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_itfixgrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_itfixgrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nwauxio(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nwauxio(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_istep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_istep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nstep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nstep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_errorestimate(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_errorestimate(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nxdiffusehllc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nxdiffusehllc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typespherical(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typespherical(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_maxitnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_maxitnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nflatgetaux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nflatgetaux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_level_io(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_level_io(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ncool(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ncool(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_cmulti(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_cmulti(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_snapshotini(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_snapshotini(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ixtest1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ixtest1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ixtest2(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ixtest2(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ixtest3(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ixtest3(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_iwtest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_iwtest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_idimtest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_idimtest(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_saveigrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_saveigrid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typecourant(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typecourant(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeresid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeresid(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeadvance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeadvance(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typelimited(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typelimited(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typesourcesplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typesourcesplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typelimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typelimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typegradlimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typegradlimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeprolonglimit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeprolonglimit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typetvd(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typetvd(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typetvdlf(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typetvdlf(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeaverage(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeaverage(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typedimsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typedimsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeaxial(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeaxial(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typepoly(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typepoly(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typedivbdiff(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typedivbdiff(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typedivbfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typedivbfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typediv(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typediv(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typegrad(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typegrad(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeglm(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeglm(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_coolcurve(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_coolcurve(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_coolmethod(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_coolmethod(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typeghostfill(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typeghostfill(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typegridfill(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typegridfill(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_filenameout(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_filenameout(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_filenameini(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_filenameini(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_filenamelog(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_filenamelog(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_fileheadout(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_fileheadout(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_wnames(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_wnames(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_primnames(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_primnames(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_typefilelog(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_typefilelog(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_convert_type(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_convert_type(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dxfiletype(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dxfiletype(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_teststr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_teststr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='string', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_time_accurate(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_time_accurate(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_addmpibarrier(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_addmpibarrier(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tmaxexact(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tmaxexact(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_treset(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_treset(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_itreset(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_itreset(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_firstprocess(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_firstprocess(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_fixprocess(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_fixprocess(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_flathllc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_flathllc(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_flatcd(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_flatcd(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_flatsh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_flatsh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_flatppm(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_flatppm(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_sourcesplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_sourcesplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_sourceunsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_sourceunsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_useprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_useprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dimsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dimsplit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_restrictprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_restrictprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_prolongprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_prolongprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_coarsenprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_coarsenprimitive(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_useprimitiverel(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_useprimitiverel(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_amrentropy(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_amrentropy(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_divbfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_divbfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_divbwave(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_divbwave(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_compactres(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_compactres(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bnormlf(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bnormlf(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_strictnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_strictnr(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_strictsmall(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_strictsmall(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_strictzero(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_strictzero(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_strictgetaux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_strictgetaux(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_usecovariant(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_usecovariant(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nocartesian(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nocartesian(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tfix(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_convert(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_convert(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_saveprim(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_saveprim(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_uselimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_uselimiter(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function # parameters file @legacy_function def set_parameters_filename(): """ Update name of the parameters file """ function = LegacyFunctionSpecification() function.addParameter('path', dtype='string', direction=function.IN, description = "filename of the parameters file" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR File does not exist """ return function @legacy_function def get_parameters_filename(): """ Retrieve name of the parameters file """ function = LegacyFunctionSpecification() function.addParameter('path', dtype='string', direction=function.OUT, description = "filename of the parameters file" ) function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR File does not exist """ 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' function.result_doc = """ 0 - OK Current value was set -1 - ERROR File does not exist """ return function # # @legacy_function def initialize_grid(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def refine_grid(): function = LegacyFunctionSpecification() function.addParameter('must_advance', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_mesh_size(): function = LegacyFunctionSpecification() function.can_handle_array = True 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.addParameter('index_of_grid', dtype='i', direction=function.IN) 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) 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('n', dtype='i', direction=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('n', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_level_of_grid(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('level', dtype='i', direction=function.OUT) function.addParameter('index_of_grid', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_cell_size_of_grid(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('dx', dtype='d', direction=function.OUT) function.addParameter('dy', dtype='d', direction=function.OUT) function.addParameter('dz', dtype='d', direction=function.OUT) function.addParameter('index_of_grid', dtype='i', direction=function.IN) function.result_type = 'i' return function @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 set_boundary_in_code(): 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 def set_boundary(self, xbound1, xbound2, ybound1, ybound2, zbound1, zbound2): map_from_amuse_to_mpiamrvac= { "reflective": "symm", "outflow":"limitinflow", "periodic":"periodic", "interface": "special", } return self.set_boundary_in_code( map_from_amuse_to_mpiamrvac.setdefault(xbound1, xbound1), map_from_amuse_to_mpiamrvac.setdefault(xbound2, xbound2), map_from_amuse_to_mpiamrvac.setdefault(ybound1, ybound1), map_from_amuse_to_mpiamrvac.setdefault(ybound2, ybound2), map_from_amuse_to_mpiamrvac.setdefault(zbound1, zbound1), map_from_amuse_to_mpiamrvac.setdefault(zbound2, zbound2) ) # # # @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_acceleration_grid_position_of_index(): 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('n', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_acceleration_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 ['a1','a2', 'a3']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('n', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def set_acceleration_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 ['a1','a2', 'a3']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('n', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_acceleration_grid_size(): function = LegacyFunctionSpecification() function.can_handle_array = True 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 @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 ['ax','ay','az']: 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 ['ax','ay','az']: 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_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 MpiAmrVac(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter self.stopping_conditions = StoppingConditions(self) CommonCode.__init__(self, MpiAmrVacInterface(**options), **options) self.set_parameters_filename(self.default_parameters_filename) 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 get_index_range_inclusive(self, index_of_grid = 1): nx, ny, nz = self.get_mesh_size(index_of_grid) return (0, nx-1, 0, ny-1, 0, nz-1) def define_properties(self, handler): handler.add_property('get_time', public_name = "model_time") def define_methods(self, handler): handler.add_method( 'evolve_model', (generic_unit_system.time,), (handler.ERROR_CODE,) ) handler.add_method( 'commit_parameters', (), (handler.ERROR_CODE,) ) handler.add_method( 'get_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.ERROR_CODE,) ) handler.add_method( 'get_acceleration_grid_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX), (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.ERROR_CODE,) ) density = generic_unit_system.density momentum = generic_unit_system.momentum_density energy = generic_unit_system.energy_density acceleration = generic_unit_system.length / generic_unit_system.time ** 2 handler.add_method( 'get_acceleration_grid_size', (), (handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'get_acceleration_grid_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX), (acceleration, acceleration, acceleration, handler.ERROR_CODE,) ) handler.add_method( 'set_acceleration_grid_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX, acceleration, acceleration, acceleration,), (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( 'set_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, density, handler.INDEX), (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_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), ( energy, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, 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( 'refine_grid', (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'get_level_of_grid', (handler.INDEX), (handler.NO_UNIT, 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_typeentropy", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_typeentropy", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_typefull1", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_typefull1", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_typepred1", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_typepred1", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_typeadvance", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_typeadvance", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_courantpar", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_courantpar", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_mxnest", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mxnest", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (generic_unit_system.time, handler.ERROR_CODE,) ) handler.add_method( 'setup_mesh', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length, generic_unit_system.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_grid_acceleration', (handler.INDEX, handler.INDEX, handler.INDEX, acceleration, acceleration, acceleration, handler.INDEX), (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( '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_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_method_parameter( "get_typeentropy", "set_typeentropy", "entropy_type", "type of the entropy", default_value = 'nul' ) handler.add_method_parameter( "get_typefull1", "set_typefull1", "spatial_discretization_method", "the spatial discretization method used for the time integration per activated grid leve", default_value = 'tvdmu' ) handler.add_method_parameter( "get_typepred1", "set_typepred1", "predictor_step_discretization_method", "the precitor step discretization method (only used when integration procedure is twostep')", default_value = 'tvdmu' ) handler.add_method_parameter( "get_typeadvance", "set_typeadvance", "time_integration_procedure", "time integration procedure", default_value = 'twostep' ) handler.add_method_parameter( "get_courantpar", "set_courantpar", "courant_number", "CFL number", default_value = 0.7 ) 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 | generic_unit_system.length, ) handler.add_caching_parameter( "setup_mesh", "ylength", "length_y", "length of model in the x direction", 10 | generic_unit_system.length, ) handler.add_caching_parameter( "setup_mesh", "zlength", "length_z", "length of model in the z direction", 10 | generic_unit_system.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_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_method_parameter( "get_mxnest", "set_mxnest", "maximum_number_of_grid_levels", "the maximum number of grid levels that can be used during the simulation, including the base grid level", default_value = 3 ) handler.add_method_parameter( "get_time_accurate", "set_time_accurate", "time_accurate", "if false will evolve to the given time, if true will take accurate steps using courant timesteps", default_value = 3 ) handler.add_method_parameter( "get_dtpar", "set_dtpar", "timestep", "if greater than zero will fix the timestep to the given value", default_value = 3 ) self.stopping_conditions.define_parameters(handler) def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def get_acceleration_grid_index_range_inclusive(self): nx, ny, nz = self.get_acceleration_grid_size() return (1, nx, 1, ny, 1, nz) def define_particle_sets(self, handler): handler.define_grid('acceleration_grid') handler.set_grid_range('acceleration_grid', 'get_acceleration_grid_index_range_inclusive') handler.add_getter('acceleration_grid', 'get_acceleration_grid_position_of_index', names=('x','y','z')) handler.add_getter('acceleration_grid', 'get_acceleration_grid_acceleration', names=('ax','ay','az')) handler.add_setter('acceleration_grid', 'set_acceleration_grid_acceleration', names=('ax','ay','az')) 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 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_setter('set_grid_density', names=('rho',)) definition.add_setter('set_grid_momentum_density', names=('rhovx','rhovy','rhovz')) definition.add_setter('set_grid_energy_density', names=('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',)) 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 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_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', 'get_acceleration_grid_acceleration', 'set_acceleration_grid_acceleration', 'get_acceleration_grid_size', 'get_mesh_size', 'get_number_of_grids', 'get_level_of_grid', 'refine_grid' ]: handler.add_method(state, methodname) self.stopping_conditions.define_state(handler) Mpiamrvac = MpiAmrVac
94,470
33.179088
153
py
amuse
amuse-main/src/amuse/community/mpiamrvac/patch_files_ifort91.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 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(): run_patch('ifort91', 'ifort91.diff') def main(undo_patches = False): print("applying ifort91 patches to source code") apply_patches_using_patch() if __name__ == '__main__': main()
1,168
28.974359
116
py
amuse
amuse-main/src/amuse/community/mosse/__init__.py
from .interface import Mosse
29
14
28
py
amuse
amuse-main/src/amuse/community/mosse/interface.py
import numpy from operator import itemgetter from amuse.community import * from amuse.units import units from amuse.units import constants from amuse.support.interface import InCodeComponentImplementation from amuse.community.interface import common from amuse.datamodel import Particles from amuse.datamodel import ParticlesSubset class MOSSEInterface(CodeInterface, common.CommonCodeInterface , LiteratureReferencesMixIn): """ MOSSE (Massive Object in SSE) is an updated version of the **rapid** binary-star evolution (SSE) algorithm. With respect to SSE, the major upgrades are that MOSSE includes up-to-date equations for metal-dependent stellar winds and new prescriptions for core-collapse supernova explosion (SNe). Moreover, MOSSE includes the dependence of stellar winds on the Eddington factor: if a star approaches the Eddington limit stellar winds become almost insensitive to metallicity. MOSSE 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 MOSSE 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 SSE can be found in the SSE paper: .. [#] 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="mosse_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('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('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('status', dtype='i', direction=function.OUT, unit = NO_UNIT) return function @legacy_function def evolve_star(): function = LegacyFunctionSpecification() function.name = 'evolve0' function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.INOUT, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('mt', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('r', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('lum', dtype='d', direction=function.INOUT, unit = units.LSun) function.addParameter('mc', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('rc', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('menv', dtype='d', direction=function.INOUT, unit = units.MSun) function.addParameter('renv', dtype='d', direction=function.INOUT, unit = units.RSun) function.addParameter('ospin', dtype='d', direction=function.INOUT, unit = units.yr**-1) function.addParameter('epoch', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tm', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tphys', dtype='d', direction=function.INOUT, unit = units.Myr) function.addParameter('tphysf', 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('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('age', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('tm', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('epoch', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('dt', dtype='d', direction=function.OUT, unit = units.Myr) return function @legacy_function def get_mass_loss_wind(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('lum', dtype='d', direction=function.IN, unit = units.LSun) function.addParameter('r', dtype='d', direction=function.IN, unit = units.RSun) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mc', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mlout', dtype='d', direction=function.OUT, unit = units.MSun/units.yr) return function @legacy_function def get_gyration_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('kw', dtype='i', direction=function.IN, unit = units.stellar_type) function.addParameter('mass', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('mt', dtype='d', direction=function.IN, unit = units.MSun) function.addParameter('r', dtype='d', direction=function.IN, unit = units.RSun) function.addParameter('lum', dtype='d', direction=function.IN, unit = units.LSun) function.addParameter('epoch', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('tm', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('tphys', dtype='d', direction=function.IN, unit = units.Myr) function.addParameter('rg', dtype='d', direction=function.OUT, unit = NO_UNIT) return function 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 MOSSEParticles(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"]) self.add_function_attribute("evolve_one_step", self.particleset_evolve_one_step, self.evolve_one_step) self.add_function_attribute("evolve_for", self.particleset_evolve_for, self.evolve_for) 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, "CO_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.yr**-1, "main_sequence_lifetime": 0 | units.Myr, "age": 0 | units.Myr } 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(MOSSEParticles, self).add_particles_to_store(keys, all_attributes, all_values) added_particles = ParticlesSubset(self, keys) self._private.code_interface._evolve_particles(added_particles, 0 | units.yr) def evolve_one_step(self, particles, subset): self._private.code_interface._evolve_particles(subset.as_set(), subset.age + subset.time_step) def particleset_evolve_one_step(self, particles): self._private.code_interface._evolve_particles(particles, particles.age + particles.time_step) def evolve_for(self, particles, subset, delta_time): self._private.code_interface._evolve_particles(subset.as_set(), subset.age + delta_time) def particleset_evolve_for(self, particles, delta_time): self._private.code_interface._evolve_particles(particles, particles.age + delta_time) def get_defined_attribute_names(self): return ["mass", "radius"] class MOSSE(common.CommonCode): def __init__(self, **options): InCodeComponentImplementation.__init__(self, MOSSEInterface(**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", "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", "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 > 0 takes NS/BH mass from Belczynski et al. 2002, ApJ, 572, 407 (1).", 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 ) def define_state(self, handler): common.CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','RUN','commit_parameters') handler.add_method('RUN', 'evolve_star') 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', MOSSEParticles) handler.add_attribute( 'particles', 'time_step', 'get_time_step', ('stellar_type', 'initial_mass', 'age', 'mass', 'main_sequence_lifetime', 'epoch') ) handler.add_attribute( 'particles', 'mass_loss_wind', 'get_mass_loss_wind', ('stellar_type', 'luminosity', 'radius', 'mass', 'CO_core_mass') ) handler.add_attribute( 'particles', 'gyration_radius', 'get_gyration_radius', ('stellar_type', 'initial_mass','mass','radius', 'luminosity','epoch','main_sequence_lifetime', 'age') ) def _evolve_particles(self, particles, end_time): attributes = ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "main_sequence_lifetime", "age", "end_time" ) result = self.evolve_star( particles.stellar_type, particles.initial_mass, particles.mass, particles.radius, particles.luminosity, particles.core_mass, particles.core_radius, particles.convective_envelope_mass, particles.convective_envelope_radius, particles.spin, particles.epoch, particles.main_sequence_lifetime, particles.age, end_time.as_vector_with_length(len(particles))) # For helium (and helium exhausted) stars, the core mass returned is actually the CO core mass type = result[0].value_in(units.stellar_type) helium_star_selection = (type > 6) & (type < 16) & (type != 10) helium_stars = particles[helium_star_selection] other_stars = particles - helium_stars if len(helium_stars): helium_stars_results = [sub[helium_star_selection] for sub in result] helium_stars_results.append(helium_stars_results[2]) helium_stars.set_values_in_store(helium_stars.get_all_indices_in_store(), ( "stellar_type", "initial_mass", "mass", "radius", "luminosity", "CO_core_mass", "core_radius", "convective_envelope_mass", "convective_envelope_radius", "spin", "epoch", "main_sequence_lifetime", "age", "end_time", "core_mass"), helium_stars_results) if len(other_stars): other_star_selection = numpy.logical_not(helium_star_selection) other_stars.set_values_in_store(other_stars.get_all_indices_in_store(), attributes, [sub[other_star_selection] for sub in result]) def evolve_model(self, end_time = None, keep_synchronous = True): if not keep_synchronous: self._evolve_particles(self.particles, self.particles.time_step + self.particles.age) return if end_time is None: end_time = self.model_time + min(self.particles.time_step) self._evolve_particles(self.particles, end_time - self.model_time + self.particles.age) self.model_time = end_time def _evolve_model_old(self, end_time = None, keep_synchronous = True): """ This is the old implementation of evolve_model. Even with (keep_synchronous = True) it is unable to evolve all stars to a common age, since it relies on the individual timesteps as determined by the community code. Furthermore, it is not suited to simulations with ongoing star formation, since it evolves newly created stars to the same age as the old stars. """ if end_time is None: if keep_synchronous: ages = self.particles.age index, min_age = min(enumerate(ages), key=itemgetter(1)) new_age = min_age + self.particles[index].time_step selection = self.particles.select(lambda x : x < new_age, ["age"]) self._evolve_particles(selection, selection.time_step + selection.age) return end_time = self.particles.time_step + self.particles.age self._evolve_particles(self.particles, end_time) def commit_parameters(self): self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() def initialize_module_with_current_parameters(self): self.parameters.send_cached_parameters_to_code() def initialize_module_with_default_parameters(self): self.parameters.set_defaults() self.commit_parameters() def update_time_steps(self): pass Mosse = MOSSE
21,088
41.776876
140
py
amuse
amuse-main/src/amuse/community/phigrape/__init__.py
from .interface import Phigrape
32
15.5
31
py
amuse
amuse-main/src/amuse/community/phigrape/interface.py
import numpy from amuse.units import nbody_system from amuse.units import units 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 PhiGRAPEInterface( CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, GravityFieldInterface): """ .. [#] ADS:2007NewA...12..357H (Harfst, S., Gualandris, A., Merritt, D., Spurzem, R., Portegies Zwart, S., & Berczik, P. 2007, New Astronomy, 12, 357) """ MODE_G6LIB = 'g6lib' MODE_GPU = 'gpu' MODE_GRAPE = 'grape' def __init__(self, mode = MODE_G6LIB, number_of_workers = 1, **options): CodeInterface.__init__(self, name_of_the_worker = self.name_of_the_worker(mode, number_of_workers), number_of_workers = number_of_workers, **options) LiteratureReferencesMixIn.__init__(self) def name_of_the_worker(self, mode, number_of_workers): if number_of_workers > 1: if mode == self.MODE_G6LIB: return 'phigrape_worker_mpi' elif mode == self.MODE_GPU: return 'phigrape_worker_gpu' elif mode == self.MODE_GRAPE: return 'phigrape_worker_grape' else: return 'phigrape_worker_mpi' else: if mode == self.MODE_G6LIB: return 'phigrape_worker' elif mode == self.MODE_GPU: return 'phigrape_worker_gpu' elif mode == self.MODE_GRAPE: return 'phigrape_worker_grape' else: return 'phigrape_worker' def initialize_particles(self, time): return self.commit_particles() def reinitialize_particles(): return self.recommit_particles() @legacy_function def get_time_step(): function = LegacyFunctionSpecification() function.result_type = 'd' return function @legacy_function def set_eta(): function = LegacyFunctionSpecification() function.addParameter('etas', dtype='d', direction=function.IN) function.addParameter('eta', dtype='d', direction=function.IN) return function @legacy_function def set_eta_s(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_eta1(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_eta_s(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_initialize_once(): """ Sets the initialize GPU/GRAPE once parameter. When set the GPU will be initialized during the :func:`commit_parameters` call and released during the :func:`cleanup_code` call. """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='i', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_initialize_once(): """ Returns the current value of the initialize once parameter. """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='i', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_energy_error(): function = LegacyFunctionSpecification() function.result_type = 'd' return function @legacy_function def find_colliding_secondary(): function = LegacyFunctionSpecification() function.addParameter('id1', dtype='i', direction=function.IN) function.result_type = 'i' return function class PhiGRAPEInterfaceGL(PhiGRAPEInterface): def __init__(self, mode = PhiGRAPEInterface.MODE_G6LIB): PhiGRAPEInterface.__init__(self, mode = mode) @legacy_function def start_viewer(): function = LegacyFunctionSpecification() return function def name_of_the_worker(self, mode): if mode == self.MODE_G6LIB: return 'phigrape_worker_gl' if mode == self.MODE_GPU: return 'phigrape_worker_gl_gpu' if mode == self.MODE_GRAPE: return 'phigrape_worker_gl_grape' else: return 'phigrape_worker_gl' class PhiGRAPE(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody = None, mode = PhiGRAPEInterface.MODE_G6LIB, use_gl = False, **options): nbody_interface = None if use_gl: nbody_interface = PhiGRAPEInterfaceGL(mode, **options) else: nbody_interface = PhiGRAPEInterface(mode, **options) self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, nbody_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): 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_eta", "set_eta1", "timestep_parameter", "timestep parameter", default_value = 0.02 ) handler.add_method_parameter( "get_eta_s", "set_eta_s", "initial_timestep_parameter", "parameter to determine the initial timestep", default_value = 0.01 ) handler.add_method_parameter( "get_initialize_once", "set_initialize_once", "initialize_gpu_once", "set to 1 if the gpu must only be initialized once, 0 if it can be initialized for every call\nIf you want to run multiple instances of the code on the same gpu this parameter needs to be 0 (default)", 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 ) self.stopping_conditions.define_parameters(handler) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_eta", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_eta1", (handler.NO_UNIT, ), (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_initialize_once", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_initialize_once", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) Phigrape = PhiGRAPE
8,862
30.207746
213
py
amuse
amuse-main/src/amuse/community/ph4/test_sync.py
#!/bin/env python import math import collections import getopt import numpy import os import random import sys import unittest from time import process_time as cputime from time import time as wallclocktime from amuse.community.ph4.interface import ph4 as grav from amuse.units import nbody_system from amuse.units import units from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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(pre, time, gravity, E0 = 0.0 | nbody_system.energy, cpu0 = 0.0, wall0 = 0.0): # Standard log output. cpu = cputime() wall = wallclocktime() N = len(gravity.particles) M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy Etop = T + U E = Etop if E0 == 0 | nbody_system.energy: E0 = E Rvir = -0.5*M*M/U Q = -T/U com = pa.center_of_mass(gravity.particles) comv = pa.center_of_mass_velocity(gravity.particles) if N >= 100: dcen,rcore,rhocore \ = pa.densitycentre_coreradius_coredens(gravity.particles) cmx,cmy,cmz = dcen lagr,mf = pa.LagrangianRadii(gravity.particles, cm=dcen) # no units! print('') print(pre+"time=", time.number) print(pre+"cpu=", cpu-cpu0) print(pre+"wall=", wall-wall0) print(pre+"Ntot=", N) print(pre+"mass=", M.number) print(pre+"Etot=", E.number) print(pre+"dE/E=", E/E0 - 1) print(pre+"Rvir=", Rvir.number) print(pre+"Qvir=", Q) cmx,cmy,cmz = com print(pre+"cmpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = comv print(pre+"cmvel[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) if N >= 100: cmx,cmy,cmz = dcen print(pre+"dcpos[3]= %.8f %.8f %.8f" \ % (cmx.number, cmy.number, cmz.number)) print(pre+"Rcore=", rcore.number) print(pre+"Mlagr[9]=", end=' ') for m in mf: print("%.4f" % (m), end=' ') print('') print(pre+"Rlagr[9]=", end=' ') for r in lagr.number: print("%.8f" % (r), end=' ') print('') sys.stdout.flush() return E,cpu,wall def run_ph4(infile = None, number_of_stars = 40, end_time = 10 | nbody_system.time, delta_t = 1 | nbody_system.time, n_workers = 1, use_gpu = 1, gpu_worker = 1, gpu_id = -1, accuracy_parameter = 0.1, softening_length = -1 | nbody_system.length, manage_encounters = 1): if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("delta_t =", delta_t.number) print("n_workers =", n_workers) print("use_gpu =", use_gpu) print("manage_encounters =", manage_encounters) print("initializing the gravity module") sys.stdout.flush() # Note that there are actually really three GPU options to test: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) #print "1"; sys.stdout.flush() gpu = 0 if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") # debugger='valgrind') gpu = 1 except Exception as ex: print('*** GPU worker code not found. Reverting to non-GPU code. ***') gpu = 0 if gpu == 0: gravity = grav(number_of_workers = n_workers, redirection = "none") # debugger='valgrind') #print "2"; sys.stdout.flush() gravity.initialize_code() #print "3"; sys.stdout.flush() gravity.parameters.set_defaults() gravity.parameters.gpu_id = gpu_id #----------------------------------------------------------------- #print "4"; sys.stdout.flush() 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 if 0: 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() if 0: print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) time = 0.0 | nbody_system.time sys.stdout.flush() #----------------------------------------------------------------- #print "5"; sys.stdout.flush() if softening_length == -1 | nbody_system.length: eps2 = 0.25*(float(number_of_stars))**(-0.666667) \ | nbody_system.length**2 else: eps2 = softening_length*softening_length #print "6"; sys.stdout.flush() gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.epsilon_squared = eps2 gravity.parameters.use_gpu = use_gpu gravity.parameters.manage_encounters = manage_encounters print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) gravity.commit_particles() print('') print("number_of_stars =", number_of_stars) sys.stdout.flush() E0,cpu0,wall0 = print_log('', time, gravity) # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() #----------------------------------------------------------------- cpu0 = cputime() t0 = 0. pi = math.pi times = [1., 2., pi, 4*pi/3, 5., 2*pi, 2*pi + pi/100, 2*pi + pi/5, 7., 8., 3*pi, 10.] gravity.parameters.force_sync = 1 # stays set until explicitly unset for t in times: time = t|nbody_system.time print("\nEvolving to time", time) sys.stdout.flush() gravity.parameters.block_steps = 0 gravity.parameters.total_steps = 0 gravity.evolve_model(time) dt = t - t0 t0 = t cpu = cputime() dcpu = cpu - cpu0 cpu0 = cpu # 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 stopping_condition.is_set(): star1 = stopping_condition.particles(0)[0] star2 = stopping_condition.particles(1)[0] print('\nstopping condition set at time', \ gravity.get_time().number,'for:\n') print(star1) print('') print(star2) print('') raise Exception("no encounter handling") 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, cpu0, wall0) print('@@@') print('@@@ t =', time.number, ' dt =', dt) print('@@@ sync_time =', gravity.parameters.sync_time.number) print('@@@ dcpu/dt =', dcpu/dt) nb = gravity.parameters.block_steps ns = gravity.parameters.total_steps print('@@@ d(block_steps) =', nb, ' #/dt =', nb/dt) print('@@@ d(total steps) =', ns, ' #/dt =', ns/dt) #print stars sys.stdout.flush() #----------------------------------------------------------------- print('') gravity.stop() if __name__ == '__main__': infile = None N = 100 t_end = 5.0 | nbody_system.time delta_t = 1.0 | nbody_system.time n_workers = 1 use_gpu = 1 gpu_worker = 1 gpu_id = -1 accuracy_parameter = 0.1 softening_length = 0.01 | nbody_system.length random_seed = -1 manage_encounters = 1 try: opts, args = getopt.getopt(sys.argv[1:], "a:c:d:e:f:gGi:n: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 == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-i": gpu_id = int(a) elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) 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) #os.system('env') assert is_mpd_running() run_ph4(infile, N, t_end, delta_t, n_workers, use_gpu, gpu_worker, gpu_id, accuracy_parameter, softening_length, manage_encounters)
10,277
29.140762
82
py
amuse
amuse-main/src/amuse/community/ph4/test_multiples2.py
import collections import getopt import numpy import os import random import sys import unittest from time import process_time as clock from amuse.community.ph4.interface import ph4 as grav from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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(pre, time, gravity, E0 = 0.0 | nbody_system.energy, cpu0 = 0.0): cpu = clock() N = len(gravity.particles) M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy Etop = T + U Nmul, Nbin, Emul = gravity.get_total_multiple_energy() tmp1,tmp2,Emul2 = gravity.get_total_multiple_energy2() Etot = Etop + Emul Eext = gravity.multiples_external_tidal_correction Eint = gravity.multiples_internal_tidal_correction Eerr = gravity.multiples_integration_energy_error Edel = gravity.multiples_external_tidal_correction \ + gravity.multiples_internal_tidal_correction \ + gravity.multiples_integration_energy_error Ecor = Etot - Edel if E0 == 0 | nbody_system.energy: E0 = Ecor Rvir = -0.5*M*M/U Q = -T/U com = pa.center_of_mass(gravity.particles) comv = pa.center_of_mass_velocity(gravity.particles) dcen,rcore,rhocore = pa.densitycentre_coreradius_coredens(gravity.particles) cmx,cmy,cmz = dcen lagr,mf = pa.LagrangianRadii(gravity.particles, cm=dcen) # no units! print('') print(pre+"time=", time.number) print(pre+"CPU=", cpu - cpu0) print(pre+"Ntot=", N) print(pre+"mass=", M.number) print(pre+"Etot=", Etot.number) print(pre+"Etop=", Etop.number) print(pre+"Eext=", Eext.number) print(pre+"Eint=", Eint.number) print(pre+"Eerr=", Eerr.number) print(pre+"Edel=", Edel.number) print(pre+"Ecor=", Ecor.number) print(pre+"dE/E=", Ecor/E0 - 1) print(pre+"Rvir=", Rvir.number) print(pre+"Qvir=", Q) cmx,cmy,cmz = com print(pre+"cmpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = comv print(pre+"cmvel[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = dcen print(pre+"dcpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) print(pre+"Rcore=", rcore.number) print(pre+"Mcore=", (rhocore*rcore**3).number) # fake... print(pre+"Mlagr[9]=", end=' ') for m in mf: print("%.4f" % (m), end=' ') print('') print(pre+"Rlagr[9]=", end=' ') for r in lagr.number: print("%.8f" % (r), end=' ') print('') kT = T/N Nmul,Nbin,Emul = gravity.print_multiples2(pre, kT, dcen) print(pre+"Nmul=", Nmul) print(pre+"Nbin=", Nbin) print(pre+"Emul= %.5f" % (Emul.number)) print(pre+"Emul2= %.5f" % (Emul2.number)) print(pre+"Emul/kT= %.5f" % (Emul.number/kT.number)) print(pre+"Emul/E= %.5f" % (Emul.number/Etot.number)) print('') sys.stdout.flush() return Ecor,cpu SMALLN = None def new_smalln(): SMALLN.reset() return SMALLN def init_smalln(): global SMALLN sys.stdout.flush() SMALLN = SmallN() sys.stdout.flush() SMALLN.parameters.timestep_parameter = 0.1 #SMALLN.parameters.cm_index = 2001 # don't set this here!! sys.stdout.flush() def init_kepler(star1, star2): try: star1.mass.value_in(units.kg) # see if SI units, throw exception if not unit_converter \ = nbody_system.nbody_to_si(star1.mass + star2.mass, (star2.position-star1.position).length()) except Exception as ex: unit_converter = None kep = Kepler(unit_converter, redirection = "none") kep.initialize_code() return kep def run_ph4(infile = None, outfile = None, number_of_stars = 100, number_of_binaries = 0, end_time = 10 | nbody_system.time, delta_t = 1 | nbody_system.time, n_workers = 1, use_gpu = 1, gpu_worker = 1, salpeter = 0, accuracy_parameter = 0.1, softening_length = 0.0 | nbody_system.length, manage_encounters = 1, random_seed = 1234, debug_level = 1): 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) if infile != None: print("input file =", infile) print("end_time =", end_time) print("delta_t =", delta_t) print("n_workers =", n_workers) print("use_gpu =", use_gpu) print("manage_encounters =", manage_encounters) print("\ninitializing the gravity module") sys.stdout.flush() init_smalln() # Note that there are actually three GPU options: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") except Exception as ex: gravity = grav(number_of_workers = n_workers, redirection = "none") else: gravity = grav(number_of_workers = n_workers, 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") if salpeter == 0: print('equal masses') total_mass = 1.0 | nbody_system.mass scaled_mass = total_mass / number_of_stars else: print('salpeter mass function') scaled_mass = new_salpeter_mass_distribution_nbody(number_of_stars) stars.mass = scaled_mass print("centering stars") stars.move_to_center() print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) else: # Read the input data. Units are dynamical (sorry). # Format: id mass pos[3] vel[3] 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 total_mass = stars.mass.sum() ke = pa.kinetic_energy(stars) kT = ke/(1.5*number_of_stars) if number_of_binaries > 0: # Turn selected stars into binary components. # Only tested for equal-mass case. kep = Kepler(redirection = "none") kep.initialize_code() added_mass = 0.0 | nbody_system.mass # Work with energies rather than semimajor axes. Emin = 10*kT Emax = 20*kT ecc = 0.1 nbin = 0 companion_base_id = 100*(number_of_stars//10) for i in range(0, number_of_stars, number_of_stars//number_of_binaries): # Star i is CM, becomes component, add other star at end. nbin += 1 mass = stars[i].mass new_mass = numpy.random.uniform()*mass # uniform q mbin = mass + new_mass fac = new_mass/mbin E = Emin + numpy.random.uniform()*(Emax-Emin) a = 0.5*nbody_system.G*mass*new_mass/E kep.initialize_from_elements(mbin, a, ecc) # Binaries should be approaching in order to be picked up # by multiples. kep.advance_to_apastron() kep.advance_to_radius(a) dr = quantities.AdaptingVectorQuantity() dr.extend(kep.get_separation_vector()) dv = quantities.AdaptingVectorQuantity() dv.extend(kep.get_velocity_vector()) newstar = datamodel.Particles(1) newstar.mass = new_mass newstar.position = stars[i].position + (1-fac)*dr newstar.velocity = stars[i].velocity + (1-fac)*dv stars[i].position = stars[i].position - fac*dr stars[i].velocity = stars[i].velocity - fac*dv newstar.id = companion_base_id + stars[i].id stars.add_particles(newstar) added_mass += new_mass if nbin >= number_of_binaries: break kep.stop() print('created', nbin, 'binaries') sys.stdout.flush() stars.mass = stars.mass * total_mass/(total_mass+added_mass) number_of_stars += nbin # Set dynamical radii (assuming virial equilibrium and standard # units). Note that this choice should be refined, and updated # as the system evolves. Probably the choice of radius should be # made entirely in the multiples module. TODO. In these units, # M = 1 and <v^2> = 0.5, so the mean 90-degree turnaround impact # parameter is # # b_90 = G (m_1+m_2) / vrel^2 # = 2 <m> / 2<v^2> # = 2 / N for equal masses # # Taking r_i = m_i / 2<v^2> = m_i in virial equilibrium means # that, approximately, "contact" means a 90-degree deflection (r_1 # + r_2 = b_90). A more conservative choice with r_i less than # this value will isolate encounters better, but also place more # load on the large-N dynamical module. stars.radius = stars.mass.number | nbody_system.length time = 0.0 | nbody_system.time # print "IDs:", stars.id.number print("recentering stars") stars.move_to_center() sys.stdout.flush() #----------------------------------------------------------------- if softening_length < 0.0 | nbody_system.length: # Use ~interparticle spacing. Assuming standard units here. TODO eps2 = 0.25*(float(number_of_stars))**(-0.666667) \ | nbody_system.length**2 else: eps2 = softening_length*softening_length print('softening length =', eps2.sqrt()) gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.epsilon_squared = eps2 gravity.parameters.use_gpu = use_gpu # gravity.parameters.manage_encounters = manage_encounters print('') print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) gravity.commit_particles() print('') print("number_of_stars =", number_of_stars) sys.stdout.flush() # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() # Debugging: prevent the multiples code from being called. if 0: stopping_condition.disable() print('stopping condition disabled') sys.stdout.flush() # ----------------------------------------------------------------- # Create the coupled code and integrate the system to the desired # time, managing interactions internally. kep = init_kepler(stars[0], stars[1]) multiples_code = multiples.Multiples(gravity, new_smalln, kep) multiples_code.neighbor_perturbation_limit = 0.1 #multiples_code.neighbor_distance_factor = 2.0 multiples_code.neighbor_veto = True multiples_code.global_debug = debug_level print('') print('multiples_code.initial_scale_factor =', \ multiples_code.initial_scale_factor) print('multiples_code.neighbor_perturbation_limit =', \ multiples_code.neighbor_perturbation_limit) print('multiples_code.neighbor_veto =', \ multiples_code.neighbor_veto) print('multiples_code.final_scale_factor =', \ multiples_code.final_scale_factor) print('multiples_code.initial_scatter_factor =', \ multiples_code.initial_scatter_factor) print('multiples_code.final_scatter_factor =', \ multiples_code.final_scatter_factor) print('multiples_code.retain_binary_apocenter =', \ multiples_code.retain_binary_apocenter) print('multiples_code.wide_perturbation_limit =', \ multiples_code.wide_perturbation_limit) # Find initial binaries. gravity.parameters.zero_step_mode = 1 print('\nidentifying initial binaries') multiples_code.evolve_model(time) gravity.parameters.zero_step_mode = 0 pre = "%%% " E0,cpu0 = print_log(pre, time, multiples_code) print("evolving to time =", end_time, \ "in steps of", delta_t) while time < end_time: time += delta_t multiples_code.evolve_model(time) # 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") print_log(pre, time, multiples_code, E0, cpu0) sys.stdout.flush() #----------------------------------------------------------------- if not outfile == None: # Write data to a file. f = open(outfile, 'w') #-------------------------------------------------- # Need to save top-level stellar data and parameters. # Need to save multiple data and parameters. f.write('%.15g\n'%(time.number)) for s in multiples_code.stars: write_star(s, f) #-------------------------------------------------- f.close() print('wrote file', outfile) print('') gravity.stop() def write_star(s, f): x,y,z = s.position.number vx,vy,vz = s.velocity.number f.write('%d %.15g %.15g %.15g %.15g %.15g %.15g %.15g\n' \ %(s.id, s.mass.number, x, y, z, vx, vy, vz)) if __name__ == '__main__': print('\ncommand line:', end=' ') for a in sys.argv: print(a, end=' ') print('\n') infile = None outfile = None N = 100 Nbin = 10 t_end = 10.0 | nbody_system.time delta_t = 1.0 | nbody_system.time n_workers = 2 use_gpu = 0 gpu_worker = 0 salpeter = 0 accuracy_parameter = 0.1 softening_length = 0 | nbody_system.length random_seed = 42 manage_encounters = 1 debug_level = 1 try: opts, args = getopt.getopt(sys.argv[1:], "a:b:c:d:D:e:f:-F:gGn:s:St: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 == "-b": Nbin = int(a) elif o == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-D": debug_level = int(a) elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-F": outfile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-S": salpeter = 1 elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) else: print("unexpected argument", o) assert is_mpd_running() run_ph4(infile, outfile, N, Nbin, t_end, delta_t, n_workers, use_gpu, gpu_worker, salpeter, accuracy_parameter, softening_length, manage_encounters, random_seed, debug_level)
17,202
31.336466
80
py
amuse
amuse-main/src/amuse/community/ph4/plot_energy_vs_t.py
#!/usr/bin/env python import getopt import string from pylab import * import re import numpy from math import log10 # Display a time sequence from a (not yet standard) AMUSE log file. if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "f:lq:t:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) infile = '' quantity = '' log = 0 lt = 'b-' for o, a in opts: if o == "-f": infile = a elif o == "-l": log = 1 elif o == "-q": quantity = a elif o == "-t": lt = a else: print("unexpected argument", o) #if infile == '' or quantity == '': #print 'plotq -f file -q quantity -t linetype' #sys.exit(0) tlist = [] qlist = [] nq = 1 f = open(infile, 'r') for line in f: if len(line) > 0: cols = line.split() if len(cols) > 0 and cols[0] == '%%%': if cols[1] == 'time=': tlist.append(float(cols[2])) elif cols[1] == 'Multiple': bin_id = int(cols[2]) #if log: q = log10(q) strsplit = cols[10].split('=') if len(strsplit) == 2: mykT = float(strsplit[1]) mydata = [tlist[len(tlist)-1], bin_id, mykT] qlist.append(mydata) #elif re.search(quantity+'\[.*\]'+'=', cols[1]): #s = re.search(quantity+'\[.*\]'+'=', cols[1]).group() # Messy! There must surely be a better way to do this... #i1 = string.index(s,'[') #i2 = string.index(s,']') #nq = int(s[i1+1:i2]) #clist = [] #for i in range(2,2+nq): #q = float(cols[i]) #if log: q = log10(q) #clist.append(q) #qlist.append(clist) f.close() multiple_index = [] i=0 while i<len(qlist): j=0 original = True while j<len(multiple_index): if multiple_index[j] == qlist[i][1]: original = False j += 1 if original: multiple_index.append(qlist[i][1]) i += 1 counter = 0 i=0 while i<len(multiple_index): myidata = [] myxdata = [] myydata = [] j=0 while j<len(qlist): if multiple_index[i] == qlist[j][1]: myidata.append(multiple_index[i]) myxdata.append(qlist[j][0]) myydata.append(qlist[j][2]) if qlist[j][0] == 300.0: counter += 1 j += 1 plot(myxdata, myydata) hold('on') i += 1 show() i=0 while i<len(myxdata): print(myxdata[i]) i += 1 print(counter) """ if len(qlist) > 0: if log: quantity = 'log10 '+quantity if nq == 1: plot(tlist, qlist, lt) else: qplot = numpy.array(qlist) for i in range(nq): plot(tlist, qplot[:,i], lt, linewidth=1.0) xlabel('time') ylabel(quantity) show() else: print 'No data to plot.' """
3,376
24.583333
76
py
amuse
amuse-main/src/amuse/community/ph4/plot_kT_vs_t.py
#!/usr/bin/env python import getopt import string from pylab import * import re import numpy from math import log10 # Display a time sequence from a (not yet standard) AMUSE log file. if __name__ == '__main__': try: opts, args = getopt.getopt(sys.argv[1:], "f:lq:t:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) infile = '' quantity = '' log = 0 lt = 'b-' for o, a in opts: if o == "-f": infile = a elif o == "-l": log = 1 elif o == "-q": quantity = a elif o == "-t": lt = a else: print("unexpected argument", o) #if infile == '' or quantity == '': #print 'plotq -f file -q quantity -t linetype' #sys.exit(0) tlist = [] qlist = [] nq = 1 f = open(infile, 'r') for line in f: if len(line) > 0: cols = line.split() if len(cols) > 0 and cols[0] == '%%%': if cols[1] == 'time=': tlist.append(float(cols[2])) elif cols[1] == 'Multiple': bin_id = int(cols[2]) #if log: q = log10(q) strsplit = cols[11].split('=') if len(strsplit) == 2: mykT = float(strsplit[1]) mydata = [tlist[len(tlist)-1], bin_id, mykT] qlist.append(mydata) #elif re.search(quantity+'\[.*\]'+'=', cols[1]): #s = re.search(quantity+'\[.*\]'+'=', cols[1]).group() # Messy! There must surely be a better way to do this... #i1 = string.index(s,'[') #i2 = string.index(s,']') #nq = int(s[i1+1:i2]) #clist = [] #for i in range(2,2+nq): #q = float(cols[i]) #if log: q = log10(q) #clist.append(q) #qlist.append(clist) f.close() multiple_index = [] i=0 while i<len(qlist): j=0 original = True while j<len(multiple_index): if multiple_index[j] == qlist[i][1]: original = False j += 1 if original: multiple_index.append(qlist[i][1]) i += 1 counter = 0 i=0 while i<len(multiple_index): myidata = [] myxdata = [] myydata = [] j=0 while j<len(qlist): if multiple_index[i] == qlist[j][1]: myidata.append(multiple_index[i]) myxdata.append(qlist[j][0]) myydata.append(qlist[j][2]) if qlist[j][0] == 300.0: counter += 1 j += 1 plot(myxdata, myydata) hold('on') i += 1 show() i=0 while i<len(myxdata): print(myxdata[i]) i += 1 print(counter) """ if len(qlist) > 0: if log: quantity = 'log10 '+quantity if nq == 1: plot(tlist, qlist, lt) else: qplot = numpy.array(qlist) for i in range(nq): plot(tlist, qplot[:,i], lt, linewidth=1.0) xlabel('time') ylabel(quantity) show() else: print 'No data to plot.' """
3,250
23.628788
72
py
amuse
amuse-main/src/amuse/community/ph4/test_multiples.py
import collections import getopt import numpy import os import random import sys import unittest from amuse.community.ph4.interface import ph4 as grav from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples from amuse.units import nbody_system from amuse.units import units from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.rfi.core import is_mpd_running from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution_nbody def print_log(time, gravity, E0 = 0.0 | nbody_system.energy): M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy Ebin = gravity.get_binary_energy() Etop = T + U E = Etop + Ebin if E0 == 0 | nbody_system.energy: E0 = E Rv = -0.5*M*M/U Q = -T/U print("") print("time =", time.number, " energy = ", E.number, \ " dE/E0 = ", (E/E0 - 1)) print('%s %.4f %.6f %.6f %.6f %.6f %.6f %.6f %.6f' % \ ("%%", time.number, M.number, T.number, U.number, \ E.number, Ebin.number, Rv.number, Q)) sys.stdout.flush() return E def new_smalln(): result = SmallN() result.parameters.timestep_parameter = 0.1 #result.parameters.cm_index = 2001 return result def run_ph4(infile = None, number_of_stars = 40, end_time = 10 | nbody_system.time, delta_t = 1 | nbody_system.time, n_workers = 1, use_gpu = 1, gpu_worker = 1, accuracy_parameter = 0.1, softening_length = -1 | nbody_system.length, manage_encounters = 1, random_seed = 1234): 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) if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("delta_t =", delta_t.number) print("n_workers =", n_workers) print("use_gpu =", use_gpu) print("manage_encounters =", manage_encounters) print("\ninitializing the gravity module") sys.stdout.flush() # Note that there are actually three GPU options to test: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") except Exception as ex: gravity = grav(number_of_workers = n_workers, redirection = "none") else: gravity = grav(number_of_workers = n_workers, 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.02 | nbody_system.length print("centering stars") stars.move_to_center() print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) 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() #----------------------------------------------------------------- if softening_length == -1 | nbody_system.length: eps2 = 0.25*(float(number_of_stars))**(-0.666667) \ | nbody_system.length**2 else: eps2 = softening_length*softening_length gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.epsilon_squared = eps2 gravity.parameters.use_gpu = use_gpu # gravity.parameters.manage_encounters = manage_encounters print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) 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) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() kep = Kepler(redirection = "none") kep.initialize_code() multiples_code = multiples.Multiples(gravity, new_smalln, kep) while time < end_time: time += delta_t multiples_code.evolve_model(time) # 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") print_log(time, gravity, E0) sys.stdout.flush() print('') gravity.stop() if __name__ == '__main__': infile = None N = 100 t_end = 5.0 | nbody_system.time delta_t = 1.0 | nbody_system.time n_workers = 2 use_gpu = 1 gpu_worker = 1 accuracy_parameter = 0.1 softening_length = -1 | nbody_system.length random_seed = -1 manage_encounters = 1 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 == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) else: print("unexpected argument", o) assert is_mpd_running() run_ph4(infile, N, t_end, delta_t, n_workers, use_gpu, gpu_worker, accuracy_parameter, softening_length, manage_encounters, random_seed)
8,236
30.083019
79
py
amuse
amuse-main/src/amuse/community/ph4/__init__.py
# generated file from .interface import Ph4
44
14
26
py
amuse
amuse-main/src/amuse/community/ph4/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode # *** This script, together with the defaults in # *** GravitationalDynamicsInterface, will be used to generate both # *** the header file interface.h and the stub interface.cc. Since # *** interface.cc has been hand-coded to implement the details, # *** MAKE SURE TO SAVE IT SOMEWHERE, as build.py can overwrite it! class ph4Interface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, GravityFieldInterface): """ Parallel, GPU-accelerated, N-body integration module with block time steps, using a 4th-order Hermite integration scheme. .. [#] ADS:2018araa.book.....P (Portegies Zwart, S. & McMillan, S.L.W., 2018) """ # Interface specification. include_headers = ['interface.h', 'stopcond.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_muse_worker(mode), **options ) LiteratureReferencesMixIn.__init__(self) # 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) """, unit = INDEX ) function.addParameter('mass', dtype='float64', direction=function.IN, description = "The mass of the particle", unit = nbody_system.mass) function.addParameter('x', dtype='float64', direction=function.IN, description = "The initial position vector of the particle", unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.IN, description = "The initial position vector of the particle", unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.IN, description = "The initial position vector of the particle", unit = nbody_system.length) function.addParameter('vx', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle", unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle", unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.IN, description = "The initial velocity vector of the particle", unit = nbody_system.speed) function.addParameter('radius', dtype='float64', direction=function.IN, description = "The radius of the particle", default = -1, unit = nbody_system.length) function.addParameter('id', dtype='int32', direction=function.IN, description = "Identifier of the particle, " +"option for restoring state after loading", default = -1, unit = NO_UNIT) 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 get_particle_timestep(): """ Retrieve the timestep of a particle. """ function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description = "Index of the particle to get the timestep from. This index must have been returned by an earlier call to :meth:`new_particle`") function.addParameter('timestep', dtype='float64', unit=nbody_system.time, direction=function.OUT, description = "The current timestep of the particle") function.result_type = 'int32' function.can_handle_array = True return function def name_of_the_muse_worker(self, mode): if mode == self.MODE_CPU: return 'ph4_worker' elif mode == self.MODE_GPU: return 'ph4_worker_gpu' else: return 'ph4_worker' # Inheritance from GravitationalDynamicsInterface means that # functions in the standard interface don't need to be defined. # See interface.py.2 for a laboriously hand-coded version written # before I discovered this fact! (Steve McMillan, 10/10) # Additional functions defined here will be reflected in # interface.h and must be provided in interface.cc in order for # ph4_worker to build. # The following functions aren't defined in the default interface: @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 accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta(): """ Get the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_gpu(): """ Set use_gpu. """ function = LegacyFunctionSpecification() function.addParameter('gpu', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gpu(): """ Get use_gpu. """ function = LegacyFunctionSpecification() function.addParameter('gpu', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_gpu_id(): """ Set gpu_id. """ function = LegacyFunctionSpecification() function.addParameter('gpu_id', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gpu_id(): """ Get gpu_id. """ function = LegacyFunctionSpecification() function.addParameter('gpu_id', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_manage_encounters(): """ Set the value of manage_encounters. """ function = LegacyFunctionSpecification() function.addParameter('manage_encounters', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_manage_encounters(): """ Get the value of manage_encounters. """ function = LegacyFunctionSpecification() function.addParameter('manage_encounters', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_zero_step_mode(): """ Set the value of zero_step_mode. """ function = LegacyFunctionSpecification() function.addParameter('zero_step_mode', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_zero_step_mode(): """ Get the value of zero_step_mode. """ function = LegacyFunctionSpecification() function.addParameter('zero_step_mode', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_force_sync(): """ Set the value of force_sync. """ function = LegacyFunctionSpecification() function.addParameter('force_sync', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_force_sync(): """ Get the value of force_sync. """ function = LegacyFunctionSpecification() function.addParameter('force_sync', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_sync_time(): """ Set the value of sync_time. """ function = LegacyFunctionSpecification() function.addParameter('sync_time', dtype='float64', direction=function.IN, unit = nbody_system.time) function.result_type = 'int32' return function @legacy_function def get_sync_time(): """ Get the value of sync_time. """ function = LegacyFunctionSpecification() function.addParameter('sync_time', dtype='float64', direction=function.OUT, unit = nbody_system.time) function.result_type = 'int32' return function @legacy_function def set_block_steps(): """ Set the value of block_steps. """ function = LegacyFunctionSpecification() function.addParameter('set_block_steps', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_block_steps(): """ Get the value of block_steps. """ function = LegacyFunctionSpecification() function.addParameter('get_block_steps', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_total_steps(): """ Set the value of total_steps. """ function = LegacyFunctionSpecification() function.addParameter('set_total_steps', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_total_steps(): """ Get the value of total_steps. """ function = LegacyFunctionSpecification() function.addParameter('get_total_steps', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_number_of_particles_updated(): """ Return the number of particles added or deleted 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_updated_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.addParameter('kind_of_update', dtype='int32', direction=function.OUT, description = 'kind of update (2, addition), (1, deletion)') function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def get_binary_energy(): """ Return the total energy in all binaries. """ function = LegacyFunctionSpecification() function.addParameter( 'binary_energy', dtype='float64', direction=function.OUT, unit = nbody_system.energy ) function.result_type = 'int32' return function @legacy_function def set_initial_timestep_fac(): """ Set the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_fac', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_initial_timestep_fac(): """ Get the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_fac', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_initial_timestep_limit(): """ Set the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_limit', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_initial_timestep_limit(): """ Get the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_limit', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_initial_timestep_median(): """ Set the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_median', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_initial_timestep_median(): """ Get the current accuracy parameter. """ function = LegacyFunctionSpecification() function.addParameter('initial_timestep_median', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def recompute_timesteps(): """ Force recomputation of all timesteps (assume a synchronized system), """ function = LegacyFunctionSpecification() function.result_type = 'int32' return function class ph4(GravitationalDynamics,GravityFieldCode): # The actual module. def __init__(self, convert_nbody = None, **keyword_arguments): legacy_interface = ph4Interface(**keyword_arguments) self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **keyword_arguments) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) handler.add_method('RUN', 'get_particle_timestep') GravityFieldCode.define_state(self, handler) handler.add_method('EDIT', 'set_state') handler.add_method('EDIT', 'set_velocity') handler.add_method('EDIT', 'set_mass') handler.add_method('EDIT', 'set_position') handler.add_method('CHANGED','before_get_parameter') handler.add_transition('RUN', 'CHANGED', 'set_state', False) handler.add_transition('RUN', 'CHANGED', 'set_velocity', False) handler.add_transition('RUN', 'CHANGED', 'set_mass', False) handler.add_transition('RUN', 'CHANGED', 'set_position', False) handler.add_transition('CHANGED', 'RUN', 'synchronize_model') handler.add_method('CHANGED', 'get_state') handler.add_method('CHANGED', 'get_mass') handler.add_method('CHANGED', 'get_position') handler.add_method('CHANGED', 'get_velocity') handler.add_method('CHANGED', 'get_particle_timestep') self.stopping_conditions.define_state(handler) def define_parameters(self, handler): # Set/get parameters specific to the module, not part of the # standard interface. Accessors used here must be defined # above and reflected in interface.cc. Python access is # (e.g.) # # ph4.parameters.timestep_parameter = xxx handler.add_method_parameter( "get_eta", # getter name in interface.cc "set_eta", # setter name in interface.cc "timestep_parameter", # python parameter name "timestep parameter", # description default_value = 0.14 ) handler.add_method_parameter( "get_eps2", # already defined in standard interface "set_eps2", # already defined in standard interface "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_gpu", # getter name in interface.cc "set_gpu", # setter name in interface.cc "use_gpu", # python parameter name "use GPU", # description default_value = 1 ) handler.add_method_parameter( "get_gpu_id", # getter name in interface.cc "set_gpu_id", # setter name in interface.cc "gpu_id", # python parameter name "GPU ID", # description default_value = -1 ) handler.add_method_parameter( "get_manage_encounters", # getter name in interface.cc "set_manage_encounters", # setter name in interface.cc "manage_encounters", # python parameter name "manage close encounters", # description default_value = 4 ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time at which to start the simulation", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_sync_time", "set_sync_time", "sync_time", "last model synchronization time", default_value = 0.0 | nbody_system.time ) handler.add_method_parameter( "get_zero_step_mode", "set_zero_step_mode", "zero_step_mode", "force evolve_model to take zero-length steps", default_value = 0 ) handler.add_method_parameter( "get_force_sync", "set_force_sync", "force_sync", "force evolve_model to sync at specified time", default_value = 0 ) handler.add_method_parameter( "get_block_steps", "set_block_steps", "block_steps", "number of block steps", default_value = 0 ) handler.add_method_parameter( "get_total_steps", "set_total_steps", "total_steps", "total number of steps", default_value = 0 ) handler.add_method_parameter( "get_initial_timestep_fac", # getter name in interface.cc "set_initial_timestep_fac", # setter name in interface.cc "initial_timestep_fac", # python parameter name "initial timestep factor", # description default_value = 0.0625 ) handler.add_method_parameter( "get_initial_timestep_limit", # getter name in interface.cc "set_initial_timestep_limit", # setter name in interface.cc "initial_timestep_limit", # python parameter name "initial timestep limit", # description default_value = 0.03125 ) handler.add_method_parameter( "get_initial_timestep_median", # getter name in interface.cc "set_initial_timestep_median", # setter name in interface.cc "initial_timestep_median", # python parameter name "initial timestep median factor", # description default_value = 8.0 ) self.stopping_conditions.define_parameters(handler) 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 == 0: return indices_in_update_list = list(range(number_of_updated_particles)) particle_indices, updates \ = self.get_id_of_updated_particle(indices_in_update_list) incode_storage = self.particles._private.attribute_storage indices_to_remove = [] indices_to_add = [] for index, status in zip(particle_indices, updates): if status == 1: # deletion indices_to_remove.append(index) elif status == 2: # addition indices_to_add.append(index) print('') print("indices_to_remove:", indices_to_remove) print("indices_to_add:", indices_to_add) if len(indices_to_remove) > 0: incode_storage._remove_indices(indices_to_remove) if len(indices_to_add) > 0: incode_storage._add_indices(indices_to_add) def define_methods(self, 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 ) ) 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 ) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) handler.add_getter('particles', 'get_particle_timestep', names = ('timestep',)) handler.add_getter('particles', 'get_potential', names=('potential_in_code',)) self.stopping_conditions.define_particle_set(handler) Ph4 = ph4
25,871
34.833795
172
py
amuse
amuse-main/src/amuse/community/ph4/test_ph4.py
#!/bin/env python import collections import getopt import numpy import os import random import sys import unittest from time import process_time as cputime from time import time as wallclocktime from amuse.community.ph4.interface import ph4 as grav from amuse.units import nbody_system from amuse.units import units from amuse.units.quantities import zero from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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(pre, time, gravity, E0 = 0.0 | nbody_system.energy, cpu0 = 0.0, wall0 = 0.0): cpu = cputime() wall = wallclocktime() N = len(gravity.particles) M = gravity.total_mass print('') print(pre+"time=", time.number) print(pre+"cpu=", cpu-cpu0) print(pre+"wall=", wall-wall0) print(pre+"Ntot=", N) print(pre+"mass=", M.number) E = 0 | nbody_system.energy if N > 0: U = gravity.potential_energy T = gravity.kinetic_energy Etop = T + U E = Etop if E0 == 0 | nbody_system.energy: E0 = E Rvir = -0.5*M*M/U Q = -T/U com = pa.center_of_mass(gravity.particles) comv = pa.center_of_mass_velocity(gravity.particles) if N > 15: dcen,rcore,rhocore \ = pa.densitycentre_coreradius_coredens(gravity.particles) else: dcen = com rcore = zero rhocore = zero cmx,cmy,cmz = dcen lagr,mf = pa.LagrangianRadii(gravity.particles, cm=dcen) # no units! print(pre+"Etot=", E.number) print(pre+"dE/E=", E/E0 - 1) print(pre+"Rvir=", Rvir.number) print(pre+"Qvir=", Q) cmx,cmy,cmz = com print(pre+"cmpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = comv print(pre+"cmvel[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = dcen print(pre+"dcpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) print(pre+"Rcore=", rcore.number) print(pre+"Mlagr[9]=", end=' ') for m in mf: print("%.4f" % (m), end=' ') print('') print(pre+"Rlagr[9]=", end=' ') for r in lagr.number: print("%.8f" % (r), end=' ') print('') sys.stdout.flush() return E,cpu,wall def run_ph4(infile = None, number_of_stars = 40, end_time = 10 | nbody_system.time, delta_t = 1 | nbody_system.time, n_workers = 1, use_gpu = 1, gpu_worker = 1, gpu_id = -1, accuracy_parameter = 0.1, softening_length = -1 | nbody_system.length, manage_encounters = 1): if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("delta_t =", delta_t.number) print("n_workers =", n_workers) print("use_gpu =", use_gpu) print("manage_encounters =", manage_encounters) print("\ninitializing the gravity module") sys.stdout.flush() # Note that there are actually three GPU options to test: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) #print "1"; sys.stdout.flush() gpu = 0 if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") # debugger='valgrind') gpu = 1 except Exception as ex: print('*** GPU worker code not found. Reverting to non-GPU code. ***') gpu = 0 if gpu == 0: gravity = grav(number_of_workers = n_workers, redirection = "none") # debugger='valgrind') #print "2"; sys.stdout.flush() gravity.initialize_code() #print "3"; sys.stdout.flush() gravity.parameters.set_defaults() gravity.parameters.gpu_id = gpu_id #----------------------------------------------------------------- #print "4"; sys.stdout.flush() 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") if number_of_stars > 0: stars.mass = (1.0 / number_of_stars) | nbody_system.mass if 0: 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() if 0: print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) 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() #----------------------------------------------------------------- #print "5"; sys.stdout.flush() if softening_length == -1 | nbody_system.length and number_of_stars > 0: eps2 = 0.25*(float(number_of_stars))**(-0.666667) \ | nbody_system.length**2 else: eps2 = softening_length*softening_length #print "6"; sys.stdout.flush() gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.epsilon_squared = eps2 gravity.parameters.use_gpu = use_gpu gravity.parameters.manage_encounters = manage_encounters print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) gravity.commit_particles() print('Taking step') sys.stdout.flush() gravity.evolve_model(time) 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,cpu0,wall0 = print_log('', time, gravity) # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() while time < end_time: time += delta_t 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 stopping_condition.is_set(): star1 = stopping_condition.particles(0)[0] star2 = stopping_condition.particles(1)[0] print('\nstopping condition set at time', \ gravity.get_time().number,'for:\n') print(star1) print('') print(star2) print('') raise Exception("no encounter handling") 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, cpu0, wall0) sys.stdout.flush() print('') gravity.stop() if __name__ == '__main__': infile = None N = 250 t_end = 5.0 | nbody_system.time delta_t = 1.0 | nbody_system.time n_workers = 1 use_gpu = 1 gpu_worker = 1 gpu_id = -1 accuracy_parameter = 0.1 softening_length = -1 | nbody_system.length random_seed = -1 manage_encounters = 1 try: opts, args = getopt.getopt(sys.argv[1:], "a:c:d:e:f:gGi:n: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 == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-i": gpu_id = int(a) elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) 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) #os.system('env') assert is_mpd_running() run_ph4(infile, N, t_end, delta_t, n_workers, use_gpu, gpu_worker, gpu_id, accuracy_parameter, softening_length, manage_encounters)
11,044
29.938375
84
py
amuse
amuse-main/src/amuse/community/ph4/binary_hist.py
from pylab import * import sys import re if __name__ == '__main__': if len(sys.argv) != 3: print("usage: python binary_hist.py <input filename> <time of histogram>") sys.exit(1) else: fname = sys.argv[1] time = float(sys.argv[2]) f = open(fname, "r") inblock = False EkTs = [] for line in f: if re.search("%%% time= (\d+\.\d*)", line): if float(re.search("%%% time= (\d+\.\d*)", line).group(1)) == time: inblock = True if inblock and re.search("%%% .*E/kT=(-?\d+\.\d+)", line): EkTs.append(float(re.search("%%%.*E/kT=(-?\d+\.\d+)", line).group(1))) if inblock and re.search("%%% Emul/E", line): inblock = False f.close() if len(EkTs) > 0: hist(EkTs) show() else: print("No binaries found at time = %f." % time)
1,007
29.545455
83
py
amuse
amuse-main/src/amuse/community/ph4/plotq.py
#!/usr/bin/env python import sys from math import log10, sqrt import numpy as np import matplotlib.pyplot as plt import string import re # Display a time sequence from a set of (not yet standard) AMUSE log # files. Files, colors, and styles should be separated by spaces. if __name__ == '__main__': # Command-line arguments and defaults: infiles = [] # -f [list] log = 0 # -L (sets log = 1) outfile = '' # -o filename or . quantities = [] # -q [list] layout = '' # -l (rows)x(cols) space = 0.3 # -S space # Separate the point colors and the line styles. Replicate the # last color/style in case of multiple files. colors = ['b','g','r','c','m','k'] # -c [list] ls = ['-'] # -s [list] # Parse the argument list the old-fashioned way to enable multiple # arguments (unaccountably not supported by getopt): i = 1 n = len(sys.argv) while i < n: if sys.argv[i][0] == '-': if len(sys.argv[i]) > 1: if sys.argv[i][1] == 'c': colors = [] # Accumulate colors until we find a leading '-' or # reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 colors.append(sys.argv[i]) elif sys.argv[i][1] == 'f': # Accumulate names until we find a leading '-' or # reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 infiles.append(sys.argv[i]) elif sys.argv[i][1] == 'L': log = 1 elif sys.argv[i][1] == 'l': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 layout = sys.argv[i] elif sys.argv[i][1] == 'o': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 outfile = sys.argv[i] elif sys.argv[i][1] == 'q': # Accumulate quantities until we find a leading # '-' or reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 quantities.append(sys.argv[i]) elif sys.argv[i][1] == 'S': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 space = float(sys.argv[i]) elif sys.argv[i][1] == 's': ls = [] # Accumulate line styles until we find a leading # '-' or reach the end of the list. Problem: '-' # is a legal line style, so accept a lone '-' in # this case. while i < n-1 \ and (sys.argv[i+1][0] != '-' or len(sys.argv[i+1]) == 1): i += 1 ls.append(sys.argv[i]) else: print('unknown option', sys.argv[i]) i += 1 li = len(infiles) lq = len(quantities) if li == 0 or lq == 0: print('plotq -f file-list -q quantity-list') sys.exit(0) # Extend the color list if neessary. lc = len(colors) if lc < li: for i in range(li-lc): colors.append(colors[lc-1]) # Extend the line style list if necessary. lt = len(ls) if lt < li: for i in range(li-lt): ls.append(ls[lt-1]) plt.figure(figsize=(12,8)) plt.subplots_adjust(wspace=space, hspace=space) # Determine the plot layout (mxn). if layout == '': # Automatic. m = int(sqrt(float(lq))) if m*m < lq: m += 1 n = lq/m if m*n < lq: n += 1 else: # User-specified: m,n = layout.split('x') m = int(m) n = int(n) i = 100*m+10*n # assume m, n < 10 figs = [] for ii in range(lq): figs.append(plt.subplot(i+ii+1)) print('infiles: ', end=' ') for f in infiles: print(f, end=' ') print('') print('quantities: ', end=' ') for q in quantities: print(q, end=' ') print('') print('colors: ', end=' ') for ic in range(li): print(colors[ic], end=' ') print('') print('styles: ', end=' ') for i in range(li): print(ls[i], end=' ') print('') print(m, 'x', n, 'plot layout') ifile = 0 for infile in infiles: # loop over input files # Extract data from infile. tlist = [] qlist = [[] for iq in range(lq)] # list of lq empty lists nq = [1 for iq in range(lq)] # default qlist length f = open(infile, 'r') for line in f: # process data line by line if len(line) > 0: cols = line.split() if len(cols) > 0 and cols[0] == '%%%': if cols[1] == 'time=': tlist.append(float(cols[2])) else: foundq = False for iq in range(lq): if cols[1] == quantities[iq]+'=': foundq = True q = float(cols[2]) if log: q = log10(q) qlist[iq].append(q) if not foundq: for iq in range(lq): qq = quantities[iq] if re.search(qq+'\[.*\]'+'=', cols[1]): s = re.search(qq+'\[.*\]'+'=', cols[1]).group() # Messy! There must surely be a # better way to do this... i1 = string.index(s,'[') i2 = string.index(s,']') nq[iq] = int(s[i1+1:i2]) clist = [] for i in range(2,2+nq[iq]): q = float(cols[i]) if log: q = log10(q) clist.append(q) qlist[iq].append(clist) f.close() # Plot the data. for iq in range(lq): qq = quantities[iq] if len(qlist[iq]) > 0: if log: qq = 'log10 '+qq if nq[iq] == 1: figs[iq].plot(tlist, qlist[iq], colors[ifile]+ls[ifile]) else: qplot = np.array(qlist[iq]) for i in range(nq[iq]): figs[iq].plot(tlist, qplot[:,i], colors[ifile]+ls[ifile], linewidth=1.0) figs[iq].set_xlabel('time') figs[iq].set_ylabel(qq) else: print('No', qq, 'data to plot in '+infile+'.') ifile += 1 # Save to a file if specified; otherwise, display to the screen. if outfile == '': plt.show() else: if outfile == '.': qq = '' for iq in range(lq): if iq > 0: qq += '+' qq += quantities[iq] outfile = qq+'.pdf' outfile = outfile.replace('/','_') print('saving to', outfile) plt.savefig(outfile)
7,704
29.334646
76
py
amuse
amuse-main/src/amuse/community/ph4/util/plot_smalln_data.py
import sys import getopt import math import numpy import time import matplotlib.pyplot as plt import matplotlib.animation as animate # TODO: Colormap should respond to changes in index array. def unpack_line(r, np, nq): tt = float(r[0]) ii = [] mm = [] xx = [] yy = [] zz = [] for j in range(np): ii.append(int(r[nq*j+1])) if nq == 4: mm.append(2.**(-j)) else: mm.append(float(r[nq*j+2])) xx.append(float(r[nq*j+nq-2])) yy.append(float(r[nq*j+nq-1])) zz.append(float(r[nq*j+nq])) return tt, ii, mm, xx, yy, zz def interpolate(xp, xx, tfac): xint = [] for j in range(len(xx)): xint.append(xp[j] + tfac*(xx[j]-xp[j])) return xint def read_data(filename, dt, N, have_mass): # Read in the data file. Format is defined in smalln. print('reading data from', filename) sys.stdout.flush() f = open(filename) ll = f.readlines() f.close() nt = len(ll) print(nt, 'records read') sys.stdout.flush() # Do some preliminary analysis. r = ll[0].split() # trust the first line if have_mass: nq = 5 else: nq = 4 np = (len(r)-1)/nq print('np =', np, 'nq =', nq) tt, ii, mm, xx, yy, zz = unpack_line(r, np, nq) tnext = tt if N > 0: # N trumps dt r = ll[nt-1].split() # last line tlast, dum, dum, dum, dum = unpack_line(r, np, nq) pdt = False if dt > 0: pdt = True dt = (tlast-tt)/N if pdt: print('resetting dt =', dt) t = [] i = [] m = [] x = [] y = [] z = [] line = 0 short = 0 for l in ll: r = l.split() line += 1 # Format is: time id1 m1 x1 y1 z1 id2 m2 x2 y2 z2 id3 m3 x3 y3 z3 ... if nq*np + 1 == len(r): # Save old data and unpack the line. tp = tt mp= mm xp = list(xx) yp = list(yy) zp = list(zz) tt, ii, mm, xx, yy, zz = unpack_line(r, np, nq) while tt >= tnext: if line == 1 or dt == 0.0: tint = tt mint = mm xint = list(xx) yint = list(yy) zint = list(zz) else: # Interpolate to time tnext. tint = tnext tfac = (tnext-tp)/(tt-tp) mint = interpolate(mp, mm, tfac) xint = interpolate(xp, xx, tfac) yint = interpolate(yp, yy, tfac) zint = interpolate(zp, zz, tfac) # Append the data to the master arrays. t.append(tint) i.append(ii) m.append(mint) x.append(xint) y.append(yint) z.append(zint) tnext += dt if dt == 0.0: break else: # temporary 2-body treatment #print 'ignoring short record:', len(r), '!=', 4*np+1 short += 1 ta = numpy.array(t) ia = numpy.array(i) ma = numpy.array(m) xa = numpy.array(x) # should be nt x np ya = numpy.array(y) za = numpy.array(z) nt = len(ta) print('nt =', nt) print(short, 'short records') #print 'xa.shape =', xa.shape # should be nt x np return nt, ta, ia, ma, xa, ya, za def print_help(): print('keyboard controls:') print(' space pause/resume') print(' a expand view to contain all particl;es') print(' h print this message') print(' q quit') print(' z zoom in') print(' Z zoom out') print(' right pan right') print(' left pan left') print(' up pan up') print(' down pan down') print(' < first frame') print(' > last frame') print('mouse click reverses direction') # We seem to need some of these global for the animate functions to work... nf = 0 df = 1 xmin = 0.0 xmax = 0.0 ymin = 0.0 ymax = 0.0 anim_running = True current_frame = 0 shift = 0.25 zoom = 1.5 def animate_data(t, m, x, y, id, lx, ly, scale, delay): global xmin, xmax, ymin, ymax print('animating data') colormap = ['r', 'y', 'b', 'm', 'g', 'c', 'k', 'k', 'k', 'k', 'k', 'k'] # Determine length scales. xmin = numpy.min(x[0,:]) xmax = numpy.max(x[0,:]) dx = xmax - xmin xav = 0.5*(xmin+xmax) ymin = numpy.min(y[0,:]) ymax = numpy.max(y[0,:]) dy = ymax - ymin yav = 0.5*(ymin+ymax) # Allow modification of overall scale by user-specified scale factor. dx = 5*max(dx, dy)*scale xmin = xav - 0.5*dx xmax = xav + 0.5*dx ymin = yav - 0.5*dx ymax = yav + 0.5*dx # Determine time scales. dtscale = t[-1] if t[0] < 0: dtscale = max(dtscale, -t[0]) nf = int(math.floor(math.log10(dtscale))) #print 'dtscale =', dtscale, 'nf =', nf if nf > 3: tformat = '%'+str(nf+2)+'.0f' elif nf > 0: tformat = '%'+str(nf+4)+'.2f' else: tformat = '%'+str(-nf+7)+'.'+str(-nf+4)+'f' lformat = tformat+'/'+tformat+' frame %d/%d' s = numpy.log(list(m[0,:])) smin = numpy.min(s) smax = numpy.max(s) s = 5 + 25*(s-smin)/(smax-smin) # sizes logarithmic in mass, range 5-30 print('s =', s) nt,np = x.shape fig = plt.figure() scat = plt.scatter(x[0,:], y[0,:], c=colormap[:np], s=s) #plt.axis('square') # fails in ubuntu plt.xlabel(lx) plt.ylabel(ly) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.grid() def update(frame): # What idiot decided that the syntax for set_offsets should # be so different from the syntax for scatter?? off = [] for j in range(np): off.append(x[frame,j]) off.append(y[frame,j]) scat.set_offsets(off) text = fig.suptitle('') text.set_text('') text.set_text('time '+lformat%(t[frame],t[-1], frame, nt-1)) return scat, def nextframe(nt): # step nf forward or backward by df global nf, df # stay fixed at nf = 0 or nt-1 global current_frame nf = 0 while nf < nt: current_frame = nf yield nf nf += df if nf < 0: nf = 0 if nf >= nt: nf = nt-1 def new_limits(x, y, fac): xmin = x.min() xmax = x.max() ymin = y.min() ymax = y.max() xm = 0.5*(xmin+xmax) dx = xmax - xm xmax = xm + fac*dx xmin = xm - fac*dx ym = 0.5*(ymin+ymax) dy = ymax - ym ymax = ym + fac*dy ymin = ym - fac*dy return xmin, xmax, ymin, ymax def onClick(event): # reverse direction on mouse click global nf, df df = -df def onKey(event): # manage key presses global anim_running global nf, df global xmin, xmax, ymin, ymax global current_frame global shift, zoom if event.key == 'a': # a = reset limits to current particles xmin, xmax, ymin, ymax = \ new_limits(x[current_frame], y[current_frame], 1.25) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) elif event.key == 'q': # q = quit sys.exit(0) elif event.key == 'z': # z = zoom in xm = 0.5*(xmin+xmax) dx = xmax - xm xmax = xm + dx/zoom xmin = xm - dx/zoom ym = 0.5*(ymin+ymax) dy = ymax - ym ymax = ym + dy/zoom ymin = ym - dy/zoom plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) elif event.key == 'Z': # Z = zoom out xm = 0.5*(xmin+xmax) dx = xmax - xm xmax = xm + dx*zoom xmin = xm - dx*zoom ym = 0.5*(ymin+ymax) dy = ymax - ym ymax = ym + dy*zoom ymin = ym - dy*zoom plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) elif event.key == ' ': # space = pause/restart if anim_running: anim.event_source.stop() anim_running = False else: anim.event_source.start() anim_running = True elif event.key == 'right': dx = shift*(xmax - xmin) xmax += dx xmin += dx plt.xlim(xmin, xmax) elif event.key == 'left': dx = shift*(xmax - xmin) xmax -= dx xmin -= dx plt.xlim(xmin, xmax) elif event.key == 'up': shift = 0.5 dy = shift*(ymax - ymin) ymax += dy ymin += dy plt.ylim(ymin, ymax) elif event.key == 'down': shift = 0.5 dy = shift*(ymax - ymin) ymax -= dy ymin -= dy plt.ylim(ymin, ymax) elif event.key == '<': nf = 0 df = 1 elif event.key == '>': nf = nt - 1 df = -1 elif event.key == 'h': print_help() else: print('key =', event.key) fig.canvas.mpl_connect('key_press_event', onKey) fig.canvas.mpl_connect('button_press_event', onClick) anim = animate.FuncAnimation(fig, update, frames=nextframe(nt), interval=delay, repeat=False) plt.show() def plot_data(t, x, lx, ly): nt,np = x.shape fig = plt.figure() plt.plot(t, x, 'b-') plt.xlabel(lx) plt.ylabel(ly) plt.grid() plt.show() def write_data(t, x, y, i, filename): nt,np = x.shape f = open(filename) for i in range(nt): s = str(t[i])+' ' for j in range(np): s += str(i(i,j))+' '+str(x(i,j))+' '+str(y(i,j))+' 0.0\n' f.write(s) f.close() if __name__ == '__main__': anim = True dt = 0.0 delay = 30 file = 'abc.dat' have_mass = True N = 0 outfile = None proj = 3 scale = 1.5 try: opts, args = getopt.getopt(sys.argv[1:], "ad:D:f:mN:o:p:s:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) for o, a in opts: if o == "-a": anim = not anim elif o == "-d": dt = float(a) elif o == "-D": delay = int(a) elif o == "-f": file = a elif o == "-m": have_mass = not have_mass elif o == '-N': N = int(a) elif o == "-o": outfile = a elif o == '-p': proj = int(a) elif o == "-s": scale = float(a) else: print("unexpected argument", o) sys.exit(1) nt, t, i, m, x, y, z = read_data(file, dt, N, have_mass) # Animate or plot the data. if anim: a1 = x a2 = y l1 = 'x' l2 = 'y' if proj == 1: a1 = y a2 = z l1 = 'y' l2 = 'z' elif proj == 2: a2 = z l2 = 'z' animate_data(t, m, a1, a2, i[:nt], l1, l2, scale, delay) else: plot_data(t, m, x, 't', 'x')
11,443
24.774775
78
py
amuse
amuse-main/src/amuse/community/ph4/util/initialize_system.py
import collections import getopt import numpy import os import random import sys import unittest import pickle from time import clock from time import gmtime from time import mktime from amuse.community.ph4.interface import ph4 as grav from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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 from amuse import io from utils import * def make_nbody(number_of_stars = 100, time = 0.0, n_workers = 1, use_gpu = 1, gpu_worker = 1, salpeter = 0, delta_t = 1.0 | nbody_system.time, timestep_parameter = 0.1, softening_length = 0.0 | nbody_system.length, random_seed = 1234): # Make an N-body system, print out some statistics on it, and save # it in a restart file. The restart file name is of the form # 't=nnnn.n.xxx', where the default time is 0.0. 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) init_smalln() # Note that there are actually three GPU options: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") except Exception as ex: gravity = grav(number_of_workers = n_workers, redirection = "none") else: gravity = grav(number_of_workers = n_workers, redirection = "none") gravity.initialize_code() gravity.parameters.set_defaults() #----------------------------------------------------------------- # Make a standard N-body system. 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") if salpeter == 0: print('equal masses') total_mass = 1.0 | nbody_system.mass scaled_mass = total_mass / number_of_stars else: print('salpeter mass function') mmin = 0.5 | nbody_system.mass mmax = 10.0 | nbody_system.mass scaled_mass = new_salpeter_mass_distribution_nbody(number_of_stars, mass_min = mmin, mass_max = mmax) stars.mass = scaled_mass print("centering stars") stars.move_to_center() print("scaling stars to virial equilibrium") stars.scale_to_standard(smoothing_length_squared = gravity.parameters.epsilon_squared) # Set dynamical radii (assuming virial equilibrium and standard # units). Note that this choice should be refined, and updated # as the system evolves. Probably the choice of radius should be # made entirely in the multiples module. TODO. In these units, # M = 1 and <v^2> = 0.5, so the mean 90-degree turnaround impact # parameter is # # b_90 = G (m_1+m_2) / vrel^2 # = 2 <m> / 2<v^2> # = 2 / N for equal masses # # Taking r_i = m_i / 2<v^2> = m_i in virial equilibrium means # that, approximately, "contact" means a 90-degree deflection (r_1 # + r_2 = b_90). A more conservative choice with r_i less than # this value will isolate encounters better, but also place more # load on the large-N dynamical module. stars.radius = 0.5*stars.mass.number | nbody_system.length time = 0.0 | nbody_system.time # print "IDs:", stars.id.number print("recentering stars") stars.move_to_center() sys.stdout.flush() #----------------------------------------------------------------- if softening_length < 0.0 | nbody_system.length: # Use ~interparticle spacing. Assuming standard units here. TODO softening_length = 0.5*float(number_of_stars)**(-0.3333333) \ | nbody_system.length print('softening length =', softening_length) gravity.parameters.timestep_parameter = timestep_parameter gravity.parameters.epsilon_squared = softening_length*softening_length gravity.parameters.use_gpu = use_gpu print('') print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) gravity.commit_particles() print('') print("number_of_stars =", number_of_stars) sys.stdout.flush() # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() # ----------------------------------------------------------------- # Create the coupled code and integrate the system to the desired # time, managing interactions internally. kep = init_kepler(stars[0], stars[1]) multiples_code = multiples.Multiples(gravity, new_smalln, kep) multiples_code.neighbor_perturbation_limit = 0.1 multiples_code.neighbor_veto = True print('') print('multiples_code.initial_scale_factor =', \ multiples_code.initial_scale_factor) print('multiples_code.neighbor_perturbation_limit =', \ multiples_code.neighbor_perturbation_limit) print('multiples_code.neighbor_veto =', \ multiples_code.neighbor_veto) print('multiples_code.final_scale_factor =', \ multiples_code.final_scale_factor) print('multiples_code.initial_scatter_factor =', \ multiples_code.initial_scatter_factor) print('multiples_code.final_scatter_factor =', \ multiples_code.final_scatter_factor) print('multiples_code.retain_binary_apocenter =', \ multiples_code.retain_binary_apocenter) print('multiples_code.wide_perturbation_limit =', \ multiples_code.wide_perturbation_limit) # Take a dummy step, just in case... multiples_code.evolve_model(time) # 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") pre = "%%% " E0,cpu0 = print_log(pre, time, multiples_code) sys.stdout.flush() # file = 't='+'{:07.2f}'.format(time.number) # fails in Python 2.6 file = 't=%07.2f'%time.number write_state_to_file(time, stars, gravity, multiples_code, file, delta_t, E0, cpu0) tree_copy = multiples_code.root_to_tree.copy() del multiples_code sys.stdout.flush() gravity.stop() kep.stop() stop_smalln() print('') if __name__ == '__main__': # Defaults: N = 1000 time = 0.0 | nbody_system.time delta_t = 1.0 | nbody_system.time n_workers = 1 use_gpu = 1 gpu_worker = 1 salpeter = 0 timestep_parameter = 0.1 softening_length = 0.0 | nbody_system.length random_seed = -1 try: opts, args = getopt.getopt(sys.argv[1:], "n:st:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) for o, a in opts: if o == "-n": N = int(a) elif o == "-s": salpeter = 1 elif o == "-t": time = float(a) | nbody_system.time else: print("unexpected argument", o) assert is_mpd_running() make_nbody(N, time, n_workers, use_gpu, gpu_worker, salpeter, delta_t, timestep_parameter, softening_length, random_seed)
8,274
30.949807
77
py
amuse
amuse-main/src/amuse/community/ph4/util/run_ph4.py
import collections import getopt import numpy import os import random import sys import pickle import math import unittest from time import clock from amuse.community.ph4.interface import ph4 as grav from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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 from amuse import io from utils import * def handle_callback (time, star1, star2): print('') print(' callback') print(' ', time) print(' ', star1) print(' ', star2) print('') return True # NOTE: returning False will skip this encounter def run_ph4(initial_file = None, end_time = 0 | nbody_system.time, input_delta_t = 0.0 | nbody_system.time, input_Delta_t = 1.0 | nbody_system.time, input_timestep_parameter = 0.0, input_softening_length = -1.0 | nbody_system.length, n_workers = 1, use_gpu = 1, gpu_worker = 1, use_multiples = True, save_restart = False, strict_restart = False ): # Read an N-body system from a file and run it to the specified # time using the specified steps. Print log information and # optionally save a restart file after every step. If the # specified time is less than the time in the initial file, don't # take a step, but still print out the log info. (Hence run_ph4 # also functions like Starlab sys_stats.) print("initial_file =", initial_file) print("end_time =", end_time.number) print("n_workers =", n_workers) print("use_gpu =", use_gpu) print("use_multiples =", use_multiples) print("save_restart =", save_restart) print("strict_restart =", strict_restart) print("\ninitializing the gravity module") sys.stdout.flush() init_smalln() # Note that there are actually three GPU options: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) if gpu_worker == 1: try: gravity = grav(number_of_workers = n_workers, redirection = "none", mode = "gpu") except Exception as ex: gravity = grav(number_of_workers = n_workers, redirection = "none") else: gravity = grav(number_of_workers = n_workers, redirection = "none") gravity.initialize_code() gravity.parameters.set_defaults() kep = Kepler(None, redirection = "none") kep.initialize_code() stars, time, delta_t, E0, cpu0, multiples_code \ = read_state_from_file(initial_file, gravity, kep) # Allow overrides of the restored data (OK for delta_t, NOT # recommended for timestep_parameter or softening_length). Note # that reading the state also commits the particles, and hence # calculates the initial time steps. Probably should reinitialize # if timestep_parameter or softening_length are changed. TODO if input_delta_t.number > 0: if input_delta_t != delta_t: print('modifying delta_t from stored', delta_t, \ 'to input', input_delta_t) delta_t = input_delta_t else: print("using stored delta_t =", delta_t) print(input_timestep_parameter) print(gravity.parameters.timestep_parameter) if input_timestep_parameter > 0: if input_timestep_parameter != gravity.parameters.timestep_parameter: print('modifying timestep_parameter from stored', \ gravity.parameters.timestep_parameter, \ 'to input', input_timestep_parameter) gravity.parameters.timestep_parameter \ = input_timestep_parameter else: print('timestep_parameter =', gravity.parameters.timestep_parameter) if input_softening_length.number >= 0: if input_softening_length*input_softening_length \ != gravity.parameters.epsilon_squared: print('modifying softening_length from stored', \ gravity.parameters.epsilon_squared.sqrt(), \ 'to input', input_softening_length) gravity.parameters.epsilon_squared \ = softening_length*softening_length else: print('softening length =', gravity.parameters.epsilon_squared.sqrt()) gravity.parameters.use_gpu = use_gpu gravity.parameters.begin_time = time if 0: print('') print(gravity.parameters.begin_time) print(stars.mass) #print stars.position for s in stars: print('%.18e %.18e %.18e' % (s.x.number, s.y.number, s.z.number)) print(stars.velocity) channel = gravity.particles.new_channel_to(stars) if use_multiples: stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() gravity.parameters.force_sync = 1 # end exactly at the specified time pre = "%%% " print_log(pre, time, multiples_code, E0, cpu0) tsave = time + Delta_t save_file = '' while time < end_time: time += delta_t multiples_code.evolve_model(time) #, callback=handle_callback) # 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") # Write log information. print_log(pre, time, multiples_code, E0, cpu0) sys.stdout.flush() # Optionally create a restart file. if save_restart and time >= tsave: #save_file = 't='+'{:07.2f}'.format(time.number) # not in Python 2.6 save_file = 't=%07.2f'%time.number write_state_to_file(time, stars, gravity, multiples_code, save_file, delta_t, E0, cpu0) sys.stdout.flush() tsave += Delta_t if strict_restart: break gravity.stop() kep.stop() stop_smalln() return time, save_file def print_help(): print("Options:") print(" -d set log output interval [1.0]") print(" -h print this help message") print(" -i set initial file name [t=0000.0]") print(" -m suppress multiples [False]") print(" -s save restart files [False]") print(" -t set final time [0.0]") if __name__ == '__main__': initial_file = 't=0000.0' t_end = 0.0 | nbody_system.time # default is to print log and exit delta_t = 0.0 | nbody_system.time # log output time scale Delta_t = 1.0 | nbody_system.time # restart output time scale Delta_t_set = False timestep_parameter = -1 softening_length = -1 | nbody_system.length n_workers = 1 use_gpu = 1 gpu_worker = 1 use_multiples = True save_restart = False strict_restart = False try: opts, args = getopt.getopt(sys.argv[1:], "d:D:hi:msSt:") except getopt.GetoptError as err: print(str(err)) sys.exit(1) for o, a in opts: if o == "-d": delta_t = float(a) | nbody_system.time elif o == "-D": Delta_t = float(a) | nbody_system.time Delta_t_set = True elif o == "-h": print_help() sys.exit(1) elif o == "-i": initial_file = a elif o == "-m": use_multiples = False elif o == "-s": save_restart = True elif o == "-S": strict_restart = True save_restart = True elif o == "-t": t_end = float(a) | nbody_system.time else: print("unexpected argument", o) print_help() sys.exit(1) if not save_restart: strict_restart = False if strict_restart: save_restart = True if not Delta_t_set: Delta_t = delta_t # Code implicitly assumes that delta_t and Delta_t are # commensurate. Check that here. if math.fmod(Delta_t.number, delta_t.number) != 0: x = math.floor(Delta_t/delta_t) Delta_t = x*delta_t print('reset Delta_t to', Delta_t) assert is_mpd_running() # In non-strict_mode, OK to let run_ph4 loop over steps. If # strict_restart is True, handle the loop here and force a new # restart at every step -- seems substantially slower, but # should be reproducible. if (not strict_restart): run_ph4(initial_file, t_end, delta_t, Delta_t, timestep_parameter, softening_length, n_workers, use_gpu, gpu_worker, use_multiples, save_restart, strict_restart) else: t = -1.0 | nbody_system.time while t < t_end: t, initial_file = run_ph4(initial_file, t_end, delta_t, Delta_t, timestep_parameter, softening_length, n_workers, use_gpu, gpu_worker, use_multiples, save_restart, strict_restart) delta_t = 0.0 | nbody_system.time timestep_parameter = -1 softening_length = -1 | nbody_system.length print('')
9,744
32.259386
80
py
amuse
amuse-main/src/amuse/community/ph4/util/utils.py
import collections import getopt import numpy import os import random import sys import pickle import numpy as np import unittest from time import clock from amuse.community.ph4.interface import ph4 as grav from amuse.community.smalln.interface import SmallN from amuse.community.kepler.interface import Kepler from amuse.couple import multiples from amuse.units import nbody_system from amuse.units import units from amuse.units import quantities from amuse import datamodel from amuse.datamodel import particle_attributes as pa 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 from amuse import io SMALLN = None def new_smalln(): SMALLN.reset() return SMALLN def init_smalln(): global SMALLN sys.stdout.flush() SMALLN = SmallN()#redirection='none') sys.stdout.flush() SMALLN.parameters.timestep_parameter = 0.1 #SMALLN.parameters.cm_index = 2001 # don't set this here!! sys.stdout.flush() def stop_smalln(): global SMALLN SMALLN.stop() def init_kepler(star1, star2): try: star1.mass.value_in(units.kg) # see if SI units, throw exception if not unit_converter \ = nbody_system.nbody_to_si(star1.mass + star2.mass, (star2.position-star1.position).length()) except Exception as ex: unit_converter = None kep = Kepler(unit_converter) # , redirection = "none") kep.initialize_code() return kep def print_binaries(pre, stars, kT, limit): # print all bound pairs with # binding energy >= limit*kT Emax = -(limit*kT).number m = np.array(stars.mass.number) pos = np.array(stars.position.number) vel = np.array(stars.velocity.number) n = len(stars) dx = np.zeros((n,3)) dv = np.zeros((n,3)) tiny = 1.e-12 Ntop = 0 Etop = 0.0 print('bound top-level pairs:') for i in range(n): dx[:,:] = pos[:,:] - pos[i,:] dv[:,:] = vel[:,:] - vel[i,:] dr2 = (dx**2).sum(axis=1) + tiny dr2i = 1./dr2 dr2i[i] = 0.0 mi = m[i] dpot = -(m+mi)*np.sqrt(dr2i) dpot[:i] = 0.0 dkin = 0.5*(dv**2).sum(axis=1) mu = mi*m/(mi+m) de = mu*(dpot + dkin) w = np.where(de < Emax) jw = np.arange(n)[w] if len(jw) > 0: for j in jw: print(' ', stars.id[i], stars.id[j], de[j]/kT.number, 'kT') Ntop += 1 Etop += de[j] if Ntop == 0: print('(none)') print('') print(pre, 'Ntop =', Ntop) print(pre, 'Etop =', Etop) print(pre, 'Etop/kT =', Etop/kT.number) def print_log(pre, time, gravity, E0 = 0.0 | nbody_system.energy, cpu0 = 0.0): cpu = clock() N = len(gravity.particles) M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy Etop = T + U Nmul, Nbin, Emul = gravity.get_total_multiple_energy() tmp1,tmp2,Emul2 = gravity.get_total_multiple_energy2() Etot = Etop + Emul Eext = gravity.multiples_external_tidal_correction Eint = gravity.multiples_internal_tidal_correction Eerr = gravity.multiples_integration_energy_error Edel = Eext + Eint + Eerr Ecor = Etot - Edel if E0 == 0 | nbody_system.energy: E0 = Ecor Rvir = -0.5*M*M/U Q = -T/U com = pa.center_of_mass(gravity.particles) comv = pa.center_of_mass_velocity(gravity.particles) # Hop complains if we have too few particles. dcen = com if N >= 100: dcen,rcore,rhocore \ = pa.densitycentre_coreradius_coredens(gravity.particles) cmx,cmy,cmz = dcen lagr,mf = pa.LagrangianRadii(gravity.particles, cm=dcen) # no units! print('') print(pre+"time=", time.number) print(pre+"CPU=", cpu - cpu0) print(pre+"Ntot=", N) print(pre+"mass=", M.number) print(pre+"Etot=", Etot.number) print(pre+"Etop=", Etop.number) print(pre+"Eext=", Eext.number) print(pre+"Eint=", Eint.number) print(pre+"Eerr=", Eerr.number) print(pre+"Edel=", Edel.number) print(pre+"Ecor=", Ecor.number) print(pre+"dE=", Ecor.number - E0.number) print(pre+"dE/E=", Ecor/E0 - 1) print(pre+"Rvir=", Rvir.number) print(pre+"Qvir=", Q) cmx,cmy,cmz = com print(pre+"cmpos[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) cmx,cmy,cmz = comv print(pre+"cmvel[3]= %.8f %.8f %.8f" % (cmx.number, cmy.number, cmz.number)) if N >= 100: cmx,cmy,cmz = dcen print(pre+"dcpos[3]= %.8f %.8f %.8f" \ % (cmx.number, cmy.number, cmz.number)) print(pre+"Rcore=", rcore.number) print(pre+"Mcore=", (rhocore*rcore**3).number) # fake... print(pre+"Mlagr[9]=", end=' ') for m in mf: print("%.4f" % (m), end=' ') print('') print(pre+"Rlagr[9]=", end=' ') for r in lagr.number: print("%.8f" % (r), end=' ') print('') kT = 2*T/(3.*N) # 3/2 N kT = total KE, by definition kT0 = -2*E0/(3.*N) print(pre+"kT= %.8f" % (kT.number)) Nmul,Nbin,Emul = gravity.print_multiples2(pre, kT, dcen) print(pre+"Nmul=", Nmul) print(pre+"Nbin=", Nbin) print(pre+"Emul= %.5f" % (Emul.number)) print(pre+"Emul2= %.5f" % (Emul2.number)) print(pre+"Emul/kT= %.5f" % (Emul/kT)) print(pre+"Emul/kT0= %.5f" % (Emul/kT0)) print(pre+"Emul/E= %.5f" % (Emul/Etot)) print('') stars = gravity.particles.copy() schannel = gravity.particles.new_channel_to(stars) schannel.copy_attribute("index_in_code", "id") print_binaries(pre, stars, kT, 0.1) sys.stdout.flush() return Ecor,cpu # Save code from Brewer... def write_state_to_file(time, stars_python, gravity_code, multiples_code, write_file=None, delta_t=1.0|nbody_system.time, E0_log=0.0, cpu0_log=0.0): # Function for saving everything. If you need to track more than # is normally saved, should be safe to tack it onto params. if write_file is not None: particles = gravity_code.particles.copy() write_channel = gravity_code.particles.new_channel_to(particles) write_channel.copy_attribute("index_in_code", "id") params = {'timestep_parameter': \ gravity_code.parameters.timestep_parameter, 'epsilon_squared': gravity_code.parameters.epsilon_squared, 'neighbor_veto': multiples_code.neighbor_veto, 'multiples_external_tidal_correction': \ multiples_code.multiples_external_tidal_correction, 'multiples_integration_energy_error': \ multiples_code.multiples_integration_energy_error, 'multiples_internal_tidal_correction': \ multiples_code.multiples_internal_tidal_correction, 'model_time': multiples_code.model_time, 'delta_t': delta_t, 'EZero': E0_log, 'CPUZero': cpu0_log, 'root_index': multiples.root_index } for root, tree in multiples_code.root_to_tree.items(): root_in_particles = root.as_particle_in_set(particles) subset = tree.get_tree_subset().copy() if root_in_particles is not None: root_in_particles.components = subset io.write_set_to_file(particles, write_file+".stars.hdf5", 'amuse', version='2.0', append_to_file=False, copy_history=False, close_file=True) io.write_set_to_file(stars_python, write_file+".stars_python.hdf5", 'amuse', version='2.0', append_to_file=False, copy_history=False, close_file=True) config = {'time': time, 'py_seed': pickle.dumps(random.getstate()), 'numpy_seed': pickle.dumps(numpy.random.get_state()), } with open(write_file + ".conf", "wb") as f: pickle.dump(config, f) f.close() with open(write_file + ".params", "wb") as f: pickle.dump(params, f) f.close() print("\nwrote state to file ", write_file, 'at time', time) # Restore code from Brewer. def read_state_from_file(restart_file, gravity_code, kep, MT=0): # Function to load from file. If you change params in # write_state_to_file, make sure you match the changes here. stars = io.read_set_from_file(restart_file+".stars.hdf5", 'amuse', version='2.0', close_file=True).copy() stars_python = io.read_set_from_file( restart_file+".stars_python.hdf5", 'amuse',version='2.0', close_file=True).copy() with open(restart_file + ".params", "rb") as f: params = pickle.load(f) f.close() if MT == 0: root_to_tree = {} for root in stars: if hasattr(root, 'components') and not root.components is None: root_to_tree[root] \ = datamodel.trees.BinaryTreeOnParticle(root.components[0]) else: root_to_tree = MT gravity_code.parameters.timestep_parameter = params['timestep_parameter'] gravity_code.parameters.epsilon_squared = params['epsilon_squared'] gravity_code.particles.add_particles(stars) gravity_code.commit_particles() # sets time steps multiples_code = multiples.Multiples(gravity_code, new_smalln, kep) multiples_code.neighbor_veto = params['neighbor_veto'] multiples_code.multiples_external_tidal_correction \ = params['multiples_external_tidal_correction'] multiples_code.multiples_integration_energy_error \ = params['multiples_integration_energy_error'] multiples_code.multiples_internal_tidal_correction \ = params['multiples_internal_tidal_correction'] multiples.root_index = params['root_index'] multiples_code.root_to_tree = root_to_tree print("\nread state from file ", restart_file, \ 'at time', params['model_time']) return stars_python, params['model_time'], params['delta_t'], \ params['EZero'], params['CPUZero'], multiples_code
10,630
33.516234
80
py
amuse
amuse-main/src/amuse/community/ph4/util/plotq.py
#!/usr/bin/env python import sys from math import log10, sqrt import numpy as np import matplotlib.pyplot as plt import string import re # Display a time sequence from a set of (not yet standard) AMUSE log # files. Files, colors, and styles should be separated by spaces. if __name__ == '__main__': # Command-line arguments and defaults: infiles = [] # -f [list] log = 0 # -L (sets log = 1) outfile = '' # -o filename or . quantities = [] # -q [list] layout = '' # -l (rows)x(cols) space = 0.3 # -S space # Separate the point colors and the line styles. Replicate the # last color/style in case of multiple files. colors = ['b','g','r','c','m','k'] # -c [list] ls = ['-'] # -s [list] # Parse the argument list the old-fashioned way to enable multiple # arguments (unaccountably not supported by getopt): i = 1 n = len(sys.argv) while i < n: if sys.argv[i][0] == '-': if len(sys.argv[i]) > 1: if sys.argv[i][1] == 'c': colors = [] # Accumulate colors until we find a leading '-' or # reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 colors.append(sys.argv[i]) elif sys.argv[i][1] == 'f': # Accumulate names until we find a leading '-' or # reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 infiles.append(sys.argv[i]) elif sys.argv[i][1] == 'L': log = 1 elif sys.argv[i][1] == 'l': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 layout = sys.argv[i] elif sys.argv[i][1] == 'o': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 outfile = sys.argv[i] elif sys.argv[i][1] == 'q': # Accumulate quantities until we find a leading # '-' or reach the end of the list. while i < n-1 and sys.argv[i+1][0] != '-': i += 1 quantities.append(sys.argv[i]) elif sys.argv[i][1] == 'S': if i < n-1 and sys.argv[i+1][0] != '-': i += 1 space = float(sys.argv[i]) elif sys.argv[i][1] == 's': ls = [] # Accumulate line styles until we find a leading # '-' or reach the end of the list. Problem: '-' # is a legal line style, so accept a lone '-' in # this case. while i < n-1 \ and (sys.argv[i+1][0] != '-' or len(sys.argv[i+1]) == 1): i += 1 ls.append(sys.argv[i]) else: print('unknown option', sys.argv[i]) i += 1 li = len(infiles) lq = len(quantities) if li == 0 or lq == 0: print('plotq -f file-list -q quantity-list') sys.exit(0) # Extend the color list if neessary. lc = len(colors) if lc < li: for i in range(li-lc): colors.append(colors[lc-1]) # Extend the line style list if necessary. lt = len(ls) if lt < li: for i in range(li-lt): ls.append(ls[lt-1]) plt.figure(figsize=(12,8)) plt.subplots_adjust(wspace=space, hspace=space) # Determine the plot layout (mxn). if layout == '': # Automatic. m = int(sqrt(float(lq))) if m*m < lq: m += 1 n = lq/m if m*n < lq: n += 1 else: # User-specified: m,n = layout.split('x') m = int(m) n = int(n) i = 100*m+10*n # assume m, n < 10 figs = [] for ii in range(lq): figs.append(plt.subplot(i+ii+1)) print('infiles: ', end=' ') for f in infiles: print(f, end=' ') print('') print('quantities: ', end=' ') for q in quantities: print(q, end=' ') print('') print('colors: ', end=' ') for ic in range(li): print(colors[ic], end=' ') print('') print('styles: ', end=' ') for i in range(li): print(ls[i], end=' ') print('') print(m, 'x', n, 'plot layout') ifile = 0 for infile in infiles: # loop over input files # Extract data from infile. tlist = [] qlist = [[] for iq in range(lq)] # list of lq empty lists nq = [1 for iq in range(lq)] # default qlist length f = open(infile, 'r') for line in f: # process data line by line if len(line) > 0: cols = line.split() if len(cols) > 0 and cols[0] == '%%%': if cols[1] == 'time=': tlist.append(float(cols[2])) else: foundq = False for iq in range(lq): if cols[1] == quantities[iq]+'=': foundq = True q = float(cols[2]) if log: q = log10(q) qlist[iq].append(q) if not foundq: for iq in range(lq): qq = quantities[iq] if re.search(qq+'\[.*\]'+'=', cols[1]): s = re.search(qq+'\[.*\]'+'=', cols[1]).group() # Messy! There must surely be a # better way to do this... i1 = string.index(s,'[') i2 = string.index(s,']') nq[iq] = int(s[i1+1:i2]) clist = [] for i in range(2,2+nq[iq]): q = float(cols[i]) if log: q = log10(q) clist.append(q) qlist[iq].append(clist) f.close() # Plot the data. for iq in range(lq): qq = quantities[iq] if len(qlist[iq]) > 0: if log: qq = 'log10 '+qq if nq[iq] == 1: figs[iq].plot(tlist, qlist[iq], colors[ifile]+ls[ifile]) else: qplot = np.array(qlist[iq]) for i in range(nq[iq]): figs[iq].plot(tlist, qplot[:,i], colors[ifile]+ls[ifile], linewidth=1.0) figs[iq].set_xlabel('time') figs[iq].set_ylabel(qq) else: print('No', qq, 'data to plot in '+infile+'.') ifile += 1 # Save to a file if specified; otherwise, display to the screen. if outfile == '': plt.show() else: if outfile == '.': qq = '' for iq in range(lq): if iq > 0: qq += '+' qq += quantities[iq] outfile = qq+'.pdf' outfile = outfile.replace('/','_') print('saving to', outfile) plt.savefig(outfile)
7,704
29.334646
76
py
amuse
amuse-main/src/amuse/community/hacs64/test_hacs.py
import collections import getopt import numpy import os import random import sys import unittest from amuse.community.hacs64.interface import Hacs64 as grav from amuse.units import nbody_system from amuse.units import units from amuse import datamodel from amuse.datamodel import particle_attributes from amuse.rfi.core import is_mpd_running from amuse.ic.plummer import new_plummer_model from amuse.ic.salpeter import new_salpeter_mass_distribution_nbody def print_log(time, gravity, E0 = 0.0 | nbody_system.energy): M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy Ebin = 0.0 | nbody_system.energy # gravity.get_binary_energy() Etop = T + U E = Etop + Ebin if E0 == 0 | nbody_system.energy: E0 = E Rv = -0.5*M*M/U Q = -T/U print("") print("time =", time.number, " energy = ", E.number, \ " dE/E0 = ", (E/E0 - 1)) print('%s %.4f %.6f %.6f %.6f %.6f %.6f %.6f %.6f' % \ ("%%", time.number, M.number, T.number, U.number, \ E.number, Ebin.number, Rv.number, Q)) sys.stdout.flush() return E def run_hacs(infile = None, number_of_stars = 128, nmax = 2048, end_time = 0.1 | nbody_system.time, delta_t = 0.125 | nbody_system.time, dt_max = 0.0625 | nbody_system.time, n_ngb = 16, eta_irr = 0.6, eta_reg = 0.1, softening_length = 0.0 | nbody_system.length): if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("nstars= ", number_of_stars, end=' ') print("nmax= ", nmax, end=' ') print("delta_t= ", delta_t.number) print("dt_max= ", dt_max.number) print("n_ngb= ", n_ngb, end=' ') print("eta_irr= ", eta_irr) print("eta_reg= ", eta_reg) print("eps2= ", softening_length.number**2) print("\ninitializing the gravity module") sys.stdout.flush() # gravity = grav(number_of_workers = 1, redirection = "none", mode='cpu') gravity = grav(number_of_workers = 1, redirection = "none", mode='cpu') gravity.initialize_code() #----------------------------------------------------------------- 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 = gravity.parameters.eps2) 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 print(len(mass), len(pos), len(vel), len(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 nmax = 2*len(mass) # print "IDs:", stars.id.number sys.stdout.flush() #----------------------------------------------------------------- gravity.parameters.nmax = nmax gravity.parameters.dtmax = dt_max # gravity.parameters.n_ngb = n_ngb; gravity.parameters.eta_irr = eta_irr gravity.parameters.eta_reg = eta_reg gravity.parameters.eps2 = softening_length**2 gravity.commit_parameters() print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) 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) stopping_condition = gravity.stopping_conditions.collision_detection stopping_condition.enable() # stopping_condition.disable() while time < end_time: if (gravity.get_time() >= time): time += delta_t 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. # this breaks the code ... channel.copy() # Copy values from the module to the set in memory. channel.copy_attribute("index_in_code", "id") # 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. if stopping_condition.is_set(): star1 = stopping_condition.particles(0)[0] star2 = stopping_condition.particles(1)[0] gravity.synchronize_model() print('\nstopping condition set at time', \ gravity.get_time().number,'for:\n') print(star1) print('') print(star2) print('') gravity.particles.remove_particle(star1) gravity.particles.remove_particle(star2) gravity.recommit_particles() print('ls=', len(stars)) gravity.update_particle_set() gravity.particles.synchronize_to(stars) print('ls=', len(stars)) 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(gravity.get_time(), gravity, E0) sys.stdout.flush() print('') print_log(gravity.get_time(), gravity, E0) sys.stdout.flush() gravity.stop() if __name__ == '__main__': infile = None N = 4009 dt_max = 0.0625 | nbody_system.time n_ngb = 16 eta_irr = 0.8 eta_reg = 0.14 eta_irr = 0.6 eta_reg = 0.1 t_end = 1.0 | nbody_system.time delta_t = 0.125 | nbody_system.time random_seed = -1 # random_seed = 123 # random_seed = 15345 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 == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) 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) Nmax = N*2 softening_length = 0.0/N | nbody_system.length assert is_mpd_running() run_hacs(infile, N, Nmax, t_end, delta_t, dt_max, n_ngb, eta_irr, eta_reg, softening_length)
9,186
29.121311
94
py
amuse
amuse-main/src/amuse/community/hacs64/test_multiples.py
import sys, unittest, numpy, random, collections, getopt, os, math from amuse.units import nbody_system from amuse.units import units from amuse.community.hacs64.interface import Hacs64 as grav 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 def is_a_parent(child1_key, child2_key): return child1_key > 0 or child2_key > 0 def is_not_a_child(is_a_child): return is_a_child == 0 def print_log(s, gravity, E0 = 0.0 | nbody_system.energy): M = gravity.total_mass U = gravity.potential_energy T = gravity.kinetic_energy try: Ebin = gravity.get_binary_energy() except: Ebin = 0 | nbody_system.energy Etop = T + U E = Etop + Ebin if E0 == 0 | nbody_system.energy: E0 = E Rv = -0.5*M*M/U Q = -T/U print("") print("%s: time = %.10f, mass = %.10f, dE/E0 = %.5e" \ % (s, gravity.get_time().number, M.number, (E/E0 - 1))) print("%senergies = %.10f %.10f %.10f" \ % (' '*(2+len(s)), E.number, U.number, T.number)) #print '%s %.4f %.6f %.6f %.6f %.6f %.6f %.6f %.6f' % \ # (s+"%%", time.number, M.number, T.number, U.number, \ # E.number, Ebin.number, Rv.number, Q.number) sys.stdout.flush() return E def get_component_binary_elements(comp1, comp2): kep = Kepler(redirection = "none") kep.initialize_code() mass = comp1.mass + comp2.mass pos = comp2.position - comp1.position vel = comp2.velocity - comp1.velocity kep.initialize_from_dyn(mass, pos[0], pos[1], pos[2], vel[0], vel[1], vel[2]) a,e = kep.get_elements() r = kep.get_separation() E,J = kep.get_integrals() # per unit reduced mass, note kep.stop() return mass,a,e,r,E def get_cm_binary_elements(p): return get_component_binary_elements(p.child1, p.child2) def run_smallN( particles, end_time = 1000 | nbody_system.time, delta_t = 10 | nbody_system.time, accuracy_parameter = 0.1 ): gravity = SmallN(redirection = "none") # , debugger="gdb") gravity.initialize_code() gravity.parameters.set_defaults() gravity.parameters.timestep_parameter = accuracy_parameter gravity.parameters.cm_index = 2001 gravity.commit_parameters() time = 0 | nbody_system.time print("\nadding particles to smallN") sys.stdout.flush() gravity.set_time(time) gravity.particles.add_particles(particles) print("committing particles to smallN") gravity.commit_particles() print("smallN: number_of_stars =", len(particles)) print("smallN: evolving to time =", end_time.number, end=' ') print("in steps of", delta_t.number) sys.stdout.flush() E0 = print_log('smallN', gravity) # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(particles) while time < end_time: time += delta_t print('evolving smallN to time', time.number) sys.stdout.flush() gravity.evolve_model(time) print_log('smallN', gravity, E0) over = gravity.is_over() if over.number: print('interaction is over\n'); sys.stdout.flush() # Create a tree in the module representing the binary structure. gravity.update_particle_tree() # Return the tree structure to AMUSE. Children are # identified by get_children_of_particle in interface.??, # and the information is returned in the copy operation. gravity.update_particle_set() gravity.particles.synchronize_to(particles) channel.copy() channel.copy_attribute("index_in_code", "id") gravity.stop() # Basic diagnostics: BinaryTreesOnAParticleSet creates # binary tree structure for all particles in the set; then # we loop over roots (top-level nodes) and print data on # all binaries below each. print("smallN binaries:"); sys.stdout.flush() x = trees.BinaryTreesOnAParticleSet(particles, "child1", "child2") roots = list(x.iter_roots()) for r in roots: for level, particle in r.iter_levels(): print(' '*level, int(particle.id.number), end=' ') if not particle.child1 is None: M,a,e,r,E = get_cm_binary_elements(particle) print(" mass = %.5e" % (M.number)) m1 = particle.child1.mass m2 = particle.child2.mass print_elements(' ', a, e, r, E*m1*m2/M) else: print('') sys.stdout.flush() return E0 sys.stdout.flush() gravity.stop() raise Exception("Did not finish the small-N simulation " +"before end time {0}".format(end_time)) root_index = 1000 def new_root_index(): global root_index root_index += 1 return root_index def openup_tree(star, stars, particles_in_encounter): # Create a binary tree for star. Note that star is in the memory # set, and so star and leaves all have IDs reflecting the naming in # the dynamics module. root = trees.BinaryTreeOnParticle(star, 'child1', 'child2') # List the leaves. leaves = root.get_descendants_subset() # Compare with the position stored when replacing the particles # with the root particle, and move the particles accordingly. # Note that once the CM is in the gravity module, the components # are frozen and the coordinates are absolute, so we need the # original coordinates to offset them later. # Better just to store relative coordinates. TODO. dx = star.x - star.original_x dy = star.y - star.original_y dz = star.z - star.original_z dvx = star.vx - star.original_vx dvy = star.vy - star.original_vy dvz = star.vz - star.original_vz leaves.x += dx leaves.y += dy leaves.z += dz leaves.vx += dvx leaves.vy += dvy leaves.vz += dvz particles_in_encounter.add_particles(leaves) # Remove the inner (CM) binary tree nodes from the stars list. # New ones will be added later as necessary. stars.remove_particles(root.get_inner_nodes_subset()) def sep2(star1, star2): # squared separation of star1 and star2 return ((star1.position-star2.position).number**2).sum() def sep(star1, star2): # separation of star1 and star2 return math.sqrt(sep2(star1, star2)) def phi_tidal(star1, star2, star3): # compute tidal potential of # (star1,star2) relative to star3 phi13 = -star1.mass*star3.mass/sep(star1,star3) phi23 = -star2.mass*star3.mass/sep(star2,star3) m12 = star1.mass + star2.mass f1 = star1.mass/m12 cmx = (f1*star1.x+(1-f1)*star2.x).number cmy = (f1*star1.y+(1-f1)*star2.y).number cmz = (f1*star1.z+(1-f1)*star2.z).number phicm = -m12*star3.mass/math.sqrt((star3.x.number-cmx)**2 + (star3.y.number-cmy)**2 + (star3.z.number-cmz)**2) return (phi13+phi23-phicm).number def find_nnn(star1, star2, stars): # print next nearest neighbor # of (star1, star2) top_level = stars.select(is_not_a_child, ["is_a_child"]) min_dr = 1.e10 id1 = star1.id.number id2 = star2.id.number for t in top_level: tid = t.id.number if tid != id1 and tid != id2: dr2 = sep2(t, star1) if dr2 > 0 and dr2 < min_dr: min_dr = dr2 nnn = t min_dr = math.sqrt(min_dr) print('star =', int(id1), ' min_dr =', min_dr, \ ' nnn =', int(nnn.id.number), '(', nnn.mass.number, ')') print(' phi_tidal =', phi_tidal(star1, star2, nnn)) print(' nnn pos:', nnn.x.number, nnn.y.number, nnn.z.number) sys.stdout.flush() return nnn def total_energy(slist): # Return the total energy of the particles in slist, in the center # of mass approximation. kinetic = 0.0 potential = 0.0 for s in slist: # print 'slist:', int(s.id.number) smass = s.mass.number spos = s.position.number svel = s.velocity.number kinetic += smass*((svel**2).sum()) spot = 0.0 for ss in slist: if not ss == s: ssmass = ss.mass.number sspos = ss.position.number r = math.sqrt(((sspos-spos)**2).sum()) # print int(s.id.number), int(ss.id.number), r spot -= ssmass/r potential += smass*spot kinetic /= 2 potential /= 2 # print 'kin, pot:', kinetic, potential return kinetic+potential def relative_potential(slist, klist, stars): # Return the total potential energy of slist relative to stars # (excluding klist). potential = 0.0 top_level = stars.select(is_not_a_child, ["is_a_child"]) for t in top_level: tpot = 0.0 skip = 0 for s in klist: if s == t: skip = 1 break if skip == 0: tpos = t.position.number for s in slist: dpos = s.position.number - tpos tpot -= s.mass.number/ math.sqrt((dpos*dpos).sum()) potential += t.mass.number*tpot return potential def offset_particle_tree(particle, dpos, dvel): # Recursively offset a particle and all of its descendants by # the specified position and velocity. if not particle.child1 is None: offset_particle_tree(particle.child1, dpos, dvel) if not particle.child2 is None: offset_particle_tree(particle.child2, dpos, dvel) particle.position += dpos particle.velocity += dvel # print 'offset', int(particle.id.number), 'by', dpos; sys.stdout.flush() def compress_binary_components(comp1, comp2, scale): # Compress the two-body system consisting of comp1 and comp2 to # lie within distance scale of one another. pos1 = comp1.position pos2 = comp2.position sep12 = ((pos2-pos1)**2).sum() if sep12 > scale*scale: print('\ncompressing components', int(comp1.id.number), \ 'and', int(comp2.id.number), 'to separation', scale.number) sys.stdout.flush() mass1 = comp1.mass mass2 = comp2.mass total_mass = mass1 + mass2 vel1 = comp1.velocity vel2 = comp2.velocity cmpos = (mass1*pos1+mass2*pos2)/total_mass cmvel = (mass1*vel1+mass2*vel2)/total_mass # For now, create and delete a temporary kepler # process to handle the transformation. Obviously # more efficient to define a single kepler at the # start of the calculation and reuse it. kep = Kepler(redirection = "none") kep.initialize_code() mass = comp1.mass + comp2.mass rel_pos = pos2 - pos1 rel_vel = vel2 - vel1 kep.initialize_from_dyn(mass, rel_pos[0], rel_pos[1], rel_pos[2], rel_vel[0], rel_vel[1], rel_vel[2]) M,th = kep.get_angles() a,e = kep.get_elements() if e < 1: peri = a*(1-e) apo = a*(1+e) else: peri = a*(e-1) apo = 2*a # OK - used ony to reset scale limit = peri + 0.01*(apo-peri) if scale < limit: scale = limit if M < 0: # print 'approaching' kep.advance_to_periastron() kep.advance_to_radius(limit) else: # print 'receding' if kep.get_separation() < scale: kep.advance_to_radius(limit) else: kep.return_to_radius(scale) # a,e = kep.get_elements() # r = kep.get_separation() # E,J = kep.get_integrals() # print 'kepler: a,e,r =', a.number, e.number, r.number # print 'E, J =', E, J # Note: if periastron > scale, we are now just past periastron. new_rel_pos = kep.get_separation_vector() new_rel_vel = kep.get_velocity_vector() kep.stop() # Enew = 0 # r2 = 0 # for k in range(3): # Enew += 0.5*(new_rel_vel[k].number)**2 # r2 += (new_rel_pos[k].number)**2 # rnew = math.sqrt(r2) # Enew -= mass.number/r1 # print 'E, Enew, rnew =', E.number, E1, r1 # Problem: the vectors returned by kepler are lists, # not numpy arrays, and it looks as though we can say # comp1.position = pos, but not comp1.position[k] = # xxx, as we'd like... Also, we don't know how to # copy a numpy array with units... TODO newpos1 = pos1 - pos1 # stupid trick to create zero vectors newpos2 = pos2 - pos2 # with the proper form and units... newvel1 = vel1 - vel1 newvel2 = vel2 - vel2 frac2 = mass2/total_mass for k in range(3): dxk = new_rel_pos[k] dvk = new_rel_vel[k] newpos1[k] = cmpos[k] - frac2*dxk newpos2[k] = cmpos[k] + (1-frac2)*dxk newvel1[k] = cmvel[k] - frac2*dvk newvel2[k] = cmvel[k] + (1-frac2)*dvk # Perform the changes to comp1 and comp2, and recursively # transmit them to the (currently absolute) coordinates of # all lower components. offset_particle_tree(comp1, newpos1-pos1, newvel1-vel1) offset_particle_tree(comp2, newpos2-pos2, newvel2-vel2) def print_elements(s, a, e, r, E): print('%s elements a = %.4e e = %.5f r = %.4e E = %.4e' \ % (s, a.number, e.number, r.number, E.number)) def print_multiple(m, level=0): # Recursively print the structure of (multipe) node m. print(' '*level, int(m.id.number), ' mass =', m.mass.number) print(' '*level, 'pos =', m.position.number) print(' '*level, 'vel =', m.velocity.number) if not m.child1 is None and not m.child2 is None: M,a,e,r,E = get_component_binary_elements(m.child1, m.child2) print_elements(' '+' '*level+'binary', a, e, r, (E*m.child1.mass*m.child2.mass/M)) if not m.child1 is None: print_multiple(m.child1, level+1) if not m.child2 is None: print_multiple(m.child2, level+1) def print_pair_of_stars(s, star1, star2): m1 = star1.mass m2 = star2.mass M,a,e,r,E = get_component_binary_elements(star1, star2) print_elements(s, a, e, r, E*m1*m2/(m1+m2)) print_multiple(star1) print_multiple(star2) def scale_top_level_list(binaries, scale, stars, klist, phi_external_init): # The smallN particles were followed until their interaction could # be unambiguously classified as over. They may now be very far # apart. Input binaries is an object describing the final # hierarchical structure of the interacting particles in smallN. # It consists of a flat tree of binary trees. # Scale the positions and velocities of the top-level nodes to # bring them within a sphere of diameter scale, conserving energy # and angular momentum (if possible). Also offset all children to # reflect changes at the top level -- TODO will change when # offsets are implemented... # We are currently ignoring any possibility of a physical # collision during the smallN encounter. TODO # Logic: 1 node - must be a binary, use kepler to reduce to scale # 2 nodes - use kepler, reduce binary children too? TODO # 3+ nodes - shrink radii and rescale velocities to preserve # energy, but this doesn't preserve angular # momentum TODO - also reduce children? TODO # TODO # Figure out the tree structure. singles = binaries.particles_not_in_a_multiple() multiples = binaries.roots() top_level_nodes = singles + multiples ls = len(singles) lm = len(multiples) lt = ls + lm if lt == 1: if lm == 1: # Special case. We have a single bound binary node. Its # children are the components we want to transform. Note # that, if the components are binaries (or multiples), # they must be stable, so it is always OK to move the # components to periastron. root = multiples[0] print('\nunscaled binary node:') print_multiple(root) comp1 = root.child1 comp2 = root.child2 compress_binary_components(comp1, comp2, scale) print('\nscaled binary node:') print_multiple(root) elif lt == 2: # We have two unbound top-level nodes, and we will scale them # using kepler to the desired separation, hence conserving # both energy and angular momentum of the top-level motion. # We might also want to scale the daughter nodes. Note as # above that, if the daughters are binaries (or multiples), # they must be stable, so it is always OK to move them to # periastron. comp1 = top_level_nodes[0] comp2 = top_level_nodes[1] print('\nunscaled top-level pair:') print_pair_of_stars('pair', comp1, comp2) compress_binary_components(comp1, comp2, scale) print('\nscaled top-level pair:') print_pair_of_stars('pair', comp1, comp2) else: # Now we have three or more top-level nodes. We don't know # how to compress them in a conservative way. For now, we # will conserve energy and think later about how to preserve # angular momentum. TODO print(lt, 'top-level nodes'); sys.stdout.flush() # Recompute the external field, compute the tidal error, and # absorb it into the top-level energy. Optional code. # Alternatively, we can simply absorb the tidal error into the # dEmult correction returned for bookkeeping purposes. dEmult = 0.0 phi_external_final = relative_potential(top_level_nodes, klist, stars) print('phi_external_final =', phi_external_final) dphi = phi_external_final - phi_external_init print('dphi =', dphi) # Correction code parallels that above, but we must repeat it # here, since we have to complete the rescaling before the # tidal correction can be computed and applied. if lt == 1: # Only one top-level node. Don't apply any correction. # Instead, always include the tidal term in dEmult. dEmult += dphi elif lt == 2: # Absorb dphi into the relative motion of the top-level nodes, # using kepler. Alternatively, add dphi to dEmult. comp1 = top_level_nodes[0] comp2 = top_level_nodes[1] dEmult += dphi else: # Absorb dphi into the relative motion of the top-level nodes, # simply by scaling their velocities. Need to improve this. # TODO Alternatively, add dphi to dEmult. print(lt, 'top-level nodes'); sys.stdout.flush() dEmult += dphi # Finally, include the internal top-level energy in dEmult. etot = total_energy(top_level_nodes) print('final etot =', etot) dEmult += etot return dEmult def manage_encounter(star1, star2, stars, gravity_stars): # Manage an encounter between star1 and star2. stars is the # python memory data set. gravity_stars points to the gravity # module data. Return value is the energy correction due to # multiples. # Establish child flags for use during the encounter calculation. stars.is_a_child = 0|units.none parents = stars.select(is_a_parent, ["child1", "child2"]) for s in stars: for p in parents: if p.child1 == s or p.child2 == s: s.is_a_child = 1|units.none # Currently we don't include neighbors in the integration and the # size limitation on any final multiple is poorly implemented. print('\nin manage_encounter'); sys.stdout.flush() # 1. Star1 and star2 reflect the data in the gravity module. Find # the corresponding particles in the local particle set. star1_in_memory = star1.as_particle_in_set(stars) # pointers star2_in_memory = star2.as_particle_in_set(stars) # 1a. Copy the current position and velocity to mememory (need to # create a better call for this, for example: # star1.copy_to(star1_in_memory) star1_in_memory.position = star1.position star1_in_memory.velocity = star1.velocity star2_in_memory.position = star2.position star2_in_memory.velocity = star2.velocity # Basic diagnostics: print_pair_of_stars('**encounter**', star1_in_memory, star2_in_memory) print('') find_nnn(star1_in_memory, star2_in_memory, stars) find_nnn(star2_in_memory, star1_in_memory, stars) # 1b. Calculate the potential of [star1, star2] relative to the # other top-level objects in the stars list (later: just use # neighbors TODO). Start the correction of dEmult by removing # the initial top-level energy of the interacting particles # from it. (Add in the final energy later, on return from # scale_top_level_list.) slist = [star1_in_memory, star2_in_memory] etot = total_energy(slist) print('initial etot =', etot) dEmult = -etot klist = [star1_in_memory, star2_in_memory] phi_external_init = relative_potential(slist, klist, stars) print('phi_external_init =', phi_external_init) # 2. Create a particle set to perform the close encounter # calculation. particles_in_encounter = datamodel.Particles(0) # 3. Add stars to the encounter set, add in components when we # encounter a binary. if not star1_in_memory.child1 is None: openup_tree(star1_in_memory, stars, particles_in_encounter) else: particles_in_encounter.add_particle(star1_in_memory) if not star2_in_memory.child1 is None: openup_tree(star2_in_memory, stars, particles_in_encounter) else: particles_in_encounter.add_particle(star2_in_memory) # particles_in_encounter.id = -1 | units.none # need to make this -1 to # ensure smallN will set the # IDs, or else smallN seems # to fail... TODO # *** Desirable to propagate the IDs into smallN, for internal # *** diagnostic purposes... # print 'particles in smallN encounter:' # print particles_in_encounter.to_string(['x','y','z', # 'vx','vy','vz','mass','id']) print('\nparticles in encounter (flat tree):') for p in particles_in_encounter: print_multiple(p) initial_scale \ = math.sqrt(((star1.position -star2.position).number**2).sum())|nbody_system.length print('initial_scale =', initial_scale.number); sys.stdout.flush() # 4. Run the small-N encounter in the center of mass frame. # Probably desirable to make this a true scattering experiment by # separating star1 and star2 to a larger distance before starting # smallN. TODO total_mass = star1.mass+star2.mass cmpos = (star1.mass*star1.position+star2.mass*star2.position)/total_mass cmvel = (star1.mass*star1.velocity+star2.mass*star2.velocity)/total_mass print('CM KE =', 0.5*total_mass.number*((cmvel.number)**2).sum()) for p in particles_in_encounter: p.position -= cmpos p.velocity -= cmvel run_smallN(particles_in_encounter) for p in particles_in_encounter: p.position += cmpos p.velocity += cmvel # print 'after smallN:' # print particles_in_encounter.to_string(['x','y','z', # 'vx','vy','vz', # 'mass', 'id']) # sys.stdout.flush() # 5. Carry out bookkeeping after the encounter and update the # gravity module with the new data. # 5a. Remove star1 and star2 from the gravity module. gravity_stars.remove_particle(star1) gravity_stars.remove_particle(star2) # 5b. Create an object to handle the new binary information. binaries = trees.BinaryTreesOnAParticleSet(particles_in_encounter, "child1", "child2") # 5bb. Compress the top-level nodes before adding them to the # gravity code. Also recompute the external potential and # absorb the tidal error into the top-level nodes of the # encounter list. Fially, add the change in top-level energy # of the interacting subset into dEmult, so E(hacs64) + dEmult # should be conserved. dEmult += scale_top_level_list(binaries, initial_scale, stars, klist, phi_external_init) # 5c. Update the positions and velocities of the stars (leaves) in # the encounter; copy the position and velocity attributes of # all stars updated during the encounter to the stars particle # set in memory. Do not copy child or any other attributes. tmp_channel = particles_in_encounter.new_channel_to(stars) tmp_channel.copy_attributes(['x','y','z', 'vx', 'vy', 'vz']) # 5d. Add stars not in a binary to the gravity code. stars_not_in_a_multiple = binaries.particles_not_in_a_multiple() stars_not_in_a_multiple_in_stars = \ stars_not_in_a_multiple.get_intersecting_subset_in(stars) if len(stars_not_in_a_multiple_in_stars) > 0: gravity_stars.add_particles(stars_not_in_a_multiple_in_stars) # 5e. Add the inner (CM) nodes (root plus subnodes) to the stars # in memory (the descendant nodes are already part of the # set). for root in binaries.iter_roots(): stars_in_a_multiple = root.get_descendants_subset() # print 'root.get_inner_nodes_subset():' # print root.get_inner_nodes_subset(); sys.stdout.flush() stars.add_particles(root.get_inner_nodes_subset()) # 5f. Add roots of the binaries tree to the gravity code. # Must set radii to reflect multiple structure. TODO for root in binaries.iter_roots(): root_in_stars = root.particle.as_particle_in_set(stars) root_in_stars.id = new_root_index() # print 'root_in_stars:' # print root_in_stars; sys.stdout.flush(); sys.stdout.flush() gravity_stars.add_particle(root_in_stars) # 5g. Store the original position and velocity of the root so that # the subparticle position can be updated later. for root in binaries.iter_roots(): root_in_stars = root.particle.as_particle_in_set(stars) # Save root position and velocity so we can update the # position and velocity of the components when we open up the # binary tree. root_in_stars.original_x = root_in_stars.x root_in_stars.original_y = root_in_stars.y root_in_stars.original_z = root_in_stars.z root_in_stars.original_vx = root_in_stars.vx root_in_stars.original_vy = root_in_stars.vy root_in_stars.original_vz = root_in_stars.vz return dEmult def print_energies(stars): # Brute force N^2 over top level, pure python... top_level = stars.select(is_not_a_child, ["is_a_child"]) mass = 0 kinetic = 0 potential = 0 for t in top_level: m = t.mass.number x = t.x.number y = t.y.number z = t.z.number vx = t.vx.number vy = t.vy.number vz = t.vz.number mass += m kinetic += 0.5*m*(vx**2+vy**2+vz**2) dpot = 0 for tt in top_level: if tt != t: mm = tt.mass.number xx = tt.x.number-x yy = tt.y.number-y zz = tt.z.number-z dpot -= mm/math.sqrt(xx**2+yy**2+zz**2) potential += 0.5*m*dpot print('len(stars) =', len(stars)) print('len(top_level) =', len(top_level)) print('mass =', mass) print('kinetic =', kinetic) print('potential =', potential) print('energy =', kinetic+potential) sys.stdout.flush() def run_multiples(infile = None, number_of_stars = 64, nmax = 2048, end_time = 0.1 | nbody_system.time, delta_t = 0.125 | nbody_system.time, dt_max = 0.0625 | nbody_system.time, n_ngb = 16, eta_irr = 0.6, eta_reg = 0.1, softening_length = 0.0 | nbody_system.length, random_seed = 1234): if infile != None: print("input file =", infile) print("end_time =", end_time.number) print("nstars= ", number_of_stars, end=' ') print("nmax= ", nmax, end=' ') print("delta_t= ", delta_t.number) print("dt_max= ", dt_max.number) print("n_ngb= ", n_ngb, end=' ') print("eta_irr= ", eta_irr) print("eta_reg= ", eta_reg) print("eps2= ", softening_length.number**2) print("\ninitializing the gravity module") sys.stdout.flush() 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) # Note that there are actually three GPU options to test: # # 1. use the GPU code and allow GPU use (default) # 2. use the GPU code but disable GPU use (-g) # 3. use the non-GPU code (-G) gravity = grav(number_of_workers = 1, debugger="none", redirection = "none") gravity.initialize_code() #----------------------------------------------------------------- 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 ** 2) time = 0.0 | nbody_system.time sys.stdout.flush() else: # Read the input data. Units are dynamical. print("reading file", infile); sys.stdout.flush() 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])) id.append(count) 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 nmax = 2*len(mass) # print "IDs:", stars.id.number sys.stdout.flush() global root_index root_index = len(stars) + 10000 #----------------------------------------------------------------- gravity.parameters.nmax = nmax gravity.parameters.dtmax = dt_max # gravity.parameters.n_ngb = n_ngb; gravity.parameters.eta_irr = eta_irr gravity.parameters.eta_reg = eta_reg gravity.parameters.eps2 = softening_length**2 gravity.commit_parameters() print("adding particles") # print stars sys.stdout.flush() gravity.particles.add_particles(stars) 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('hacs64', gravity) dEmult = 0.0 # Channel to copy values from the code to the set in memory. channel = gravity.particles.new_channel_to(stars) stopping_condition = gravity.stopping_conditions.collision_detection #stopping_condition.enable() # Tree structure on the stars dataset: stars.child1 = 0 | units.object_key stars.child2 = 0 | units.object_key while time < end_time: time += delta_t while gravity.get_time() < time: gravity.evolve_model(time) if stopping_condition.is_set(): star1 = stopping_condition.particles(0)[0] star2 = stopping_condition.particles(1)[0] print('\n--------------------------------------------------') print('stopping condition set at time', \ gravity.get_time().number) E = print_log('hacs64', gravity, E0) print('dEmult =', dEmult, 'dE =', (E-E0).number-dEmult) # channel.copy() # need other stars to be current in memory # print_energies(stars) # Synchronize everything for now. Later we will just # synchronize neighbors if gravity supports that. TODO gravity.synchronize_model() gravity.particles.synchronize_to(stars) dEmult += manage_encounter(star1, star2, stars, gravity.particles) # Recommit reinitializes all particles (and redundant # here, since done automatically). Later we will just # recommit and reinitialize a list if gravity supports # it. TODO gravity.recommit_particles() E = print_log('hacs64', gravity, E0) print('dEmult =', dEmult, 'dE =', (E-E0).number-dEmult) print('\n--------------------------------------------------') ls = len(stars) # 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() E = print_log('hacs64', gravity, E0) print('dEmult =', dEmult, 'dE =', (E-E0).number-dEmult) print('') gravity.stop() if __name__ == '__main__': infile = None N = 1024 dt_max = 0.0625 | nbody_system.time n_ngb = 16 eta_irr = 0.8 eta_reg = 0.14 # eta_irr = 0.6 # eta_reg = 0.1 t_end = 1.0 | nbody_system.time delta_t = 0.125 | nbody_system.time random_seed = -1 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 == "-c": manage_encounters = int(a) elif o == "-d": delta_t = float(a) | nbody_system.time elif o == "-e": softening_length = float(a) | nbody_system.length elif o == "-f": infile = a elif o == "-g": use_gpu = 0 elif o == "-G": use_gpu = 0 gpu_worker = 0 elif o == "-n": N = int(a) elif o == "-s": random_seed = int(a) elif o == "-t": t_end = float(a) | nbody_system.time elif o == "-w": n_workers = int(a) else: print("unexpected argument", o) Nmax = N*2 softening_length = 0.0/N | nbody_system.length assert is_mpd_running() run_multiples(infile, N, Nmax, t_end, delta_t, dt_max, n_ngb, eta_irr, eta_reg, softening_length, random_seed)
37,750
33.857802
80
py
amuse
amuse-main/src/amuse/community/hacs64/__init__.py
# generated file from .interface import Hacs64
47
15
29
py
amuse
amuse-main/src/amuse/community/hacs64/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. Since # *** interface.cc has been hand-coded to implement the details, # *** MAKE SURE TO SAVE IT SOMEWHERE, as build.py can overwrite it! class Hacs64Interface(CodeInterface, GravitationalDynamicsInterface, StoppingConditionInterface): """ HACS64, GPU-accelerated Hermite Ahmad-Cohen Scheme 6th order irregular & 4th order regular step """ # Interface specification. include_headers = ['interface.h', 'stopcond.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_muse_worker(mode), **options ) # Inheritance from GravitationalDynamicsInterface means that # functions in the standard interface don't need to be defined. # See interface.py.2 for a laboriously hand-coded version written # before I discovered this fact! (Steve McMillan, 10/10) # Additional functions defined here will be reflected in # interface.h and must be provided in interface.cc in order for # ph4_worker to build. # The following functions aren't defined in the default interface: def name_of_the_muse_worker(self, mode): if mode == self.MODE_CPU: return 'hacs64_worker' elif mode == self.MODE_GPU: return 'hacs64_worker_gpu' else: return 'hacs64_worker' @legacy_function def get_number_of_particles_updated(): """ Return the number of particles added or deleted 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_updated_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.addParameter('kind_of_update', dtype='int32', direction=function.OUT, description = 'kind of update (2, addition), (1, deletion)') function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def set_nmax(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('nmax', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nmax(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('nmax', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtmax(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('dtmax', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtmax(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('dtmax', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_h2max(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('h2max', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_h2max(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('h2max', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eta_reg(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta_reg', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta_reg(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta_reg', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_eta_irr(): """ Set the current time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta_irr', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_eta_irr(): """ Set the current system time step parameter. """ function = LegacyFunctionSpecification() function.addParameter('eta_irr', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function class Hacs64(GravitationalDynamics): # The actual module. def __init__(self, convert_nbody = None, **keyword_arguments): legacy_interface = Hacs64Interface(**keyword_arguments) self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **keyword_arguments) def define_parameters(self, handler): # Set/get parameters specific to the module, not part of the # standard interface. Accessors used here must be defined # above and reflected in interface.cc. Python access is # (e.g.) # # ph4.parameters.timestep_parameter = xxx handler.add_method_parameter( "get_nmax", # getter name in interface.cc "set_nmax", # setter name in interface.cc "nmax", # python parameter name "maximal number of particles", # description default_value = -1 # default ) handler.add_method_parameter( "get_dtmax", # getter name in interface.cc "set_dtmax", # setter name in interface.cc "dtmax", # python parameter name "maximal timestep", # description default_value = 0.0625 | nbody_system.time # default ) handler.add_method_parameter( "get_h2max", # getter name in interface.cc "set_h2max", # setter name in interface.cc "h2max", # python parameter name "maximal neighbour radius squared", # description default_value = 0.5 | nbody_system.length*nbody_system.length # default ) handler.add_method_parameter( "get_eta_reg", # getter name in interface.cc "set_eta_reg", # setter name in interface.cc "eta_reg", # python parameter name "regular timestep parameter", # description default_value = 0.1 # default ) handler.add_method_parameter( "get_eta_irr", # getter name in interface.cc "set_eta_irr", # setter name in interface.cc "eta_irr", # python parameter name "irregular timestep parameter", # description default_value = 0.6 ) handler.add_method_parameter( "get_eps2", # already defined in standard interface "set_eps2", # already defined in standard interface "eps2", # python parameter name "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 ) self.stopping_conditions.define_parameters(handler) 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 == 0: return indices_in_update_list = list(range(number_of_updated_particles)) particle_indices, updates = self.get_id_of_updated_particle(indices_in_update_list) incode_storage = self.particles._private.attribute_storage indices_to_remove = [] indices_to_add = [] for index, status in zip(particle_indices, updates): if status == 1: # deletion indices_to_remove.append(index) elif status == 2: # addition indices_to_add.append(index) print('') print("indices_to_remove:", indices_to_remove) print("indices_to_add:", indices_to_add) if len(indices_to_remove) > 0: incode_storage._remove_indices(indices_to_remove) if len(indices_to_add) > 0: incode_storage._add_indices(indices_to_add) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) # Similarly, we can add module-specific methods, if desired. # See hermite0/interface.py for examples. handler.add_method("get_nmax", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_nmax", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_dtmax", (), (nbody_system.time, handler.ERROR_CODE,)) handler.add_method("set_dtmax", (nbody_system.time, ), (handler.ERROR_CODE,)) handler.add_method("get_h2max", (), (nbody_system.length*nbody_system.length, handler.ERROR_CODE,)) handler.add_method("set_h2max", (nbody_system.length*nbody_system.length, ), (handler.ERROR_CODE,)) handler.add_method("get_eta_irr", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_eta_irr", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_eta_reg", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_eta_reg", (handler.NO_UNIT, ), (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,)) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) self.stopping_conditions.define_state(handler)
13,192
35.955182
97
py
amuse
amuse-main/src/amuse/community/fi/patch_globals_dot_h.py
#!/usr/bin/env python from optparse import OptionParser import os.path import sys import re def get_substitution_rules( value_of_periodic_flag = False, ): result = [] replace_periodic_re = re.compile(r'PARAMETER \(periodic=\.([A-Z]+)\.\)') fortran_boolean_value = "TRUE" if value_of_periodic_flag else "FALSE" sub_periodic = r'PARAMETER (periodic=.{0}.)'.format(fortran_boolean_value) result.append((replace_periodic_re, sub_periodic,)) return result def patch_global_h( value_of_periodic_flag = False, is_dry_run = True, inputfile = "src/globals.h", outputfile = "src/globals.h", name_of_backupfile = "src/globals.h.bck", ): rules = get_substitution_rules(value_of_periodic_flag) with open(inputfile, "r") as input: lines = input.readlines() if not is_dry_run and inputfile == outputfile: with open(name_of_backupfile, "w") as output: output.writelines(lines) output_lines = [] for line in lines: for expression, substitution in rules: line =expression.sub(substitution, line) output_lines.append(line) if is_dry_run: sys.stdout.writelines(output_lines) else: with open(outputfile, "w") as output: output.writelines(output_lines) def new_option_parser(): result = OptionParser() result.add_option( "-p", "--periodic", dest="value_of_periodic_flag", action="store_true", default = False, help="patch the globals.h file, set the periodic flag to true if set (false otherwise)" ) result.add_option( "-n", "--try", dest="is_dry_run", action="store_true", default = False, help="don't patch the file only output on standard input" ) result.add_option( "-i", "--input", dest="inputfile", default = "src/globals.h", help="name of the globals.h file" ) result.add_option( "-o", "--output", dest="outputfile", default = "src/globals.h", help="name of the globals.h file" ) return result if __name__ == "__main__": options, arguments = new_option_parser().parse_args() patch_global_h(**options.__dict__)
2,385
25.511111
95
py
amuse
amuse-main/src/amuse/community/fi/__init__.py
from .interface import Fi, FiMap
33
16
32
py
amuse
amuse-main/src/amuse/community/fi/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 GravityFieldInterface from amuse.community.interface.gd import GravityFieldCode from amuse.community import * from amuse.support.options import option from amuse.units import generic_unit_system from amuse.community.interface.common import CommonCode class FiInterface( CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn, StoppingConditionInterface, GravityFieldInterface, CodeWithDataDirectories): """ FI is a parallel TreeSPH code for galaxy simulations. Extensively rewritten, extended and parallelized it is a development from code from Jeroen Gerritsen and Roelof Bottema, which itself goes back to Treesph. Note that some features are not working atm. These may be fixed in the future. (and I will think of a better name) The relevant references are: .. [#] ADS:1989ApJS...70..419H ** (Hernquist & Katz, 1989, ApJS 70, 419) .. [#] ADS:2004A&A...422...55P ** (Pelupessy, van der Werf & Icke, 2004, A&A 422, 55) .. [#] ADS:2005PhDT........17P (Pelupessy, PhD thesis 2005, Leiden Observatory) .. [#] ADS:1997A&A...325..972G (Gerritsen & Icke, 1997, A&A 325, 972) """ get_total_radius=None get_total_mass=None get_center_of_mass_position=None get_center_of_mass_velocity=None set_acceleration=None get_acceleration=None use_modules=['StoppingConditions','AmuseInterface'] MODE_NORMAL = 'normal' MODE_NORMAL_OPENMP = 'openmp' MODE_PERIODIC_BOUNDARIES = 'periodic' def __init__(self, mode = MODE_NORMAL, **options): self.mode = mode if "number_of_workers" in options and options["number_of_workers"]!=1: raise Exception("Fi expects number_of_workers to be 1,\nfor multiple processors use mode='openmp' and set the OMP_NUM_THREADS environment variable") CodeInterface.__init__(self, name_of_the_worker = self.name_of_the_worker(mode), **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL: return 'fi_worker' elif mode == self.MODE_NORMAL_OPENMP: return 'fi_worker_mp' elif mode == self.MODE_PERIODIC_BOUNDARIES: return 'fi_worker_periodic' else: return 'fi_worker' def new_particle(self, mass, x, y, z, vx, vy, vz, radius = 0.0): return self.new_dm_particle(mass, x, y, z, vx, vy, vz, radius) @legacy_function def new_dm_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.OUT) for x in ['mass','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def new_sph_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.OUT) for x in ['mass','x','y','z','vx','vy','vz','u']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('h_smooth', dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def new_star_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.OUT) for x in ['mass','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('tform', dtype='d', direction=function.IN, default = 0) function.addParameter('radius', dtype='d', direction=function.IN, default = 0) 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 ['mass','x','y','z','vx','vy','vz','radius']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_state_sph(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','x','y','z','vx','vy','vz','u','h_smooth']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_state_star(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','x','y','z','vx','vy','vz','tform','radius']: function.addParameter(x, dtype='d', direction=function.OUT) 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 ['mass','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def set_state_star(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','x','y','z','vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('tform', dtype='d', direction=function.IN, default = 0) function.addParameter('radius', dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def set_state_sph(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['mass','x','y','z','vx','vy','vz','u',]: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('h_smooth', dtype='d', direction=function.IN, default = 0) function.result_type = 'i' return function @legacy_function def get_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('u', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_dinternal_energy_dt(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('du_dt', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_smoothing_length(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('h_smooth', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_density(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('rho', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_pressure(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('pressure', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_star_tform(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('tform', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_mass(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_radius(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('radius', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_position(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_internal_energy(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('u', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_smoothing_length(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('h_smooth', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_star_tform(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('tform', 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_kinetic_energy(): function = LegacyFunctionSpecification() function.addParameter('kinetic_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_potential_energy(): function = LegacyFunctionSpecification() function.addParameter('potential_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_thermal_energy(): function = LegacyFunctionSpecification() function.addParameter('thermal_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_total_energy(): function = LegacyFunctionSpecification() function.addParameter('total_energy', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) 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_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('number_of_particles', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_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 synchronize_model(): """ synchronize the model """ function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def trigger_partremoval(): function = LegacyFunctionSpecification() return function # setting/ getting parameters # logicals @legacy_function def set_use_hydro(): """ set_use_hydro([0,1]): SPH hydro if 1, gravity only if 0 """ function = LegacyFunctionSpecification() function.addParameter('use_hydro_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_use_hydro(): """ get_use_hydro(): SPH hydro if 1, gravity only if 0 """ function = LegacyFunctionSpecification() function.addParameter('use_hydro_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_radiate(): """ set_radiate([0,1]): rad cooling/heating if 1, not if 0 radiate false implies starform false """ function = LegacyFunctionSpecification() function.addParameter('radiation_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_radiate(): """ get_radiate(): rad cooling/heating if 1, not if 0 radiate false implies starform false """ function = LegacyFunctionSpecification() function.addParameter('radiation_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_starform(): """ set_starform([0,1]): star formation if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('star_formation_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_starform(): """ get_starform(): star formation if 1, not if 0 """ function = LegacyFunctionSpecification() function.addParameter('star_formation_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_cosmo(): """ set_cosmo([0,1]): not functional at the moment """ function = LegacyFunctionSpecification() function.addParameter('zeroiftrue', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_cosmo(): """ get_cosmo(): not functional at the moment """ function = LegacyFunctionSpecification() function.addParameter('zeroiftrue', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sqrttstp(): """ set_sqrttstp([0,1]): use sqrt(eps/acc) timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('square_root_timestep_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sqrttstp(): """ get_sqrttstp(): use sqrt(eps/acc) timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('square_root_timestep_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_acc_tstp(): """ set_acc_tstp([0,1]): use vref/acc timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('acc_timestep_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_acc_tstp(): """ get_acc_tstp(): use vref/acc timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('acc_timestep_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_freetstp(): """ set_freetstp([0,1]): use freeform (v/freev)**freevexp * (a/freea)**freeaexp timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('freeform_timestep_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_freetstp(): """ get_freetstp(): use freeform timestep crit if 1""" function = LegacyFunctionSpecification() function.addParameter('freeform_timestep_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_usequad(): """ set_usequad([0,1]): calc. and use quadrupole cell moments if 1""" function = LegacyFunctionSpecification() function.addParameter('quadrupole_moments_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_usequad(): """ get_usequad(): calc. and use quadrupole cell moments if 1""" function = LegacyFunctionSpecification() function.addParameter('quadrupole_moments_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_directsum(): """ set_directsum([0,1]): direct N**2 grav sum if 1""" function = LegacyFunctionSpecification() function.addParameter('direct_sum_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_directsum(): """ get_directsum(): direct N**2 grav sum if 1""" function = LegacyFunctionSpecification() function.addParameter('direct_sum_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_selfgrav(): """ set_selfgrav([0,1]): calculate self-gravity if 1 if set to 0, self gravity is not used, only external potentials""" function = LegacyFunctionSpecification() function.addParameter('self_gravity_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_selfgrav(): """ get_selfgrav(): calculate self-gravity if 1 """ function = LegacyFunctionSpecification() function.addParameter('self_gravity_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_fixthalo(): """ set_fixthalo([0,1]): use fixed (spherical) potential if 1 """ function = LegacyFunctionSpecification() function.addParameter('fixed_halo_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_fixthalo(): """ get_fixthalo(): use fixed (spherical) potential if 1 """ function = LegacyFunctionSpecification() function.addParameter('fixed_halo_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_adaptive_eps(): """ set_adaptive_eps([0,1]): use of adaptive grav smoothing for all part if 1 """ function = LegacyFunctionSpecification() function.addParameter('adaptive_smoothing_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_adaptive_eps(): """ get_adaptive_eps(): use of adaptive grav smoothing for all part if 1 """ function = LegacyFunctionSpecification() function.addParameter('adaptive_smoothing_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_smoothinput(): """ set_smoothinput([0,1]): smooth input SPH prop. if 1 (not working) """ function = LegacyFunctionSpecification() function.addParameter('smooth_input_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_smoothinput(): """ get_smoothinput(): smooth input SPH prop. if 1 (not working) """ function = LegacyFunctionSpecification() function.addParameter('smooth_input_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_consph(): """ set_consph([0,1]): use springel&Hernquist conservative SPH form. if 1 at the moment this is only option""" function = LegacyFunctionSpecification() function.addParameter('conservative_sph_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_consph(): """ get_consph(): use springel&Hernquist conservative SPH form. if 1 at the moment this is only option""" function = LegacyFunctionSpecification() function.addParameter('conservative_sph_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sphinit(): """ set_sphinit([0,1]): initialize sph dens and hsmooth if 1 most probably useless for AMUSE interface""" function = LegacyFunctionSpecification() function.addParameter('sph_dens_init_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sphinit(): """ set_sphinit([0,1]): initialize sph dens and hsmooth if 1 most probably useless for AMUSE interface""" function = LegacyFunctionSpecification() function.addParameter('sph_dens_init_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_uentropy(): """ set_uentropy([0,1]): integrate entropy if 1, internal energy if 0""" function = LegacyFunctionSpecification() function.addParameter('integrate_entropy_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_uentropy(): """ get_uentropy(): integrate entropy if 1, internal energy if 0""" function = LegacyFunctionSpecification() function.addParameter('integrate_entropy_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_isotherm(): """ set_isotherm([0,1]): isothermal gas if 1 note that isotherm needs set_uentropy(0) (false)""" function = LegacyFunctionSpecification() function.addParameter('isothermal_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_isotherm(): """ get_isotherm(): isothermal gas if 1 note that isotherm needs set_uentropy(0) (false)""" function = LegacyFunctionSpecification() function.addParameter('isothermal_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_eps_is_h(): """ set_eps_is_h([0,1]): gas particles grav. eps to SPH h if 1""" function = LegacyFunctionSpecification() function.addParameter('eps_is_h_flag', dtype='i', direction=function.IN) 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_balsara(): """ set_balsara([0,1]): use Balsara viscosity limiter if 1""" function = LegacyFunctionSpecification() function.addParameter('balsara_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_balsara(): """ set_balsara([0,1]): use Balsara viscosity limiter if 1""" function = LegacyFunctionSpecification() function.addParameter('balsara_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_mingaseps(): """ set_mingaseps([0,1]): enforce minimum gas grav eps if 1""" function = LegacyFunctionSpecification() function.addParameter('mingaseps_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_mingaseps(): """ set_mingaseps([0,1]): enforce minimum gas grav eps if 1""" function = LegacyFunctionSpecification() function.addParameter('mingaseps_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function # integers @legacy_function def set_firstsnap(): """ no. of first snapshot """ function = LegacyFunctionSpecification() function.addParameter('first_snapshot', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_firstsnap(): """ no. of first snapshot """ function = LegacyFunctionSpecification() function.addParameter('first_snapshot', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_stepout(): """ no. of steps between output """ function = LegacyFunctionSpecification() function.addParameter('output_interval', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_stepout(): """ no. of steps between output """ function = LegacyFunctionSpecification() function.addParameter('output_interval', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_steplog(): """ no. of steps between logs """ function = LegacyFunctionSpecification() function.addParameter('log_interval', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_steplog(): """ no. of steps between logs """ function = LegacyFunctionSpecification() function.addParameter('log_interval', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_max_tbin(): """ maximum time bin (dtime*2**-max_tbin=minimum time step)""" function = LegacyFunctionSpecification() function.addParameter('maximum_time_bin', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_max_tbin(): """ maximum time bin (dtime*2**-max_tbin=minimum time step)""" function = LegacyFunctionSpecification() function.addParameter('maximum_time_bin', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_minppbin(): """ target no. of particles per time bin""" function = LegacyFunctionSpecification() function.addParameter('minimum_part_per_bin', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_minppbin(): """ target no. of particles per time bin""" function = LegacyFunctionSpecification() function.addParameter('minimum_part_per_bin', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_targetnn(): """ target no. of neighbour particles for variable grav. eps""" function = LegacyFunctionSpecification() function.addParameter('targetnn', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_targetnn(): """ target no. of neighbour particles for variable grav. eps""" function = LegacyFunctionSpecification() function.addParameter('targetnn', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_verbosity(): """ level of terminal output (0=minimum)""" function = LegacyFunctionSpecification() function.addParameter('verbosity', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_verbosity(): """ level of terminal output (0=minimum)""" function = LegacyFunctionSpecification() function.addParameter('verbosity', 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 # real @legacy_function def set_pboxsize(): """ size of simulation domain box (particles outside get deleted)""" function = LegacyFunctionSpecification() function.addParameter('pboxsize', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_pboxsize(): """ size of simulation domain box (particles outside get deleted)""" function = LegacyFunctionSpecification() function.addParameter('pboxsize', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_dtime(): """ timestep (code units)""" function = LegacyFunctionSpecification() function.addParameter('dtime', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_dtime(): """ timestep (code units)""" function = LegacyFunctionSpecification() function.addParameter('dtime', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_unitm_in_msun(): """ code mass unit (in Msun, 10^9 standard) """ function = LegacyFunctionSpecification() function.addParameter('unitm_in_msun', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_unitm_in_msun(): """ code mass unit (in Msun, 10^9 standard) """ function = LegacyFunctionSpecification() function.addParameter('unitm_in_msun', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_unitl_in_kpc(): """ code length unit (in kpc, 1) """ function = LegacyFunctionSpecification() function.addParameter('unitl_in_kpc', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_unitl_in_kpc(): """ code length unit (in kpc, 1) """ function = LegacyFunctionSpecification() function.addParameter('unitl_in_kpc', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_tstepcrit(): """ sqrttstp timestep constant (unitless,standard=1.) """ function = LegacyFunctionSpecification() function.addParameter('tstepcrit', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_tstepcrit(): """ sqrttstp timestep constant (unitless,standard=1.) """ function = LegacyFunctionSpecification() function.addParameter('tstepcrit', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_tstpcr2(): """ acc_tstp timestep constant (unitless,standard=0.25) """ function = LegacyFunctionSpecification() function.addParameter('tstpcr2', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_tstpcr2(): """ acc_tstp timestep constant (unitless,standard=0.25) """ function = LegacyFunctionSpecification() function.addParameter('tstpcr2', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_freev(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freev', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_freev(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freev', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_freea(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freea', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_freea(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freea', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_freevexp(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freevexp', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_freevexp(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freevexp', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_freeaexp(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freeaexp', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_freeaexp(): """ freeform timestep constant """ function = LegacyFunctionSpecification() function.addParameter('freeaexp', dtype='d', 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_eps(): """ gravitational softening length, spline soft. (code length, 1.) """ function = LegacyFunctionSpecification() function.addParameter('eps', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_eps(): """ gravitational softening length, spline soft. (code length, 1.) """ function = LegacyFunctionSpecification() function.addParameter('eps', dtype='d', direction=function.OUT) function.result_type = 'i' return function def set_eps2(self,eps2): return self.set_eps(eps2**0.5) def get_eps2(self): eps,err=self.get_eps() return eps**2, err @legacy_function def set_gdgtol(): """ Gadget cell openings criterion parameter (unitless, .01) """ 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, .01) """ function = LegacyFunctionSpecification() function.addParameter('gdgtol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_nn_tol(): """ fractional tolerance in nn_target (0.1) """ function = LegacyFunctionSpecification() function.addParameter('nn_tol', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_nn_tol(): """ fractional tolerance in nn_target (0.1) """ function = LegacyFunctionSpecification() function.addParameter('nn_tol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_epsgas(): """ gas grav smoothing eps""" function = LegacyFunctionSpecification() function.addParameter('epsgas', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_epsgas(): """ gas grav smoothing eps""" function = LegacyFunctionSpecification() function.addParameter('epsgas', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_gamma(): """ gas polytropic index (1.666667) """ function = LegacyFunctionSpecification() function.addParameter('gamma', dtype='d', direction=function.IN) 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*alpha=1.0) """ 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*alpha=1.0) """ function = LegacyFunctionSpecification() function.addParameter('beta', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_epssph(): """ SPH artificial viscosity safety against divergence (0.01) """ function = LegacyFunctionSpecification() function.addParameter('epssph', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_epssph(): """ SPH artificial viscosity safety against divergence (0.01) """ function = LegacyFunctionSpecification() function.addParameter('epssph', 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_removgas(): """ minimum gas particle mass (fraction of initial (average) mass) """ function = LegacyFunctionSpecification() function.addParameter('removgas', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_removgas(): """ minimum gas particle mass (fraction of initial (average) mass) """ function = LegacyFunctionSpecification() function.addParameter('removgas', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_consthsm(): """ SPH smoothing length if constant""" function = LegacyFunctionSpecification() function.addParameter('consthsm', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_consthsm(): """ SPH smoothing length if constant""" function = LegacyFunctionSpecification() function.addParameter('consthsm', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_nsmtol(): """ tolerance in number of SPH neighbours """ function = LegacyFunctionSpecification() function.addParameter('nsmtol', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_nsmtol(): """ tolerance in number of SPH neighbours """ function = LegacyFunctionSpecification() function.addParameter('nsmtol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_graineff(): """ FUV grain heating efficiency parameter (unitless, 0.05) """ function = LegacyFunctionSpecification() function.addParameter('graineff', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_graineff(): """ FUV grain heating efficiency parameter (unitless, 0.05) """ function = LegacyFunctionSpecification() function.addParameter('graineff', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_crionrate(): """ primary cosmic ray ionization rate (in units of 1.8e-17 sec^-1, 1.) """ function = LegacyFunctionSpecification() function.addParameter('crionrate', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_crionrate(): """ primary cosmic ray ionization rate (in units of 1.e-17 sec^-1, 3.6) """ function = LegacyFunctionSpecification() function.addParameter('crionrate', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_heat_par1(): """ additional heating 1 (0.0)""" function = LegacyFunctionSpecification() function.addParameter('heat_par1', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_heat_par1(): """ additional heating 1 (0.0)""" function = LegacyFunctionSpecification() function.addParameter('heat_par1', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_heat_par2(): """ additional heating 2 (0.0)""" function = LegacyFunctionSpecification() function.addParameter('heat_par2', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_heat_par2(): """ additional heating 2 (0.0)""" function = LegacyFunctionSpecification() function.addParameter('heat_par2', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_cool_par(): """ additional cooling (0.0)""" function = LegacyFunctionSpecification() function.addParameter('cool_par', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_cool_par(): """ additional cooling (0.0)""" function = LegacyFunctionSpecification() function.addParameter('cool_par', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_optdepth(): """ 1/(mean free path) for UV photons (code length **-1, 0.0)""" function = LegacyFunctionSpecification() function.addParameter('optdepth', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_optdepth(): """ 1/(mean free path) for UV photons (code length **-1, 0.0)""" function = LegacyFunctionSpecification() function.addParameter('optdepth', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_tcollfac(): """ star formation delay parameter (unitless, 1) """ function = LegacyFunctionSpecification() function.addParameter('tcollfac', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_tcollfac(): """ star formation delay parameter (unitless, 1) """ function = LegacyFunctionSpecification() function.addParameter('tcollfac', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_masscrit(): """ star formation cloud reference mass (Msun, 1.e5) """ function = LegacyFunctionSpecification() function.addParameter('masscrit', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_masscrit(): """ star formation cloud reference mass (Msun, 1.e5) """ function = LegacyFunctionSpecification() function.addParameter('masscrit', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sfeff(): """ gas particle mass fraction converted to stars (0.125) """ function = LegacyFunctionSpecification() function.addParameter('sfeff', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sfeff(): """ gas particle mass fraction converted to stars (0.125) """ function = LegacyFunctionSpecification() function.addParameter('sfeff', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_tbubble(): """ Supernova activity time, (Myr, 3.e7) """ function = LegacyFunctionSpecification() function.addParameter('tbubble', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_tbubble(): """ Supernova activity time, (Myr, 3.e7) """ function = LegacyFunctionSpecification() function.addParameter('tbubble', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sne_eff(): """ Supernova feedback coupling efficiency, (0.1) """ function = LegacyFunctionSpecification() function.addParameter('sne_eff', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sne_eff(): """ Supernova feedback coupling efficiency, (0.1) """ function = LegacyFunctionSpecification() function.addParameter('sne_eff', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_tsnbeg(): """ Supernova feedback start time, (Myr, 3.e6) """ function = LegacyFunctionSpecification() function.addParameter('tsnbeg', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_tsnbeg(): """ Supernova feedback start time, (Myr, 3.e6) """ function = LegacyFunctionSpecification() function.addParameter('tsnbeg', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_rhomax(): """ Maximum density in case of star formation (force SF if exceeded, ignored if star formation is off) """ function = LegacyFunctionSpecification() function.addParameter('rhomax', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_rhomax(): """ Maximum density in case of star formation (force SF if exceeded, ignored if star formation is off) """ function = LegacyFunctionSpecification() function.addParameter('rhomax', dtype='d', direction=function.OUT) function.result_type = 'i' return function # character @legacy_function def set_halofile(): """ halo model file (none) """ function = LegacyFunctionSpecification() function.addParameter('halofile', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_halofile(): """ halo model file (none) """ function = LegacyFunctionSpecification() function.addParameter('halofile', dtype='string', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_feedback(): """ feedback model (fuv, pres, kine, solo, solh) """ function = LegacyFunctionSpecification() function.addParameter('feedback', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_feedback(): """ feedback model (fuv, pres, kine, solo, solh) """ function = LegacyFunctionSpecification() function.addParameter('feedback', dtype='string', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sfmode(): """ star formation model (gerritsen, nieuw) """ function = LegacyFunctionSpecification() function.addParameter('sfmode', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sfmode(): """ star formation model (gerritsen, nieuw) """ function = LegacyFunctionSpecification() function.addParameter('sfmode', dtype='string', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_hupdatemethod(): """ SPH smoothing length criterion (at the moment always 'mass') """ function = LegacyFunctionSpecification() function.addParameter('hupdatemethod', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_hupdatemethod(): """ SPH smoothing length criterion (at the moment always 'mass') """ function = LegacyFunctionSpecification() function.addParameter('hupdatemethod', dtype='string', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_sph_visc(): """ SPH viscosity (sph,sphv, bulk) not all may work """ function = LegacyFunctionSpecification() function.addParameter('sph_visc', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_sph_visc(): """ SPH viscosity (sph,sphv, bulk) not all may work """ function = LegacyFunctionSpecification() function.addParameter('sph_visc', dtype='string', direction=function.OUT) function.result_type = 'i' return function @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 set_fi_data_directory(): """ Update the path to the Fi database. """ function = LegacyFunctionSpecification() function.addParameter('fi_data_directory', dtype='string', direction=function.IN, description = "Name of the Fi data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR Directory does not exist """ return function @legacy_function def get_fi_data_directory(): """ Retrieve the path to the Fi database currently used. """ function = LegacyFunctionSpecification() function.addParameter('fi_data_directory', dtype='string', direction=function.OUT, description = "Name of the Fi data directory") function.result_type = 'int32' function.result_doc = """ 0 - OK Value was retrieved -1 - ERROR Could not retrieve value """ return function def get_periodic_boundaries_flag(self): return self.mode == self.MODE_PERIODIC_BOUNDARIES @legacy_function def get_number_of_sph_particles_removed(): """ Return the number of particles deleted 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_removed_sph_particle(): """ Return the id of the nth particle deleted during the last evolve. """ function = LegacyFunctionSpecification() function.addParameter('index_of_delete', dtype='int32', direction=function.IN, description = 'index in the deleted particles list (zero based)') function.addParameter('index_of_particle', dtype='int32', direction=function.OUT) function.can_handle_array = True function.result_type = 'int32' return function class GlFiInterface(FiInterface): def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL: return 'fi_worker_gl' elif mode == self.MODE_PERIODIC_BOUNDARIES: return 'fi_worker_periodic_gl' else: return 'fi_worker_gl' def __init__(self,mode=FiInterface.MODE_NORMAL, **options): self.mode=mode CodeInterface.__init__(self,name_of_the_worker = self.name_of_the_worker(mode), **options) @legacy_function def get_image_target(): """ target point of image """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT, unit=nbody_system.length) function.addParameter('y', dtype='d', direction=function.OUT, unit=nbody_system.length) function.addParameter('z', dtype='d', direction=function.OUT, unit=nbody_system.length) function.result_type = 'i' return function @legacy_function def set_image_target(): """ target point of image """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN, unit=nbody_system.length) function.addParameter('y', dtype='d', direction=function.IN, unit=nbody_system.length) function.addParameter('z', dtype='d', direction=function.IN, unit=nbody_system.length) function.result_type = 'i' return function @legacy_function def get_viewpoint(): """ camera position (for perspective proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT, unit=nbody_system.length) function.addParameter('y', dtype='d', direction=function.OUT, unit=nbody_system.length) function.addParameter('z', dtype='d', direction=function.OUT, unit=nbody_system.length) function.result_type = 'i' return function @legacy_function def set_viewpoint(): """ camera position (for perspective proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN, unit=nbody_system.length) function.addParameter('y', dtype='d', direction=function.IN, unit=nbody_system.length) function.addParameter('z', dtype='d', direction=function.IN, unit=nbody_system.length) function.result_type = 'i' return function @legacy_function def get_upvector(): """ specify the orientation of the image by setting the direction vector of image y """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT, unit=units.none) function.addParameter('y', dtype='d', direction=function.OUT, unit=units.none) function.addParameter('z', dtype='d', direction=function.OUT, unit=units.none) function.result_type = 'i' return function @legacy_function def get_image_angle(): """ angle of image in x direction (for perpective proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_angle', dtype='d', direction=function.OUT, unit=units.deg) function.result_type = 'i' return function @legacy_function def set_image_angle(): """ angle of image in x direction (for perpective proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_angle', dtype='d', direction=function.IN, unit=units.deg) function.result_type = 'i' return function @legacy_function def get_image_ratio(): """ width/height of image """ function = LegacyFunctionSpecification() function.addParameter('image_ratio', dtype='d', direction=function.OUT, unit=None) function.result_type = 'i' return function @legacy_function def viewer(): function = LegacyFunctionSpecification() return function @legacy_function def trigger_partremoval(): function = LegacyFunctionSpecification() return function @legacy_function def trigger_viewer_refresh(): function = LegacyFunctionSpecification() return function def start_viewer(self): self.viewer() class FiDoc(object): def __get__(self, instance, owner): return instance.legacy_doc+"\n\n"+instance.parameters.__doc__ class Fi(GravitationalDynamics, GravityFieldCode): __doc__ = FiDoc() def __init__(self, convert_nbody = None, mode = 'normal', use_gl = False, **options): if(use_gl): legacy_interface = GlFiInterface(mode = mode, **options) else: legacy_interface = FiInterface(mode = mode, **options) self.legacy_doc = legacy_interface.__doc__ #if convert_nbody is None: # convert_nbody=nbody_system.nbody_to_si(1.0e9 | units.MSun, 1.0 | units.kpc) self.stopping_conditions = StoppingConditions(self) GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) def initialize_code(self): result = self.overridden().initialize_code() self.parameters.fi_data_directory = self.legacy_interface.get_data_directory()+'/' if not self.unit_converter is None: value=self.unit_converter.to_si(nbody_system.length) self.parameters._original.code_length_unit = value value=self.unit_converter.to_si(nbody_system.mass) self.parameters._original.code_mass_unit = value return result def define_properties(self, handler): GravitationalDynamics.define_properties(self, handler) handler.add_property("get_thermal_energy") handler.add_property("get_total_energy") def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) handler.add_transition('END', 'INITIALIZED', 'initialize_code', False) handler.add_method('END', 'initialize_code') 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_method('EDIT', 'new_star_particle') handler.add_method('UPDATE', 'new_star_particle') handler.add_transition('RUN', 'UPDATE', 'new_star_particle', False) handler.add_method('RUN', 'get_velocity') handler.add_method('RUN', 'get_acceleration') handler.add_method('RUN', 'get_internal_energy') handler.add_method('RUN', 'get_dinternal_energy_dt') handler.add_method('RUN', 'get_smoothing_length') handler.add_method('RUN', 'get_density') handler.add_method('RUN', 'get_pressure') handler.add_method('RUN', 'get_star_tform') handler.add_method('RUN', 'get_state_sph') handler.add_method('RUN', 'get_state_star') handler.remove_transition('EVOLVED', 'RUN', 'synchronize_model') handler.add_transition('EVOLVED', 'UPDATED', 'update_particle_set') handler.add_transition('UPDATED', 'RUN', 'synchronize_model') 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_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_time') handler.add_method('EDIT', 'get_time') handler.add_method('UPDATE', 'get_time') handler.add_method('INITIALIZED', 'get_time') handler.add_method('CHANGE_PARAMETERS_RUN', 'get_time') handler.add_method('CHANGE_PARAMETERS_EDIT', 'get_time') handler.add_method('CHANGE_PARAMETERS_UPDATE', 'get_time') handler.add_method('RUN', 'get_hydro_state_at_point') handler.add_method('EDIT', 'get_gravity_at_point') handler.add_method('EDIT', 'get_potential_at_point') self.stopping_conditions.define_state(handler) def define_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_dtime", "set_dtime", "timestep", "timestep for system", default_value = 1.0 | nbody_system.time ) handler.add_boolean_parameter( "get_radiate", "set_radiate", "radiation_flag", "Radiation flag. True means: radiation (i.e. radiative cooling/heating) is included. " "False means: no radiation, and implies no star formation.", False ) handler.add_boolean_parameter( "get_starform", "set_starform", "star_formation_flag", "Star-formation flag. True means: star formation is included. " "False means: no star formation included.", False ) handler.add_boolean_parameter( "get_use_hydro", "set_use_hydro", "use_hydro_flag", "Hydrodynamics flag. True means: SPH hydro included, False means: gravity only.", True ) handler.add_boolean_parameter( "get_sqrttstp", "set_sqrttstp", "square_root_timestep_flag", "Square-root-timestep flag. True means: use sqrt(eps/acc) timestep criterion.", False ) handler.add_boolean_parameter( "get_acc_tstp", "set_acc_tstp", "acc_timestep_flag", "Acceleration-timestep flag. True means: use vref/acc timestep criterion.", True ) handler.add_boolean_parameter( "get_freetstp", "set_freetstp", "freeform_timestep_flag", "Freeform-timestep flag. True means: use freeform (v/freev)**freevexp * (a/freea)**freeaexp timestep criterion.", False ) handler.add_boolean_parameter( "get_usequad", "set_usequad", "quadrupole_moments_flag", "Quadrupole-moments flag. True means: calculate and use quadrupole cell moments.", False ) handler.add_boolean_parameter( "get_directsum", "set_directsum", "direct_sum_flag", "Direct-summation flag. True means: direct N**2 gravity summation.", False ) handler.add_boolean_parameter( "get_selfgrav", "set_selfgrav", "self_gravity_flag", "Self-gravity flag. False means: self-gravity is not used, only external potentials.", True ) handler.add_boolean_parameter( "get_fixthalo", "set_fixthalo", "fixed_halo_flag", "Fixed-halo flag. True means: use fixed (spherical) potential.", False ) handler.add_boolean_parameter( "get_adaptive_eps", "set_adaptive_eps", "adaptive_smoothing_flag", "Adaptive-smoothing flag. True means: use of adaptive gravity smoothing for all particles.", 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.", True ) handler.add_boolean_parameter( "get_smoothinput", "set_smoothinput", "smooth_input_flag", "Smooth-input flag. True means: smooth input SPH properties.", False ) handler.add_boolean_parameter( "get_consph", "set_consph", "conservative_sph_flag", "Conservative-SPH flag. True means: use Springel & Hernquist conservative SPH form (currently the only option).", True ) handler.add_boolean_parameter( "get_sphinit", "set_sphinit", "sph_dens_init_flag", "SPH-density-init flag. True means: initialize sph density and h_smooth (most probably useless for AMUSE interface).", True ) handler.add_boolean_parameter( "get_uentropy", "set_uentropy", "integrate_entropy_flag", "Integrate-entropy flag. True means: integrate entropy, else: internal energy.", True ) handler.add_boolean_parameter( "get_isotherm", "set_isotherm", "isothermal_flag", "Isothermal flag. True means: isothermal gas (requires integrate_entropy_flag == False).", False ) handler.add_boolean_parameter( "get_eps_is_h", "set_eps_is_h", "eps_is_h_flag", "Eps-is-h flag. True means: set gas particles gravitational epsilon to h (SPH smoothing length).", True ) handler.add_boolean_parameter( "get_balsara", "set_balsara", "balsara_flag", "balsara flag. True means: use Balsara viscosity limiter.", False ) handler.add_boolean_parameter( "get_mingaseps", "set_mingaseps", "enforce_min_sph_grav_softening_flag", "mingaseps flag. True means: enforce minimum gas grav eps.", False ) handler.add_method_parameter( "get_firstsnap", "set_firstsnap", "first_snapshot", "The number of the first snapshot.", default_value = 0 ) handler.add_method_parameter( "get_stepout", "set_stepout", "output_interval", "The number of steps between output.", default_value = 5 ) handler.add_method_parameter( "get_steplog", "set_steplog", "log_interval", "The number of steps between logs.", default_value = 5 ) handler.add_method_parameter( "get_max_tbin", "set_max_tbin", "maximum_time_bin", "The maximum time bin (dtime*2**-max_tbin=minimum time step).", default_value = 4096 ) handler.add_method_parameter( "get_minppbin", "set_minppbin", "minimum_part_per_bin", "The minimum number of particles per time bin.", default_value = 1 ) handler.add_method_parameter( "get_targetnn", "set_targetnn", "targetnn", "The target number of neighbour particles for variable gravitational eps.", default_value = 32 ) handler.add_method_parameter( "get_verbosity", "set_verbosity", "verbosity", "The level of terminal output (0=minimum).", default_value = 0 ) handler.add_method_parameter( "get_nsmooth", "set_nsmooth", "n_smooth", "The target number of SPH neighbours.", default_value = 64 ) handler.add_method_parameter( "get_pboxsize", "set_pboxsize", "periodic_box_size", "The size of simulation domain box (particles outside get deleted).", default_value = 10000.0 | nbody_system.length ) handler.add_method_parameter( "get_unitm_in_msun", "set_unitm_in_msun", "code_mass_unit", "The code mass unit (in Msun, 10^9 standard).", default_value = 1.0e9 | units.MSun ) handler.add_method_parameter( "get_unitl_in_kpc", "set_unitl_in_kpc", "code_length_unit", "The code length unit (in kpc, 1 standard).", default_value = 1.0 | units.kpc ) handler.add_method_parameter( "get_tstepcrit", "set_tstepcrit", "sqrt_timestep_crit_constant", "Square-root-timestep criterion constant (unitless,standard=1.).", default_value = 1.0 ) handler.add_method_parameter( "get_tstpcr2", "set_tstpcr2", "acc_timestep_crit_constant", "Acceleration-timestep criterion constant (unitless,standard=0.25).", default_value = 0.25 ) handler.add_method_parameter( "get_freev", "set_freev", "free_timestep_crit_constant_v", "Freeform-timestep criterion constant v.", default_value = 0.5 ) handler.add_method_parameter( "get_freea", "set_freea", "free_timestep_crit_constant_a", "Freeform-timestep criterion constant a.", default_value = 0.35 ) handler.add_method_parameter( "get_freevexp", "set_freevexp", "free_timestep_crit_constant_vexp", "Freeform-timestep criterion constant v_exp.", default_value = 0.0 ) handler.add_method_parameter( "get_freeaexp", "set_freeaexp", "free_timestep_crit_constant_aexp", "Freeform-timestep criterion constant a_exp.", default_value = -1.0 ) 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, .01)", default_value = 0.01 ) handler.add_method_parameter( "get_nn_tol", "set_nn_tol", "nn_tol", "The fractional tolerance in nn_target (0.1).", default_value = 0.1 ) handler.add_method_parameter( "get_epsgas", "set_epsgas", "gas_epsilon", "The gas gravitational smoothing epsilon.", default_value = 0.005 | nbody_system.length ) handler.add_method_parameter( "get_gamma", "set_gamma", "gamma", "gas polytropic index (1.6666667)", default_value = 1.6666667 ) 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", "beta", "SPH artificial viscosity beta parameter (2*alpha=1.0)", default_value = 1.0 ) handler.add_method_parameter( "get_epssph", "set_epssph", "sph_artificial_viscosity_eps", "SPH artificial viscosity safety against divergence (0.01)", default_value = 0.01 ) handler.add_method_parameter( "get_courant", "set_courant", "courant", "SPH courant condition parameter (0.3)", default_value = 0.3 ) handler.add_method_parameter( "get_removgas", "set_removgas", "min_gas_part_mass", "minimum gas particle mass (fraction of initial (average) mass)", default_value = 0.25 ) handler.add_method_parameter( "get_consthsm", "set_consthsm", "sph_h_const", "SPH smoothing length if constant", default_value = 0.2 | nbody_system.length ) 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_graineff", "set_graineff", "grain_heat_eff", "FUV grain heating efficiency parameter (unitless, 0.05)", default_value = 0.05 ) handler.add_method_parameter( "get_crionrate", "set_crionrate", "zeta_cr_ion_rate", "primary cosmic ray ionization rate, zeta (in units of 1.8e-17 sec^-1, 1.)", default_value = 3.6 | 1.8e-17 * units.s**-1 ) handler.add_method_parameter( "get_heat_par1", "set_heat_par1", "heat_par1", "additional heating 1 parameter (0.0)", default_value = 0.0 ) handler.add_method_parameter( "get_heat_par2", "set_heat_par2", "heat_par2", "additional heating 2 parameter (0.0)", default_value = 0.0 ) handler.add_method_parameter( "get_cool_par", "set_cool_par", "cool_par", "additional cooling parameter (1.0)", default_value = 1.0 ) handler.add_method_parameter( "get_optdepth", "set_optdepth", "optical_depth", "1/(mean free path) for UV photons (code length **-1, 0.0)", default_value = 0.0 ) handler.add_method_parameter( "get_tcollfac", "set_tcollfac", "star_form_delay_fac", "star formation delay parameter (unitless, 1)", default_value = 1.0 ) handler.add_method_parameter( "get_masscrit", "set_masscrit", "star_form_mass_crit", "star formation cloud reference mass (Msun, 1.e5)", default_value = 1.0e5 | units.MSun ) handler.add_method_parameter( "get_sfeff", "set_sfeff", "star_form_eff", "gas particle mass fraction converted to stars (0.125)", default_value = 0.25 ) handler.add_method_parameter( "get_tbubble", "set_tbubble", "supernova_duration", "Supernova activity time, (Myr, 3.e7)", default_value = 3.0e7 | units.Myr ) handler.add_method_parameter( "get_sne_eff", "set_sne_eff", "supernova_eff", "Supernova feedback coupling efficiency, (0.0)", default_value = 0.0 ) handler.add_method_parameter( "get_tsnbeg", "set_tsnbeg", "t_supernova_start", "Supernova feedback start time, (Myr, 3.e6)", default_value = 3.0e6 | units.Myr ) handler.add_method_parameter( "get_rhomax", "set_rhomax", "max_density", "Maximum density in case of star formation (force SF if exceeded, ignored if star formation is off)", default_value = 100.0 |nbody_system.density ) handler.add_method_parameter( "get_halofile", "set_halofile", "halofile", "Path to initial halo model file, relative to the Fi data directory (none)", default_value = "none" ) handler.add_method_parameter( "get_feedback", "set_feedback", "feedback", "feedback model (fuv, pres, kine, solo, solh)", default_value = "fuv" ) handler.add_method_parameter( "get_sfmode", "set_sfmode", "star_formation_mode", "star formation model (gerritsen, nieuw)", default_value = "gerritsen" ) handler.add_method_parameter( "get_hupdatemethod", "set_hupdatemethod", "h_update_method", "SPH smoothing length criterion (at the moment always 'mass')", default_value = "mass" ) handler.add_method_parameter( "get_sph_visc", "set_sph_visc", "sph_viscosity", "SPH viscosity (sph,sphv, bulk). Note: not all may work.", default_value = "sph" ) handler.add_method_parameter( "get_fi_data_directory", "set_fi_data_directory", "fi_data_directory", "Name of the Fi data directory", default_value = "" ) handler.add_boolean_parameter( "get_periodic_boundaries_flag", None, "periodic_boundaries_flag", "Periodic boundaries flag. True means: use periodic boundary conditions (read-only)", False ) 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_particle_sets(self, handler): handler.define_super_set('particles', ['dm_particles','gas_particles','star_particles'], index_to_default_set = 0) handler.define_set('dm_particles', 'id') 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_radius') handler.add_getter('dm_particles', 'get_radius') handler.add_setter('dm_particles', 'set_velocity') handler.add_getter('dm_particles', 'get_velocity') handler.define_set('gas_particles', 'id') 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_getter('gas_particles', 'get_radius') handler.add_setter('gas_particles', 'set_radius') 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_setter('gas_particles', 'set_internal_energy') handler.add_getter('gas_particles', 'get_internal_energy') handler.add_getter('gas_particles', 'get_dinternal_energy_dt') handler.add_setter('gas_particles', 'set_smoothing_length') 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.define_set('star_particles', 'id') handler.set_new('star_particles', 'new_star_particle') handler.set_delete('star_particles', 'delete_particle') handler.add_setter('star_particles', 'set_state_star') handler.add_getter('star_particles', 'get_state_star') handler.add_setter('star_particles', 'set_mass') handler.add_getter('star_particles', 'get_mass', names = ('mass',)) handler.add_setter('star_particles', 'set_position') handler.add_getter('star_particles', 'get_position') handler.add_setter('star_particles', 'set_radius') handler.add_getter('star_particles', 'get_radius') handler.add_setter('star_particles', 'set_velocity') handler.add_getter('star_particles', 'get_velocity') handler.add_setter('star_particles', 'set_star_tform') handler.add_getter('star_particles', 'get_star_tform') self.stopping_conditions.define_particle_set(handler, 'particles') def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "set_velocity", ( handler.INDEX, nbody_system.speed, nbody_system.speed, nbody_system.speed, ), ( 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( "new_dm_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( "new_sph_particle", ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.specific_energy, nbody_system.length, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "get_state_sph", ( handler.INDEX, ), ( nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.specific_energy, nbody_system.length, handler.ERROR_CODE ) ) handler.add_method( "set_state_sph", ( handler.INDEX, nbody_system.mass, nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed, nbody_system.specific_energy, nbody_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_internal_energy", ( handler.INDEX, nbody_system.specific_energy, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_internal_energy", ( handler.INDEX, ), ( nbody_system.specific_energy, handler.ERROR_CODE ) ) handler.add_method( "get_dinternal_energy_dt", ( handler.INDEX, ), ( nbody_system.specific_energy/nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( "set_smoothing_length", (handler.INDEX, nbody_system.length), (handler.ERROR_CODE,) ) handler.add_method( "get_smoothing_length", (handler.INDEX,), (nbody_system.length, handler.ERROR_CODE) ) handler.add_method( "get_density", (handler.INDEX,), (nbody_system.density, handler.ERROR_CODE) ) handler.add_method( "get_pressure", (handler.INDEX,), (nbody_system.pressure, handler.ERROR_CODE) ) handler.add_method( "new_star_particle", ( 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.length, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( "get_state_star", ( handler.INDEX, ), ( 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.length, handler.ERROR_CODE ) ) handler.add_method( "set_state_star", ( handler.INDEX, 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.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( "set_star_tform", ( handler.INDEX, nbody_system.time, ), ( handler.ERROR_CODE, ) ) handler.add_method( "get_star_tform", ( handler.INDEX, ), ( nbody_system.time, handler.ERROR_CODE ) ) handler.add_method( 'get_hydro_state_at_point', (nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.speed, nbody_system.speed, nbody_system.speed), (nbody_system.density, nbody_system.momentum_density, nbody_system.momentum_density, nbody_system.momentum_density, nbody_system.energy_density, 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( "get_dtime", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_dtime", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_firstsnap", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_firstsnap", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_stepout", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_stepout", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_steplog", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_steplog", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_max_tbin", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_max_tbin", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_minppbin", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_minppbin", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_targetnn", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_targetnn", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_verbosity", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_verbosity", (handler.NO_UNIT, ), (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_pboxsize", (), (nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_pboxsize", (nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_unitm_in_msun", (), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "set_unitm_in_msun", (units.MSun, ), (handler.ERROR_CODE,) ) handler.add_method( "get_unitl_in_kpc", (), (units.kpc, handler.ERROR_CODE,) ) handler.add_method( "set_unitl_in_kpc", (units.kpc, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tstepcrit", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_tstepcrit", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tstpcr2", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_tstpcr2", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_freev", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_freev", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_freea", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_freea", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_freevexp", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_freevexp", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_freeaexp", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_freeaexp", (handler.NO_UNIT, ), (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_nn_tol", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_nn_tol", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_epsgas", (), (nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_epsgas", (nbody_system.length, ), (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_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_epssph", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_epssph", (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_removgas", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_removgas", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_consthsm", (), (nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_consthsm", (nbody_system.length, ), (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_graineff", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_graineff", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_crionrate", (), (1.8e-17 * units.s**-1, handler.ERROR_CODE,) ) handler.add_method( "set_crionrate", (1.8e-17 * units.s**-1, ), (handler.ERROR_CODE,) ) handler.add_method( "get_heat_par1", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_heat_par1", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_heat_par2", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_heat_par2", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_cool_par", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_cool_par", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_optdepth", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_optdepth", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tcollfac", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_tcollfac", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_masscrit", (), (units.MSun, handler.ERROR_CODE,) ) handler.add_method( "set_masscrit", (units.MSun, ), (handler.ERROR_CODE,) ) handler.add_method( "get_sfeff", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_sfeff", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tbubble", (), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "set_tbubble", (units.Myr, ), (handler.ERROR_CODE,) ) handler.add_method( "get_sne_eff", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_sne_eff", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_tsnbeg", (), (units.Myr, handler.ERROR_CODE,) ) handler.add_method( "set_tsnbeg", (units.Myr, ), (handler.ERROR_CODE,) ) handler.add_method( "get_rhomax", (), (nbody_system.density, handler.ERROR_CODE,) ) handler.add_method( "set_rhomax", (nbody_system.density, ), (handler.ERROR_CODE,) ) handler.add_method( "get_halofile", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_halofile", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_feedback", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_feedback", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_sfmode", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_sfmode", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_hupdatemethod", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_hupdatemethod", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_sph_visc", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_sph_visc", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_fi_data_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_fi_data_directory", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_thermal_energy", (), (nbody_system.energy, handler.ERROR_CODE,) ) handler.add_method( "get_total_energy", (), (nbody_system.energy, handler.ERROR_CODE,) ) handler.add_method( "get_number_of_sph_particles_removed", ( ), ( handler.NO_UNIT, handler.ERROR_CODE ) ) handler.add_method( "get_id_of_removed_sph_particle", ( handler.NO_UNIT, ), ( handler.INDEX, handler.ERROR_CODE ) ) self.stopping_conditions.define_methods(handler) 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_removed_particles = self.get_number_of_sph_particles_removed() if number_of_removed_particles == 0: return indices_in_update_list = list(range(number_of_removed_particles)) indices_to_remove = self.get_id_of_removed_sph_particle(indices_in_update_list) incode_storage = self.gas_particles._remove_indices_in_attribute_storage(indices_to_remove) def get_total_energy(self): return self.__getattr__('get_total_energy')() class FiViewer(Fi): def __init__(self, convert_nbody = None, mode = 'normal', **options): Fi.__init__(self, convert_nbody = convert_nbody, mode = mode, use_gl = True , **options) def define_parameters(self, handler): Fi.define_parameters(self,handler) handler.add_method_parameter( "get_viewpoint", "set_viewpoint", "viewpoint", "viewpoint (location of the camera)", [0,1,0] | nbody_system.length, is_vector=True ) handler.add_method_parameter( "get_image_target", "set_image_target", "image_target", "image_target (location the camera points to)", [0,0,0] | nbody_system.length, is_vector=True ) handler.add_method_parameter( "get_upvector", None, "upvector", "upvector (which direction points up, readonly)", [0,0,1] , is_vector=True ) handler.add_method_parameter( "get_image_angle", "set_image_angle", "image_angle", "image angle - vertical (?)!! ", default_value = 45 | units.deg ) handler.add_method_parameter( "get_image_ratio", None, "image_ratio", "image width/height (readonly)", default_value = 1. ) def define_state(self, handler): handler.set_initial_state('UNINITIALIZED') handler.add_transition('UNINITIALIZED', 'INITIALIZED', 'initialize_code') handler.add_transition('!UNINITIALIZED!STOPPED', 'END', 'cleanup_code') handler.add_transition('END', 'STOPPED', 'stop', False) handler.add_method('STOPPED', 'stop') handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_method('EDIT', 'new_dm_particle') handler.add_method('EDIT', 'new_sph_particle') handler.add_method('EDIT', 'new_star_particle') handler.add_method('UPDATE', 'delete_particle') handler.add_transition('EDIT', 'UPDATE', 'delete_particle') handler.add_transition('UPDATE', 'EDIT', 'trigger_partremoval') class FiMapInterface(CodeInterface): use_modules=['StoppingConditions','MapInterface'] MODE_NORMAL = 'normal' MODE_NORMAL_OPENMP = 'openmp' def __init__(self, mode = MODE_NORMAL, **options): self.mode = mode CodeInterface.__init__(self, name_of_the_worker = self.name_of_the_worker(mode), **options) def name_of_the_worker(self, mode): if mode == self.MODE_NORMAL: return 'fi_worker_map' elif mode == self.MODE_NORMAL_OPENMP: return 'fi_worker_map_mp' else: return 'fi_worker_map' @legacy_function def initialize_code(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def cleanup_code(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def generate_projection(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def init_map(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def reset_map(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def erase_map(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.OUT) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('weight', dtype='d', direction=function.IN, default = 1.) function.addParameter('radius', dtype='d', direction=function.IN, default = 0.) function.addParameter('opacity_area', dtype='d', direction=function.IN, default = 0.) function.addParameter('index', dtype='i', direction=function.IN, default = -1) 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 ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('weight', dtype='d', direction=function.IN, default = 1.) function.addParameter('radius', dtype='d', direction=function.IN, default = 0.) function.addParameter('opacity_area', dtype='d', direction=function.IN, default = 0.) function.result_type = 'i' return function @legacy_function def set_weight(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('weight', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_opacity_area(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.addParameter('opacity_area', 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 ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('weight', dtype='d', direction=function.OUT) function.addParameter('radius', dtype='d', direction=function.OUT) function.addParameter('opacity_area', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def set_random_seed(): """ random seed to use """ function = LegacyFunctionSpecification() function.addParameter('random_seed', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_random_seed(): """ random seed to use """ function = LegacyFunctionSpecification() function.addParameter('random_seed', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_extinction_flag(): """ whether to use the particle opacities (0=no, 1= yes) """ function = LegacyFunctionSpecification() function.addParameter('extinction_flag', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_extinction_flag(): """ whether to use the particle opacities (0=no, 1= yes) """ function = LegacyFunctionSpecification() function.addParameter('extinction_flag', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_minimum_distance(): """ minimum distance to the camera particles can have """ function = LegacyFunctionSpecification() function.addParameter('minimum_distance', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_minimum_distance(): """ minimum distance to the camera particles can have """ function = LegacyFunctionSpecification() function.addParameter('minimum_distance', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_image_angle(): """ angle of image in x direction (for perpective proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_angle', dtype='d', direction=function.IN,unit=units.deg) function.result_type = 'i' return function @legacy_function def get_image_angle(): """ angle of image in x direction (for perpective proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_angle', dtype='d', direction=function.OUT,unit=units.deg) function.result_type = 'i' return function @legacy_function def set_image_width(): """ width of image in x direction (for parallel proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_width', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_image_width(): """ angle of image in x direction (for parallel proj.) """ function = LegacyFunctionSpecification() function.addParameter('image_width', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_image_pixel_size(): """ pixel size of generated image """ function = LegacyFunctionSpecification() function.addParameter('nx', dtype='i', direction=function.IN) function.addParameter('ny', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_image_pixel_size(): """ pixel size of generated image """ function = LegacyFunctionSpecification() function.addParameter('nx', dtype='i', direction=function.OUT) function.addParameter('ny', dtype='i', direction=function.OUT) function.result_type = 'i' return function def get_index_range_inclusive(self): ni,nj,error = self.get_image_pixel_size() return (1, ni, 1, nj) @legacy_function def set_image_target(): """ target point of image """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN) function.addParameter('y', dtype='d', direction=function.IN) function.addParameter('z', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_image_target(): """ target point of image """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT) function.addParameter('y', dtype='d', direction=function.OUT) function.addParameter('z', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_viewpoint(): """ camera position (for perspective proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN) function.addParameter('y', dtype='d', direction=function.IN) function.addParameter('z', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_viewpoint(): """ camera position (for perspective proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT) function.addParameter('y', dtype='d', direction=function.OUT) function.addParameter('z', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_projection_direction(): """ direction of projection (for parallel proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN) function.addParameter('y', dtype='d', direction=function.IN) function.addParameter('z', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_projection_direction(): """ direction of projection (for parallel proj) """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT) function.addParameter('y', dtype='d', direction=function.OUT) function.addParameter('z', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_upvector(): """ specify the orientation of the image by setting the direction vector of image y """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.IN) function.addParameter('y', dtype='d', direction=function.IN) function.addParameter('z', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_upvector(): """ specify the orientation of the image by setting the direction vector of image y """ function = LegacyFunctionSpecification() function.addParameter('x', dtype='d', direction=function.OUT) function.addParameter('y', dtype='d', direction=function.OUT) function.addParameter('z', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_projection_mode(): """ projection mode (parallel or projection """ function = LegacyFunctionSpecification() function.addParameter('projection_mode', dtype='string', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_projection_mode(): """ projection mode (parallel or projection """ function = LegacyFunctionSpecification() function.addParameter('projection_mode', dtype='string', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_image(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['pixel_value']: 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_opdepth_map(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['pixel_opacity']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('number_of_points', 'i', function.LENGTH) function.result_type = 'i' return function class FiMap(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter CommonCode.__init__(self, FiMapInterface(**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_methods(self, handler): handler.add_method( 'new_particle', ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length**2, handler.NO_UNIT, ), ( handler.INDEX, handler.ERROR_CODE, ) ) handler.add_method( 'set_state', ( handler.INDEX, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length**2, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'set_weight', ( handler.INDEX, handler.NO_UNIT, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'set_opacity_area', ( handler.INDEX, generic_unit_system.length**2, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_state', ( handler.INDEX, ), ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.NO_UNIT, generic_unit_system.length, generic_unit_system.length**2, handler.ERROR_CODE, ) ) handler.add_method( 'delete_particle', ( handler.INDEX, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'set_minimum_distance', ( generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_minimum_distance', ( ), ( generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( 'set_image_width', ( generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_image_width', ( ), ( generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( 'set_image_target', ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_image_target', ( ), ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( 'set_viewpoint', ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, ), ( handler.ERROR_CODE, ) ) handler.add_method( 'get_viewpoint', ( ), ( generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, handler.ERROR_CODE, ) ) handler.add_method( 'get_image', ( handler.INDEX, handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) handler.add_method( 'get_opdepth_map', ( handler.INDEX, handler.INDEX, ), ( handler.NO_UNIT, handler.ERROR_CODE, ) ) def define_particle_sets(self, handler): handler.define_grid('image') handler.set_grid_range('image', 'get_index_range_inclusive') handler.add_getter('image', 'get_image') handler.add_getter('image', 'get_opdepth_map') 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_setter('particles', 'set_weight') handler.add_setter('particles', 'set_opacity_area') handler.add_getter('particles', 'get_state') def define_parameters(self, handler): handler.add_method_parameter( "get_projection_mode", "set_projection_mode", "projection_mode", "projection mode (parallel or perspective)", default_value = "parallel" ) handler.add_method_parameter( "get_random_seed", "set_random_seed", "random_seed", "random seed (used for clusters)", default_value = 45678910 ) handler.add_method_parameter( "get_minimum_distance", "set_minimum_distance", "minimum_distance", "near clipping plane", default_value = 0.001 | generic_unit_system.length ) handler.add_boolean_parameter( "get_extinction_flag", "set_extinction_flag", "extinction_flag", "extinction flag (whether to use extinction)", default_value = False ) handler.add_method_parameter( "get_image_angle", "set_image_angle", "image_angle", "image angle - horizontal (used in perspective proj.)", default_value = 45 | units.deg ) handler.add_method_parameter( "get_image_width", "set_image_width", "image_width", "image width - horizontal (used in parallel proj.)", default_value = 1 | generic_unit_system.length ) handler.add_caching_parameter( "set_image_pixel_size", "nx", "nx", "image pixel size (horizontal)", 640, ) handler.add_caching_parameter( "set_image_pixel_size", "ny", "ny", "image pixel size (vertical)", 480, ) handler.add_vector_parameter( "image_size", "image pixel size", ("nx", "ny") ) handler.add_caching_parameter( "set_image_target", "x", "target_x", "x coordinate of the point which the image centers on", 0 | generic_unit_system.length, ) handler.add_caching_parameter( "set_image_target", "y", "target_y", "y coordinate of the point which the image centers on", 0 | generic_unit_system.length, ) handler.add_caching_parameter( "set_image_target", "z", "target_z", "z coordinate of the point which the image centers on", 0 | generic_unit_system.length, ) handler.add_vector_parameter( "image_target", "point which the image centers on", ("target_x", "target_y","target_z") ) handler.add_caching_parameter( "set_viewpoint", "x", "viewpoint_x", "x coordinate of the view point (camera location)", 0 | generic_unit_system.length, ) handler.add_caching_parameter( "set_viewpoint", "y", "viewpoint_y", "y coordinate of the view point (camera location)", 1. | generic_unit_system.length, ) handler.add_caching_parameter( "set_viewpoint", "z", "viewpoint_z", "z coordinate of the view point (camera location)", 0 | generic_unit_system.length, ) handler.add_vector_parameter( "viewpoint", "viewpoint (location of the camera)", ("viewpoint_x", "viewpoint_y","viewpoint_z") ) handler.add_caching_parameter( "set_upvector", "x", "upvector_x", "x component of the up-direction of the image", 0, ) handler.add_caching_parameter( "set_upvector", "y", "upvector_y", "y component of the up-direction of the image", 0, ) handler.add_caching_parameter( "set_upvector", "z", "upvector_z", "z component of the up-direction of the image", 1, ) handler.add_vector_parameter( "upvector", "direction of the up-vector", ("upvector_x", "upvector_y","upvector_z") ) handler.add_caching_parameter( "set_projection_direction", "x", "projection_direction_x", "x component of projection direction (for parallel projections)", 0, ) handler.add_caching_parameter( "set_projection_direction", "y", "projection_direction_y", "y component of projection direction (for parallel projections)", -1, ) handler.add_caching_parameter( "set_projection_direction", "z", "projection_direction_z", "z component of projection direction (for parallel projections)", 0, ) handler.add_vector_parameter( "projection_direction", "direction of projection (for parallel projection)", ("projection_direction_x", "projection_direction_y","projection_direction_z") ) 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 = self.get_image_pixel_size() return (1, nx, 1, ny) def commit_parameters(self): self.parameters.send_cached_parameters_to_code() def define_state(self, handler): CommonCode.define_state(self, handler) #handler.add_transition('END', 'INITIALIZED', 'initialize_code', False) handler.add_transition('INITIALIZED','PREPROJ','commit_parameters') handler.add_transition('PREPROJ','PROJ','init_map') handler.add_transition('PROJ','ERASE','erase_map') handler.add_transition('ERASE','IMAGE','generate_projection') handler.add_transition('IMAGE','PROJ','new_particle',False) handler.add_transition('IMAGE','PROJ','delete_particle',False) handler.add_transition('IMAGE','PROJ','set_state',False) handler.add_transition('IMAGE','PROJ','set_weight',False) handler.add_transition('IMAGE','PROJ','set_opacity_area',False) handler.add_transition('PROJ','INITIALIZED','reset_map') handler.add_transition('IMAGE','INITIALIZED','reset_map') handler.add_method('IMAGE','get_image') handler.add_method('IMAGE','get_opdepth_map') handler.add_method('PROJ', 'new_particle') handler.add_method('PROJ', 'delete_particle') handler.add_method('PROJ', 'set_state') handler.add_method('PROJ', 'set_weight') handler.add_method('PROJ', 'set_opacity_area') handler.add_method('INITIALIZED', 'before_set_parameter') handler.add_method('PROJ', 'before_get_parameter') handler.add_method('PROJ', 'get_image_pixel_size') handler.add_method('IMAGE', 'get_image_pixel_size')
145,248
34.143721
159
py
amuse
amuse-main/src/amuse/community/evtwin/__init__.py
from .interface import Evtwin
30
14.5
29
py
amuse
amuse-main/src/amuse/community/evtwin/interface.py
import os.path from amuse.support import exceptions from amuse.community import * from amuse.community.interface.se import StellarEvolution, StellarEvolutionInterface, \ InternalStellarStructure, InternalStellarStructureInterface from amuse.support.interface import InCodeComponentImplementation from amuse.support.options import OptionalAttributes, option class EVtwinInterface(CodeInterface, LiteratureReferencesMixIn, StellarEvolutionInterface, InternalStellarStructureInterface, CodeWithDataDirectories): """ Evtwin is based on Peter Eggleton's stellar evolution code, and solves the differential equations that apply to the interior of a star. Therefore it is more accurate, but also much slower than the analytic fits-based SSE legacy code, that has the same origin. The work-around for the helium flash is not yet implemented in the AMUSE interface to evtwin. Currently only solar metallicity. .. [#] ADS:1971MNRAS.151..351E ** (Eggleton, P.P. 1971, MNRAS, 151, 351: .. [#] ... "The evolution of low mass stars") .. [#] ADS:2008A&A...488.1007G ** (Glebbeek, Pols & Hurley, 2008 A&A .. [#] ... (for enhancements to the solver)) .. [#] ADS:1972MNRAS.156..361E (Eggleton, P.P. 1972, MNRAS, 156, 361: .. [#] ... "Composition changes during stellar evolution") .. [#] ADS:1973MNRAS.163..279E (Eggleton, P.P. 1973, MNRAS, 163, 279: .. [#] ... "A numerical treatment of double shell source stars") .. [#] ADS:1973A&A....23..325E (Eggleton, P.P., Faulkner, J., & Flannery, B.P. 1973, A&A, 23, 325: .. [#] ... "An Approximate Equation of State for Stellar Material") .. [#] ADS:1994MNRAS.270..121H (Han, Z., Podsiadlowski, P., & Eggleton, P.P. 1994, MNRAS, 270, 121: .. [#] ... "A Possible Criterion for Envelope Ejection in Asymptotic Giant Branch or First Giant Branch Stars") .. [#] ADS:1995MNRAS.274..964P (Pols, O.R., Tout, C.A., Eggleton, P.P., & Han, Z. 1995, MNRAS, 274, 964: .. [#] ... "Approximate input physics for stellar modelling") .. [#] ADS:2001ASPC..229..157E (Eggleton, P.P. 2001, Evolution of Binary and Multiple Star Systems, 229, 157: .. [#] ... "The Braking of Wind") .. [#] ADS:2001ApJ...552..664N (Nelson, C.A., & Eggleton, P.P. 2001, ApJ, 552, 664: .. [#] ... "A Complete Survey of Case A Binary Evolution with Comparison to Observed Algol-type Systems") .. [#] ADS:2002ApJ...575..461E (Eggleton, P.P., & Kiseleva-Eggleton, L. 2002, ApJ, 575, 461: .. [#] ... "The Evolution of Cool Algols") .. [#] ADS:2007A&A...464L..57S (Stancliffe, Glebbeek, Izzard & Pols, 2007 A&A .. [#] ... (for thermohaline mixing)) .. [#] ADS:2004MNRAS.348..201E (Eldridge & Tout, 2004 MNRAS 348 .. [#] ... (for the OPAL 1996 opacity tables)) """ use_modules = ['twinlib', 'import'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="evtwin_worker", **options) LiteratureReferencesMixIn.__init__(self) CodeWithDataDirectories.__init__(self) set_mass_fraction_of_species_at_zone = None set_radius_at_zone = None set_density_at_zone = None set_temperature_at_zone = None @legacy_function def new_zams_star(): """ Define a new star in the code: a zero-age main sequence star with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT) function.addParameter('mass', dtype='float64', unit=units.MSun, direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_prems_star(): """ Define a new star in the code: a pre-main-sequence star with the given mass. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT) function.addParameter('mass', dtype='float64', unit=units.MSun, direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_star_from_file(): """ Define a new star in the code: read the model from file. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT) function.addParameter('filename', dtype='string', direction=function.IN) function.result_type = 'int32' return function def new_particle_with_internal_structure(self, internal_structure, age_tag): if len(internal_structure) > 1: raise exceptions.AmuseException("Can only add one particle with internal structure at a time.") internal_structure = internal_structure[0] self.new_stellar_model( internal_structure.mass[::-1].value_in(units.MSun), internal_structure.radius[::-1].value_in(units.RSun), internal_structure.rho[::-1].value_in(units.g / units.cm**3), internal_structure.pressure[::-1].value_in(units.barye), internal_structure.X_H[::-1], 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], internal_structure.X_Fe[::-1] ) return self.finalize_stellar_model(age_tag) def new_particle_method(self, mass=None, pms=False, internal_structure=None, filename=None, age_tag=0): if not filename is None: return self.new_star_from_file(filename) if not internal_structure is None: return self.new_particle_with_internal_structure(internal_structure, age_tag) if pms: return self.new_prems_star(mass) else: return self.new_zams_star(mass) new_particle = None @legacy_function def get_maximum_number_of_stars(): """ Retrieve the maximum number of stars that can be handled by this instance. """ function = LegacyFunctionSpecification() function.addParameter('maximum_number_of_stars', dtype='int32', direction=function.OUT, description = "The current value of the maximum number of stars") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value of was retrieved """ return function @legacy_function def set_maximum_number_of_stars(): """ Update the maximum number of stars that can be handled by this instance. Need to set this number before calling :method:`initialize_code`. Cannot be changed once initialize_code has been called. """ function = LegacyFunctionSpecification() function.addParameter('maximum_number_of_stars', dtype='int32', direction=function.IN, description = "The new value of the maximum number of stars.") function.result_type = 'int32' function.result_doc = """ 0 - OK Current value was set -1 - ERROR The code cannot update the maximum number of stars """ return function @legacy_function def set_ev_path(): """ Update the path to the EVtwin database. """ function = LegacyFunctionSpecification() function.addParameter('path', dtype='string', direction=function.IN) function.result_type = 'int32' 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.addParameter('max_age_stop_condition', dtype='float64', direction=function.OUT, unit=units.yr) function.result_type = 'int32' 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. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('max_age_stop_condition', dtype='float64', direction=function.IN, unit=units.yr) function.result_type = 'int32' return function @legacy_function def get_min_timestep_stop_condition(): """ Retrieve the current minimum timestep stop condition of this instance (in seconds). 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', dtype='float64', direction=function.OUT, unit=units.s) function.result_type = 'int32' return function @legacy_function def set_min_timestep_stop_condition(): """ Set the new minimum timestep stop condition of this instance (in seconds). Evolution will stop if the timestep required by the solver in order to converge has decreased below this minimum timestep. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('min_timestep', dtype='float64', direction=function.IN, unit=units.s) function.result_type = 'int32' return function @legacy_function def get_convective_overshoot_parameter(): """ Retrieve the current value of the convective overshoot parameter. """ function = LegacyFunctionSpecification() function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.OUT , description="The current value of the convective overshoot parameter.") function.result_type = 'int32' return function @legacy_function def set_convective_overshoot_parameter(): """ Set the value of the convective overshoot parameter. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('convective_overshoot_parameter', dtype='float64', direction=function.IN , description="The new value of the convective overshoot parameter.") function.result_type = 'int32' return function @legacy_function def get_mixing_length_ratio(): """ Retrieve the current value of the mixing length ratio. """ function = LegacyFunctionSpecification() function.addParameter('mixing_length_ratio', dtype='float64', direction=function.OUT , description="The current value of the mixing length ratio.") function.result_type = 'int32' return function @legacy_function def set_mixing_length_ratio(): """ Set the value of the mixing length ratio. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('mixing_length_ratio', dtype='float64', direction=function.IN , description="The new value of the mixing length ratio.") function.result_type = 'int32' return function @legacy_function def get_semi_convection_efficiency(): """ Retrieve the current value of the efficiency of semi-convection, after Langer, Sugimoto & Fricke 1983 (A&A). """ function = LegacyFunctionSpecification() function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.OUT , description="The current value of the efficiency of semi-convection.") function.result_type = 'int32' return function @legacy_function def set_semi_convection_efficiency(): """ Set the value of the efficiency of semi-convection, after Langer, Sugimoto & Fricke 1983 (A&A). This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('semi_convection_efficiency', dtype='float64', direction=function.IN , description="The new value of the efficiency of semi-convection.") function.result_type = 'int32' return function @legacy_function def get_thermohaline_efficiency(): """ Retrieve the current value of the thermohaline mixing parameter, probably only important for binaries and collision remnants. """ function = LegacyFunctionSpecification() function.addParameter('thermohaline_mixing_parameter', dtype='float64', direction=function.OUT , description="The current value of the thermohaline mixing parameter.") function.result_type = 'int32' return function @legacy_function def set_thermohaline_efficiency(): """ Set the value of the thermohaline mixing parameter, probably only important for binaries and collision remnants. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('thermohaline_mixing_parameter', dtype='float64', direction=function.IN , description="The new value of the thermohaline mixing parameter.") function.result_type = 'int32' return function @legacy_function def get_number_of_ionization_elements(): """ Retrieve the current number of elements used for ionization of this instance. With the default value (2), only the ionization of H and He are taken into account in the EoS. For values 3, 4, 5, 6, 7, 8, 9: the elements: C, N, O, Ne,Mg,Si,Fe are also included. Don't try 9. """ function = LegacyFunctionSpecification() function.addParameter('number_of_ionization_elements', dtype='int32', direction=function.OUT , description="The current number of elements used for ionization in EoS solver of this instance.") function.result_type = 'int32' return function @legacy_function def set_number_of_ionization_elements(): """ Set the new number of elements used for ionization of this instance. With the default value (2), only the ionization of H and He are taken into account in the EoS. For values 3, 4, 5, 6, 7, 8, 9: the elements: C, N, O, Ne,Mg,Si,Fe are also included. Don't try 9. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('number_of_ionization_elements', dtype='int32', direction=function.IN , description="The new number of elements used for ionization in EoS solver of this instance.") function.result_type = 'int32' return function @legacy_function def get_manual_mass_transfer_rate(): """ Retrieve the current user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('mass_change', dtype='float64', unit=units.MSun/units.yr, direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_manual_mass_transfer_rate(): """ Set a new user-specified mass transfer rate of the star. (negative for winds, positive for accretion) """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('mass_change', dtype='float64', unit=units.MSun/units.yr, direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_wind_multiplier(): """ Stellar wind switch: can be modulated between 0.0 (no wind) and 1.0 (full strength) """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('wind_multiplier', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_wind_multiplier(): """ Stellar wind switch: can be modulated between 0.0 (no wind) and 1.0 (full strength) """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('wind_multiplier', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_AGB_wind_setting(): """ Retrieve the current AGB wind setting of this instance (1 or 2). (1) means use Wachter et al. (AGB) mass loss prescription. (2) means use Vasiliadis & Wood (AGB) mass loss rate. """ function = LegacyFunctionSpecification() function.addParameter('AGB_wind_setting', dtype='int32', direction=function.OUT , description="The current AGB wind setting of this instance.") function.result_type = 'int32' return function @legacy_function def set_AGB_wind_setting(): """ Set the new AGB wind setting of this instance (1 or 2). (1) means use Wachter et al. (AGB) mass loss prescription. (2) means use Vasiliadis & Wood (AGB) mass loss rate. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('AGB_wind_setting', dtype='int32', direction=function.IN , description="The new AGB wind setting of this instance.") function.result_type = 'int32' return function @legacy_function def get_RGB_wind_setting(): """ Retrieve the current RGB wind setting of this instance. (positive) means use Schroeder & Cuntz mass loss prescription. (negative) means use Reimers mass loss rate. (0) means none. The absolute value is used as efficiency factor. """ function = LegacyFunctionSpecification() function.addParameter('RGB_wind_setting', dtype='float64', direction=function.OUT , description="The current RGB wind setting of this instance.") function.result_type = 'int32' return function @legacy_function def set_RGB_wind_setting(): """ Set the new RGB wind setting of this instance. (positive) means use Schroeder & Cuntz mass loss prescription. (negative) means use Reimers mass loss rate. (0) means none. The absolute value is used as efficiency factor. This needs to be set after calling :method:`initialize_code`. It will be overridden by initialize_code otherwise. """ function = LegacyFunctionSpecification() function.addParameter('RGB_wind_setting', dtype='float64', direction=function.IN , description="The new RGB wind setting of this instance.") function.result_type = 'int32' return function @legacy_function def get_Ostar_wind_setting(): """ Retrieve the current wind setting for O/B stars, i.e. the efficiency factor of the Vink et al. wind prescription. """ function = LegacyFunctionSpecification() function.addParameter('Ostar_wind_setting', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_Ostar_wind_setting(): """ Set the new wind setting for O/B stars, i.e. the efficiency factor of the Vink et al. wind prescription. """ function = LegacyFunctionSpecification() function.addParameter('Ostar_wind_setting', dtype='float64', 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_spin(): """ Retrieve the current spin period (in days) of this 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 stellar type of") function.addParameter('spin', dtype='float64', direction=function.OUT , description="The current spin period (in days) of this star.") function.result_type = 'int32' return function #~ @legacy_function #~ def get_mass_transfer_rate(): #~ """ #~ Retrieve the current mass transfer of the star to the other 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 mass transfer of the star to the other star.") #~ function.result_type = 'int32' #~ function.result_doc = """ #~ 0 - OK #~ The value has been retrieved. #~ -1 - ERROR #~ A star with the given index was not found. #~ """ #~ return function @legacy_function def get_wind_mass_loss_rate(): """ Retrieve the current mass loss rate of the star due to stellar wind. """ 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 mass loss rate of the star due to stellar wind.") function.result_type = 'int32' return function @legacy_function def new_stellar_model(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('mass', dtype='float64', unit=units.MSun, direction=function.IN) function.addParameter('radius', dtype='float64', unit=units.RSun, direction=function.IN) function.addParameter('rho', dtype='float64', unit=units.g / units.cm**3, direction=function.IN) function.addParameter('pressure', dtype='float64', unit=units.barye, direction=function.IN) for par in ['X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']: 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.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.OUT) function.addParameter('age_tag', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_import_model_entropy_accuracy(): """ Retrieve the current value of the entropy accuracy required for convergence, used when importing stellar (merger) models. """ function = LegacyFunctionSpecification() function.addParameter('import_model_entropy_accuracy', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_import_model_entropy_accuracy(): function = LegacyFunctionSpecification() function.addParameter('import_model_entropy_accuracy', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_import_model_entropy_force(): """ Retrieve the current value of entropy_force, used when importing stellar (merger) models. It indicates how hard EVtwin tries to match the entropy profile. Higher values give better agreement, but may be harder to evolve succesfully. """ function = LegacyFunctionSpecification() function.addParameter('import_model_entropy_force', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_import_model_entropy_force(): function = LegacyFunctionSpecification() function.addParameter('import_model_entropy_force', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_stellar_model_element(): """ Return properties of the stellar model at a specific zone. """ function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_zone', dtype='int32', direction=function.IN, description="The index of the zone to get the values of") function.addParameter('index_of_the_star', dtype='int32', direction=function.IN, description="The index of the star to get the values of") for par in ['d_mass', 'mass', 'radius', 'density', 'pressure', 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe']: function.addParameter(par, dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def write_star_to_file(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_star', dtype='int32', direction=function.IN) function.addParameter('filename', dtype='string', direction=function.IN) function.result_type = 'int32' return function class EVtwin(StellarEvolution, InternalStellarStructure): def __init__(self, **options): InCodeComponentImplementation.__init__(self, EVtwinInterface(**options), **options) self.model_time = 0.0 | units.yr def define_parameters(self, handler): StellarEvolution.define_parameters(self,handler) handler.add_boolean_parameter( "get_verbosity", "set_verbosity", "verbosity", "The level of terminal output, verbose or not.", default_value = False ) handler.add_method_parameter( "get_maximum_number_of_stars", "set_maximum_number_of_stars", "maximum_number_of_stars", "Maximum number of stars that can be allocated", default_value = 10 ) handler.add_method_parameter( "get_metallicity", "set_metallicity", "metallicity", "Metallicity of all stats", default_value = 0.02 ) handler.add_method_parameter( None, "set_ev_path", "path_to_data", "Path to the data directory", default_value = self.data_directory ) 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.0e12 | units.yr ) 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.0e6 | units.s ) handler.add_method_parameter( "get_number_of_ionization_elements", "set_number_of_ionization_elements", "number_of_ionization_elements", "The number of elements used for ionization in EoS solver of this instance.", default_value = 2 ) handler.add_method_parameter( "get_convective_overshoot_parameter", "set_convective_overshoot_parameter", "convective_overshoot_parameter", "The convective overshoot parameter.", default_value = 0.12 ) handler.add_method_parameter( "get_mixing_length_ratio", "set_mixing_length_ratio", "mixing_length_ratio", "The mixing-length ratio (alpha).", default_value = 2.0 ) handler.add_method_parameter( "get_semi_convection_efficiency", "set_semi_convection_efficiency", "semi_convection_efficiency", "The efficiency of semi-convection, after Langer, Sugimoto & Fricke 1983 (A&A).", default_value = 0.04 ) handler.add_method_parameter( "get_thermohaline_efficiency", "set_thermohaline_efficiency", "thermohaline_efficiency", "The thermohaline mixing parameter, probably only important for binaries and collision remnants.", default_value = 1.0 ) handler.add_method_parameter( "get_AGB_wind_setting", "set_AGB_wind_setting", "AGB_wind_setting", "The AGB wind setting: (1, 2) for (Wachter&al, Vasiliadis&Wood) mass loss.", default_value = 1 ) handler.add_method_parameter( "get_RGB_wind_setting", "set_RGB_wind_setting", "RGB_wind_setting", "The RGB wind setting: (positive, negative, 0) for (Schroeder&Cuntz, Reimers, none) mass loss.", default_value = 1.0 ) handler.add_method_parameter( "get_Ostar_wind_setting", "set_Ostar_wind_setting", "OB_wind_setting", "The wind setting for O/B stars, i.e. the efficiency factor of the Vink et al. wind prescription", default_value = 1.0 ) handler.add_method_parameter( "get_import_model_entropy_accuracy", "set_import_model_entropy_accuracy", "import_model_entropy_accuracy", "The entropy accuracy required for convergence, used when importing stellar (merger) models.", default_value = 1.0e-4 ) handler.add_method_parameter( "get_import_model_entropy_force", "set_import_model_entropy_force", "import_model_entropy_force", "The current value of entropy_force, used when importing stellar (merger) models." " It indicates how hard EVtwin tries to match the entropy profile." " Higher values give better agreement, but may be harder to evolve succesfully.", default_value = 20.0 ) def define_particle_sets(self, handler): handler.define_set('particles', 'index_of_the_star') handler.set_new('particles', 'new_particle_method') 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_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_manual_mass_transfer_rate', names = ('mass_transfer_rate',)) handler.add_setter('particles', 'set_manual_mass_transfer_rate', names = ('mass_transfer_rate',)) handler.add_method('particles', 'evolve_one_step') handler.add_method('particles', 'evolve_for') InternalStellarStructure.define_particle_sets(self, handler, set_name = 'particles') handler.add_method('particles', 'get_stellar_model', 'get_internal_structure') handler.add_method('particles', 'write_star_to_file') def define_state(self, handler): StellarEvolution.define_state(self, handler) handler.add_method('EDIT', 'new_particle_method') handler.add_method('UPDATE', 'new_particle_method') handler.add_transition('RUN', 'UPDATE', 'new_particle_method', False) def define_errorcodes(self, handler): handler.add_errorcode(5, 'Age greater than maximum age limit.') handler.add_errorcode(2, 'BACKUP -- tstep reduced below limit; quit') InternalStellarStructure.define_errorcodes(self, handler) def define_methods(self, handler): InternalStellarStructure.define_methods(self, handler) StellarEvolution.define_methods(self, handler) handler.add_method( "new_particle_method", (units.MSun, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, units.yr), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( "get_mass_transfer_rate", (handler.INDEX,), (units.MSun/units.yr, handler.ERROR_CODE,) ) handler.add_method( "get_wind_mass_loss_rate", (handler.INDEX,), (units.MSun/units.yr, handler.ERROR_CODE,) ) handler.add_method( "get_spin", (handler.INDEX,), (units.day, handler.ERROR_CODE,) ) handler.add_method( "finalize_stellar_model", (units.yr,), (handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "get_stellar_model_element", (handler.INDEX, handler.INDEX,), (units.MSun, units.MSun, units.RSun, units.g / units.cm**3, units.barye, handler.NO_UNIT, units.K, units.LSun, units.amu, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE) ) def initialize_module_with_default_parameters(self): self.initialize_code() self.commit_parameters() def initialize_module_with_current_parameters(self): self.commit_parameters() def setup_particles(self, particles): self.particles.add_particles(particles) 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_stellar_model(self, index_of_the_star): if hasattr(index_of_the_star, '__iter__'): return [self._create_new_grid(self._specify_stellar_model, index_of_the_star = x) for x in index_of_the_star] else: return self._create_new_grid(self._specify_stellar_model, index_of_the_star = index_of_the_star) def get_range_in_zones(self, index_of_the_star): """ Returns the inclusive range of defined zones/mesh-cells of the star. """ return (1, self.get_number_of_zones(index_of_the_star)) def _specify_stellar_model(self, definition, index_of_the_star = 0): definition.set_grid_range('get_range_in_zones') definition.add_getter('get_stellar_model_element', names=('d_mass', 'mass', 'radius', 'rho', 'pressure', 'entropy', 'temperature', 'luminosity', 'molecular_weight', 'X_H', 'X_He', 'X_C', 'X_N', 'X_O', 'X_Ne', 'X_Mg', 'X_Si', 'X_Fe')) definition.define_extra_keywords({'index_of_the_star':index_of_the_star}) def new_particle_from_model(self, internal_structure, current_age=0|units.Myr, key=None): tmp_star = datamodel.Particle(key=key) tmp_star.internal_structure = internal_structure tmp_star.age_tag = current_age return self.particles.add_particle(tmp_star) Evtwin = EVtwin
38,551
42.46336
121
py
amuse
amuse-main/src/amuse/community/mocassin/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/mocassin/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/mocassin.{version}.tar.gz" filename_template = "mocassin.{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( ['ln','-s', 'mocassin.{version}'.format(version = self.version), 'mocassin'], 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='2.02.69', 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,232
26.9125
89
py
amuse
amuse-main/src/amuse/community/mocassin/__init__.py
# generated file from .interface import Mocassin
49
15.666667
31
py
amuse
amuse-main/src/amuse/community/mocassin/interface.py
from amuse.community import * from amuse.community.interface.common import CommonCodeInterface from amuse.support.core import OrderedDictionary from amuse.units import derivedsi from amuse.support.options import option import os class MocassinInterface(CodeInterface, CommonCodeInterface, CodeWithDataDirectories): MOCASSIN_VERSION = '2.02.70' use_modules = ['mocassin_interface',] def __init__(self, **keyword_arguments): if self.channel_type == 'distributed': raise exceptions.AmuseException("Distributed channel not (yet) supported by Mocassin") CodeInterface.__init__(self, name_of_the_worker="mocassin_worker", **keyword_arguments) CodeWithDataDirectories.__init__(self) self._options = keyword_arguments self._abundancies_table = None def get_default_input_directory(self): return os.path.join(os.path.dirname(__file__), 'data', 'mocassin.{0}'.format(self.MOCASSIN_VERSION), '') def setup_abundancies(self): abundancies_file_name = os.path.join(self.output_directory, 'tmp_abundancies_file') with open(abundancies_file_name, 'w') as abundancies_file: for atomname, value in self.abundancies_table().items(): abundancies_file.write("{0} !{1}\n".format(value, atomname)) self.set_abundancies_filename(abundancies_file_name, 1) def abundancies_table(self): if self._abundancies_table is None: self._abundancies_table = self.default_abundancies_table() return self._abundancies_table def default_abundancies_table(self): result = OrderedDictionary() result['H'] = 1. result['He'] = 0.1 result['Li'] = 0. result['Be'] = 0. result['B'] = 0. result['C'] = 2.2e-4 result['N'] = 4.e-5 result['O'] = 3.3e-4 result['F'] = 0. result['Ne'] = 5.e-5 result['Na'] = 0. result['Mg'] = 0. result['Al'] = 0. result['Si'] = 0. result['P'] = 0. result['S'] = 9.e-6 result['Cl'] = 0. result['Ar'] = 0. result['K'] = 0. result['Ca'] = 0. result['Sc'] = 0. result['Ti'] = 0. result['V'] = 0. result['Cr'] = 0. result['Mn'] = 0. result['Fe'] = 0. result['Co'] = 0. result['Ni'] = 0. result['Cu'] = 0. result['Zn'] = 0. return result @legacy_function def setup_mesh(): function = LegacyFunctionSpecification() function.addParameter('nmeshx', dtype='int32', direction=function.IN) function.addParameter('nmeshy', dtype='int32', direction=function.IN) function.addParameter('nmeshz', dtype='int32', direction=function.IN) function.addParameter('xlength', dtype='float64', direction=function.IN) function.addParameter('ylength', dtype='float64', direction=function.IN) function.addParameter('zlength', dtype='float64', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.result_type = 'int32' return function @legacy_function def setup_auto_convergence(): function = LegacyFunctionSpecification() function.addParameter('convergence_level_increase', dtype='float64', direction=function.IN) function.addParameter('number_of_photons_increase', dtype='float64', direction=function.IN) function.addParameter('maximum_number_of_photons', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def has_auto_convergence(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def uset_auto_convergence(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def set_random_seed(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_position_of_index(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k']: function.addParameter(x, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) for x in ['x','y','z']: function.addParameter(x, dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_abundancies_filename(): function = LegacyFunctionSpecification() function.addParameter('filename', dtype='s', direction=function.IN) function.addParameter('index', dtype='int32', direction=function.IN, default=1) function.result_type = 'int32' return function @legacy_function def get_abundancies_filename(): function = LegacyFunctionSpecification() function.addParameter('index', dtype='int32', direction=function.IN, default=1) function.addParameter('filename', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_input_directory(): function = LegacyFunctionSpecification() function.addParameter('path', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_input_directory(): function = LegacyFunctionSpecification() function.addParameter('path', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_mocassin_output_directory(): function = LegacyFunctionSpecification() function.addParameter('path', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_mocassin_output_directory(): function = LegacyFunctionSpecification() function.addParameter('path', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_percentage_converged(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_constant_hydrogen_density(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_constant_hydrogen_density(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def has_constant_hydrogen_density(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_has_constant_hydrogen_density(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def redirect_outputs_to(): function = LegacyFunctionSpecification() function.addParameter('stdoutstring', dtype='s', direction=function.IN) function.addParameter('stderrstring', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_total_number_of_photons(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_total_number_of_photons(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_total_number_of_points_in_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_total_number_of_points_in_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_initial_nebular_temperature(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_initial_nebular_temperature(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def commit_particles(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def commit_grid(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def iterate(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def step(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def set_symmetricXYZ(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_symmetricXYZ(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dust(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dust(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dust_species_filename(): function = LegacyFunctionSpecification() function.addParameter('filename', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dust_species_filename(): function = LegacyFunctionSpecification() function.addParameter('filename', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dust_sizes_filename(): function = LegacyFunctionSpecification() function.addParameter('filename', dtype='s', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dust_sizes_filename(): function = LegacyFunctionSpecification() function.addParameter('filename', dtype='s', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_maximum_number_of_monte_carlo_iterations(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_maximum_number_of_monte_carlo_iterations(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_minimum_convergence_level(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_minimum_convergence_level(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_high_limit_of_the_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_high_limit_of_the_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_low_limit_of_the_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_low_limit_of_the_frequency_mesh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_convergence_limit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_convergence_limit(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_number_of_ionisation_stages(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_number_of_ionisation_stages(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def define_stars(): function = LegacyFunctionSpecification() 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('temperature', dtype='float64', direction=function.IN) function.addParameter('luminosity', dtype='float64', direction=function.IN) function.addParameter('npoints', dtype='int32', direction=function.LENGTH) function.must_handle_array=True function.result_type = 'int32' return function @legacy_function def set_write_snapshot_every_iteration(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_write_snapshot_every_iteration(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='bool', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_number_of_elements_used(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_grid_electron_temperature(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('electron_temperature', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_electron_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('electron_density', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_active(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('is_active', dtype='bool', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_max_indices(): function = LegacyFunctionSpecification() function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) for parametername in ['ni','nj','nk']: function.addParameter(parametername, dtype='int32', direction=function.OUT) function.can_handle_array = True function.result_type = 'int32' return function @legacy_function def set_emit_rate_of_photons(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_emit_rate_of_photons(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_grid_hydrogen_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('hydrogen_density', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def set_grid_hydrogen_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('hydrogen_density', dtype='float64', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_electron_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('density', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def set_grid_electron_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('density', dtype='float64', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_ion_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k','elemen', 'bin']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('value', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def set_grid_ion_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k','elemen', 'bin']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('value', dtype='float64', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_dust_number_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('dust_number_density', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def set_grid_dust_number_density(): function = LegacyFunctionSpecification() for parametername in ['i','j','k']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('dust_number_density', dtype='float64', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function @legacy_function def get_grid_dust_temperature(): function = LegacyFunctionSpecification() for parametername in ['i','j','k','species', 'grain_size']: function.addParameter(parametername, dtype='int32', direction=function.IN) function.addParameter('index_of_grid', dtype='int32', direction=function.IN, default = 1) function.addParameter('value', dtype='float64', direction=function.OUT) function.addParameter('n', dtype='int32', direction=function.LENGTH) function.must_handle_array = True function.result_type = 'int32' return function #class Parameters(object): # emit_rate_of_photons = MethodParameter(name = "emit_rate_of_photons", unit = units.seconds, default = ) # #class Methods(object): # get_grid_electron_density = MethodWithUnit(name = "get_grid_electron_density", i = INDEX, j = INDEX, k = INDEX, is_active = NOUNIT ) mocassin_rydberg_unit = 13.6 * units.eV class Mocassin(InCodeComponentImplementation): def __init__(self, **options): InCodeComponentImplementation.__init__(self, MocassinInterface(**options), **options) def get_index_range_inclusive(self, index_of_grid = 1): ni, nj, nk = self.get_max_indices(index_of_grid) return (1, ni, 1, nj, 1, nk) def get_index_range_inclusive_ion_density_grid(self, index_of_grid = 1): ni, nj, nk = self.get_max_indices(index_of_grid) nstages = self.get_number_of_ionisation_stages() nbins = self.get_total_number_of_points_in_frequency_mesh() return (1, ni, 1, nj, 1, nk, 1, nstages, 1, nbins) def get_index_range_inclusive_dust_temperature_grid(self, index_of_grid = 1): ni, nj, nk = self.get_max_indices(index_of_grid) nspecies = 1 nsizes = 1 return (1, ni, 1, nj, 1, nk, 1, nspecies, 1, nsizes) def define_methods(self, handler): handler.add_method( 'commit_grid', (), (handler.ERROR_CODE,) ) handler.add_method( 'commit_particles', (), (handler.ERROR_CODE,) ) handler.add_method( 'iterate', (), (handler.ERROR_CODE,) ) handler.add_method( 'step', (), (handler.ERROR_CODE,) ) handler.add_method( 'get_percentage_converged', (), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.cm, units.cm, units.cm, handler.ERROR_CODE,) ) handler.add_method( 'get_max_indices', (handler.INDEX), (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_electron_temperature', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.K, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_hydrogen_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.cm**-3, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_hydrogen_density', (handler.INDEX, handler.INDEX, handler.INDEX, units.cm**-3 , handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_dust_number_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.cm**-3, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_dust_number_density', (handler.INDEX, handler.INDEX, handler.INDEX, units.cm**-3, handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_electron_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.cm**-3, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_electron_density', (handler.INDEX, handler.INDEX, handler.INDEX, units.cm**-3 , handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_dust_temperature', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (units.K, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_ion_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_ion_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.NO_UNIT , handler.INDEX), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_active', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'define_stars', (units.cm, units.cm, units.cm, units.K, 1e36 * units.erg * (units.s**-1)), (handler.ERROR_CODE,) ) handler.add_method( "get_abundancies_filename", (handler.NO_UNIT, ), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_abundancies_filename", (handler.NO_UNIT, handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_constant_hydrogen_density", (), (1.0/units.cm**3, handler.ERROR_CODE,) ) handler.add_method( "set_constant_hydrogen_density", (1.0/units.cm**3, ), (handler.ERROR_CODE,) ) handler.add_method( "get_convergence_limit", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_convergence_limit", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_emit_rate_of_photons", (), (1e36 / units.s, handler.ERROR_CODE,) ) handler.add_method( "set_emit_rate_of_photons", (1e36 / units.s, ), (handler.ERROR_CODE,) ) handler.add_method( "get_high_limit_of_the_frequency_mesh", (), (mocassin_rydberg_unit, handler.ERROR_CODE,) ) handler.add_method( "set_high_limit_of_the_frequency_mesh", (mocassin_rydberg_unit, ), (handler.ERROR_CODE,) ) handler.add_method( "get_initial_nebular_temperature", (), (units.K, handler.ERROR_CODE,) ) handler.add_method( "set_initial_nebular_temperature", (units.K, ), (handler.ERROR_CODE,) ) handler.add_method( "get_inner_radius_of_the_ionised_region", (), (units.cm, handler.ERROR_CODE,) ) handler.add_method( "set_inner_radius_of_the_ionised_region", (units.cm, ), (handler.ERROR_CODE,) ) handler.add_method( "get_input_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_input_directory", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_mocassin_output_directory", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_mocassin_output_directory", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_low_limit_of_the_frequency_mesh", (), (mocassin_rydberg_unit, handler.ERROR_CODE,) ) handler.add_method( "set_low_limit_of_the_frequency_mesh", (mocassin_rydberg_unit, ), (handler.ERROR_CODE,) ) handler.add_method( "get_maximum_number_of_monte_carlo_iterations", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_maximum_number_of_monte_carlo_iterations", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_minimum_convergence_level", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_minimum_convergence_level", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_number_of_ionisation_stages", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_number_of_ionisation_stages", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_symmetricXYZ", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_symmetricXYZ", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_dust", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_dust", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_dust_species_filename", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_dust_species_filename", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_dust_sizes_filename", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_dust_sizes_filename", (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( "get_total_number_of_photons", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_total_number_of_photons", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_total_number_of_points_in_frequency_mesh", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_total_number_of_points_in_frequency_mesh", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_write_snapshot_every_iteration", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_write_snapshot_every_iteration", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( 'setup_mesh', (handler.NO_UNIT, handler.NO_UNIT, handler.NO_UNIT, units.cm, units.cm, units.cm, handler.NO_UNIT,), (handler.ERROR_CODE,) ) def define_parameters(self, handler): handler.add_method_parameter( "get_abundancies_filename", "set_abundancies_filename", "abundancies_filename", "<fill>", default_value = "" ) handler.add_method_parameter( "get_constant_hydrogen_density", "set_constant_hydrogen_density", "constant_hydrogen_density", "<fill>", default_value = 100.0 | (1.0/units.cm**3) ) handler.add_method_parameter( "get_convergence_limit", "set_convergence_limit", "convergence_limit", "<fill>", default_value = 0.0 ) handler.add_method_parameter( "get_emit_rate_of_photons", "set_emit_rate_of_photons", "emit_rate_of_photons", "This is the number of hydrogen-ionizing photons emitted by the source per unit time. Only used when a single star is modelled", default_value = 0.0 | (1e36 / units.s) ) handler.add_method_parameter( "get_high_limit_of_the_frequency_mesh", "set_high_limit_of_the_frequency_mesh", "high_limit_of_the_frequency_mesh", "<fill>", default_value = 15. | mocassin_rydberg_unit ) handler.add_method_parameter( "get_initial_nebular_temperature", "set_initial_nebular_temperature", "initial_nebular_temperature", "Initial guess for the nebular temperature. ", default_value = 10000.0 | units.K ) #~ handler.add_method_parameter( #~ "get_inner_radius_of_the_ionised_region", #~ "set_inner_radius_of_the_ionised_region", #~ "inner_radius_of_the_ionised_region", #~ "Inner radius of the ionised region", #~ default_value = 0.0 | units.cm #~ ) handler.add_method_parameter( "get_input_directory", "set_input_directory", "input_directory", "<fill>", default_value = 0.0 ) handler.add_method_parameter( "get_low_limit_of_the_frequency_mesh", "set_low_limit_of_the_frequency_mesh", "low_limit_of_the_frequency_mesh", "<fill>", default_value = 1.001e-5 | mocassin_rydberg_unit ) handler.add_method_parameter( "get_maximum_number_of_monte_carlo_iterations", "set_maximum_number_of_monte_carlo_iterations", "maximum_number_of_monte_carlo_iterations", "<fill>", default_value = 0.0 ) handler.add_method_parameter( "get_minimum_convergence_level", "set_minimum_convergence_level", "minimum_convergence_level", "<fill>", default_value = 0.0 ) handler.add_method_parameter( "get_number_of_ionisation_stages", "set_number_of_ionisation_stages", "number_of_ionisation_stages", "<fill>", default_value = 6 ) handler.add_method_parameter( "get_symmetricXYZ", "set_symmetricXYZ", "symmetricXYZ", "If true assumes model is symetric in the X, Y and Z axes", default_value = 0.0 ) handler.add_method_parameter( "get_dust", "set_dust", "dust", "If true also includes dust in the model", default_value = False ) handler.add_method_parameter( "get_dust_species_filename", "set_dust_species_filename", "dust_species_filename", "Name of the file that contains a list of species", default_value = "none" ) handler.add_method_parameter( "get_dust_sizes_filename", "set_dust_sizes_filename", "dust_sizes_filename", "Name of the file that contains a list of grain sizes and their fractions", default_value = "none" ) handler.add_method_parameter( "get_total_number_of_photons", "set_total_number_of_photons", "total_number_of_photons", "Total number of photons to start the iteration with", default_value = 0.0 ) handler.add_method_parameter( "get_total_number_of_points_in_frequency_mesh", "set_total_number_of_points_in_frequency_mesh", "total_number_of_points_in_frequency_mesh", "<fill>", default_value = 0.0 ) handler.add_method_parameter( "get_write_snapshot_every_iteration", "set_write_snapshot_every_iteration", "write_snapshot_every_iteration", "If True will write the data to an output directory after every monte carlo iteration", default_value = 0.0 ) 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", 2e19 | units.cm, ) handler.add_caching_parameter( "setup_mesh", "ylength", "length_y", "length of model in the x direction", 2e19 | units.cm, ) handler.add_caching_parameter( "setup_mesh", "zlength", "length_z", "length of model in the z direction", 2e19 | units.cm, ) 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") ) def commit_parameters(self): self.setup_abundancies() self.parameters.send_cached_parameters_to_code() self.overridden().commit_parameters() 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_electron_temperature', names=('electron_temperature',)) handler.add_getter('grid', 'get_grid_electron_density', names=('electron_density',)) handler.add_setter('grid', 'set_grid_electron_density', names=('electron_density',)) handler.add_getter('grid', 'get_grid_hydrogen_density', names=('hydrogen_density',)) handler.add_setter('grid', 'set_grid_hydrogen_density', names=('hydrogen_density',)) handler.add_getter('grid', 'get_grid_dust_number_density', names=('dust_number_density',)) handler.add_setter('grid', 'set_grid_dust_number_density', names=('dust_number_density',)) handler.define_extra_keywords('grid', {'index_of_grid':1}) handler.define_grid('ion_density_grid') handler.set_grid_range('ion_density_grid', 'get_index_range_inclusive_ion_density_grid') handler.add_getter('ion_density_grid', 'get_grid_ion_density', names=('density',)) handler.add_setter('ion_density_grid', 'set_grid_ion_density', names=('density',)) handler.define_extra_keywords('ion_density_grid', {'index_of_grid':1}) handler.define_grid('dust_temperature_grid') handler.set_grid_range('dust_temperature_grid', 'get_index_range_inclusive_dust_temperature_grid') handler.add_getter('dust_temperature_grid', 'get_grid_dust_temperature', names=('temperature',)) handler.define_extra_keywords('dust_temperature_grid', {'index_of_grid':1}) handler.define_inmemory_set('particles') def commit_particles(self): self.define_stars( self.particles.x, self.particles.y, self.particles.z, self.particles.temperature, self.particles.luminosity ) self.overridden().commit_particles()
46,591
34.404255
141
py
amuse
amuse-main/src/amuse/community/twobody/twobody.py
from amuse.community.twobody.interface import *
48
23.5
47
py
amuse
amuse-main/src/amuse/community/twobody/test_moon.py
import numpy import amuse.community.twobody.twobody as twobody from amuse.units.units import * if __name__=='__main__': pos_earth=numpy.array([ 8.418982185410142E-01, 5.355823303978186E-01, 2.327960005926782E-05]) | AU vel_earth=numpy.array([-9.488931818313919E-03, 1.447515189957170E-02, 3.617712172296458E-07]) | AUd pos_moon=numpy.array([8.426656721530955E-01, 5.331110650437484E-01, -6.837900390288286E-05]) | AU vel_moon=numpy.array([-8.943352544499154E-03, 1.467795416516487E-02, 4.840393580601162E-05]) | AUd mass_earth=5.9742e24 | kg mass_moon=7.3477e22 | kg radius_earth=6371 | km radius_moon=1737.1 | km cmpos=(pos_earth*mass_earth+pos_moon*mass_moon)/(mass_earth+mass_moon) cmvel=(vel_earth*mass_earth+vel_moon*mass_moon)/(mass_earth+mass_moon) pos_earth=pos_earth-cmpos vel_earth=vel_earth-cmvel pos_moon=pos_moon-cmpos vel_moon=vel_moon-cmvel nb=twobody.TwoBody() earth,err=nb.new_particle(mass_earth.value_in(kg),radius_earth.value_in(m), pos_earth[0].value_in(m),pos_earth[1].value_in(m),pos_earth[2].value_in(m), vel_earth[0].value_in(m/s),vel_earth[1].value_in(m/s),vel_earth[2].value_in(m/s)) moon,err=nb.new_particle(mass_moon.value_in(kg),radius_moon.value_in(m), pos_moon[0].value_in(m),pos_moon[1].value_in(m),pos_moon[2].value_in(m), vel_moon[0].value_in(m/s),vel_moon[1].value_in(m/s),vel_moon[2].value_in(m/s)) nb.evolve_model( (27.321582| day ).value_in(s)) moonstate,err=nb.get_state(moon) print(pos_moon[0].value_in(km), (moonstate['x'] | m).value_in(km)) print(pos_moon[1].value_in(km), (moonstate['y'] | m).value_in(km)) print(pos_moon[2].value_in(km), (moonstate['z'] | m).value_in(km)) earthstate,err=nb.get_state(earth) print(pos_earth[0].value_in(km), (earthstate['x'] | m).value_in(km)) print(pos_earth[1].value_in(km), (earthstate['y'] | m).value_in(km)) print(pos_earth[2].value_in(km), (earthstate['z'] | m).value_in(km))
2,236
43.74
87
py
amuse
amuse-main/src/amuse/community/twobody/__init__.py
from .interface import Twobody
31
15
30
py
amuse
amuse-main/src/amuse/community/twobody/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 import copy,numpy import numpy as math from amuse.units.quantities import zero # tbd: initial value for time_Radius solver from amuse.datamodel import Particles from amuse.rfi.core import * from functools import reduce def stumpff_C(z): if(z==0): return 1/2. if(z>0): sz=math.sqrt(z) return (1-math.cos(sz))/z if(z<0): sz=math.sqrt(-z) return -(math.cosh(sz)-1)/z def stumpff_S(z): if(z==0): return 1/6. if(z>0): sz=math.sqrt(z) return (sz-math.sin(sz))/sz**3 if(z<0): sz=math.sqrt(-z) return (math.sinh(sz)-sz)/sz**3 def stumpff_C_prime(z): return (stumpff_C(z)-3*stumpff_S(z))/2/z def stumpff_S_prime(z): return (1-stumpff_S(z)-2*stumpff_C(z))/2/z def lagrange_f(xi,r0,vr0,smu,alpha): return 1.-xi**2/r0*stumpff_C(alpha*xi**2) def lagrange_dfdxi(xi,r0,vr0,smu,alpha): z=alpha*xi**2 return xi/r0*(z*stumpff_S(z)-1) def lagrange_g(xi,r0,vr0,smu,alpha): z=alpha*xi**2 return r0*vr0*(xi/smu)**2*stumpff_C(z)-r0*xi*z/smu*stumpff_S(z)+r0*xi/smu def lagrange_dgdxi(xi,r0,vr0,smu,alpha): z=alpha*xi**2 return r0*vr0/smu*(xi/smu)*(1-z*stumpff_S(z))-z*r0/smu*stumpff_C(z)+r0/smu def universal_kepler(xi,r0,vr0,smu,alpha): z=alpha*xi**2 return (r0*vr0*xi**2*stumpff_C(z)/smu+ (1-alpha*r0)*xi**3*stumpff_S(z)+r0*xi) def universal_kepler_dxi(xi,r0,vr0,smu,alpha): z=alpha*xi**2 return (r0*vr0*xi*(1-alpha*xi**2*stumpff_S(z))/smu + (1-alpha*r0)*xi**2*stumpff_C(z)+r0) def universal_kepler_dxidxi(xi,r0,vr0,smu,alpha): z=alpha*xi**2 # return r0*vr0/smu-alpha*r0*vr0*xi**2/smu*stumpff_C(z)+\ # (1-alpha*r0)*xi*(1-z*stumpff_S(z)) return -alpha*universal_kepler(xi,r0,vr0,smu,alpha)+r0*vr0/smu+xi def newton(f,x0,fprime=None,args=(),tol=1.48e-8,maxiter=50): if fprime is None: print("provide fprime") return x0 i=0 x=x0 while (i<maxiter): fv=f(x,*args) dfv=fprime(x,*args) if(dfv==0): return x0,-2 delta=-fv/dfv if(abs(delta)<tol): return x+delta,0 x=x+delta i=i+1 return x,-1 def laguerre(f,x0,fprime=None,fprimeprime=None,args=(),order=4,tol=1.e-14,maxiter=50): if fprime is None: print("provide fprime") return x0 if fprimeprime is None: print("provide fprimeprime") return x0 i=0 x=x0 while (i<maxiter): fv=f(x,*args) dfv=fprime(x,*args) ddfv=fprimeprime(x,*args) if(dfv==0 or ddfv==0): return x0,-2 delta=-order*fv/(dfv+math.sign(dfv)* math.abs((order-1)**2*dfv**2-order*(order-1)*fv*ddfv)**0.5) if(abs(delta)<tol): return x+delta,0 x=x+delta i=i+1 return x,-1 def universal_time_radius_solver(radius,mu,pos0,vel0,dt): r02=reduce(lambda x,y: x+ y**2,pos0,0) v02=reduce(lambda x,y: x+ y**2,vel0,0) v0r0=reduce(lambda x,y: x+y, pos0*vel0,0) r0=math.sqrt(r02) v0=math.sqrt(v02) vr0=v0r0/r0 h2=r02*v02-(v0r0)**2 p=h2/mu alpha=2./r0-v0**2/mu rp=p/(1+math.sqrt(1-p*alpha)) if(radius < rp): return dt,0 if(r0==radius): return 0.,1 if(alpha>0): ra=p/(1-math.sqrt(1-p*alpha)) if(radius > ra): return dt,0 smu=math.sqrt(mu) xi0=1/math.sqrt(alpha) def f(xi): return universal_kepler_dxi(xi,r0,vr0,smu,alpha)-radius def df(xi): return universal_kepler_dxidxi(xi,r0,vr0,smu,alpha) xi,err=newton(f,xi0,fprime=df,tol=1.e-10) dt_coll=universal_kepler(xi,r0,vr0,smu,alpha)/smu if(dt_coll > 0 and dt_coll < dt): return dt_coll,1 else: return dt,0 def collision(radius,mu,pos0,vel0,dt): return universal_time_radius_solver(radius,mu,pos0,vel0,dt) def universal_solver_newton(mu,pos0,vel0,dt): smu=math.sqrt(mu) r0=math.sqrt(reduce(lambda x,y: x+ y**2,pos0,0)) v0=math.sqrt(reduce(lambda x,y: x+ y**2,vel0,0)) vr0=(reduce(lambda x,y: x+y, pos0*vel0,0))/r0 alpha=2./r0-v0**2/mu if(alpha >= 0): xi0=smu*alpha*dt else: xi0=math.sign(dt)/math.sqrt(-alpha)*math.log(1-2*mu*dt*alpha/((vr0*r0)+ math.sign(dt)*smu/math.sqrt(-alpha)*(1-r0*alpha)) ) # this last formula is 4.5.11 in bate et al., fundamentals of astrodynamics # with +1 in the logarithm dxi0=smu/r0*dt if(abs(alpha*dxi0**2)<1): xi0=dxi0 def f(xi): return universal_kepler(xi,r0,vr0,smu,alpha)-smu*dt def df(xi): return universal_kepler_dxi(xi,r0,vr0,smu,alpha) xi,err=newton(f,xi0,fprime=df,tol=1.e-10) # print dt,xi,xi0 pos=pos0*lagrange_f(xi,r0,vr0,smu,alpha)+vel0*lagrange_g(xi,r0,vr0,smu,alpha) r=math.sqrt(reduce(lambda x,y: x+ y**2,pos,0)) vel=pos0*smu/r*lagrange_dfdxi(xi,r0,vr0,smu,alpha)+ \ vel0*smu/r*lagrange_dgdxi(xi,r0,vr0,smu,alpha) return pos,vel def universal_solver(mu,pos0,vel0,dt): smu=math.sqrt(mu) r0=math.sqrt(reduce(lambda x,y: x+ y**2,pos0,0)) v0=math.sqrt(reduce(lambda x,y: x+ y**2,vel0,0)) vr0=(reduce(lambda x,y: x+y, pos0*vel0,0))/r0 alpha=2./r0-v0**2/mu if(alpha >= 0): xi0=smu*alpha*dt else: xi0=math.sign(dt)/math.sqrt(-alpha)*math.log(1-2*mu*dt*alpha/((vr0*r0)+ math.sign(dt)*smu/math.sqrt(-alpha)*(1-r0*alpha)) ) # this last formula is 4.5.11 in bate et al., fundamentals of astrodynamics # with +1 in the logarithm dxi0=smu/r0*dt if(abs(alpha*dxi0**2)<1): xi0=dxi0 def f(xi): return universal_kepler(xi,r0,vr0,smu,alpha)-smu*dt def df(xi): return universal_kepler_dxi(xi,r0,vr0,smu,alpha) def ddf(xi): return universal_kepler_dxidxi(xi,r0,vr0,smu,alpha) xi,err=laguerre(f,xi0,fprime=df,fprimeprime=ddf) # print dt,xi,xi0 pos=pos0*lagrange_f(xi,r0,vr0,smu,alpha)+vel0*lagrange_g(xi,r0,vr0,smu,alpha) r=math.sqrt(reduce(lambda x,y: x+ y**2,pos,0)) vel=pos0*smu/r*lagrange_dfdxi(xi,r0,vr0,smu,alpha)+ \ vel0*smu/r*lagrange_dgdxi(xi,r0,vr0,smu,alpha) return pos,vel class TwoBodyImplementation(object): __G = 1.0 def __init__(self): self.initialize_code() def initialize_code(self): self.particles=[] self.tnow=0.0 self.begin_time_parameter = 0.0 return 0 def cleanup_code(self): self.particles=[] return 0 def commit_parameters(self): if self.tnow == 0.0: self.tnow = self.begin_time_parameter return 0 def commit_particles(self): return 0 def recommit_particles(self): return 0 def synchronize_model(self): return 0 def initialize(self): pass def new_particle(self, index_of_the_particle, mass, radius, x, y, z, vx, vy, vz): index_of_the_particle.value = 0 if( len(self.particles)>=2): return -1 self.particles.append( { 'mass': mass, 'radius' : radius, 'x' : x, 'y' : y, 'z' : z, 'vx' : vx, 'vy' : vy, 'vz' : vz, } ) 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: particle = self.particles[index_of_the_particle] particle['mass'] = mass particle['radius'] = radius particle['x'] =x particle['y'] =y particle['z'] =z particle['vx'] =vx particle['vy'] =vy particle['vz'] =vz return 0 except: return -1 def set_mass(self, index_of_the_particle, mass): try: particle = self.particles[index_of_the_particle] particle['mass'] = mass return 0 except: return -1 def set_velocity(self, index_of_the_particle, vx, vy, vz): try: particle = self.particles[index_of_the_particle] particle['vx'] =vx particle['vy'] =vy particle['vz'] =vz return 0 except: return -1 def set_position(self, index_of_the_particle, x, y, z): try: particle = self.particles[index_of_the_particle] particle['x'] =x particle['y'] =y particle['z'] =z return 0 except: return -1 def get_state(self, index_of_the_particle, mass, radius, x, y, z, vx, vy, vz): try: particle = self.particles[index_of_the_particle] mass.value = particle['mass'] radius.value = particle['radius'] x.value = particle['x'] y.value = particle['y'] z.value = particle['z'] vx.value = particle['vx'] vy.value = particle['vy'] vz.value = particle['vz'] return 0 except: return -1 def get_mass(self, index_of_the_particle, mass): try: particle = self.particles[index_of_the_particle] mass.value = particle['mass'] return 0 except: return -1 def get_radius(self, index_of_the_particle, radius): try: particle = self.particles[index_of_the_particle] radius.value = particle['radius'] return 0 except: return -1 def get_position(self, index_of_the_particle, x, y, z): try: particle = self.particles[index_of_the_particle] x.value = particle['x'] y.value = particle['y'] z.value = particle['z'] return 0 except: return -1 def get_velocity(self, index_of_the_particle, vx, vy, vz): try: particle = self.particles[index_of_the_particle] vx.value = particle['vx'] vy.value = particle['vy'] vz.value = particle['vz'] return 0 except: return -1 def get_time(self, time): time.value = self.tnow return 0 def get_kinetic_energy(self, kinetic_energy): if(len(self.particles)!=1 and len(self.particles)!=2): return -1 if(len(self.particles)==1): return -2 if(len(self.particles)==2): vel0=numpy.array( [self.particles[0]['vx'], self.particles[0]['vy'], self.particles[0]['vz']] ) vel1=numpy.array( [self.particles[1]['vx'], self.particles[1]['vy'], self.particles[1]['vz']] ) v0=reduce(lambda x,y: x+ y**2,vel0,0) v1=reduce(lambda x,y: x+ y**2,vel1,0) mass0=self.particles[0]['mass'] mass1=self.particles[1]['mass'] kinetic_energy.value = 0.5*(mass0*v0+mass1*v1) return 0 def get_gravity_at_point(self, eps, x, y, z, ax, ay, az, npoints): if(len(self.particles)==1): return -2 elif(len(self.particles)==2): ax.value=0. ay.value=0. az.value=0. for i in [0,1]: mass=self.particles[i]['mass'] xx=self.particles[i]['x'] yy=self.particles[i]['y'] zz=self.particles[i]['z'] dr2=((xx-x)**2+(yy-y)**2+(zz-z)**2+eps**2) ax.value+=self.__G*mass*(xx-x)/dr2**1.5 ay.value+=self.__G*mass*(yy-y)/dr2**1.5 az.value+=self.__G*mass*(zz-z)/dr2**1.5 return 0 else: return -1 def get_potential_at_point(self, eps, x, y, z, phi, npoints): if(len(self.particles)==1): return -2 elif(len(self.particles)==2): phi.value = zero for i in [0,1]: mass=self.particles[i]['mass'] xx=self.particles[i]['x'] yy=self.particles[i]['y'] zz=self.particles[i]['z'] dr2=((xx-x)**2+(yy-y)**2+(zz-z)**2+eps**2) phi.value += -self.__G*mass/dr2**0.5 return 0 else: return -1 def get_begin_time(self, value_out): value_out.value = self.begin_time_parameter return 0 def set_begin_time(self, value_in): self.begin_time_parameter = value_in return 0 def get_potential_energy(self, potential_energy): if(len(self.particles)!=1 and len(self.particles)!=2): return -1 if(len(self.particles)==1): return -2 if(len(self.particles)==2): pos0=numpy.array( [self.particles[0]['x'], self.particles[0]['y'], self.particles[0]['z']] ) pos1=numpy.array( [self.particles[1]['x'], self.particles[1]['y'], self.particles[1]['z']] ) dpos=pos0-pos1 mass0=self.particles[0]['mass'] mass1=self.particles[1]['mass'] r=math.sqrt(reduce(lambda x,y: x+ y**2,dpos,0)) potential_energy.value = -self.__G*mass0*mass1/r return 0 def evolve_model(self, time): time_end = time if(len(self.particles)!=1 and len(self.particles)!=2): return -1 if(len(self.particles)==1): mu=self.__G*self.particles[0]['mass'] radius=self.particles[0]['radius'] dpos_initial=numpy.array( [self.particles[0]['x'], self.particles[0]['y'], self.particles[0]['z']] ) dvel_initial=numpy.array( [self.particles[0]['vx'], self.particles[0]['vy'], self.particles[0]['vz']] ) dt,collisionflag=collision(radius,mu,dpos_initial,dvel_initial,time_end-self.tnow) dpos,dvel=universal_solver(mu,dpos_initial,dvel_initial,dt) self.particles[0]['x']=dpos[0] self.particles[0]['y']=dpos[1] self.particles[0]['z']=dpos[2] self.particles[0]['vx']=dvel[0] self.particles[0]['vy']=dvel[1] self.particles[0]['vz']=dvel[2] if(len(self.particles)==2): mu=self.__G*(self.particles[0]['mass']+self.particles[1]['mass']) radius=self.particles[0]['radius']+self.particles[1]['radius'] tm=(self.particles[0]['mass']+self.particles[1]['mass']) m0=self.particles[0]['mass'] m1=self.particles[1]['mass'] pos0=numpy.array( [self.particles[0]['x'], self.particles[0]['y'], self.particles[0]['z']] ) vel0=numpy.array( [self.particles[0]['vx'], self.particles[0]['vy'], self.particles[0]['vz']] ) pos1=numpy.array( [self.particles[1]['x'], self.particles[1]['y'], self.particles[1]['z']] ) vel1=numpy.array( [self.particles[1]['vx'], self.particles[1]['vy'], self.particles[1]['vz']] ) dpos_initial=pos0-pos1 dvel_initial=vel0-vel1 cmpos=(m0*pos0+m1*pos1)/tm cmvel=(m0*vel0+m1*vel1)/tm dt,collisionflag=collision(radius,mu,dpos_initial,dvel_initial,time_end-self.tnow) dpos,dvel=universal_solver(mu,dpos_initial,dvel_initial,dt) cmpos=cmpos+(time_end-self.tnow)*cmvel f0=m1/tm f1=m0/tm self.particles[0]['x']=cmpos[0]+f0*dpos[0] self.particles[0]['y']=cmpos[1]+f0*dpos[1] self.particles[0]['z']=cmpos[2]+f0*dpos[2] self.particles[0]['vx']=cmvel[0]+f0*dvel[0] self.particles[0]['vy']=cmvel[1]+f0*dvel[1] self.particles[0]['vz']=cmvel[2]+f0*dvel[2] self.particles[1]['x']=cmpos[0]-f1*dpos[0] self.particles[1]['y']=cmpos[1]-f1*dpos[1] self.particles[1]['z']=cmpos[2]-f1*dpos[2] self.particles[1]['vx']=cmvel[0]-f1*dvel[0] self.particles[1]['vy']=cmvel[1]-f1*dvel[1] self.particles[1]['vz']=cmvel[2]-f1*dvel[2] self.tnow=self.tnow+dt return collisionflag class TwoBodyInterface(PythonCodeInterface, GravitationalDynamicsInterface, GravityFieldInterface): def __init__(self, **options): PythonCodeInterface.__init__(self, TwoBodyImplementation, 'twobody_worker', **options) class TwoBody(GravitationalDynamics, GravityFieldCode): def __init__(self, convert_nbody = None, **options): nbody_interface = TwoBodyInterface(**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 get_epsilon_squared(self): return zero def define_parameters(self, handler): handler.add_method_parameter( "get_epsilon_squared", None, "epsilon_squared", "smoothing parameter for gravity calculations", default_value = zero ) 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 ) Twobody = TwoBody
18,958
31.464041
99
py
amuse
amuse-main/src/amuse/community/simplex2_5/__init__.py
0
0
0
py
amuse
amuse-main/src/amuse/community/simplex2_5/interface.py
import os.path from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community import * from amuse.community.simplex.interface import *
171
27.666667
76
py
amuse
amuse-main/src/amuse/community/fractalcluster/__init__.py
from .interface import Fractalcluster
38
18.5
37
py
amuse
amuse-main/src/amuse/community/fractalcluster/interface.py
import numpy import os.path from amuse.community import * from amuse.datamodel import Particles from amuse import datamodel from amuse.units import nbody_system from amuse.community.interface.common import CommonCodeInterface, CommonCode class FractalClusterInterface(CodeInterface, LiteratureReferencesMixIn): """ makes fractal of nstar particles of dimension fdim, using ndiv subunits forcing the number of cells if force=.true. reference: .. [#] ADS:2004A&A...413..929G (Simon Goodwin & Ant Whitworth (2004, A&A, 413, 929)) """ 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 'fractal_worker' @legacy_function def get_state(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('id', dtype='i', direction=function.IN) for x in ['x','y','z','vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('nstar', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def generate_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def get_fractal_dimension(): function = LegacyFunctionSpecification() function.addParameter('fdim', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_fractal_dimension(): function = LegacyFunctionSpecification() function.addParameter('fdim', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_random_seed(): function = LegacyFunctionSpecification() function.addParameter('seed', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_random_seed(): function = LegacyFunctionSpecification() function.addParameter('seed', dtype='i', direction=function.IN) function.result_type = 'i' return function @legacy_function def get_nstar(): function = LegacyFunctionSpecification() function.addParameter('nstar', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def set_nstar(): function = LegacyFunctionSpecification() function.addParameter('nstar', dtype='i', direction=function.IN) function.result_type = 'i' return function new_particle = None def delete_particle(self, index_of_the_particle): return 0 @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', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function class FractalCluster(CommonCode): def __init__(self, unit_converter=None, **options): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, FractalClusterInterface(**options), **options) def initialize_code(self): pass def cleanup_code(self): pass def commit_parameters(self): pass def recommit_parameters(self): pass def define_parameters(self, handler): handler.add_method_parameter( "get_nstar", "set_nstar", "number_of_particles", "the number of particles to be generated in the model", default_value = 0 ) handler.add_method_parameter( "get_fractal_dimension", "set_fractal_dimension", "fractal_dimension", "the fractal dimension of the spatial particle distribution", default_value = 1.6 ) handler.add_method_parameter( "get_random_seed", "set_random_seed", "random_seed", "the initial seed to be used by the random number generator", default_value = 1234321 ) 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_state", (handler.INDEX,), [nbody_system.length]*3 + [nbody_system.speed]*3 + [handler.ERROR_CODE] ) handler.add_method("get_target_number_of_particles", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_target_number_of_particles", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_fractal_dimension", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_fractal_dimension", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) handler.add_method("get_random_seed", (), (handler.NO_UNIT, handler.ERROR_CODE,)) handler.add_method("set_random_seed", (handler.NO_UNIT, ), (handler.ERROR_CODE,)) 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_state') def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_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', 'generate_particles', False) handler.add_transition('RUN', 'EDIT', 'clear_particle_set') handler.add_method('EDIT', 'get_number_of_particles_updated') handler.add_method('RUN', 'get_number_of_particles_updated') handler.add_method('RUN', 'get_state') def generate_particles(self): result = self.overridden().generate_particles() self.update_particle_set() 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(1, number_of_updated_particles+1)) ) def clear_particle_set(self): if len(self.particles): self.particles.remove_particles(self.particles) class MakeFractalCluster(object): def __init__(self, N=None, convert_nbody=None, masses=None, do_scale=True, random_seed=None, fractal_dimension=1.6, virial_ratio=0.5, verbose=False, match_N=True): if masses is None: if N is None: raise exceptions.AmuseException("Either keyword argument 'N' (number of particles) or " "'masses' (vector quantity with mass of each particle) is required.") self.masses = numpy.ones(N) / N | nbody_system.mass self.N = N else: if not N is None and len(masses) != N: print("warning: provided mass array not equal to masses") self.masses = masses / masses.sum() | nbody_system.mass self.N = len(masses) self.convert_nbody=convert_nbody self.do_scale=do_scale self.random_seed=random_seed self.fractal_dimension=fractal_dimension self.virial_ratio=virial_ratio self.verbose=verbose self.match_N=match_N def new_model(self): generator = FractalCluster(redirection=("none" if self.verbose else "null")) generator.parameters.number_of_particles = self.N generator.parameters.fractal_dimension = self.fractal_dimension if self.random_seed is not None: generator.parameters.random_seed = self.random_seed generator.generate_particles() if self.match_N: while len(generator.particles)<self.N: generator.generate_particles() result = generator.particles.copy() generator.stop() result.mass = self.masses result.radius = 0 | nbody_system.length return result @property def result(self): particles = self.new_model() particles.move_to_center() if self.do_scale: particles.scale_to_standard(virial_ratio=self.virial_ratio) if not self.convert_nbody is None: return datamodel.ParticlesWithUnitsConverted(particles, self.convert_nbody.as_converter_from_si_to_generic()).copy() return particles def new_fractal_cluster_model(*list_arguments, **keyword_arguments): """ create a fractal stellar distribution :argument N: Number of particles, if None then masses must be provided [None] :argument masses: optional masses, if not provided masses will be 1/N [None] :argument fractal_dimension: fractal dimension of distribution, between 1.6 and 3 [1.6] :argument random_seed: random seed [None] :argument convert_nbody: When given will convert the resulting set to SI units :argument do_scale: scale the result to exact nbody units (G=1, M=1, U=-0.5) :argument virial_ratio: ratio of kinetic to potential energy [0.5] """ uc = MakeFractalCluster(*list_arguments, **keyword_arguments) return uc.result Fractalcluster = FractalCluster
10,762
37.577061
128
py
amuse
amuse-main/src/amuse/community/hop/__init__.py
# generated file from .interface import Hop
44
14
26
py
amuse
amuse-main/src/amuse/community/hop/interface.py
''' This is the interface file for the HOP group-finding algorithm. HOP starts by determining the densest neighbor of each particle (which can be the particle proper). The algorithm then groups particles together by jumping from densest neighbor to densest neighbor until a density peak is reached. core HOP algorithm functions: calculate_densities() - calculates densities do_hop() - determines densest neighbors then groups the particles and calculates boundaries between groups ''' from amuse.units import generic_unit_system from amuse.community import * from amuse.community.interface.common import CommonCodeInterface, CommonCode class HopInterface(CodeInterface, CommonCodeInterface, LiteratureReferencesMixIn): ''' .. [#] ADS:1998ApJ...498..137E (Eisenstein, DJ, Hut, P, ApJ 498 (1998): .. [#] ... HOP: A new group-finding algorithm for N-body simulations) ''' include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="hop_worker", **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @legacy_function def new_particle(): ''' Add a new particle with the specified position. Returns the particle index of the new particle as an integer (note zero offset). ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description='index of the particle') function.addParameter('mass', dtype='float64', direction=function.IN, description='mass of the particle') function.addParameter('x', dtype='float64', direction=function.IN, description='particle position on x-axis') function.addParameter('y', dtype='float64', direction=function.IN, description='particle position on y-axis') function.addParameter('z', dtype='float64', direction=function.IN, description='particle position on z-axis') function.result_type = 'int32' return function @legacy_function def delete_particle(): ''' Remove 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 to be removed') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and removed -1 - ERROR particle could not be found """ return function @legacy_function def get_position(): ''' Retrieve the position of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('x', dtype='float64', direction=function.OUT, description = 'particle position on x-axis') function.addParameter('y', dtype='float64', direction=function.OUT, description = 'particle position on y-axis') function.addParameter('z', dtype='float64', direction=function.OUT, description = 'particle position on z-axis') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its position returned -1 - ERROR particle could not be found """ return function @legacy_function def get_mass(): ''' Retrieve the position of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('mass', dtype='float64', direction=function.OUT, description = 'particle position on x-axis') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its position returned -1 - ERROR particle could not be found """ return function @legacy_function def set_position(): ''' Set the position of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('x', dtype='float64', direction=function.IN, description = 'particle position on x-axis') function.addParameter('y', dtype='float64', direction=function.IN, description = 'particle position on y-axis') function.addParameter('z', dtype='float64', direction=function.IN, description = 'particle position on z-axis') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its position altered -1 - ERROR particle could not be found """ return function @legacy_function def get_density(): ''' Retrieve the density of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('density', dtype='float64', direction=function.OUT, description='the density of the specified particle') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its density returned -1 - ERROR particle could not be found, unphysical density encountered or density was not yet calculated """ return function @legacy_function def set_density(): ''' Set the density of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('density', dtype='float64', direction=function.IN, description='the density of the specified particle') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its density altered -1 - ERROR particle could not be found """ return function @legacy_function def get_densest_neighbor(): ''' Retrieve the particle index of the densest neighbor of a particle. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('index_of_densest_neighbor', dtype='int32', direction=function.OUT, description='particle index of the densest neighbor of the specified particle') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its densest neighbor index returned -1 - ERROR particle could not be found or its densest neighbor was not yet determined """ return function @legacy_function def get_group_id(): ''' Retrieve the group ID of a particle (-1 for ungrouped particles). ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN, description='index of a particle') function.addParameter('group_id', dtype='int32', direction=function.OUT, description='group id of the group which the specified particle is a part of (-1 for ungrouped particles)') function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found and its group id returned -1 - ERROR particle could not be found or it was not part of a group """ return function @legacy_function def get_number_of_particles(): ''' Retrieve the number of particles in the HopInstance. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('value', dtype='int32', direction=function.OUT, description='the total number of particles') function.result_type = 'int32' return function @legacy_function def calculate_densities(): ''' Calculate the densities of the particles in the HopInstance. Use set_density_method() to specify the density calculation method (DEFAULT: gather-scatter cubic spline). ''' function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = ''' 0 - OK calculating densities successful -1 - ERROR no particles or parameter values too high (higher than number of partcles) ''' return function @legacy_function def do_hop(): ''' Find the densest neighbors, then group the particles. do_hop() assigns group ids to particles, starting with 0 for the largest group. ''' function = LegacyFunctionSpecification() function.result_type = 'int32' function.result_doc = ''' 0 - OK hop successful -1 - ERROR no particles or unphysical density encountered when reading densities or parameter values too high (higher than number of particles) ''' return function @legacy_function def get_densest_particle_in_group(): ''' Retrieve the particle index of the densest particle in a group. (Requires do_hop() to be done first.) ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('group_id', dtype='int32', direction=function.IN, description='group identification number') function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT, description='particle index of the particle with highest density in specified group') function.result_type = 'int32' function.result_doc = ''' 0 - OK group was found and index of densest particle returned -1 - ERROR group could not be found ''' return function @legacy_function def get_number_of_particles_in_group(): ''' Retrieve the number of particles in a group. ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('group_id', dtype='int32', direction=function.IN, description='group identification number') function.addParameter('number_of_particles', dtype='int32', direction=function.OUT, description='number of particles in the specified group') function.result_type = 'int32' function.result_doc = ''' 0 - OK group was found and the number of particles in the group returned -1 - ERROR group could not be found ''' return function @legacy_function def get_average_boundary_density_of_groups(): ''' Retrieve the average density of the boundary between two groups. (This is O(n_groups) so it might take a while to retrieve.) (Requires do_hop() to be done first.) ''' function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('first_group_id', dtype='int32', direction=function.IN, description='identification number of the first group') function.addParameter('second_group_id', dtype='int32', direction=function.IN, description='identification number of the second group') function.addParameter('boundary_density', dtype='float64', direction=function.OUT, description='average density at the boundary between specified groups') function.result_type = 'int32' function.result_doc = ''' 0 - OK both groups were found and the average density of their boundary returned -1 - ERROR one of the groups could not be found -2 - ERROR the groups did not share a boundary ''' return function @legacy_function def get_number_of_groups(): ''' Retrieve the number of groups in the HopInstance. (Requires do_hop() to be done first.) ''' function = LegacyFunctionSpecification() function.addParameter('number_of_groups', dtype='int32', direction=function.OUT, description='the number of groups found by do_hop()') function.result_type = 'int32' function.result_doc = ''' 0 - OK number of groups found by hop returned -1 - ERROR do_hop was not run first ''' return function @legacy_function def get_number_of_particles_outside_groups(): ''' Retrieve the number of particles that do not belong to a group. (Requires do_hop() to be done first.) ''' function = LegacyFunctionSpecification() function.addParameter('number_of_particles', dtype='int32', direction=function.OUT, description='the number of particles that were not assigned a group id by do_hop()') function.result_type = 'int32' return function @legacy_function def set_nBucket(): ''' Set nBucket, to tune the performance of the kd-tree search. DEFAULT: 16 ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description='the value of nBucket affects the performance of the kd-tree search (DEFAULT: 16)') function.result_type = 'int32' return function @legacy_function def get_nBucket(): ''' Return the bucket parameter to tune the performance of the kd-tree search. DEFAULT: 16 ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description='the value of nBucket affects the performance of the kd-tree search (DEFAULT: 16)') function.result_type = 'int32' return function @legacy_function def set_nDens(): ''' Set nDens, the number of particles to smooth over when calculating densities. DEFAULT: 64 ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description='the value of nDens, the number of particles to smooth over when calculating densities (DEFAULT: 64)') function.result_type = 'int32' return function @legacy_function def get_nDens(): ''' Return the number of particles to smooth over when calculating densities. DEFAULT: 64 ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description='the value of nDens, the number of particles to smooth over when calculating densities (DEFAULT: 64)') function.result_type = 'int32' return function @legacy_function def set_nHop(): ''' Set nHop, the number of particles over which to look for density maximum. DEFAULT: 64 (minimum allowed value of nHop is nMerge+1) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description='the value of nHop, the number of particles over which to look for density maximum (DEFAULT: 64)') function.result_type = 'int32' function.result_doc = ''' 0 - OK nHop was set -1 - ERROR requested value for nHop was too low ''' return function @legacy_function def get_nHop(): ''' Return the number of particles over which to look for density maximum. DEFAULT: 64 (minimum allowed value of nHop is nMerge+1) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description='the value of nHop, the number of particles over which to look for density maximum (DEFAULT: 64)') function.result_type = 'int32' function.result_doc = ''' 0 - OK nHop was set -1 - ERROR requested value for nHop was too low ''' return function @legacy_function def set_fDensThresh(): ''' Set fDensThresh, the density below which particles are not assigned to any group. DEFAULT: -1.0 (no threshold) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.IN, description='value of fDensThresh, the minimum density of grouped particles (DEFAULT: no minimum)', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def get_fDensThresh(): ''' Return the density below which particles are not assigned to any group. DEFAULT: -1.0 (no threshold) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.OUT, description='value of fDensThresh, the minimum density of grouped particles (DEFAULT: no minimum)', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def set_saddle_densthresh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.IN, description='For two groups to merge, the density at their boundary must ' 'exceed this threshold (DEFAULT: 1.75 * outer_density_threshold)', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def get_saddle_densthresh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.OUT, description='For two groups to merge, the density at their boundary must ' 'exceed this threshold (DEFAULT: 1.75 * outer_density_threshold)', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def set_peak_densthresh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.IN, description='Groups with density below this threshold (fringe groups) are ' 'attached to other (proper) groups, or dropped (DEFAULT: max(d_saddle, 2.0 * d_outer))', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def get_peak_densthresh(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.OUT, description='Groups with density below this threshold (fringe groups) are ' 'attached to other (proper) groups, or dropped (DEFAULT: max(d_saddle, 2.0 * d_outer))', unit = generic_unit_system.density) function.result_type = 'int32' return function @legacy_function def set_saddle_density_threshold_factor(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.IN, description='For two groups to merge, the density at their boundary must ' 'exceed this factor times the lowest of the two peak densities (set relative_saddle_density_threshold to True)', unit = NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_saddle_density_threshold_factor(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'float64', direction=function.OUT, description='For two groups to merge, the density at their boundary must ' 'exceed this factor times the lowest of the two peak densities (set relative_saddle_density_threshold to True)', unit = NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_relative_saddle_density_threshold(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description="Flag to use a saddle-density-threshold relative to the lowest peak density, " "instead of the absolute saddle_density_threshold", unit = NO_UNIT) function.result_type = 'int32' return function @legacy_function def get_relative_saddle_density_threshold(): function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description="Flag to use a saddle-density-threshold relative to the lowest peak density, " "instead of the absolute saddle_density_threshold", unit = NO_UNIT) function.result_type = 'int32' return function @legacy_function def set_fPeriod(): ''' Set the x, y and z periodicity of the simulation box. DEFAULT: infinite ''' function = LegacyFunctionSpecification() function.addParameter('x', dtype = 'float64', direction=function.IN, description='periodicity in x direction') function.addParameter('y', dtype = 'float64', direction=function.IN, description='periodicity in y direction') function.addParameter('z', dtype = 'float64', direction=function.IN, description='periodicity in z direction') function.result_type = 'int32' return function @legacy_function def get_fPeriod(): ''' Get the x, y and z periodicity of the simulation box. DEFAULT: infinite ''' function = LegacyFunctionSpecification() function.addParameter('x', dtype = 'float64', direction=function.OUT, description='periodicity in x direction') function.addParameter('y', dtype = 'float64', direction=function.OUT, description='periodicity in y direction') function.addParameter('z', dtype = 'float64', direction=function.OUT, description='periodicity in z direction') function.result_type = 'int32' return function @legacy_function def set_nMerge(): ''' Set nMerge, the number of particles to catalogue group boundaries. DEFAULT: 4 (maximum allowed value of nMerge is nHop-1) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description='the value of nMerge, the numbder of particles catalogue group boundaries') function.result_type = 'int32' function.result_doc = ''' 0 - OK nMerge was set -1 - ERROR requested value for nMerge was too high ''' return function @legacy_function def get_nMerge(): ''' Return the number of particles to catalogue group boundaries. DEFAULT: 4 (maximum allowed value of nMerge is nHop-1) ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description='the value of nMerge, the numbder of particles catalogue group boundaries') function.result_type = 'int32' function.result_doc = ''' 0 - OK nMerge was set -1 - ERROR requested value for nMerge was too high ''' return function @legacy_function def set_density_method(): ''' Set the density calculation method used by calculate_densities(). 0 - gather-scatter cubic spline kernel (DEFAULT) 1 - gather-only cubic spline kernal 2 - tophat kernal ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.IN, description='value representing the density calculation method (DEFAULT: 0; gather scatter cubic spline)') function.result_type = 'int32' function.result_doc = ''' 0 - OK density method set -1 - ERROR invalid density method requested ''' return function @legacy_function def get_density_method(): ''' Get the density calculation method used by calculate_densities(). 0 - gather-scatter cubic spline kernel (DEFAULT) 1 - gather-only cubic spline kernal 2 - tophat kernal ''' function = LegacyFunctionSpecification() function.addParameter('value', dtype = 'int32', direction=function.OUT, description='value representing the density calculation method (DEFAULT: 0; gather scatter cubic spline)') function.result_type = 'int32' function.result_doc = ''' 0 - OK density method set -1 - ERROR invalid density method requested ''' return function @legacy_function def show_parameters(): ''' Print all parameters and their values. ''' function = LegacyFunctionSpecification() function.result_type = 'int32' return function def commit_particles(self): pass def recommit_particles(self): pass class Hop(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter InCodeComponentImplementation.__init__(self, HopInterface(**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_errorcodes(self, handler): handler.add_errorcode(-1, 'Something went wrong...') handler.add_errorcode(-2, 'Not implemented.') handler.add_errorcode(-3, 'A particle with the given index was not found.') handler.add_errorcode(-4, 'Negative density encountered.') handler.add_errorcode(-5, 'Too few particles.') def define_methods(self, builder): builder.add_method( 'new_particle', (generic_unit_system.mass, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length,), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( 'delete_particle', (builder.INDEX,), (builder.ERROR_CODE) ) builder.add_method( 'get_position', (builder.INDEX,), (generic_unit_system.length, generic_unit_system.length, generic_unit_system.length, builder.ERROR_CODE), public_name = 'get_position' ) builder.add_method( 'set_position', (builder.INDEX, generic_unit_system.length, generic_unit_system.length, generic_unit_system.length,), (builder.ERROR_CODE), public_name = 'set_position' ) builder.add_method( 'get_density', (builder.INDEX,), (generic_unit_system.density, builder.ERROR_CODE) ) builder.add_method( 'get_mass', (builder.INDEX,), (generic_unit_system.mass, builder.ERROR_CODE) ) builder.add_method( 'set_density', (builder.INDEX, generic_unit_system.density,), (builder.ERROR_CODE) ) builder.add_method( 'get_densest_neighbor', (builder.INDEX,), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( 'get_group_id', (builder.INDEX,), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( 'get_number_of_particles', (), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( 'calculate_densities', (), (builder.ERROR_CODE) ) builder.add_method( 'do_hop', (), (builder.ERROR_CODE) ) builder.add_method( 'get_densest_particle_in_group', (builder.INDEX,), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( 'get_number_of_particles_in_group', (builder.INDEX,), (builder.INDEX, builder.ERROR_CODE) ) builder.add_method( 'get_average_boundary_density_of_groups', (builder.INDEX, builder.INDEX,), (generic_unit_system.density, builder.ERROR_CODE) ) builder.add_method( 'get_number_of_groups', (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( 'get_number_of_particles_outside_groups', (), (builder.NO_UNIT, builder.ERROR_CODE) ) builder.add_method( 'show_parameters', (), (builder.ERROR_CODE) ) builder.add_method( "get_nHop", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_nHop", (builder.NO_UNIT, ), (builder.ERROR_CODE,) ) builder.add_method( "get_nDens", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_nDens", (builder.NO_UNIT, ), (builder.ERROR_CODE,) ) builder.add_method( "get_nBucket", (), (builder.NO_UNIT, builder.ERROR_CODE,) ) builder.add_method( "set_nBucket", (builder.NO_UNIT, ), (builder.ERROR_CODE,) ) def define_parameters(self, handler): handler.add_method_parameter( "get_fDensThresh", "set_fDensThresh", "outer_density_threshold", "the density below which particles are not assigned to any group", default_value = -1.0 | generic_unit_system.density ) handler.add_method_parameter( "get_saddle_densthresh", "set_saddle_densthresh", "saddle_density_threshold", "For two groups to merge, the density at their boundary must exceed this " "threshold (DEFAULT: 1.75 * outer_density_threshold)", default_value = -1.0 | generic_unit_system.density ) handler.add_method_parameter( "get_peak_densthresh", "set_peak_densthresh", "peak_density_threshold", "Groups with density below this threshold (fringe groups) are attached to " "other (proper) groups, or dropped (DEFAULT: max(saddle_density_threshold, 2.0 * outer_density_threshold))", default_value = -1.0 | generic_unit_system.density ) handler.add_method_parameter( "get_saddle_density_threshold_factor", "set_saddle_density_threshold_factor", "saddle_density_threshold_factor", "For two groups to merge, the density at their boundary must exceed this " "factor times the lowest of the two peak densities (set relative_saddle_density_threshold to True)", default_value = 0.80 ) handler.add_boolean_parameter( "get_relative_saddle_density_threshold", "set_relative_saddle_density_threshold", "relative_saddle_density_threshold", "Flag to use a saddle-density-threshold relative to the lowest peak density, " "instead of the absolute saddle_density_threshold", False ) handler.add_method_parameter( "get_nHop", "set_nHop", "number_of_neighbors_for_hop", "The number of neighbors to search for local density maximum (search is performed iteratively until a true maximum is found)", default_value = 64 ) handler.add_method_parameter( "get_density_method", "set_density_method", "density_method", "method used for density computation (0,1,2 = gather-scatter spline, gather spline, tophat)", default_value = 0 ) handler.add_method_parameter( "get_nDens", "set_nDens", "number_of_neighbors_for_local_density", "Return the number of particles to smooth over when calculating densities.", default_value = 64 ) handler.add_method_parameter( "get_nBucket", "set_nBucket", "number_of_buckets", "Return the bucket parameter to tune the performance of the kd-tree search.", default_value = 16 ) handler.add_method_parameter( "get_nMerge", "set_nMerge", "number_of_particles_per_group_pair_boundary", "The number of (densest) particles per boundary between each pair of groups, for merging.", default_value = 4 ) def define_particle_sets(self, builder): builder.define_set('particles', 'index_of_the_particle') builder.set_new('particles', 'new_particle') builder.set_delete('particles', 'delete_particle') builder.add_setter('particles', 'set_position') builder.add_setter('particles', 'set_density', names=('density',)) builder.add_getter('particles', 'get_position') builder.add_getter('particles', 'get_density', names=('density',)) builder.add_getter('particles', 'get_mass', names=('mass',)) #builder.add_getter('particles', 'get_densest_neighbor') builder.add_getter('particles', 'get_group_id', names=('group_id',)) def define_state(self, handler): CommonCode.define_state(self, handler) handler.add_transition('INITIALIZED','EDIT','commit_parameters') handler.add_transition('RUN','CHANGE_PARAMETERS_RUN','before_set_parameter', False) handler.add_transition('EDIT','CHANGE_PARAMETERS_EDIT','before_set_parameter', False) handler.add_transition('UPDATE','CHANGE_PARAMETERS_UPDATE','before_set_parameter', False) handler.add_transition('CHANGE_PARAMETERS_RUN','RUN','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_EDIT','EDIT','recommit_parameters') handler.add_transition('CHANGE_PARAMETERS_UPDATE','UPDATE','recommit_parameters') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_set_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_set_parameter') handler.add_method('CHANGE_PARAMETERS_RUN', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_EDIT', 'before_get_parameter') handler.add_method('CHANGE_PARAMETERS_UPDATE','before_get_parameter') handler.add_method('RUN', 'before_get_parameter') handler.add_method('EDIT', 'before_get_parameter') handler.add_method('UPDATE','before_get_parameter') handler.add_method('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_method('RUN', 'calculate_densities') handler.add_method('RUN', 'do_hop') handler.add_method('RUN', 'get_mass') handler.add_method('RUN', 'get_position') handler.add_method('RUN', 'get_density') handler.add_method('RUN', 'get_group_id') def no_group(self): return self.particles.select(lambda group_id: group_id == -1, ["group_id"]) def groups(self): number_of_groups = self.get_number_of_groups() group_id = self.particles.group_id for index in range(number_of_groups): result = self.particles[group_id == index] result.add_function_attribute('id_of_group', lambda particles: particles[0].group_id) #result.add_function_attribute('get_density_of_group', lambda particles: self.get_group_density(particles.id_of_group())) yield result
38,683
37.878392
139
py
amuse
amuse-main/src/amuse/community/mameclot/__init__.py
from .interface import Mameclot
32
15.5
31
py
amuse
amuse-main/src/amuse/community/mameclot/interface.py
import numpy import os from amuse.community import LiteratureReferencesMixIn from amuse.datamodel import Particles,ParticlesWithUnitsConverted from subprocess import Popen, PIPE from amuse.units import units,nbody_system class mameclot(LiteratureReferencesMixIn): """ MAMECLOT: MAke ME a CLuster Or Two Construct initial conditions of 1 (or 2) cluster(s) for N-body simulations A 2 cluster system with orbit in the x-y plane is made if the mass ratio q>0 Five equilibrium models are available, a cut-off radius can be provided The velocities can be isotropic or radially anisotropic (a la Osipkov-Merritt) Optional angular momentum by aligning the angular momentum vectors along z System is scaled to N-body units with G = M = -4E = 1 (Heggie & Mathieu 1986) In the case of a two-body system E = mu*e_orb + E_1 + E_2 (mu = reduced mass) The 2-body orbit is computed from input q, e_hat and l_hat (and eta if q<1): e_hat = e_orb/0.5<sigma^2> l_hat = l_orb/<r_vir*sigma> eta => defines the relative radii: r2/r1 = q^eta, for example: eta=[-0.33/0/0.33/0.5] for equal [t_rh/r_h/rho_h/Sigma_h] Relevant references: .. [#] Gieles, M., https://github.com/mgieles/mameclot :argument targetN: Number of particles :argument convert_nbody: When given will convert the resulting set to SI units :argument cluster_model: cluster model to generate ["Henon"] :argument mass_ratio: mass ratio, zero means only 1 cluster [0] :argument size_eta_parameter: eta, relative cluster sizes: r2/r1 = q^eta [0.333] :argument imf: IMF [single mass] :argument angular_momentum_signs: Angular momentum in z-direction, -, + or x ["xx"] :argument fraction_of_max_rot_energy: Fraction of maximum rotational energy [1], :argument OsipkovMerritt_anisotropy_radius_r0: Osipkov-Merritt anisotropy radius in units of r_0 [999] :argument cutoff_radius_halfmass_radius: Cut-off radius in units of r_h [20] :argument physical_radius: Physical scale [1| units.parsec] :argument distance: Distance between 2 clusters in N-body units [20 | nbody_system.length] :argument orbital_energy: Dimensionless orbital energy of two-cluster system [0] :argument orbital_angular_momentum: Dimensionless orbital angular momentum two-cluster system [4] :argument seed: random seed 123456 """ available_cluster_models={"Dehnen" : 0, "Hernquist":1 ,"Jaffe":2,"Henon": 3, "Plummer" :4 } available_imf_model={"single mass" : 0, "Kroupa" : 1} angular_momentum_sign_key={"xx":0,"++":1,"+x":2,"+-":3,"x+":4,"x-":5,"--":-1,"-x":-2,"-+":-3} def __init__(self, targetN=10000, cluster_model="Henon", mass_ratio=0, size_eta_parameter=0.3333333, imf="single mass", angular_momentum_signs="xx", fraction_of_max_rot_energy=1, OsipkovMerritt_anisotropy_radius_r0=999,cutoff_radius_halfmass_radius=20,physical_radius=1| units.parsec, distance=20 | nbody_system.length,orbital_energy=0,orbital_angular_momentum=0,seed=123456, convert_to_physical=False): LiteratureReferencesMixIn.__init__(self) self._bin_path = os.path.dirname(os.path.abspath(__file__)) self._particles=None self.convert_to_physical=convert_to_physical self._exec="mameclot_worker" self.targetN=targetN self.cluster_model=cluster_model self.mass_ratio=mass_ratio self.size_eta_parameter=size_eta_parameter self.imf=imf self.angular_momentum_signs=angular_momentum_signs self.fraction_of_max_rot_energy=fraction_of_max_rot_energy self.OsipkovMerritt_anisotropy_radius_r0=OsipkovMerritt_anisotropy_radius_r0 self.cutoff_radius_halfmass_radius=cutoff_radius_halfmass_radius self.physical_radius=physical_radius self.distance=distance self.orbital_energy=orbital_energy self.orbital_angular_momentum=orbital_angular_momentum self.seed=seed def arguments(self): arguments=[] arguments.extend([ "-N", str(self.targetN) ]) arguments.extend([ "-m", str(self.available_cluster_models[self.cluster_model]) ]) arguments.extend([ "-q", str(self.mass_ratio) ]) arguments.extend([ "-e", str(self.size_eta_parameter) ]) arguments.extend([ "-i", str(self.available_imf_model[self.imf]) ]) arguments.extend([ "-l", self.angular_momentum_signs ]) arguments.extend([ "-f", str(self.fraction_of_max_rot_energy) ]) arguments.extend([ "-a", str(self.OsipkovMerritt_anisotropy_radius_r0) ]) arguments.extend([ "-c", str(self.cutoff_radius_halfmass_radius) ]) arguments.extend([ "-r", str(self.physical_radius.value_in(units.parsec)) ]) arguments.extend([ "-d", str(self.distance) ]) arguments.extend([ "-E", str(self.orbital_energy) ]) arguments.extend([ "-L", str(self.orbital_angular_momentum) ]) arguments.extend([ "-s", str(self.seed) ]) return arguments def make_model(self): call=[self._exec]+self.arguments() print(call) mameclot=Popen(call, stdout=PIPE,stderr=PIPE,executable=os.path.join(self._bin_path,self._exec)) (out,err)=mameclot.communicate() print(err) outsplit=out.decode().strip().split("\n") errsplit=err.decode().strip().split("\n") if self.mass_ratio==0: nline=errsplit[6].split() mline=errsplit[7].split() rline=errsplit[8].split() N1=int(nline[2]) N2=0 mscale=(float(mline[4])/float(mline[2])) | units.MSun rscale=(float(rline[4])/float(mline[2])) | units.parsec else: nline=errsplit[8].split() n2line=errsplit[22].split() mline=errsplit[9].split() rline=errsplit[10].split() N1=int(nline[2]) N2=int(n2line[2]) mscale=(float(mline[4])/float(mline[2])) | units.MSun rscale=(float(rline[4])/float(mline[2])) | units.parsec print(N1,N2) N=len( outsplit) parts=Particles(N) masses=numpy.zeros((N,)) energy=numpy.zeros((N,)) position=numpy.zeros((N,3)) velocity=numpy.zeros((N,3)) for i,line in enumerate(outsplit): l=line.split() masses[i]=float(l[0]) position[i,0:3]=[float(l[1]),float(l[2]),float(l[3])] velocity[i,0:3]=[float(l[4]),float(l[5]),float(l[6])] energy[i]=float(l[7]) parts.mass=masses | nbody_system.mass parts.position=position | nbody_system.length parts.velocity=velocity | nbody_system.speed parts.specific_energy=energy| nbody_system.specific_energy parts.move_to_center() if self.convert_to_physical: print("mass scale:", mscale) print("length scale:", rscale) convert_nbody=nbody_system.nbody_to_si(mscale,rscale) parts = ParticlesWithUnitsConverted(parts, convert_nbody.as_converter_from_si_to_generic()) parts = parts.copy() self._all=parts self._cluster1=parts[:N1] self._cluster2=parts[N1:] @property def result(self): self.make_model() return self._all @property def result_split(self): self.make_model() return self._all,self._cluster1,self._cluster2 def new_mameclot_model(*args,**keyword_arguments): """ MAMECLOT: MAke ME a CLuster Or Two Construct initial conditions of 1 (or 2) cluster(s) for N-body simulations A 2 cluster system with orbit in the x-y plane is made if the mass ratio q>0 Five equilibrium models are available, a cut-off radius can be provided The velocities can be isotropic or radially anisotropic (a la Osipkov-Merritt) Optional angular momentum by aligning the angular momentum vectors along z System is scaled to N-body units with G = M = -4E = 1 (Heggie & Mathieu 1986) In the case of a two-body system E = mu*e_orb + E_1 + E_2 (mu = reduced mass) The 2-body orbit is computed from input q, e_hat and l_hat (and eta if q<1): e_hat = e_orb/0.5<sigma^2> l_hat = l_orb/<r_vir*sigma> eta => defines the relative radii: r2/r1 = q^eta, for example: eta=[-0.33/0/0.33/0.5] for equal [t_rh/r_h/rho_h/Sigma_h] :argument targetN: Number of particles :argument convert_nbody: When given will convert the resulting set to SI units :argument cluster_model: cluster model to generate ["Henon"] :argument mass_ratio: mass ratio, zero means only 1 cluster [0] :argument size_eta_parameter:eta: Relative cluster sizes: r2/r1 = q^eta [0.333] :argument imf: IMF ["single mass"] :argument angular_momentum_signs: Angular momentum in z-direction, -, + or x ["xx"] :argument fraction_of_max_rot_energy: Fraction of maximum rotational energy [1], :argument OsipkovMerritt_anisotropy_radius_r0: Osipkov-Merritt anisotropy radius in units of r_0 [999] :argument cutoff_radius_halfmass_radius: Cut-off radius in units of r_h [20] :argument physical_radius: Physical scale [1| units.parsec] :argument distance: Distance between 2 clusters in N-body units [20 | nbody_system.length] :argument orbital_energy: Dimensionless orbital energy of two-cluster system [0] :argument orbital_angular_momentum: Dimensionless orbital angular momentum two-cluster system [4] :argument seed: random seed 123456 """ uc = mameclot(*args, **keyword_arguments) return uc.result if __name__=="__main__": from matplotlib import pyplot clusters,cluster1,cluster2=mameclot(mass_ratio=0.25,convert_to_physical=False).result_split print(cluster1.total_mass()) print(len(cluster2)) pyplot.plot(cluster1.x.number,cluster1.y.number,"r.") pyplot.plot(cluster2.x.number,cluster2.y.number,"g.") pyplot.show() Mameclot = mameclot
10,163
42.435897
113
py
amuse
amuse-main/src/amuse/community/hermite/__init__.py
from .interface import Hermite
31
15
30
py
amuse
amuse-main/src/amuse/community/hermite/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 HermiteInterface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, SinglePointGravityFieldInterface): """ N-body integration module with shared but variable time step (the same for all particles but its size changing in time), using the Hermite integration scheme. .. [#] ADS:1995ApJ...443L..93H (Hut, P., Makino, J. & McMillan, S., *Astrophysical Journal Letters* , **443**, L93-L96 (1995)) """ include_headers = ['worker_code.h', 'stopcond.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="hermite_worker", **options) LiteratureReferencesMixIn.__init__(self) def reinitialize_particles(self): self.recommit_particles() @legacy_function def get_dt_dia(): """ Get the time interval between diagnostics output. """ function = LegacyFunctionSpecification() function.addParameter('dt_dia', dtype='float64', direction=function.OUT, description = "time interval between diagnostic outputs") 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_dt_dia(): """ Set the time interval between diagnostics output. """ function = LegacyFunctionSpecification() function.addParameter('dt_dia', dtype='float64', direction=function.IN, description = "the time interval between diagnostics output") 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_dt_param(): """ Get the timestep scaling factor. """ function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='float64', direction=function.OUT, description = "the timestep scaling factor") 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_dt_param(): """ Set the timestep scaling factor. """ function = LegacyFunctionSpecification() function.addParameter('dt_param', dtype='float64', direction=function.IN, description = "the timestep scaling factor") 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_is_time_reversed_allowed(): """ If time reversed is allowed for this code, the code will calculate backwards in time if the endtime given in evolve_model is less than the system time. """ 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_time_reversed_allowed(): """ If time reversed is allowed for this code, the code will calculate backwards in time if the endtime given in evolve_model is less than the system time. """ 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_time(): """ Get the current simulation time. """ function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT, description = "the current simulation time") function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was retrieved -1 - ERROR could not retrieve parameter """ return function @legacy_function def get_end_time_accuracy_factor(): """ Get the end time accuracy factor: < 0 will stop between factor * dt befor the end time and the end time 0 will stop at exactly the end time > 0 will stop between the end time and factor * dt after the end time """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', 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_end_time_accuracy_factor(): """ Set the end time accuracy factor """ function = LegacyFunctionSpecification() function.addParameter('value', dtype='float64', direction=function.IN) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function class HermiteDoc(object): def __get__(self, instance, owner): return instance.legacy_doc+"\n\n"+instance.parameters.__doc__ class Hermite(GravitationalDynamics, GravityFieldCode): __doc__ = HermiteDoc() __interface__ = HermiteInterface 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) def define_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_dt_param", "set_dt_param", "dt_param", "timestep scaling factor", default_value = 0.03 ) handler.add_method_parameter( "get_end_time_accuracy_factor", "set_end_time_accuracy_factor", "end_time_accuracy_factor", """ Get the end time accuracy factor: < 0.0 will stop on or before the end time (larger factor, more before) 0.0 will stop at exactly the end time > 0.0 will stop on or after the end time Valid factors are between -1.0 and 1.0 """, default_value = 1.0 ) handler.add_method_parameter( "get_dt_dia", "set_dt_dia", "dt_dia", "time interval between diagnostics output", default_value = 1.0 | nbody_system.time ) handler.add_method_parameter( "get_is_time_reversed_allowed", "set_is_time_reversed_allowed", "is_time_reversed_allowed", "if True will calculate back in time when evolve_model end time is less than systemtime", default_value = False ) handler.add_method_parameter( "get_begin_time", "set_begin_time", "begin_time", "model time to start the simulation at", default_value = 0.0 | nbody_system.time ) self.stopping_conditions.define_parameters(handler) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( "get_dt_param", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_dt_param", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) handler.add_method( "get_dt_dia", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_dt_dia", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_time", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time", (nbody_system.time, ), (handler.ERROR_CODE,) ) handler.add_method( "get_pair_detect_factor", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( "set_pair_detect_factor", (handler.NO_UNIT, ), (handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler)
11,097
30.982709
130
py
amuse
amuse-main/src/amuse/community/flash/__init__.py
from .interface import Flash
29
14
28
py
amuse
amuse-main/src/amuse/community/flash/interface.py
from amuse.community import * from amuse.community.interface.hydro import HydrodynamicsInterface from amuse.support.options import OptionalAttributes, option from amuse.units import generic_unit_system from amuse.units import si from amuse.community.interface.common import CommonCode import numpy as np import os length = generic_unit_system.length time = generic_unit_system.time mass = generic_unit_system.mass speed = generic_unit_system.speed density = generic_unit_system.density momentum = generic_unit_system.momentum_density energy = generic_unit_system.energy_density potential_energy = generic_unit_system.energy magnetic_field = generic_unit_system.mass / generic_unit_system.current / generic_unit_system.time ** 2 acc = generic_unit_system.acceleration potential = generic_unit_system.potential class FlashInterface(CodeInterface, HydrodynamicsInterface): use_modules = ['flash_run'] include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="flash_worker", **keyword_arguments) @legacy_function def initialize_code(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def cleanup_code(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid', 'nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx', 'rhovy', 'rhovz', 'rhoen']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def set_grid_state(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid', 'nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rho','rhovx', 'rhovy', 'rhovz', 'rhoen']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_grid_momentum_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid', 'nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rhovx', 'rhovy', 'rhovz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def set_grid_momentum_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['rhovx', 'rhovy', 'rhovz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_grid_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['vx', 'vy', 'vz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def set_grid_velocity(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) for x in ['vx', 'vy', 'vz']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_grid_energy_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('rhoen', dtype='d', direction=function.OUT) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def set_grid_energy_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('rhoen', dtype='d', direction=function.IN) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_grid_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('rho', dtype='d', direction=function.OUT) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def set_grid_density(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['i','j','k', 'index_of_grid','nproc']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('rho', dtype='d', direction=function.IN) function.addParameter('ngridpoints', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_potential(): function = LegacyFunctionSpecification() function.can_handle_array = True for x in ['i','j','k', 'index_of_grid']: function.addParameter(x, dtype='i', direction=function.IN) function.addParameter('potential', dtype='d', direction=function.OUT) function.result_type='int32' return function @legacy_function def get_potential_at_point(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['eps','x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('gpot', dtype='d', direction=function.OUT) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_gravity_at_point(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['eps','x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['gax','gay','gaz']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type='int32' return function @legacy_function def get_number_of_grids(): function = LegacyFunctionSpecification() function.addParameter('nproc', dtype='int32', direction=function.IN) function.addParameter('n', dtype='int32', direction=function.OUT) function.result_type='int32' return function @legacy_function def get_grid_range(): function = LegacyFunctionSpecification() for x in ['nx','ny','nz']: function.addParameter(x, dtype='int32', direction=function.OUT) function.addParameter('index_of_grid', dtype='int32', direction=function.IN) function.addParameter('nproc', dtype='int32', direction=function.IN) function.result_type='int32' return function @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() 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('Proc_ID', dtype='i', direction=function.IN, default = 0) 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 index of the grid and the local processor number on which this grid resides. """ function = LegacyFunctionSpecification() 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('index_of_grid', dtype='i', direction=function.OUT) function.addParameter('Proc_ID', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_leaf_indices(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('dummy', dtype='i', direction=function.IN) function.addParameter('ind', dtype='i', direction=function.OUT) function.addParameter('ret_cnt', dtype='i', direction=function.OUT) function.addParameter('num_of_blks', dtype='i', direction=function.OUT) function.addParameter('nparts',dtype='i', direction=function.LENGTH) function.result_type='i' return function @legacy_function def get_max_refinement(): function = LegacyFunctionSpecification() function.addParameter('max_refine', dtype='int32', direction=function.OUT) function.result_type='i' return function @legacy_function def set_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.IN) function.result_type='i' return function @legacy_function def get_timestep(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.OUT) function.result_type='i' return function @legacy_function def set_end_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.IN, default=0.0) function.result_type='i' return function @legacy_function def get_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.OUT) function.result_type='i' return function @legacy_function def get_end_time(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='d', direction=function.OUT) function.result_type='i' return function @legacy_function def set_max_num_steps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN) function.result_type='i' return function @legacy_function def get_max_num_steps(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type='i' return function @legacy_function def set_begin_iter_step(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.IN, default=1) function.result_type='i' return function @legacy_function def get_begin_iter_step(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='int32', direction=function.OUT) function.result_type='i' return function @legacy_function def initialize_restart(): function = LegacyFunctionSpecification() function.result_type='i' return function @legacy_function def get_restart(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='b', direction=function.OUT) function.result_type='i' return function @legacy_function def set_restart(): function = LegacyFunctionSpecification() function.addParameter('value', dtype='b', direction=function.IN) 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','rhoen']: function.addParameter(x, dtype='d', direction=function.OUT) function.result_type = 'i' return function # This needs to look like "get_grid_density" etc etc. @legacy_function def get_cell_volume(): function = LegacyFunctionSpecification() for x in ['block','i','j','k']: function.addParameter(x, dtype='int32', direction=function.IN) function.addParameter('vol', dtype='d', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_number_of_procs(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='i', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_all_local_num_grids(): function = LegacyFunctionSpecification() function.must_handle_array=True function.addParameter('num_grids_array', dtype='i', direction=function.INOUT) function.addParameter('nprocs', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function # WORK IN PROGRESS!!!! #@legacy_function #def get_data_all_local_blks(): #function = LegacyFunctionSpecification() #function.must_handle_array = True #function.addParameter('data_array', dtype='d', direction=function.INOUT) #function.addParameter('numcells', dtype='i', direction=function.LENGTH) #function.result_type = 'i' #return function @legacy_function def get_1blk_cell_coords(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('axis', dtype='i', direction=function.IN) function.addParameter('blockID', dtype='i', direction=function.IN) function.addParameter('limits', dtype='i', direction=function.IN) function.addParameter('coords', dtype='d', direction=function.OUT) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def kick_grid(): function = LegacyFunctionSpecification() function.addParameter('dt', dtype='d', direction=function.IN) function.result_type = 'i' return function @legacy_function def kick_block(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['accel_x', 'accel_y', 'accel_z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('blockID', dtype='i', direction=function.IN) function.addParameter('block_arr', dtype='i', direction=function.IN) function.addParameter('limits', dtype='i', direction=function.IN) function.addParameter('dt', dtype='d', direction=function.IN) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type='i' return function ######################################## # Particle Stuff ######################################## @legacy_function def get_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_accel_gas_on_particles(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('eps', dtype='d', direction=function.IN) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) for x in ['ax','ay','az']: function.addParameter(x, dtype='d', direction=function.OUT) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_num_part_prop(): function = LegacyFunctionSpecification() function.addParameter('n', dtype='int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def get_particle_position_array(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN,unit=NO_UNIT) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.OUT, unit=length) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def set_particle_position(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN, unit=NO_UNIT) for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN, unit=length) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def set_particle_velocity(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN, unit=NO_UNIT) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.IN, unit=speed) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_velocity_array(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN, unit=NO_UNIT) for x in ['vx','vy','vz']: function.addParameter(x, dtype='d', direction=function.OUT, unit=speed) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def make_sink(): function = LegacyFunctionSpecification() function.must_handle_array = True for x in ['x','y','z']: function.addParameter(x, dtype='d', direction=function.IN) function.addParameter('tags', dtype='d', direction=function.OUT) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def set_particle_mass(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.IN) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_mass(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN) function.addParameter('mass', dtype='d', direction=function.OUT) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_gpot(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('gpot', dtype='d', direction=function.OUT) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def set_particle_gpot(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('tags', dtype='d', direction=function.IN) function.addParameter('gpot', dtype='d', direction=function.IN) function.addParameter('nparts',dtype='i',direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_tags(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('tags', dtype='d', direction=function.OUT) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_proc(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('procs', dtype='int32', direction=function.OUT) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_particle_block(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.IN) function.addParameter('blocks', dtype='int32', direction=function.OUT) function.addParameter('nparts', dtype='i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_new_tags(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('new_tags_length', dtype = 'i', direction=function.IN) function.addParameter('new_tags_array', dtype = 'i', direction=function.OUT) function.addParameter('nparts', dtype = 'i', direction=function.LENGTH) function.result_type = 'i' return function @legacy_function def get_number_of_new_tags(): function = LegacyFunctionSpecification() function.addParameter('new_tag_num', dtype = 'int32', direction=function.OUT) function.result_type = 'i' return function @legacy_function def clear_new_tags(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def particles_gather(): function = LegacyFunctionSpecification() function.result_type = 'i' return function # @legacy_function # def make_particle_tree(): # function = LegacyFunctionSpecification() # function.result_type = 'i' # return function ######################## # IO Stuff ######################## @legacy_function def write_chpt(): function = LegacyFunctionSpecification() function.result_type = 'i' return function ############################################### # Default implemenation made by build.py - Josh ############################################### #class Flash(InCodeComponentImplementation): # def __init__(self, unit_converter = None, **options): # InCodeComponentImplementation.__init__(self, FlashInterface(**options), **options) # handler.set_converter(self.unit_converter.as_converter_from_si_to_generic()) ##################################################### # Attempt to copy amrvac's class implemenation, working so far! - Josh ##################################################### class Flash(CommonCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter self.stopping_conditions = StoppingConditions(self) CommonCode.__init__(self, FlashInterface(**options), **options) # self.set_parameters_filename(self.default_parameters_filename) 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 get_index_range_inclusive(self, index_of_grid = 1, nproc=0): nx, ny, nz = self.get_grid_range(index_of_grid, nproc) return (0, nx-1, 0, ny-1, 0, nz-1) def get_particle_position(self, tags): [x, y, z] = self.get_particle_position_array(tags) pos_array = np.array([x.value_in(units.cm), y.value_in(units.cm), z.value_in(units.cm)]).transpose() | units.cm if (hasattr(x,"__len__") == False): pos_array = pos_array.flatten() return pos_array def get_particle_velocity(self, tags): [x, y, z] = self.get_particle_velocity_array(tags) vel_array = np.array([x.value_in(units.cm / units.s), y.value_in(units.cm / units.s), z.value_in(units.cm / units.s)]).transpose() | units.cm / units.s if (hasattr(x,"__len__") == False): vel_array = vel_array.flatten() return vel_array def define_methods(self, handler): #length = units.cm #time = units.s #mass = units.g #speed = units.cm*units.s**-1 #density = units.g*units.cm**-3 #momentum = density*speed #energy = units.cm**2*units.g*units.s**-2 #potential_energy = energy #magnetic_field = units.g*0.1*units.C**-1*units.s**-1 #acc = units.cm*units.s**-2 ### These two are included in CommonCode #handler.add_method( #'initialize_code', #(), #(handler.ERROR_CODE) #) #handler.add_method( #'cleanup_code', #(), #(handler.ERROR_CODE) #) handler.add_method( 'evolve_model', (time,), (handler.ERROR_CODE,) ) handler.add_method( 'get_position_of_index', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (length, length, length, handler.ERROR_CODE,) ) handler.add_method( 'get_index_of_position', (length, length, length), (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.ERROR_CODE,) ) handler.add_method( "get_max_refinement", (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'get_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, momentum, momentum, momentum, energy, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_state', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, density, momentum, momentum, momentum, energy), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), ( energy, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_energy_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, energy), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (density, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, density), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_momentum_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (momentum, momentum, momentum, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_momentum_density', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, momentum, momentum, momentum), (handler.ERROR_CODE,) ) handler.add_method( 'get_grid_velocity', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (speed, speed, speed, handler.ERROR_CODE,) ) handler.add_method( 'set_grid_velocity', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX, speed, speed, speed), (handler.ERROR_CODE,) ) handler.add_method( 'get_potential', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (potential, handler.ERROR_CODE,) ) handler.add_method( 'get_potential_at_point', (length, length, length, length), (potential, handler.ERROR_CODE,) ) handler.add_method( 'get_gravity_at_point', (length, length, length, length), (acc, acc, acc, handler.ERROR_CODE,) ) handler.add_method( 'get_cell_volume', (handler.INDEX, handler.INDEX, handler.INDEX, handler.INDEX), (length**3, handler.ERROR_CODE,) ) handler.add_method( 'get_number_of_procs', (), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_all_local_num_grids', (handler.INDEX), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( 'get_data_all_local_blks', (handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_1blk_cell_coords', (handler.NO_UNIT,handler.NO_UNIT,handler.NO_UNIT), (length, handler.ERROR_CODE) ) handler.add_method( 'get_leaf_indices', (handler.NO_UNIT), (handler.NO_UNIT, handler.INDEX, handler.INDEX, handler.ERROR_CODE) ) handler.add_method( 'kick_grid', (time), (handler.ERROR_CODE,) ) handler.add_method( 'kick_block', (acc, acc, acc, handler.INDEX, handler.INDEX, handler.NO_UNIT, 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_end_time", (), (time, handler.ERROR_CODE,) ) handler.add_method( "set_end_time", (time, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_time', (), (time, handler.ERROR_CODE,) ) handler.add_method( 'get_max_num_steps', (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'set_max_num_steps', (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( 'get_restart', (), (handler.NO_UNIT, handler.ERROR_CODE,) ) handler.add_method( 'set_restart', (handler.NO_UNIT,), (handler.ERROR_CODE,) ) handler.add_method( 'get_hydro_state_at_point', (length, length, length, speed, speed, speed), (density, momentum, momentum, momentum, energy, handler.ERROR_CODE) ) handler.add_method( 'get_number_of_particles', (), (handler.NO_UNIT,handler.ERROR_CODE,) ) handler.add_method( 'get_accel_gas_on_particles', (length,length,length,length), (acc,acc,acc, handler.ERROR_CODE,) ) handler.add_method( 'get_num_part_prop', (), (handler.NO_UNIT,handler.ERROR_CODE) ) ### I'm implementing this with my own defined function ### so that the structure of the array return looks ### right. #handler.add_method( #'get_particle_position', #(handler.NO_UNIT), #(length, length, length, handler.ERROR_CODE) #) handler.add_method( 'set_particle_position', (handler.NO_UNIT, length, length, length), (handler.ERROR_CODE) ) ### Same as above. #handler.add_method( #'get_particle_velocity', #(handler.NO_UNIT), #(speed, speed, speed, handler.ERROR_CODE) #) handler.add_method( 'set_particle_velocity', (handler.NO_UNIT, speed, speed, speed), (handler.ERROR_CODE) ) handler.add_method( 'make_sink', (length, length, length), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_particle_mass', (handler.INDEX), (mass, handler.ERROR_CODE) ) handler.add_method( 'set_particle_mass', (handler.INDEX, mass), (handler.ERROR_CODE) ) handler.add_method( 'get_particle_gpot', (handler.INDEX), (potential, handler.ERROR_CODE) ) handler.add_method( 'set_particle_gpot', (handler.NO_UNIT, potential), (handler.ERROR_CODE) ) handler.add_method( 'get_particle_tags', (handler.INDEX), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_particle_proc', (handler.INDEX), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_particle_block', (handler.INDEX), (handler.INDEX, handler.ERROR_CODE) ) handler.add_method( 'write_chpt', (), (handler.ERROR_CODE) ) handler.add_method( 'get_new_tags', (handler.NO_UNIT), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'get_number_of_new_tags', (), (handler.NO_UNIT, handler.ERROR_CODE) ) handler.add_method( 'clear_new_tags', (), (handler.ERROR_CODE) ) handler.add_method( 'particles_gather', (), (handler.ERROR_CODE) ) # handler.add_method( # 'make_particle_tree', # (), # (handler.ERROR_CODE) # ) def specify_grid(self, definition, index_of_grid = 1, nproc=0): 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_velocity', names=('vx','vy','vz')) #definition.add_setter('set_grid_velocity', names=('vx','vy','vz')) 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,'nproc':nproc}) @property def grid(self): return self._create_new_grid(self.specify_grid, index_of_grid = 1, nproc=0) # Define an handler that returns a list of all the blocks in the simulation. # This iterates over all processors and then loops over the blocks on the local processors. def itergrids(self): m = self.get_number_of_procs() for x in range(m): # Loop over processors. n = self.get_number_of_grids(x) #n = max(num_grids) #print "N =",n, "X =",x for y in range(1, n+1): # Loop over blocks. yield self._create_new_grid(self.specify_grid, index_of_grid = y, nproc=x) 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_at_point', 'get_potential', 'get_gravity_at_point', # '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_grid_velocity', 'set_grid_velocity', 'get_position_of_index', 'get_index_of_position', 'get_max_refinement', # 'set_grid_scalar', # 'get_grid_scalar', 'get_number_of_grids', 'get_index_range_inclusive', 'get_cell_volume', 'get_number_of_procs', 'get_all_local_num_grids', 'get_data_all_local_blks', 'get_1blk_cell_coords', 'get_leaf_indices', 'kick_grid', 'kick_block', # 'get_boundary_state', # 'set_boundary_state', # 'get_boundary_position_if_index', # 'get_boundary_index_range_inclusive', 'get_timestep', 'set_timestep', 'get_end_time', 'set_end_time', 'get_time', 'get_max_num_steps', 'set_max_num_steps', 'get_restart', 'get_number_of_particles', 'get_accel_gas_on_particles', 'get_particle_position', 'set_particle_position', 'get_particle_velocity', 'set_particle_velocity', 'make_sink', 'get_particle_mass', 'set_particle_mass', 'set_particle_gpot', 'get_particle_gpot', 'get_particle_tags', 'get_particle_proc', 'get_particle_block', 'get_new_tags', 'get_number_of_new_tags', 'clear_new_tags', 'particles_gather', #'make_particle_tree', 'write_chpt' ]: handler.add_method(state, methodname)
44,808
35.60866
171
py
amuse
amuse-main/src/amuse/community/bonsai/__init__.py
# generated file from .interface import Bonsai
47
15
29
py
amuse
amuse-main/src/amuse/community/bonsai/interface.py
import os.path 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 BonsaiInterface(CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, CodeWithDataDirectories, SinglePointGravityFieldInterface): """ .. [#] 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', 'bonsai', 'src', '') ) @legacy_function def set_src_directory(): function = LegacyFunctionSpecification() function.addParameter('src_directory', dtype='string', direction=function.IN, description = "The path to the Bonsai 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 Bonsai(GravitationalDynamics): def __init__(self, unit_converter = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = BonsaiInterface(**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,857
41.121581
166
py
amuse
amuse-main/src/amuse/community/cachedse/__init__.py
from .interface import Cachedse
32
15.5
31
py
amuse
amuse-main/src/amuse/community/cachedse/interface.py
import os import pickle import fnmatch #import numpy as np from amuse.units import units from amuse.units import constants from amuse import datamodel class CachedStellarEvolution: """ The CachedStellarEvolution wraps around any other stellar evolution class and then caches the evolution. In particular, a) if the class has not been called before with this particular combination of {model, initial_mass}, it runs the actual underlying stellar evolution code while storing the stellar state parameters after each call to .evolve_model() into a .pkl file in the cache directory; b) if the class finds this particular {model, initial_mass} combination to exist in the cache, it uses the results stored in the .pkl files and doesn't run the actual underlying stellar evolution object, thus making the stellar evolution code "run" significantly faster. CachedStellarEvolution does not save the internal state of the underlying stellar evolution code and thus does not protect against "cache underruns". In other words, if a star with mass 1.0MSun has been cached until 100Myr, it will throw an exception upon a call to .evolve_model(end_time = 200 | units.Myr). CachedStellarEvolution can use partial cache. In other words, when evolving a set of particles with initial masses m={1.0, 2.0, 3.0}MSun with cached results only available for m={1.0, 3.0}MSun, it will use cached results and run the underlying stellar evolution model only for m=2.0MSun. Examples of the usage of the class can be found in the scripts: test/examples/test_HRdiagram_cluster.py test/examples/test_HRdiagram_tracks.py Both scripts implement the argument '--cache', which can be used to determine the location of the cache directory. The caching is then implemented by first creating a regular stellar evolution code and then the feeding this to the constructor for CachedStellarEvolution (along with the location of the cache on disk, stored in options.cacheDir in our example). if not (options.cacheDir is None): print "Using cache directory: %s" % (options.cacheDir) code = CachedStellarEvolution(code, options.cacheDir) The 'code' object can now be used like any stellar evolution code, e.g. reading the state with code.particles and evolving with code.evolve_model(). In test_HRdiagram_cluster.py, the initial masses are determined randomly, which means that we need to specify a seed in order for the cache to have a meaningful effect. This can be done through adding the additional argument, e.g. '--seed 6' on the command line. """ # extra fields that should logically reside in the particles-list but are non-quantity values class ParticleCache: pass def __init__(self, baseStellarEvolution, cacheDirectory): self.particles = datamodel.Particles() self.particlesCache = [] self.baseStellarEvolution = baseStellarEvolution self.cacheDirectory = cacheDirectory # create cache directory if it has not been created already if not os.path.exists(self.cacheDirectory): os.makedirs(self.cacheDirectory) #print "__init__: created cache directory" else: #print "__init__: cache directory exists" pass def commit_parameters(self): self.baseStellarEvolution.commit_parameters() def initialize_module_with_current_parameters(self): self.commit_parameters() def _particle_update(self, index): particle = self.particles[index] particleCache = self.particlesCache[index] # if particle is cached: load next state, update if particleCache.isCached: #print "_particle_update(): using cache for m=%s" % (particle.mass) state = pickle.load(particleCache.cachefh) if isinstance(state, dict): particle.mass = state['mass'] | units.MSun particle.age = state['age'] | units.Myr particle.luminosity = state['luminosity'] | units.LSun particle.temperature = state['temperature'] | units.K particle.stellar_type = state['stellar_type'] | units.stellar_type particle.radius = state['radius'] | units.RSun # cache contains an exception else: #print "_particle_update(): loaded exception: %s" % (state,) raise(state) # particle is not cached: update state, save state else: #print "_particle_update(): evolving for m=%s" % (particle.mass) particle.mass = particleCache.baseParticle.mass particle.age = particleCache.baseParticle.age particle.luminosity = particleCache.baseParticle.luminosity particle.temperature = particleCache.baseParticle.temperature particle.stellar_type = particleCache.baseParticle.stellar_type particle.radius = particleCache.baseParticle.radius pickle.dump(dict( mass = particleCache.baseParticle.mass.value_in(units.MSun), age = particleCache.baseParticle.age.value_in(units.Myr), luminosity = particleCache.baseParticle.luminosity.value_in(units.LSun), temperature = particleCache.baseParticle.temperature.value_in(units.K), stellar_type = particleCache.baseParticle.stellar_type.value_in(units.stellar_type), radius = particleCache.baseParticle.radius.value_in(units.RSun), ), particleCache.cachefh) def commit_particles(self): # clean up non-cached particles for particleCache in self.particlesCache: if not particleCache.isCached: self.baseStellarEvolution.particles.remove_particle(particleCache.baseParticle) # loop over all particles self.particlesCache = [] for index in range(len(self.particles)): self.particlesCache.append(self.ParticleCache()) particle = self.particles[index] particleCache = self.particlesCache[index] particleCache.cachefn = "%s/model-%s-mass-%s.pkl" % ( self.cacheDirectory, self.baseStellarEvolution.__class__.__name__, ("%0.8f" % particle.mass.value_in(units.MSun)).zfill(12) ) # open cache file if (os.path.isfile(particleCache.cachefn)): print("Using cache: %s" % (particleCache.cachefn, )) particleCache.isCached = True particleCache.cachefh = open(particleCache.cachefn, 'rb') else: print("Creating cache: %s" % (particleCache.cachefn, )) particleCache.isCached = False particleCache.cachefh = open(particleCache.cachefn, 'wb') particleCache.baseParticle = self.baseStellarEvolution.particles.add_particle(particle) # initialize uncached stars self.baseStellarEvolution.commit_particles() # initialize states for all particles for index in range(len(self.particles)): self._particle_update(index) def evolve_model(self, end_time = None): # evolve non-cached models if len(self.baseStellarEvolution.particles) > 0: try: self.baseStellarEvolution.evolve_model(end_time) # store the exception object for all cached particles except Exception as ex: #print "CachedStellarEvolution.evolve_model(): caching exception:%s" % (ex,) for (particle, particleCache) in zip(self.particles, self.particlesCache): if not particleCache.isCached: pickle.dump(ex, particleCache.cachefh) raise(ex) # update state on every star once (enough for default timestep advancement) for index in range(len(self.particles)): self._particle_update(index) # further advance states for cached stars and end_time != None if not (end_time is None): for index in range(len(self.particles)): particle = self.particles[index] particleCache = self.particlesCache[index] while particle.age < end_time and particleCache.isCached: self._particle_update(index) def stop(self): self.baseStellarEvolution.stop() for index in range(len(self.particles)): particle = self.particles[index] particleCache = self.particlesCache[index] particleCache.cachefh.close() # clean up non-cached particles for particleCache in self.particlesCache: if not particleCache.isCached: self.baseStellarEvolution.particles.remove_particle(particleCache.baseParticle) # return a list of available cached masses def cached_mass(self): model_files = fnmatch.filter(os.listdir(self.cacheDirectory), 'model-%s-*.pkl' % (self.baseStellarEvolution.__class__.__name__)) model_files.sort() cached_masses = [] for model_file in model_files: model_fileh = open("%s/%s" % (self.cacheDirectory, model_file), 'rb') state = pickle.load(model_fileh) cached_masses.append(state['mass'] | units.MSun) model_fileh.close() return cached_masses class ParticlesTimeseries: """ Helper object for collecting/keeping stellar evolution states as timeseries. Example use case looks something like the following. stellar_evolution = ... Particles = stellar_evolution.add_particles(...) ParticlesSeries = ParticlesTimeseries(Particles) while(...) stellar_evolution.evolve_model() ParticlesSeries.update() plot(ParticlesSeries.age_Myr(), ParticlesSeries.mass_MSun()) """ class ParticleTimeseries: pass def __init__(self, pParticlesBase): self.particlesBase = pParticlesBase.as_set() self.particles = [] for i in range(len(self.particlesBase)): self.particles.append(self.ParticleTimeseries()) for particle in self.particles: particle.mass = [] particle.age = [] particle.luminosity = [] particle.temperature = [] particle.stellar_type = [] particle.radius = [] def add_timepoint(self): for particle, baseParticle in zip(self.particles, self.particlesBase): particle.mass.append(baseParticle.mass) particle.age.append(baseParticle.age) particle.luminosity.append(baseParticle.luminosity) particle.temperature.append(baseParticle.temperature) particle.stellar_type.append(baseParticle.stellar_type) particle.radius.append(baseParticle.radius) def list_value_in(self, list, unit): result = [] for element in list: result.append(element.value_in(unit)) return result def mass_MSun(self, index=0): return self.list_value_in(self.particles[index].mass, units.MSun) def age_Myr(self, index=0): return self.list_value_in(self.particles[index].age, units.Myr) def radius_RSun(self, index=0): return self.list_value_in(self.particles[index].radius, units.RSun) def luminosity_LSun(self, index=0): return self.list_value_in(self.particles[index].luminosity, units.LSun) def temperature_K(self, index=0): return self.list_value_in(self.particles[index].temperature, units.K) def stellar_type(self, index=0): return self.list_value_in(self.particles[index].stellar_type, units.stellar_type) CachedSE = CachedStellarEvolution Cachedse = CachedStellarEvolution
12,736
41.036304
136
py
amuse
amuse-main/src/amuse/community/kepler_orbiters/test_kepler.py
import numpy import struct from .interface import Kepler from amuse.units import nbody_system from amuse.units import units,constants from amuse.ic.plummer import new_plummer_model from amuse.datamodel import Particle #from matplotlib import pyplot import time from amuse.ext.orbital_elements import orbital_elements_from_binary,new_binary_from_orbital_elements def elements(starmass,x,y,z,vx,vy,vz,G=constants.G): mu=G*starmass r=(x**2+y**2+z**2)**0.5 v2=(vx**2+vy**2+vz**2) e=v2/2-mu/r a=-mu/2/e hx=y*vz-z*vy hy=z*vx-x*vz hz=x*vy-y*vx rdotv=x*vx+y*vy+z*vz ex=v2*x/mu-rdotv*vx/mu-x/r ey=v2*y/mu-rdotv*vy/mu-y/r ez=v2*z/mu-rdotv*vz/mu-z/r h2=(hx**2+hy**2+hz**2) eps=(1-h2/mu/a)**0.5 return a,eps def test_kepler(N=10000, tend=1.| units.yr,method=0): numpy.random.seed(12345) conv=nbody_system.nbody_to_si(2.| units.MSun, 5.|units.AU) comets=new_plummer_model(N,conv) sun=Particle(mass=1.|units.MSun) sun.position=[0,0,0]|units.AU sun.velocity=[0,0,0]|units.kms comets.mass*=0. code=Kepler(conv,redirection="none") code.set_method(method) code.central_particle.add_particle(sun) code.orbiters.add_particles(comets) a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz) # print code.orbiters.x[0] print(orbital_elements_from_binary(code.particles[0:2],constants.G)) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2],constants.G)) # print code.orbiters.x[0] a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 dev=numpy.where(da > 0.00001)[0] print(len(dev)) print(a0[dev].value_in(units.AU)) print(eps0[dev]) # pyplot.plot(a0[dev].value_in(units.AU),eps0[dev],"ro") # pyplot.plot(a[dev].value_in(units.AU),eps[dev],"g+") print("max da,deps:",da.max(), deps.max()) print("time:",t2-t1) # pyplot.show() return t2-t1,da.max(),deps.max() def test_kepler_almost_parabolic( tend=1,method=0): code=Kepler(redirection="none") code.set_method(method) mass1=1.| nbody_system.mass mass2=0| nbody_system.mass semimajor_axis=1.|nbody_system.length eccentricity=0.9999999 p=2*numpy.pi*(semimajor_axis**3/nbody_system.G/mass1)**0.5 tend=tend*p print(tend) parts=new_binary_from_orbital_elements( mass1, mass2, semimajor_axis, eccentricity = eccentricity, true_anomaly = 0.0102121 ) code.central_particle.add_particle(parts[0]) code.orbiters.add_particle(parts[1]) a0,eps0=elements(mass1,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(mass1,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) print("time:",t2-t1) def test_kepler_parabolic( tend=1,method=0, sign=+1): code=Kepler(redirection="none") code.set_method(method) sun=Particle() sun.mass=1. | nbody_system.mass sun.x=0. | nbody_system.length sun.y=0. | nbody_system.length sun.z=0. | nbody_system.length sun.vx=0. | nbody_system.speed sun.vy=0. | nbody_system.speed sun.vz=0. | nbody_system.speed comet=Particle() comet.mass= 0 | nbody_system.mass comet.x=1. | nbody_system.length comet.y=0. | nbody_system.length comet.z=0. | nbody_system.length comet.vx=0. | nbody_system.speed comet.vy=(1.0 + sign * 1.0e-10)*(2*nbody_system.G*sun.mass/comet.x)**0.5 comet.vz=0. | nbody_system.speed tend=tend | nbody_system.time print(tend) code.central_particle.add_particle(sun) code.orbiters.add_particle(comet) a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) print("time:",t2-t1) def crash_test(method=1): code=Kepler(redirection="none") code.set_method(method) smu=1.224744871391589 mu=smu**2 r0=2.787802728537455 rv0=-0.9899959571994231 alpha=0.01380749549277993 smudt=2.809925892593303 v02=(mu*(2/r0-alpha)) vx=rv0 vy=(v02-vx**2)**0.5 sun=Particle() sun.mass=mu | nbody_system.mass sun.x=0. | nbody_system.length sun.y=0. | nbody_system.length sun.z=0. | nbody_system.length sun.vx=0. | nbody_system.speed sun.vy=0. | nbody_system.speed sun.vz=0. | nbody_system.speed comet=Particle() comet.mass= 0 | nbody_system.mass comet.x=r0| nbody_system.length comet.y=0. | nbody_system.length comet.z=0. | nbody_system.length comet.vx=vx | nbody_system.speed comet.vy=vy | nbody_system.speed comet.vz=0. | nbody_system.speed tend=(smudt/smu) | nbody_system.time print(tend) code.central_particle.add_particle(sun) code.orbiters.add_particle(comet) a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) print("time:",t2-t1) def crash_test2(method=1): code=Kepler(redirection="none") code.set_method(method) """ mu=struct.unpack('!d','3ff7ffffffffffff'.decode('hex'))[0] dt=struct.unpack('!d','40025ab746b00001'.decode('hex'))[0] pos1=struct.unpack('!d','bfed36dc82998ed4'.decode('hex'))[0] pos2=struct.unpack('!d','40051297fc6e5256'.decode('hex'))[0] pos3=struct.unpack('!d','0000000000000000'.decode('hex'))[0] vel1=struct.unpack('!d','3fb09d8008ba33b9'.decode('hex'))[0] vel2=struct.unpack('!d','bff06788b551b81d'.decode('hex'))[0] vel3=struct.unpack('!d','0000000000000000'.decode('hex'))[0] """ mu=float.fromhex("0x1.8p+0") dt=float.fromhex("0x1.25ab746bp+1") pos1=float.fromhex("-0x1.d36dc82998ed4p-1") pos2=float.fromhex("0x1.51297fc6e5256p+1") pos3=float.fromhex("0x0p+0") vel1=float.fromhex("0x1.09d8008ba33b9p-4") vel2=float.fromhex("-0x1.06788b551b81ep+0") vel3=float.fromhex("0x0p+0") sun=Particle() sun.mass=mu | nbody_system.mass sun.x=0. | nbody_system.length sun.y=0. | nbody_system.length sun.z=0. | nbody_system.length sun.vx=0. | nbody_system.speed sun.vy=0. | nbody_system.speed sun.vz=0. | nbody_system.speed comet=Particle() comet.mass= 0 | nbody_system.mass comet.x=pos1 | nbody_system.length comet.y=pos2 | nbody_system.length comet.z=pos3 | nbody_system.length comet.vx=vel1 | nbody_system.speed comet.vy=vel2 | nbody_system.speed comet.vz=vel3 | nbody_system.speed tend=dt | nbody_system.time print(tend,mu) code.central_particle.add_particle(sun) code.orbiters.add_particle(comet) a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) print("time:",t2-t1) def test_softening(method=1): code=Kepler(redirection="none") code.set_method(method) dt=float.fromhex("0x1.67b39e372f04dp+4") mu=float.fromhex("0x1.fffffffffffdfp-3") e2=float.fromhex("0x1.0000000000003p+0") pos1=float.fromhex("0x1.1b76542265052p-1") pos2=float.fromhex("0x1.0c4dbda42097cp-6") pos3=float.fromhex("0x1.54fd66cd1e212p-3") vel1=float.fromhex("0x1.d6ef43d58ca7ep-2") vel2=float.fromhex("0x1.7a85379e59794p-2") vel3=float.fromhex("-0x1.5421044d1acffp-1") sun=Particle() sun.mass=mu | nbody_system.mass sun.x=0. | nbody_system.length sun.y=0. | nbody_system.length sun.z=0. | nbody_system.length sun.vx=0. | nbody_system.speed sun.vy=0. | nbody_system.speed sun.vz=0. | nbody_system.speed comet=Particle() comet.mass= 0 | nbody_system.mass comet.x=pos1 | nbody_system.length comet.y=pos2 | nbody_system.length comet.z=pos3 | nbody_system.length comet.vx=vel1 | nbody_system.speed comet.vy=vel2 | nbody_system.speed comet.vz=vel3 | nbody_system.speed tend=dt | nbody_system.time print(tend,mu) code.central_particle.add_particle(sun) code.orbiters.add_particle(comet) code.parameters.epsilon_squared = e2 | nbody_system.length**2 a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) t1=time.time() code.evolve_model(tend) t2=time.time() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) print("time:",t2-t1) def t_linear(tend=1,N=100,method=0): code=Kepler(redirection="none") code.set_method(method) mass=1. | nbody_system.mass x=1. | nbody_system.length vx=0 | nbody_system.speed e=0.5*vx**2-nbody_system.G*mass/x semimajor_axis=-nbody_system.G*mass/2/e p=2*numpy.pi*(semimajor_axis**3/nbody_system.G/mass)**0.5 print(semimajor_axis) print(p) tend=tend*p dt=p/N sun=Particle() sun.mass=mass sun.x=0. | nbody_system.length sun.y=0. | nbody_system.length sun.z=0. | nbody_system.length sun.vx=0. | nbody_system.speed sun.vy=0. | nbody_system.speed sun.vz=0. | nbody_system.speed comet=Particle() comet.mass= 0 | nbody_system.mass comet.x=x comet.y=0. | nbody_system.length comet.z=0. | nbody_system.length comet.vx=vx comet.vy=0. | nbody_system.speed comet.vz=0. | nbody_system.speed code.central_particle.add_particle(sun) code.orbiters.add_particle(comet) a0,eps0=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) print(orbital_elements_from_binary(code.particles[0:2])) #pyplot.ion() #f=pyplot.figure(figsize=(8,6)) #pyplot.show() tnow=0*tend time=[] xs=[] while tnow<tend: tnow+=dt print(tnow,int(tnow/dt)) code.evolve_model(tnow) #f.clf() time.append(tnow/tend) xs.append(code.orbiters.x[0].number) #pyplot.plot(time,xs,"r+") #pyplot.xlim(-0.1,1.1) #pyplot.ylim(-1.1,3.1) #pyplot.draw() print(orbital_elements_from_binary(code.particles[0:2])) print(code.orbiters.position) a,eps=elements(sun.mass,code.orbiters.x,code.orbiters.y,code.orbiters.z, code.orbiters.vx,code.orbiters.vy,code.orbiters.vz,G=nbody_system.G) da=abs((a-a0)/a0) deps=abs(eps-eps0)/eps0 print(da,deps) input() if __name__=="__main__": for method in [1,0]: t_linear(N=100,method=method) print() print("-"*10) print() tend = 1.0 for method in [1,0]: crash_test(method=method) print() print("-"*10) print() for method in [1,0]: crash_test2(method=method) print() print("-"*10) print() for method in [1,0]: test_kepler_parabolic(tend=tend,method=method, sign=+1) print() print("-"*10) print() for method in [1,0]: test_kepler_parabolic(tend=tend,method=method, sign=-1) print() print("-"*10) print() for method in [1,0]: test_kepler_almost_parabolic(tend=tend,method=method) print() print("-"*10) print() for method in [1,0]: test_kepler(N=10000,tend=tend | units.yr,method=method) print() print("-"*10) print() for method in [0,]: test_softening(method=method) print()
13,220
23.758427
100
py
amuse
amuse-main/src/amuse/community/kepler_orbiters/__init__.py
from .interface import Kepler_orbiters
39
19
38
py
amuse
amuse-main/src/amuse/community/kepler_orbiters/interface.py
from amuse.community import * from amuse.community.interface.common import CommonCodeInterface, CommonCode from amuse.community.interface.gd import GravitationalDynamicsInterface from amuse.community.interface.gd import GravitationalDynamics, GravityFieldCode from amuse.support.options import option from amuse.units import units from amuse.datamodel import Particles import os.path class KeplerInterface(CodeInterface, GravitationalDynamicsInterface): """ kepler_orbiters is a code to solve Kepler's equations for number of two-body problems that share one of the bodies. It is Suited for problems with a dominant central mass (e.g., planetary systems, debris disks). The orbits are initialized from mass, position, and velocity. The shared body is represented by particle 'central_particle' and defined as: instance.central_particle.add_particles(central_particle) and the other particles are 'orbiters': instance.orbiters.add_particles(orbiters) The postition and velocity vectors of the orbiters are integrated, while these of the central particle stays fixed. The Kepler's equations are solved using universal variables with two independent solvers provided and set by parameter 'method': * solver from the SAKURA code (Goncalves Ferrari et al., 2014), default, instance.parameters.method = 0 * solver from the HUAYNO code (Pelupessy et al., 2012) instance.parameters.method = 1 See the example kepler_orbiters_planets_around_sun.py. The relevant references are: .. [#] ADS:2014MNRAS.440..719G (Goncalves Ferrari, Boekholt, Portegies Zwart; 2014 MNRAS, 440, 719 .. [#] ... (SAKURA, method 0 -- default) .. [#] ADS:2012NewA...17..711P (Pelupessy, Janes, Portegies Zwart; 2012, New Astronomy, 17, 711 .. [#] ... (HUAYNO, method 1)) """ include_headers = ['interface.h'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker = "keplerorbiters_worker", **options) @legacy_function def get_method(): function = LegacyFunctionSpecification() function.addParameter('method', dtype='i', direction=function.OUT, default=0) function.result_type = 'int32' return function @legacy_function def set_method(): function = LegacyFunctionSpecification() function.addParameter('method', dtype='i', direction=function.IN, default=0) function.result_type = 'int32' return function @legacy_function def get_central_mass(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN, default=0) function.addParameter('mass', dtype='float64', direction=function.OUT, unit = nbody_system.mass) function.result_type = 'int32' return function @legacy_function def set_central_mass(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN) function.addParameter('mass', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.result_type = 'int32' return function @legacy_function def get_central_radius(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN, default=0) function.addParameter('radius', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_central_radius(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN) function.addParameter('radius', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_central_pos(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN, default=0) function.addParameter('x', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.OUT, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def set_central_pos(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN) function.addParameter('x', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.IN, unit = nbody_system.length) function.result_type = 'int32' return function @legacy_function def get_central_vel(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN, default=0) function.addParameter('vx', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.OUT, unit = nbody_system.speed) function.result_type = 'int32' return function @legacy_function def set_central_vel(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN) function.addParameter('vx', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.result_type = 'int32' return function @legacy_function def new_central_particle(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.OUT) function.addParameter('mass', dtype='float64', direction=function.IN, unit = nbody_system.mass) function.addParameter('x', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('y', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('z', dtype='float64', direction=function.IN, unit = nbody_system.length) function.addParameter('vx', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vy', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('vz', dtype='float64', direction=function.IN, unit = nbody_system.speed) function.addParameter('radius', dtype='float64', direction=function.IN, unit = nbody_system.length,default=0.) function.result_type = 'int32' return function @legacy_function def delete_central_particle(): function = LegacyFunctionSpecification() function.can_handle_array=True function.addParameter('index_of_the_particle', dtype='i', direction=function.IN) function.result_type = 'int32' return function def get_gravity_at_point(self,radius,x,y,z): mass,err=self.get_central_mass() xc,yc,zc,err=self.get_central_pos() dr2=((x-xc)**2+(y-yc)**2+(z-zc)**2+radius**2) dr=dr2**0.5 ax=-mass*(x-xc)/(dr2*dr) ay=-mass*(y-yc)/(dr2*dr) az=-mass*(z-zc)/(dr2*dr) return ax,ay,az def get_potential_at_point(self,radius,x,y,z): mass,err=self.get_central_mass() xc,yc,zc,err=self.get_central_pos() dr2=((x-xc)**2+(y-yc)**2+(z-zc)**2+radius**2) dr=dr2**0.5 phi=-mass/dr return phi class Kepler(GravitationalDynamics, GravityFieldCode): def __init__(self, unit_converter = None, **options): self.unit_converter = unit_converter CommonCode.__init__(self, KeplerInterface(**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_parameters(self, handler): handler.add_method_parameter( "get_eps2", "set_eps2", "epsilon_squared", "smoothing parameter for gravity calculations", default_value = 0.0 | nbody_system.length * nbody_system.length ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_eps2", (), (nbody_system.length * nbody_system.length, handler.ERROR_CODE,) ) handler.add_method( "set_eps2", (nbody_system.length * nbody_system.length, ), (handler.ERROR_CODE,) ) handler.add_method( 'get_gravity_at_point', ( nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.length, ), ( nbody_system.acceleration, nbody_system.acceleration, nbody_system.acceleration, ) ) handler.add_method( 'get_potential_at_point', ( nbody_system.length, nbody_system.length, nbody_system.length, nbody_system.length, ), ( nbody_system.potential, ) ) def define_particle_sets(self, handler): handler.define_super_set('particles', ['central_particle','orbiters'], index_to_default_set = 1) handler.define_set('central_particle', 'index_of_the_particle') handler.set_new('central_particle', 'new_central_particle') handler.set_delete('central_particle', 'delete_central_particle') handler.add_setter('central_particle', 'set_central_mass') handler.add_getter('central_particle', 'get_central_mass') handler.add_setter('central_particle', 'set_central_radius') handler.add_getter('central_particle', 'get_central_radius') handler.add_setter('central_particle', 'set_central_pos') handler.add_getter('central_particle', 'get_central_pos') handler.add_setter('central_particle', 'set_central_vel') handler.add_getter('central_particle', 'get_central_vel') handler.define_set('orbiters', 'index_of_the_particle') handler.set_new('orbiters', 'new_particle') handler.set_delete('orbiters', 'delete_particle') handler.add_setter('orbiters', 'set_state') handler.add_getter('orbiters', 'get_state') handler.add_setter('orbiters', 'set_mass') handler.add_getter('orbiters', 'get_mass') handler.add_setter('orbiters', 'set_position') handler.add_getter('orbiters', 'get_position') handler.add_setter('orbiters', 'set_velocity') handler.add_getter('orbiters', 'get_velocity') def get_gravity_at_point(self,radius,x,y,z): xx=x-self.central_particle.x yy=y-self.central_particle.y zz=z-self.central_particle.z return self.overridden().get_gravity_at_point(radius,xx,yy,zz) def get_potential_at_point(self,radius,x,y,z): xx=x-self.central_particle.x yy=y-self.central_particle.y zz=z-self.central_particle.z return self.overridden().get_potential_at_point(radius,xx,yy,zz) Kepler_orbiters = Kepler
13,309
40.987382
102
py
amuse
amuse-main/src/amuse/community/bhtree/__init__.py
# -*- mode: python; coding: utf-8 -*- __author__ = 'Simon Portegies Zwart' __author_email__ = '<spz@science.uva.nl>' __date__ = '2006-11-11 15:32:00 CEST' # Dummy file to indicate that this directory is a package. from .interface import Bhtree
260
28
58
py
amuse
amuse-main/src/amuse/community/bhtree/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 BHTreeInterface( CodeInterface, LiteratureReferencesMixIn, GravitationalDynamicsInterface, StoppingConditionInterface, SinglePointGravityFieldInterface): """ .. [#] ADS:1986Natur.324..446B (Barnes, J., Hut, P., *Nature*, **4**, 324 (1986)) """ include_headers = ['interface.h', 'worker_code.h', 'stopcond.h'] def __init__(self, convert_nbody = None, mode = 'cpu', **kwargs): CodeInterface.__init__(self, name_of_the_worker=self.name_of_the_worker(mode), **kwargs) """ self.parameters = parameters.Parameters(self.parameter_definitions, self) if convert_nbody is None: convert_nbody = nbody_system.nbody_to_si.get_default() self.convert_nbody = convert_nbody """ LiteratureReferencesMixIn.__init__(self) def name_of_the_worker(self, mode): if mode == "g6": return 'bhtree_worker_g6' elif mode == "gpu": return 'bhtree_worker_gpu' else: return 'bhtree_worker' @legacy_function def reinitialize_particles(): function = LegacyFunctionSpecification() function.result_type = 'i' return function @legacy_function def set_time_step(): """ Update timestep. """ function = LegacyFunctionSpecification() function.addParameter('timestep', dtype='float64', direction=function.IN, description = "timestep") function.result_type = 'int32' function.result_doc = """ 0 - OK particle was found in the model and the information was set -1 - ERROR particle could not be found """ return function @legacy_function def get_epsilon_squared(): """ Get epsilon^2, a softening parameter for gravitational potentials with point particles. """ function = LegacyFunctionSpecification() 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_epsilon_squared(): """ 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.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ 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_use_self_gravity(): """ Get use_self_gravity flag, the flag for usage of self gravity, 1 or 0 (true or false). """ function = LegacyFunctionSpecification() function.addParameter('use_self_gravity', dtype='int32', direction=function.OUT, description = "flag for usage of self gravity, 1 or 0 (true or false)") 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_use_self_gravity(): """ Set use_self_gravity flag, the flag for usage of self gravity, 1 or 0 (true or false). """ function = LegacyFunctionSpecification() function.addParameter('use_self_gravity', dtype='int32', direction=function.IN, description = "flag for usage of self gravity, 1 or 0 (true or false)") 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_ncrit_for_tree(): """ Get Ncrit, the maximum number of particles sharing an interaction list. """ function = LegacyFunctionSpecification() function.addParameter('ncrit_for_tree', dtype='int32', direction=function.OUT, description = "Ncrit, the maximum number of particles sharing an interaction list") 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_ncrit_for_tree(): """ Set Ncrit, the maximum number of particles sharing an interaction list. """ function = LegacyFunctionSpecification() function.addParameter('ncrit_for_tree', dtype='int32', direction=function.IN, description = "Ncrit, the maximum number of particles sharing an interaction list") 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_dt_dia(): """ Get the time interval between diagnostics output. """ function = LegacyFunctionSpecification() function.addParameter('dt_dia', dtype='float64', direction=function.OUT, description = "the time interval between diagnostics output", unit = nbody_system.time) 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_dt_dia(): """ Set the time interval between diagnostics output. """ function = LegacyFunctionSpecification() function.addParameter('dt_dia', dtype='float64', direction=function.IN, description = "the time interval between diagnostics output", unit = nbody_system.time) function.result_type = 'int32' function.result_doc = """ 0 - OK the parameter was set -1 - ERROR could not set parameter """ return function class BHTree(GravitationalDynamics, GravityFieldCode): __interface__ = BHTreeInterface def __init__(self, convert_nbody = None, **options): self.stopping_conditions = StoppingConditions(self) legacy_interface = self.__interface__(**options) GravitationalDynamics.__init__( self, legacy_interface, convert_nbody, **options ) 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.125 | nbody_system.length * nbody_system.length ) handler.add_method_parameter( "get_time_step", "set_time_step", "timestep", "constant timestep for iteration", default_value = 0.015625 | nbody_system.time ) handler.add_method_parameter( "get_theta_for_tree", "set_theta_for_tree", "opening_angle", "opening angle, theta, for building the tree: between 0 and 1", default_value = 0.75 ) handler.add_method_parameter( "get_use_self_gravity", "set_use_self_gravity", "use_self_gravity", "flag for usage of self gravity, 1 or 0 (true or false)", default_value = 1 ) handler.add_method_parameter( "get_ncrit_for_tree", "set_ncrit_for_tree", "ncrit_for_tree", "Ncrit, the maximum number of particles sharing an interaction list", default_value = 12 ) handler.add_method_parameter( "get_dt_dia", "set_dt_dia", "dt_dia", "time interval between diagnostics output", default_value = 1.0 | 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 ) self.stopping_conditions.define_parameters(handler) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) handler.add_method( "get_time_step", (), (nbody_system.time, handler.ERROR_CODE,) ) handler.add_method( "set_time_step", (nbody_system.time, ), (handler.ERROR_CODE,) ) self.stopping_conditions.define_methods(handler) def define_state(self, handler): GravitationalDynamics.define_state(self, handler) GravityFieldCode.define_state(self, handler) self.stopping_conditions.define_state(handler) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler) self.stopping_conditions.define_particle_set(handler) Bhtree = BHTree
11,557
32.894428
111
py
amuse
amuse-main/src/amuse/community/etics/__init__.py
# generated file from .interface import Etics
46
14.666667
28
py
amuse
amuse-main/src/amuse/community/etics/interface.py
from amuse.community import * from amuse.community.interface.gd import GravitationalDynamics from amuse.community.interface.gd import GravitationalDynamicsInterface class EticsInterface(CodeInterface, GravitationalDynamicsInterface, LiteratureReferencesMixIn): """ .. [#] ADS:2014ApJ...792...98M (Meiron, Y., Li, B., Holley-Bockelmann, K., & Spurzem, R. 2014, ApJ, 792, 98) """ include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker='etics_worker', **keyword_arguments) LiteratureReferencesMixIn.__init__(self) @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 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_time_step(): function = LegacyFunctionSpecification() function.addParameter('time_step', dtype='float64', direction=function.IN, description = 'time step') function.result_type = 'int32' return function @legacy_function def update_force_potential_arrays(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('dt', dtype='float64', direction=function.IN) function.result_type = 'int32' return function class Etics(GravitationalDynamics): def __init__(self, convert_nbody = None, **keyword_arguments): legacy_interface = EticsInterface(**keyword_arguments) GravitationalDynamics.__init__(self, legacy_interface, convert_nbody, **keyword_arguments) def define_parameters(self, handler): 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_step', 'set_time_step', 'time_step', 'constant timestep for iteration', default_value = 0.001953125 | nbody_system.time ) def define_methods(self, handler): GravitationalDynamics.define_methods(self, handler) # Define some shortcuts for better readability. M = nbody_system.mass L = nbody_system.length V = nbody_system.speed T = nbody_system.time handler.add_method('new_particle', (M,L,L,L,V,V,V,L), (handler.INDEX, handler.ERROR_CODE)) handler.add_method('set_state', (handler.INDEX, M,L,L,L,L,V,V,V), (handler.ERROR_CODE)) handler.add_method('get_state', (handler.INDEX), (M,L,L,L,L,V,V,V, handler.ERROR_CODE)) handler.add_method('set_time_begin', (T), (handler.ERROR_CODE)) handler.add_method('get_time_begin', (), (T, handler.ERROR_CODE)) handler.add_method('get_number_of_particles', (), (units.none, handler.ERROR_CODE)) handler.add_method('get_time_step', (), (T, handler.ERROR_CODE)) handler.add_method('set_time_step', (T), (handler.ERROR_CODE)) handler.add_method('update_force_potential_arrays', (T), (handler.ERROR_CODE)) def define_particle_sets(self, handler): GravitationalDynamics.define_particle_sets(self, handler)
8,146
49.91875
128
py
amuse
amuse-main/src/amuse/community/etics/format-convert.py
#!/usr/bin/env python # This script converts phiGRAPE snapshot files to HDF5. # Author: Yohai Meiron import argparse, os, sys, numpy, re if __name__ == "__main__": # Set commandline parameters parser = argparse.ArgumentParser(description='Convert phiGRPAE snapshot files into HDF5 (h5part) format.') parser.add_argument('InputFile', metavar='InputFile', type=str, help='first input file (numbers in the file name must represet numerical order)') parser.add_argument('--num', type=int, help='number of snapshot to convert (by default, all are converted)') parser.add_argument('-o', '--output', default='output', help='output file name (or pattern)') parser.add_argument('--particles', type=int, help='number of particles (if not the whole thing)') parser.add_argument('--maxfs', type=float, help='maximum size in MB of a single HDF5 output') parser.add_argument('--single', action='store_true', help='use single precision instead of double') parser.add_argument('--bh', type=int, nargs='?', const=1, default=0, help='number of black holes to grab from the end of the file') # Print message and parse input print('Welcome to Yohai\'s format converter! (phiGRAPE ---> HDF5)\n') args = parser.parse_args() # Parameter conflict tests if (args.bh > 0) and (args.particles==None): parser.print_usage() print('%s: error: cannot --bh without --particles' % sys.argv[0]) sys.exit(2) Nbh = args.bh # Verify h5py try: import h5py except: print('%s: error: booooo, can\'t find h5py.' % sys.argv[0]) sys.exit(1) # Check if input file exists, separate name from path and get file name pattern if not os.path.exists(args.InputFile): print('File `%s` not found!' % args.InputFile) sys.exit(1) InputFileName = os.path.basename(args.InputFile) InputFilePath = os.path.dirname(os.path.realpath(args.InputFile)) Pattern = re.sub(r'\d', r'\d', InputFileName) Pattern = '^' + Pattern + "$" r = re.compile(Pattern) # Look for the other files ListDir = os.listdir(InputFilePath) FileList = [] for Filename in ListDir: m = r.search(Filename) if not m is None: FileList.append(Filename) FileList.sort() FileList = FileList[FileList.index(InputFileName):] # Verify that enough files were found; shorten list if needed if (not args.num==None) and args.num > len(FileList): print('Requested to convert %d files, but only %d found!' % (args.num, len(FileList))) sys.exit(1) if (not args.num==None): num = args.num else: num = len(FileList) FileList = FileList[:num] print('Will convert %d files in the directory `%s`.' % (num, InputFilePath)) NumperOfStepsPerFile = 2147483647 OutputFileNum = 2 StepCounter = 0 FirstTime = True OutputFile = False for Filename in FileList: if StepCounter > NumperOfStepsPerFile: OutputFile.close() OutputFile = h5py.File('output(%d).h5part' % OutputFileNum, 'w') StepCounter = 0 OutputFileNum += 1 FullFilename = os.path.join(InputFilePath, Filename) with open(FullFilename, 'r') as File: Line = File.readline() try: StepNumer = int(Line) except: print('Error to read snapshot number (line 1 in file `%s`)' % Filename) sys.exit(1) File.readline() Line = File.readline() try: Time = numpy.double(Line) except: print('Error to read snapshot time (line 3 in file `%s`)' % Filename) sys.exit(1) Data = numpy.loadtxt(FullFilename, skiprows=3) if (not args.particles==None) and (args.particles > Data.shape[0]): print('Requested to use %d paticles, but file %s has only %d!' % (args.particles, Filename, Data.shape[0])) sys.exit(1) if (not args.particles==None): N = args.particles else: N = Data.shape[0] if FirstTime: if Nbh == 0: print('Reading %d particles.' % (N)) else: print('Reading %d normal particles + %d black hole(s).' % (N, Nbh)) if args.single: EstimatedDataSize = 32*N/1024.0**2 else: EstimatedDataSize = 60*N/1024.0**2 if not args.maxfs==None: NumperOfStepsPerFile = (int)(args.maxfs/EstimatedDataSize) FirstTime = False if NumperOfStepsPerFile > num: OutputFile = h5py.File('output.h5part', 'w') else: OutputFile = h5py.File('output(1).h5part', 'w') DataBH = Data[-Nbh-1:-1] Data = Data[:N] Data = numpy.vstack((Data, DataBH)) Group = OutputFile.create_group('Step#%d' % (StepNumer)) Group.attrs['Time'] = Time Group.attrs['TotalN'] = N + Nbh if args.single: T='f' else: T='d' DataSet = Group.create_dataset('ID', (N+Nbh,), dtype='i'); DataSet[...] = Data[:,0] DataSet = Group.create_dataset('Mass', (N+Nbh,), dtype=T); DataSet[...] = Data[:,1] DataSet = Group.create_dataset('X', (N+Nbh,), dtype=T); DataSet[...] = Data[:,2] DataSet = Group.create_dataset('Y', (N+Nbh,), dtype=T); DataSet[...] = Data[:,3] DataSet = Group.create_dataset('Z', (N+Nbh,), dtype=T); DataSet[...] = Data[:,4] DataSet = Group.create_dataset('VX', (N+Nbh,), dtype=T); DataSet[...] = Data[:,5] DataSet = Group.create_dataset('VY', (N+Nbh,), dtype=T); DataSet[...] = Data[:,6] DataSet = Group.create_dataset('VZ', (N+Nbh,), dtype=T); DataSet[...] = Data[:,7] OutputFile.flush() print('Completed /Step#%d' % (StepNumer)) StepCounter += 1 OutputFile.close()
5,836
44.248062
149
py
amuse
amuse-main/src/amuse/community/mmc/validnoctrl.py
import numpy as np from amuse.community import * from amuse.test.amusetest import TestWithMPI from amuse.community.hermite0.interface import HermiteInterface from amuse.community.phiGRAPE.interface import PhiGRAPEInterface from amuse.community.bhtree.interface import BHTreeInterface from amuse.ext.ClusterCore import * from amuse.ic.plummer import MakePlummerModel import time as systime from . import coreradius from .interface import mmcInterface from .interface import mmc def plummer(x): plummer = MakePlummerModel(x) mass,pos,vel=plummer.new_model() mass=mass[0:,0] x=pos[0:,0] y=pos[0:,1] z=pos[0:,2] vx=vel[0:,0] vy=vel[0:,1] vz=vel[0:,2] radius=mass*0. return mass,radius,x,y,z,vx,vy,vz def sort_by_radii(mass, r, vr, vt): indices = [r.argsort(),] return mass[indices], r[indices], vr[indices], vt[indices] def crossing_time(r, vr, vt): R = np.sum(r) V = np.sqrt(np.sum(vr**2 + vt**2)) return 2*R/V def compare(mass, r, vr, vt, mass_, r_, vr_, vt_): for i, v in enumerate(mass): print("{0} {1} {2} {3} {4} {5} {6} {7}".format(mass[i], r[i], vr[i], vt[i], mass_[i], r_[i], vr_[i], vt_[i])) def tests_tocartesian(): x,y,z,vx,vy,vz,ex,ey,ez = to_cartesian(np.ones(100), np.zeros(100),np.ones(100)) for i, x in enumerate(x): print(x,y[i],z[i],vx[i],vy[i],vz[i],ex[i],ey[i],ez[i]) def example_M67(): #in this example we take M67 from mmc and evolve it in both #mmc and hermite. We compare coreradii mmc = mmcInterface(redirection="null") #mmc = mmcInterface(redirection="none") mmc.set_mmc_data_directory(mmc.data_directory) mmc.amuse_input() print("1") mmc.set_nt(2400) """ mmc.set_irun(10) print mmc.get_irun() mmc.set_iseed(10) mmc.set_nt(2000) print mmc.get_nt() mmc.set_nt0(2000) mmc.set_nt00(2000) mmc.set_istart(1) mmc.set_ncor(20) mmc.set_nmin(5) mmc.set_nz0(100) mmc.set_nzonc(1) mmc.set_nminzo(30) mmc.set_ntwo(10) mmc.set_imodel(3) mmc.set_iprint(3) mmc.set_ib3f(3) mmc.set_iexch(2) mmc.set_tcrit(600000.0) mmc.set_tcomp(18000.0) mmc.set_qe(1.e-0) mmc.set_alphal(1.3) mmc.set_alphah(2.3) mmc.set_brakem(0.5) #counterintuitive but ok mmc.set_body1(100.0) mmc.set_bodyn(0.1) mmc.set_fracb(0.00) mmc.set_amin(0.0) mmc.set_amax(10747.0) mmc.set_qvir(0.5) mmc.set_rbar(100.0) mmc.set_zmbar(426000.0) mmc.set_w0(5.0) mmc.set_bmin(0.01) mmc.set_bmin0(0.01) mmc.set_bmax(2.0 * 0.01) mmc.set_tau0(0.002) mmc.set_gamma(0.02) mmc.set_xtid(1.36) mmc.set_rplum(60.0) print mmc.get_rplum() mmc.set_dttp(500.0) mmc.set_dtte(500.0) mmc.set_dtte0(100.0) mmc.set_tcrevo(1000.0) mmc.set_xtau(1.0) mmc.set_ytau(2.0) mmc.set_ybmin(2.0) mmc.set_zini(0.0200) mmc.set_ikroupa(0) mmc.set_iflagns(2) mmc.set_iflagbh(2) mmc.set_nitesc(0) mmc.set_flagr([0.005,0.01,0.02,0.03, 0.04,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.99]) nlagra = mmc.get_nlagra().nlagrange #print mmc.get_flagr(range(1,nlagra+1)) """ mmc.nonstandard_init() n_total = mmc.get_number_of_particles().n_ # mass,radius,x,y,z,vx,vy,vz = plummer(n_total) # r_, vr_, vt_ = mmc.phase_to_polar(x, y, z, vx, vy, vz) # mmcstate = mmc.get_state(range(1,n_total+1)) # x, y, z, vx, vy, vz,ex,ey,ez = mmc.phase_to_cartesian(mmcstate.r, mmcstate.vr, mmcstate.vt) # mass, r_, vr_, vt_ = sort_by_radii(mass, r_, vr_, vt_) # mmc.commit_particles() n_total = mmc.get_number_of_particles().n_ # mmc.set_tcrit(0) # control = HermiteInterface(number_of_workers=3) # control.initialize_code() # control.commit_parameters() # res = control.new_particle(mass, # 1/n_total * np.ones(len(mass)), # x, y, z, # vx, vy, vz) # # control_parts = res['index_of_the_particle'] # control.commit_particles() mmc.set_istart(1) print(mmc.get_nt()) print("2") for time_end in np.arange(0.001, 1.2, 0.001): print("3") n_total = mmc.get_number_of_particles().n_ x, y, z = mmc.get_positions_3d(list(range(1, n_total+1))) M = mmc.get_state(list(range(1, n_total+1))) print("4") tcross = crossing_time(M.r, M.vr, M.vt) x_core,y_core,z_core,rc = coreradius.coreradius(M.mass,x,y,z) tic = systime.clock() print("5") #mmc.evolve_model(time_end) import pdb;pdb.set_trace() mmc.call_zone() import pdb;pdb.set_trace() mmc.call_relaxt() import pdb;pdb.set_trace() mmc.call_amuse_output() print(mmc.get_timet()) print("6") toc = systime.clock() time = mmc.get_time().time tcrit_control = mmc.get_tcrit().termination_time_units_crossing_time timet = mmc.get_timet().time tcr = mmc.get_crossing_time().tcr # control.evolve_model(time_end) # H = control.get_state(control_parts) # control_xcore,control_ycore,control_zcore,control_rc = \ # coreradius.coreradius(H.mass,H.x,H.y,H.z) # print time, time_end, rc, control_rc, toc-tic print(time, time_end, rc, mmc.get_nc()) mmc.stop() # control.stop() def example_plummer(): pass if __name__ == '__main__': example_M67() # M67 from mmc example_plummer() # plummer from amuse
6,175
29.423645
117
py
amuse
amuse-main/src/amuse/community/mmc/interface_orig.py
from amuse.community import * class mmc2Interface(CodeInterface): include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="mmc2_worker", **keyword_arguments) @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 class mmc2(InCodeComponentImplementation): def __init__(self): InCodeComponentImplementation.__init__(self, mmc2Interface())
771
29.88
91
py
amuse
amuse-main/src/amuse/community/mmc/makeinterface.py
""" this is a tmp script, after all fctns are in place etc.. I'll remove this """ funcs =\ [['irun','','init_sequence_of_rnd_numbs'], ['nt','','tot_numb_of_objs'], ['nt0','','num'], ['istart','','start_or_restart'], ['ncor','','numb_of_stars_to_calc_c_parms'], ['nmin','','min_numb_of_stars_to_calc_c_parms'], ['nz0','','numb_of_stars_in_each_zone_at_t0'], ['nzonc','','min_numb_of_zones_in_the_core'], ['nminzo','','min_numb_of_stars_in_a_zone'], ['ntwo','','max_index_od_two'], ['imodel','','initial_model'], ['iprint','','diag_info'], ['ib3f','','spitzer_or_heggie'], ['iexch','','exchange_mode'], ['tcrit','DOUBLE PRECISION','termination_time_units_crossing_time'], ['tcomp','DOUBLE PRECISION','max_comp_time_in_hours'], ['qe', 'DOUBLE PRECISION','energy_tolerance'], ['alphal','DOUBLE PRECISION','pwr_law_index_lt_breake_mass'], ['alphah', 'DOUBLE PRECISION','pwr_law_index_ht_breake_mass'], ['brakem','DOUBLE PRECISION','mass_in_which_IMF_breaks'], ['body1','DOUBLE PRECISION','max_particle_mass_before_scaling'], ['bodyn','DOUBLE PRECISION','min_particle_mass_before_scaling'], ['fracb','DOUBLE PRECISION','primordial_bin_fraction'], ['amin','DOUBLE PRECISION','min_semi_major_ax_of_bins'], ['amax','DOUBLE PRECISION','max_semi_major_ax_of_bins'], ['qvir','DOUBLE PRECISION','virial_ratio'], ['rbar','DOUBLE PRECISION','tidal_radius'], ['zmbar','DOUBLE PRECISION','total_mass_cluster'], ['w0','DOUBLE PRECISION','king_model_parameter'], ['bmin','DOUBLE PRECISION','min_val_of_sin_betasqr'], ['bmax','DOUBLE PRECISION','max_val_of_sin_betasqr'], ['tau0','DOUBLE PRECISION','time_step_for_complete_cluster_model'], ['gamma','DOUBLE PRECISION','param_in_coulomb_log'], ['xtid','DOUBLE PRECISION','coeff_front_tidal_energy'], ['rplum','DOUBLE PRECISION','rsplum_scale_radius_plummer_model'], ['dttp','DOUBLE PRECISION','time_step_for_profile_output'], ['dtte','DOUBLE PRECISION','time_step_for_mloss_call'], ['dtte0','DOUBLE PRECISION','time_step_for_mloss_call_tph_lt_tcr'], ['tcrevo','DOUBLE PRECISION','critical_time_step_dtte0_to_dtte'], ['xtau','DOUBLE PRECISION','call_mloss'], ['ytau','DOUBLE PRECISION','mult_tau0'], ['ybmin','DOUBLE PRECISION','mult_bmin0'], ['zini','DOUBLE PRECISION','initial_metalicity'], ['ikroupa','','initial_bins_parameters'], ['iflagns','','natal_kicks_ns'], ['iflagbh','','natal_kicks_bh'], ['nitesc','','iteration_tidal_radius'], ['nt00','','num'], ['bmin0','DOUBLE PRECISION','num'], ['iseed','','rnd_seed']] codestringfort = \ """ MODULE MMC interface function run_a_while(iphase) integer :: run_a_while integer :: iphase end function run_a_while function set_flagr(temp_, N) integer, intent(in)::N double precision temp_(N) integer set_flagr end function function get_flagr(id, flagr_) integer id double precision flagr_ integer get_flagr end function function get_nlagra(temp_) integer get_nlagra integer temp_ end function end interface CONTAINS FUNCTION nonstandard_init() INTEGER :: nonstandard_init INTEGER :: init_sequence INTEGER :: res ! read initial parameters PRINT*,'calling input' res = init_sequence() nonstandard_init = res PRINT*,'init done' END FUNCTION FUNCTION set_mmc_data_directory(data_directory) INTEGER :: set_mmc_data_directory CHARACTER(len=200) :: data_directory CALL amuse_set_mmc_data_directory(data_directory) set_mmc_data_directory = 0 END FUNCTION FUNCTION evolve_model(time_end) INTEGER :: evolve_model INTEGER :: evolve_src INTEGER :: res DOUBLE PRECISION time_end res = evolve_src(time_end) evolve_model = res END FUNCTION FUNCTION get_time(time_) INTEGER :: get_time INTEGER :: get_time_src INTEGER :: res DOUBLE PRECISION :: time_ res = get_time_src(time_) get_time = res END FUNCTION FUNCTION get_timet(time_) INTEGER :: get_timet INTEGER :: get_timet_src INTEGER :: res DOUBLE PRECISION :: time_ res = get_timet_src() get_timet = res END FUNCTION FUNCTION get_crossing_time(time_) INTEGER :: get_crossing_time INTEGER :: get_crossing_time_src INTEGER :: res DOUBLE PRECISION :: time_ res = get_crossing_time_src() get_crossing_time = res END FUNCTION FUNCTION set_time(time_) INTEGER :: set_time COMMON /SYSTEM/ TIME DOUBLE PRECISION :: time DOUBLE PRECISION :: time_ time = time_ set_time = 0 END FUNCTION FUNCTION get_number_of_particles(n_) INTEGER :: get_number_of_particles INTEGER :: get_number_of_particles_, res INTEGER :: n_ res = get_number_of_particles_src(n_) print*, "n call = ",n_ get_number_of_particles=0 END FUNCTION FUNCTION new_particle( index_of_the_particle, x, y, z) IMPLICIT NONE INTEGER :: new_particle INTEGER :: index_of_the_particle DOUBLE PRECISION :: x, y, z new_particle=0 END FUNCTION FUNCTION delete_particle( index_of_the_particle) IMPLICIT NONE INTEGER :: delete_particle INTEGER :: index_of_the_particle delete_particle=0 END FUNCTION FUNCTION set_state( index_of_the_particle, mass_, r_, vr_, vt_) IMPLICIT NONE INTEGER :: set_state, set_state_src INTEGER :: index_of_the_particle INTEGER :: res DOUBLE PRECISION :: mass_, r_, vr_, vt_ res = set_state_src(index_of_the_particle, mass_, r_, vr_, vt_) set_state=0 END FUNCTION FUNCTION get_state( index_of_the_particle, mass_, r_, vr_, vt_) INTEGER :: get_state INTEGER :: get_state_src,res INTEGER :: index_of_the_particle DOUBLE PRECISION :: mass_, r_, vr_, vt_ res = get_state_src(index_of_the_particle, mass_,r_,vr_,vt_) get_state=0 END FUNCTION FUNCTION get_total_kinetic_energy(T) INTEGER :: get_total_kinetic_energy INTEGER :: get_total_kinetic_energy_src INTEGER :: res DOUBLE PRECISION :: T res = get_total_kinetic_energy_src(T) get_total_kinetic_energy = 0 END FUNCTION FUNCTION get_total_potential_energy(V) INTEGER :: get_total_potential_energy INTEGER :: get_total_potential_energy_src INTEGER :: res DOUBLE PRECISION :: V res = get_total_potential_energy_src(T) get_total_potential_energy = 0 END FUNCTION FUNCTION commit_particles() CALL commit_particles_src() END FUNCTION FUNCTION recommit_particles() CALL recommit_particles_src() END FUNCTION FUNCTION test_sort_routine(n, aa, bb) INTEGER n REAL*8 aa INTEGER bb INTEGER test_sort_routine INTEGER res dimension aa(n), bb(n) res = test_sort(n, aa, bb) test_sort_routine = 0 END FUNCTION FUNCTION run( ) IMPLICIT NONE INTEGER :: run run=0 END FUNCTION FUNCTION amuse_input() INTEGER amuse_input call amuse_input_src() amuse_input = 0 END FUNCTION FUNCTION commit_parameters( ) IMPLICIT NONE INTEGER commit_parameters commit_parameters=0 END FUNCTION FUNCTION get_rc(rc_) INTEGER get_rc DOUBLE PRECISION rc_ get_rc = get_rc_src(rc_) END FUNCTION FUNCTION get_nc(nc_) INTEGER get_nc INTEGER nc_ get_nc = get_nc_src(nc_) END FUNCTION FUNCTION call_zone() INTEGER call_zone call zone() call_zone = 0 END FUNCTION FUNCTION call_relaxt() INTEGER call_relaxt call relaxt() call_relaxt = 0 END FUNCTION FUNCTION call_amuse_output() INTEGER call_amuse_output call_amuse_output = amuse_output() END FUNCTION """ if __name__ == '__main__': f = open('interface.f90','w') g = open('src/amuse_interface2.f','w') h = open('interface_specs.tmp','w') f.write(codestringfort) for O in funcs: i=O[0] tp = O[1] nm = O[2] f.write( "FUNCTION set_{0}(tmp_)\n".format(i)) f.write( " INTEGER :: set_{0}\n".format(i)) if tp == '': #f.write(" INTEGER {0}\n".format(i)) f.write(" INTEGER :: tmp_\n") else: #f.write( " {0} {1}\n".format(tp,i)) f.write( " {0} :: tmp_\n".format(tp)) f.write( " INTEGER :: res\n") f.write( " INTEGER :: set_{0}_src\n".format(i)) f.write( " res = set_{0}_src(tmp_)\n".format(i)) f.write( " set_{0} = res\n".format(i)) f.write( "END FUNCTION\n".format(i)) f.write('\n') f.write( "FUNCTION get_{0}(tmp_)\n".format(i)) f.write( " INTEGER :: get_{0}\n".format(i)) if tp == '': f.write(" INTEGER :: tmp_\n") else: f.write( " {0} :: tmp_\n".format(tp)) f.write( " INTEGER :: res\n") f.write( " INTEGER :: get_{0}_src\n".format(i)) f.write( " res = get_{0}_src(tmp_)\n".format(i)) f.write( " get_{0} = res\n".format(i)) f.write( "END FUNCTION\n".format(i)) f.write('\n') g.write( " FUNCTION set_{0}_src(tmp_)\n".format(i)) g.write( " INCLUDE 'common.h'\n") if tp == '': #g.write(" INTEGER {0}\n".format(i)) g.write(" INTEGER tmp_\n") else: #g.write( " {0} {1}\n".format(tp,i)) g.write( " {0} tmp_\n".format(tp)) g.write( " INTEGER set_{0}_src\n".format(i)) g.write( " {0} = tmp_\n".format(i)) g.write( " set_{0}_src = 0\n".format(i)) g.write( " END FUNCTION\n".format(i)) g.write('\n') g.write( " FUNCTION get_{0}_src(tmp_)\n".format(i)) g.write( " INCLUDE 'common.h'\n") if tp == '': g.write(" INTEGER tmp_\n") else: g.write( " {0} tmp_\n".format(tp)) g.write( " INTEGER get_{0}_src\n".format(i)) g.write( " tmp_ = {0}\n".format(i)) g.write( " get_{0}_src = 0\n".format(i)) g.write( " END FUNCTION\n".format(i)) g.write('\n') if tp == '': typus = 'int32' else: typus = 'float64' h.write("@legacy_function\n") h.write("def set_{0}():\n".format(i)) h.write(" function = LegacyFunctionSpecification()\n") h.write(" function.addParameter('{0}', dtype='{1}', direction=function.IN)\n".format(nm, typus)) h.write(" function.result_type = 'int32'\n") h.write(" return function\n\n") h.write("@legacy_function\n") h.write("def get_{0}():\n".format(i)) h.write(" function = LegacyFunctionSpecification()\n") h.write(" function.addParameter('{0}', dtype='{1}', direction=function.OUT)\n".format(nm,typus)) h.write(" function.result_type = 'int32'\n") h.write(" return function\n\n") print("mmc.set_{0}()".format(i)) f.write("END MODULE\n") f.close() g.close() h.close()
10,752
27.372032
107
py
amuse
amuse-main/src/amuse/community/mmc/coreradius.py
import os import sys import numpy from amuse.community.hop.interface import HopInterface as Hop from amuse.ic.plummer import MakePlummerModel import logging #logging.basicConfig(level=logging.DEBUG) numpy.random.seed(1234) def hopfromnb(nb,ids): m,r,x,y,z,vx,vy,vz,err=nb.get_state(ids) hop=Hop() ids2,err=hop.new_particle(x,y,z) return hop,ids2 def plummer(x): plummer=MakePlummerModel(x) mass,pos,vel=plummer.new_model() mass=mass[0:,0] x=pos[0:,0] y=pos[0:,1] z=pos[0:,2] vx=vel[0:,0] vy=vel[0:,1] vz=vel[0:,2] radius=mass*0. tm=numpy.sum(mass) cmx=numpy.sum(mass*x)/tm cmy=numpy.sum(mass*y)/tm cmz=numpy.sum(mass*z)/tm return mass,radius,x,y,z,vx,vy,vz def coreradius(mass,x,y,z): hop=Hop() ids,err=hop.new_particle(mass,x,y,z) hop.set_density_method(2) hop.set_nDens(7) hop.calculate_densities() dens,err=hop.get_density(ids) tdens=numpy.sum(dens) x_core=numpy.sum(dens*x)/tdens y_core=numpy.sum(dens*y)/tdens z_core=numpy.sum(dens*z)/tdens rc=numpy.sqrt( numpy.sum(dens**2*((x-x_core)**2+(y-y_core)**2+(z-z_core)**2))/numpy.sum(dens**2)) return x_core,y_core,z_core,rc if __name__=="__main__": mass,radius,x,y,z,vx,vy,vz=plummer(1000) print(coreradius(mass,x,y,z))
1,263
19.387097
88
py
amuse
amuse-main/src/amuse/community/mmc/__init__.py
# generated file from .interface import Mmc
44
14
26
py
amuse
amuse-main/src/amuse/community/mmc/interface.py
from amuse.community import * from amuse.community.mmc.amuselib.interface import supportInterface from amuse.support.options import OptionalAttributes, option from amuse.ext.polarsupport import PolarSupport import os import numpy as np class mmcInterface(CodeInterface, PolarSupport, CodeWithDataDirectories): use_modules = ['MMC'] def __init__(self, **options): CodeInterface.__init__(self, name_of_the_worker="mmc_worker", **options) CodeWithDataDirectories.__init__(self) @legacy_function def nonstandard_init(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def commit_parameters(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def set_mmc_data_directory(): function = LegacyFunctionSpecification() function.addParameter('data_directory', dtype='string', direction=function.IN) function.result_type = 'int32' return function @legacy_function def new_particle(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.OUT) 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.result_type = 'int32' return function @legacy_function def delete_particle(): function = LegacyFunctionSpecification() function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_state(): function = LegacyFunctionSpecification() function.can_handle_array = True function.addParameter('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('mass', dtype='float64', direction=function.OUT) function.addParameter('r', dtype='float64', direction=function.OUT) function.addParameter('vr', dtype='float64', direction=function.OUT) function.addParameter('vt', 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('index_of_the_particle', dtype='int32', direction=function.IN) function.addParameter('mass_', dtype='float64', direction=function.IN) function.addParameter('r_', dtype='float64', direction=function.IN) function.addParameter('vr_', dtype='float64', direction=function.IN) function.addParameter('vt_', dtype='float64', direction=function.IN) 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 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 test_sort_routine(): function = LegacyFunctionSpecification() function.must_handle_array = True function.addParameter('n', dtype='int32', direction=function.LENGTH) function.addParameter('aa', dtype='float64', direction=function.INOUT) function.addParameter('bb', dtype='int32', direction=function.INOUT) 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_crossing_time(): function = LegacyFunctionSpecification() function.addParameter('tcr', 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_timet(): function = LegacyFunctionSpecification() function.addParameter('time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def run_a_while(): function = LegacyFunctionSpecification() function.addParameter('iphase', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def evolve_model(): function = LegacyFunctionSpecification() function.addParameter('time_end', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def amuse_input(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def run(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def get_number_of_particles(): function = LegacyFunctionSpecification() function.addParameter('n_', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_irun(): function = LegacyFunctionSpecification() function.addParameter('init_sequence_of_rnd_numbs', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_iseed(): function = LegacyFunctionSpecification() function.addParameter('init_sequence_of_rnd_numbs', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_flagr(): function = LegacyFunctionSpecification() function.addParameter('lagrangeradii', dtype='float64', direction=function.IN) function.addParameter('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def get_flagr(): function = LegacyFunctionSpecification() function.addParameter('id', dtype='int32', direction=function.IN) function.addParameter('flagr_', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def get_nlagra(): function = LegacyFunctionSpecification() function.addParameter('nlagrange', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_irun(): function = LegacyFunctionSpecification() function.addParameter('init_sequence_of_rnd_numbs', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nt(): function = LegacyFunctionSpecification() function.addParameter('tot_numb_of_objs', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_nt0(): function = LegacyFunctionSpecification() function.addParameter('tot_numb_of_objs', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_nt00(): function = LegacyFunctionSpecification() function.addParameter('tot_numb_of_objs', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nt(): function = LegacyFunctionSpecification() function.addParameter('tot_numb_of_objs', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_istart(): function = LegacyFunctionSpecification() function.addParameter('start_or_restart', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_istart(): function = LegacyFunctionSpecification() function.addParameter('start_or_restart', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ncor(): function = LegacyFunctionSpecification() function.addParameter('numb_of_stars_to_calc_c_parms', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ncor(): function = LegacyFunctionSpecification() function.addParameter('numb_of_stars_to_calc_c_parms', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nmin(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_stars_to_calc_c_parms', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nmin(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_stars_to_calc_c_parms', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nz0(): function = LegacyFunctionSpecification() function.addParameter('numb_of_stars_in_each_zone_at_t0', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nz0(): function = LegacyFunctionSpecification() function.addParameter('numb_of_stars_in_each_zone_at_t0', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nzonc(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_zones_in_the_core', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nzonc(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_zones_in_the_core', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nminzo(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_stars_in_a_zone', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nminzo(): function = LegacyFunctionSpecification() function.addParameter('min_numb_of_stars_in_a_zone', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ntwo(): function = LegacyFunctionSpecification() function.addParameter('max_index_od_two', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ntwo(): function = LegacyFunctionSpecification() function.addParameter('max_index_od_two', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_imodel(): function = LegacyFunctionSpecification() function.addParameter('initial_model', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_imodel(): function = LegacyFunctionSpecification() function.addParameter('initial_model', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_iprint(): function = LegacyFunctionSpecification() function.addParameter('diag_info', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_iprint(): function = LegacyFunctionSpecification() function.addParameter('diag_info', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ib3f(): function = LegacyFunctionSpecification() function.addParameter('spitzer_or_heggie', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ib3f(): function = LegacyFunctionSpecification() function.addParameter('spitzer_or_heggie', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_iexch(): function = LegacyFunctionSpecification() function.addParameter('exchange_mode', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_iexch(): function = LegacyFunctionSpecification() function.addParameter('exchange_mode', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tcrit(): function = LegacyFunctionSpecification() function.addParameter('termination_time_units_crossing_time', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tcrit(): function = LegacyFunctionSpecification() function.addParameter('termination_time_units_crossing_time', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tcomp(): function = LegacyFunctionSpecification() function.addParameter('max_comp_time_in_hours', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tcomp(): function = LegacyFunctionSpecification() function.addParameter('max_comp_time_in_hours', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_qe(): function = LegacyFunctionSpecification() function.addParameter('energy_tolerance', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_qe(): function = LegacyFunctionSpecification() function.addParameter('energy_tolerance', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_alphal(): function = LegacyFunctionSpecification() function.addParameter('pwr_law_index_lt_breake_mass', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_alphal(): function = LegacyFunctionSpecification() function.addParameter('pwr_law_index_lt_breake_mass', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_alphah(): function = LegacyFunctionSpecification() function.addParameter('pwr_law_index_ht_breake_mass', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_alphah(): function = LegacyFunctionSpecification() function.addParameter('pwr_law_index_ht_breake_mass', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_brakem(): function = LegacyFunctionSpecification() function.addParameter('mass_in_which_IMF_breaks', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_brakem(): function = LegacyFunctionSpecification() function.addParameter('mass_in_which_IMF_breaks', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_body1(): function = LegacyFunctionSpecification() function.addParameter('max_particle_mass_before_scaling', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_body1(): function = LegacyFunctionSpecification() function.addParameter('max_particle_mass_before_scaling', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bodyn(): function = LegacyFunctionSpecification() function.addParameter('min_particle_mass_before_scaling', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bodyn(): function = LegacyFunctionSpecification() function.addParameter('min_particle_mass_before_scaling', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_fracb(): function = LegacyFunctionSpecification() function.addParameter('primordial_bin_fraction', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_fracb(): function = LegacyFunctionSpecification() function.addParameter('primordial_bin_fraction', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_amin(): function = LegacyFunctionSpecification() function.addParameter('min_semi_major_ax_of_bins', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_amin(): function = LegacyFunctionSpecification() function.addParameter('min_semi_major_ax_of_bins', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_amax(): function = LegacyFunctionSpecification() function.addParameter('max_semi_major_ax_of_bins', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_amax(): function = LegacyFunctionSpecification() function.addParameter('max_semi_major_ax_of_bins', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_qvir(): function = LegacyFunctionSpecification() function.addParameter('virial_ratio', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_qvir(): function = LegacyFunctionSpecification() function.addParameter('virial_ratio', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_rbar(): function = LegacyFunctionSpecification() function.addParameter('tidal_radius', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_rbar(): function = LegacyFunctionSpecification() function.addParameter('tidal_radius', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_zmbar(): function = LegacyFunctionSpecification() function.addParameter('total_mass_cluster', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_zmbar(): function = LegacyFunctionSpecification() function.addParameter('total_mass_cluster', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_w0(): function = LegacyFunctionSpecification() function.addParameter('king_model_parameter', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_w0(): function = LegacyFunctionSpecification() function.addParameter('king_model_parameter', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bmin(): function = LegacyFunctionSpecification() function.addParameter('min_val_of_sin_betasqr', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def set_bmin0(): function = LegacyFunctionSpecification() function.addParameter('min_val_of_sin_betasqr', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bmin(): function = LegacyFunctionSpecification() function.addParameter('min_val_of_sin_betasqr', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_bmax(): function = LegacyFunctionSpecification() function.addParameter('max_val_of_sin_betasqr', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_bmax(): function = LegacyFunctionSpecification() function.addParameter('max_val_of_sin_betasqr', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tau0(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_complete_cluster_model', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tau0(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_complete_cluster_model', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_gamma(): function = LegacyFunctionSpecification() function.addParameter('param_in_coulomb_log', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_gamma(): function = LegacyFunctionSpecification() function.addParameter('param_in_coulomb_log', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_xtid(): function = LegacyFunctionSpecification() function.addParameter('coeff_front_tidal_energy', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_xtid(): function = LegacyFunctionSpecification() function.addParameter('coeff_front_tidal_energy', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_rplum(): function = LegacyFunctionSpecification() function.addParameter('rsplum_scale_radius_plummer_model', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_rplum(): function = LegacyFunctionSpecification() function.addParameter('rsplum_scale_radius_plummer_model', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dttp(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_profile_output', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dttp(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_profile_output', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtte(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_mloss_call', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtte(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_mloss_call', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_dtte0(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_mloss_call_tph_lt_tcr', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_dtte0(): function = LegacyFunctionSpecification() function.addParameter('time_step_for_mloss_call_tph_lt_tcr', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_tcrevo(): function = LegacyFunctionSpecification() function.addParameter('critical_time_step_dtte0_to_dtte', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_tcrevo(): function = LegacyFunctionSpecification() function.addParameter('critical_time_step_dtte0_to_dtte', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_xtau(): function = LegacyFunctionSpecification() function.addParameter('call_mloss', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_xtau(): function = LegacyFunctionSpecification() function.addParameter('call_mloss', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ytau(): function = LegacyFunctionSpecification() function.addParameter('mult_tau0', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ytau(): function = LegacyFunctionSpecification() function.addParameter('mult_tau0', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ybmin(): function = LegacyFunctionSpecification() function.addParameter('mult_bmin0', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ybmin(): function = LegacyFunctionSpecification() function.addParameter('mult_bmin0', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_zini(): function = LegacyFunctionSpecification() function.addParameter('initial_metalicity', dtype='float64', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_zini(): function = LegacyFunctionSpecification() function.addParameter('initial_metalicity', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_ikroupa(): function = LegacyFunctionSpecification() function.addParameter('initial_bins_parameters', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_ikroupa(): function = LegacyFunctionSpecification() function.addParameter('initial_bins_parameters', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_iflagns(): function = LegacyFunctionSpecification() function.addParameter('natal_kicks_ns', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_iflagns(): function = LegacyFunctionSpecification() function.addParameter('natal_kicks_ns', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_iflagbh(): function = LegacyFunctionSpecification() function.addParameter('natal_kicks_bh', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_iflagbh(): function = LegacyFunctionSpecification() function.addParameter('natal_kicks_bh', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def set_nitesc(): function = LegacyFunctionSpecification() function.addParameter('iteration_tidal_radius', dtype='int32', direction=function.IN) function.result_type = 'int32' return function @legacy_function def get_nitesc(): function = LegacyFunctionSpecification() function.addParameter('iteration_tidal_radius', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_rc(): function = LegacyFunctionSpecification() function.addParameter('coreradius', dtype='float64', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def get_nc(): function = LegacyFunctionSpecification() function.addParameter('numberdensity', dtype='int32', direction=function.OUT) function.result_type = 'int32' return function @legacy_function def call_zone(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def call_relaxt(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function @legacy_function def call_amuse_output(): function = LegacyFunctionSpecification() function.result_type = 'int32' return function def get_positions_3d_incode(self, particles): #this is an experiment! r = self.get_state(particles).r i = supportInterface() x = np.zeros(len(r)) y = np.zeros(len(r)) z = np.zeros(len(r)) R = i.rnd_points_on_sphere(x, y, z) #R = i.many_points_on_sphere(x, y, z) i.stop() return {'x':np.array(r*R.x), 'y':np.array(r*R.y),'z':np.array(r*R.z)} def get_positions_3d(self, particles): r = self.get_state(particles).r return self.position_to_cartesian(r) class mmc(InCodeComponentImplementation): def __init__(self): InCodeComponentImplementation.__init__(self, mmcInterface()) Mmc = mmc
33,402
34.686966
117
py
amuse
amuse-main/src/amuse/community/mmc/valid.py
import numpy as np from amuse.community import * from amuse.test.amusetest import TestWithMPI from amuse.community.hermite0.interface import HermiteInterface from amuse.community.phiGRAPE.interface import PhiGRAPEInterface from amuse.community.bhtree.interface import BHTreeInterface import time as systime from . import coreradius from .interface import mmcInterface from .interface import mmc from amuse.ic.plummer import MakePlummerModel def plummer(x): plummer = MakePlummerModel(x) mass,pos,vel=plummer.new_model() mass=mass[0:,0] x=pos[0:,0] y=pos[0:,1] z=pos[0:,2] vx=vel[0:,0] vy=vel[0:,1] vz=vel[0:,2] radius=mass*0. return mass,radius,x,y,z,vx,vy,vz def sort_by_radii(mass, r, vr, vt): indices = [r.argsort(),] return mass[indices], r[indices], vr[indices], vt[indices] def crossing_time(r, vr, vt): R = np.sum(r) V = np.sqrt(np.sum(vr**2 + vt**2)) return 2*R/V def compare(mass, r, vr, vt, mass_, r_, vr_, vt_): for i, v in enumerate(mass): print("{0} {1} {2} {3} {4} {5} {6} {7}".format(mass[i], r[i], vr[i], vt[i], mass_[i], r_[i], vr_[i], vt_[i])) def tests_tocartesian(): x,y,z,vx,vy,vz,ex,ey,ez = to_cartesian(np.ones(100), np.zeros(100),np.ones(100)) for i, x in enumerate(x): print(x,y[i],z[i],vx[i],vy[i],vz[i],ex[i],ey[i],ez[i]) def example_M67(): #in this example we take M67 from mmc and evolve it in both #mmc and hermite. We compare coreradii mmc = mmcInterface(redirection="null") mmc.set_mmc_data_directory(mmc.data_directory) mmc.set_irun(10) mmc.set_iseed(10) mmc.set_nt(2000) mmc.set_nt0(2000) mmc.set_nt00(2000) mmc.set_istart(1) mmc.set_ncor(20) mmc.set_nmin(5) mmc.set_nz0(100) mmc.set_nzonc(1) mmc.set_nminzo(30) mmc.set_ntwo(10) mmc.set_imodel(4) mmc.set_iprint(3) mmc.set_ib3f(3) mmc.set_iexch(2) mmc.set_tcrit(600000.0) mmc.set_tcomp(18000.0) mmc.set_qe(1.e-0) mmc.set_alphal(1.3) mmc.set_alphah(2.3) mmc.set_brakem(0.5) mmc.set_body1(100.0) mmc.set_bodyn(0.1) mmc.set_fracb(0.00) mmc.set_amin(0.0) mmc.set_amax(10747.0) mmc.set_qvir(0.5) mmc.set_rbar(100.0) mmc.set_zmbar(426000.0) mmc.set_w0(5.0) mmc.set_bmin(0.01) mmc.set_bmin0(0.01) mmc.set_bmax(2.0 * 0.01) mmc.set_tau0(0.002) mmc.set_gamma(0.02) mmc.set_xtid(1.36) mmc.set_rplum(60.0) mmc.set_dttp(500.0) mmc.set_dtte(500.0) mmc.set_dtte0(100.0) mmc.set_tcrevo(1000.0) mmc.set_xtau(1.0) mmc.set_ytau(2.0) mmc.set_ybmin(2.0) mmc.set_zini(0.0200) mmc.set_ikroupa(0) mmc.set_iflagns(2) mmc.set_iflagbh(2) mmc.set_nitesc(0) mmc.set_flagr([0.005,0.01,0.02,0.03, 0.04,0.05,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.99]) nlagra = mmc.get_nlagra().nlagrange print(mmc.get_flagr(list(range(1,nlagra+1)))) """ mmc.amuse_input() """ mmc.nonstandard_init() n_total = mmc.get_number_of_particles().n_ mass,radius,x,y,z,vx,vy,vz = plummer(n_total) r_, vr_, vt_ = mmc.phase_to_polar(x, y, z, vx, vy, vz) mmcstate = mmc.get_state(list(range(1,n_total+1))) x, y, z, vx, vy, vz,ex,ey,ez = mmc.phase_to_cartesian(mmcstate.r, mmcstate.vr, mmcstate.vt) mass, r_, vr_, vt_ = sort_by_radii(mass, r_, vr_, vt_) mmc.commit_particles() n_total = mmc.get_number_of_particles().n_ mmc.set_tcrit(0) control = HermiteInterface(number_of_workers=3) control.initialize_code() control.commit_parameters() res = control.new_particle(mass, 1/n_total * np.ones(len(mass)), x, y, z, vx, vy, vz) control_parts = res['index_of_the_particle'] control.commit_particles() mmc.set_istart(1) for time_end in np.arange(0.001,1,0.001): n_total = mmc.get_number_of_particles().n_ x, y, z = mmc.get_positions_3d(list(range(1, n_total+1))) M = mmc.get_state(list(range(1, n_total+1))) tcross = crossing_time(M.r, M.vr, M.vt) x_core,y_core,z_core,rc = coreradius.coreradius(M.mass,x,y,z) tic = systime.clock() mmc.evolve_model(time_end) toc = systime.clock() time = mmc.get_time().time tcrit_control = mmc.get_tcrit().termination_time_units_crossing_time timet = mmc.get_timet().time tcr = mmc.get_crossing_time().tcr control.evolve_model(time_end) H = control.get_state(control_parts) control_xcore,control_ycore,control_zcore,control_rc = \ coreradius.coreradius(H.mass,H.x,H.y,H.z) print(time, time_end, rc, control_rc, toc-tic) mmc.stop() control.stop() def example_plummer(): pass if __name__ == '__main__': example_M67() # M67 from mmc example_plummer() # plummer from amuse
5,531
30.254237
117
py
amuse
amuse-main/src/amuse/community/mmc/amuselib/example.py
from amuse.community import * from amuse.test.amusetest import TestWithMPI from .interface import supportInterface import numpy as np if __name__ == '__main__': instance = supportInterface(redirection='none') x = np.zeros(2000) y = np.zeros(2000) z = np.zeros(2000) #R = instance.many_points_on_sphere(x,y,z) R = instance.rnd_points_on_sphere(x,y,z) x1 = R.x y1 = R.y z1 = R.z for i, v in enumerate(x): print(x1[i], y1[i], z1[i]) instance.stop()
505
19.24
51
py
amuse
amuse-main/src/amuse/community/mmc/amuselib/test_support.py
from amuse.community import * from amuse.test.amusetest import TestWithMPI from .interface import supportInterface import numpy as np class supportInterfaceTests(TestWithMPI): def test1(self): instance = supportInterface() print(instance.add([1,1,1,1,1],[1,1,1,1,1])['sum']) instance.stop() def test2(self): instance = supportInterface(redirection='none') x = np.zeros(10) y = np.zeros(10) z = np.zeros(10) print(instance.many_points_on_sphere(x,y,z)) instance.stop()
568
21.76
59
py
amuse
amuse-main/src/amuse/community/mmc/amuselib/__init__.py
0
0
0
py
amuse
amuse-main/src/amuse/community/mmc/amuselib/interface.py
from amuse.community import * class supportInterface(CodeInterface): include_headers = ['worker_code.h'] def __init__(self, **keyword_arguments): CodeInterface.__init__(self, name_of_the_worker="support_worker", **keyword_arguments) @legacy_function def add(): function = LegacyFunctionSpecification() function.addParameter('term1', dtype='float64', direction=function.IN) function.addParameter('term2', dtype='float64', direction=function.IN) function.addParameter('sum', dtype='float64', direction=function.OUT) function.result_type = 'int32' function.can_handle_array = True return function @legacy_function def many_points_on_sphere(): function = LegacyFunctionSpecification() 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('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function @legacy_function def rnd_points_on_sphere(): function = LegacyFunctionSpecification() 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('len', dtype='int32', direction=function.LENGTH) function.result_type = 'int32' function.must_handle_array = True return function class support(InCodeComponentImplementation): def __init__(self): CodeInterface.__init__(self, supportInterface())
1,875
38.083333
94
py
amuse
amuse-main/src/amuse/io/base.py
import textwrap import struct import numpy import os.path from amuse.support.core import late from amuse.support import exceptions registered_fileformat_processors = {} class IoException(exceptions.CoreException): formatstring = "IO exception: {0}" class UnsupportedFormatException(IoException): """Raised when the given format is not supported by AMUSE. """ formatstring = "You tried to load or save a file with fileformat '{0}', but this format is not in the supported formats list" class CannotSaveException(IoException): """Raised when the given format cannot save data (only reading of data is supported for the format) """ formatstring = "You tried to save a file with fileformat '{0}', but this format is not supported for writing files" class CannotLoadException(IoException): """Raised when the given format cannot read data (only saving of data is supported for the format) """ formatstring = "You tried to load a file with fileformat '{0}', but this format is not supported for reading files" class format_option(late): def __init__(self, initializer): late.__init__(self, initializer) self.__doc__ = initializer.__doc__ def get_name(self): return self.initializer.__name__ def _get_processor_factory(format): if isinstance(format, str): if not format in registered_fileformat_processors: raise UnsupportedFormatException(format) processor_factory = registered_fileformat_processors[format] else: processor_factory = format return processor_factory def write_set_to_file( set, filename, format='amuse', **format_specific_keyword_arguments): """ Write a set to the given file in the given format. :argument filename: name of the file to write the data to :argument format: name of a registered format or a :class:`FileFormatProcessor` subclass (must be a class and not an instance) All other keywords are set as attributes on the fileformat processor. To determine the supported options for a processor call :func:`get_options_for_format` """ processor_factory = _get_processor_factory(format) processor = processor_factory(filename, set=set, format=format) processor.set_options(format_specific_keyword_arguments) processor.store() def read_set_from_file( filename, format='amuse', **format_specific_keyword_arguments): """ Read a set from the given file in the given format. :argument filename: name of the file to read the data from :argument format: name of a registered format or a :class:`FileFormatProcessor` subclass (must be a class and not an instance) All other keywords are set as attributes on the fileformat processor. To determine the supported options for a processor call :func:`get_options_for_format` """ if 'stream' not in format_specific_keyword_arguments and not os.path.exists(filename): raise IoException("Error: file '{0}' does not exist.".format(filename)) processor_factory = _get_processor_factory(format) processor = processor_factory(filename, format=format) processor.set_options(format_specific_keyword_arguments) return processor.load() class ReportTable(object): """ Report quantities and values to a file. :argument filename: name of the file to write the data to :argument format: name of a registered format ('csv' or 'txt') All other keywords are set as attributes on the fileformat processor. To determine the supported options for a processor call :func:`get_options_for_format` Important options fot text and comma separated files are: :argument attribute_types: list of the units to store the values in :argument attribute_names: list of the names of for the values (used in the header of the file and when using add_row with keyword parameters) Writes data per row to a file. Ideal for storing intermediate values of one Particle or one Gridpoint during a run. Example usage:: report = ReportTable( "hrdiagram.txt", "txt", attribute_types=(units.Myr, units.K, units.LSun), attribute_names=('age', 'temperature_at_time', 'luminosity_at_time') ) report.add_row(particle.age, particle.temperature_at_time, particle.luminosity_at_time) """ def __init__( self, filename, format = 'csv', **format_specific_keyword_arguments ): processor_factory = _get_processor_factory(format) self.processor = processor_factory(filename, format = format) self.processor.set_options(format_specific_keyword_arguments) self.processor.open_stream() self.processor.write_header() def add_row(self, *fields, **fieldsbyname): """ Add a row to the report, columns can be added by name or by position in list. If columns are given by name the order does not matter and will alway follow to order given in the 'attribute_names' option specified when creating the ReportTable. Example usage:: report.add_row( particle.age, particle.temperature_at_time, particle.luminosity_at_time ) report.add_row( temperature_at_time = particle.temperature_at_time, age = particle.age, luminosity_at_time = particle.luminosity_at_time ) """ row = list(fields) if len(fieldsbyname) > 0: names = self.processor.attribute_names if len(names) >= len(row): row.extend([0] * (len(names) - len(row))) names_to_index = {} for i,name in enumerate(names): names_to_index[name] = i for name, value in fieldsbyname.items(): index = names_to_index[name] row[index] = value self.processor.write_row(row) def close(self): self.processor.close_stream() def get_options_for_format( format = 'amuse', ): """Retuns a list of tuples, each tuple contains the name of the option, a description of the option and the default values. :argument format: name of a registered format or a :class:`FileFormatProcessor` subclass (must be a class and not an instance) """ processor_factory = _get_processor_factory(format) processor = processor_factory(format = format) return list(processor.get_description_of_options()) def add_fileformat_processor(class_of_the_format): """ Register the specified class, so that it can be used by the :func:`write_set_to_file` and :func:`read_set_from_file` functions. Do not call this method directly, instead use :func:`FileFormatProcessor.register` """ for x in class_of_the_format.provided_formats: registered_fileformat_processors[x] = class_of_the_format _update_documentation_strings() def _update_documentation_strings(): for methodname in ['write_set_to_file', 'read_set_from_file']: method = globals()[methodname] if not hasattr(method, '_original_doc'): method._original_doc = method.__doc__ new_doc = method._original_doc new_doc += "\n Registered file formats:\n\n" sorted_formatnames = sorted(registered_fileformat_processors.keys()) for x in sorted_formatnames: processor = registered_fileformat_processors[x] processor_doc = processor.__doc__ if processor_doc is None or len(processor_doc) == 0: continue processor_doc = processor_doc.strip() line = processor_doc.splitlines()[0] line = ' **' + x + '**,\n ' + line + '\n' new_doc += line method.__doc__ = new_doc class FileFormatProcessor(object): """ Abstract base class of all fileformat processors All classes providing loading or storing of files should be subclasses of this base class. Every subclass must support the *filename*, *set* and *format* arguments. The arguments must all be optional. :argument filename: name of the file the read the data from :argument set: set (of particles or entities) to store in the file :argument format: format of the file, will be a string or class :attribute provided_formats: list of strings of the formats provided by the processor """ provided_formats = [] def __init__(self, filename = None, set = None, format = None): self.filename = filename self.set = set self.format = format @classmethod def get_options(cls): attribute_names = dir(cls) result = {} for x in attribute_names: if x.startswith('_'): continue attribute_value = getattr(cls, x) if isinstance(attribute_value, format_option): result[x] = attribute_value return result @classmethod def register(cls): """ Register this class, so that it can be found by name int the :func:`write_set_to_file` and :func:`read_set_from_file` functions. """ add_fileformat_processor(cls) def set_options(self, dictionary): supported_options = self.get_options() for key, value in dictionary.items(): if key in supported_options: setattr(self, key, value) else: self.extra_attributes[key] = value def store(self): """ Stores the set in the file. The set and the file are both properties of the processor. """ raise CannotSaveException(self.format) def load(self): """ Loads the set from the file and returns the set. """ raise CannotLoadException(self.format) def store_string(self): raise CannotSaveException(self.format) def load_string(self, string): raise CannotLoadException(self.format) def get_description_of_options(self): """Yields tuples, each tuple contains the name of the option, a description of the option and the default values """ for option, method in self.get_options().items(): default_value = getattr(self, option) doc = method.__doc__ if doc is None: doc = "" description = textwrap.dedent(doc) yield (option, description, default_value) @format_option def extra_attributes(self): """Extra attributes to store with the data set. Some formats (moste notably the amuse native format) can store extra attributes with the set in file. The 'write_set_to_file' function will collect all keyword arguments that do not match to an option into the extra attributes dictionary. """ return {} class FullTextFileFormatProcessor(FileFormatProcessor): """ Abstract base class of all fileformat processors that process their data by first reading the complete text string Subclasses need to implement the :func:`store_string` and :func:`load_string` methods. """ def store(self): with open(self.filename, 'w') as f: f.write(self.store_string()) def load(self): with open(self.filename, 'r') as f: return self.load_string(f.read()) def store_string(self): """Return a string representation of the particle set""" raise CannotSaveException(self.format) def load_string(self, string): """Return a particle set, read from the string""" raise CannotLoadException(self.format) class BinaryFileFormatProcessor(FileFormatProcessor): """ Abstract base class of all fileformat processors that process their data by first reading the complete text string Subclasses need to implement the :func:`store_file` and / or :func:`load_file` methods. """ def store(self): with open(self.filename, 'wb') as f: self.store_file(f) def load(self): with open(self.filename, 'rb') as f: return self.load_file(f) def store_file(self, file): """Store the data on the opened file""" raise CannotSaveException(self.format) def load_file(self, string): """Return a particle set, read from the binary file""" raise CannotLoadException(self.format) class FortranFileFormatProcessor(BinaryFileFormatProcessor): """ Abstract base class of all fileformat processors that process their data by first reading fortran blocks Subclasses need to implement the :func:`store_file` and / or :func:`load_file` methods. """ @format_option def endianness(self): """The endianness of the binary date stored in the file""" return '@' #native @late def float_type(self): result = numpy.dtype(numpy.float32) if self.endianness == '@': return result else: return result.newbyteorder(self.endianness) @late def double_type(self): result = numpy.dtype(numpy.float64) if self.endianness == '@': return result else: return result.newbyteorder(self.endianness) @late def uint_type(self): result = numpy.dtype(numpy.uint32) if self.endianness == '@': return result else: return result.newbyteorder(self.endianness) @late def ulong_type(self): result = numpy.dtype(numpy.uint64) if self.endianness == '@': return result else: return result.newbyteorder(self.endianness) @late def int_type(self): result = numpy.dtype(numpy.int32) if self.endianness == '@': return result else: return result.newbyteorder(self.endianness) def read_fortran_block(self, file): """Returns one block read from file. Checks if the block is consistant. Result is an array of bytes """ format = self.endianness+'I' bytes = file.read(4) if not bytes: return None length_of_block = struct.unpack(format, bytes)[0] result = file.read(length_of_block) bytes = file.read(4) length_of_block_after = struct.unpack(format, bytes)[0] if(length_of_block_after != length_of_block): raise IoException("Block is mangled sizes don't match before: {0}, after: {1}".format(length_of_block, length_of_block_after)) return result def read_fortran_block_floats(self, file): bytes = self.read_fortran_block(file) return numpy.frombuffer(bytes, dtype=self.float_type) def read_fortran_block_doubles(self, file): bytes = self.read_fortran_block(file) return numpy.frombuffer(bytes, dtype=self.double_type) def read_fortran_block_uints(self, file): bytes = self.read_fortran_block(file) return numpy.frombuffer(bytes, dtype=self.uint_type) def read_fortran_block_ulongs(self, file): bytes = self.read_fortran_block(file) return numpy.frombuffer(bytes, dtype=self.ulong_type) def read_fortran_block_ints(self, file): bytes = self.read_fortran_block(file) return numpy.frombuffer(bytes, dtype=self.int_type) def read_fortran_block_float_vectors(self, file, size = 3): result = self.read_fortran_block_floats(file) return result.reshape(len(result)//size,size) def write_fortran_block(self, file, input): format = self.endianness+'I' input_bytes = bytearray(input) length_of_block = len(input_bytes) file.write(struct.pack(format, length_of_block)) file.write(input_bytes) file.write(struct.pack(format, length_of_block)) def write_fortran_block_floats(self, file, values): array = numpy.asarray(values, dtype=self.float_type) self.write_fortran_block(file, array.data) def write_fortran_block_doubles(self, file, values): array = numpy.asarray(values, dtype=self.double_type) self.write_fortran_block(file, array.data) def write_fortran_block_uints(self, file, values): array = numpy.asarray(values, dtype=self.uint_type) self.write_fortran_block(file, array.data) def write_fortran_block_ulongs(self, file, values): array = numpy.asarray(values, dtype=self.ulong_type) self.write_fortran_block(file, array.data) def write_fortran_block_ints(self, file, values): array = numpy.asarray(values, dtype=self.int_type) self.write_fortran_block(file, array.data) def write_fortran_block_float_vectors(self, file, values, size = 3): array = numpy.asarray(values, dtype=self.float_type) array = array.reshape(len(array) * size) self.write_fortran_block(file, array.data)
17,890
32.503745
138
py
amuse
amuse-main/src/amuse/io/phigrape.py
import re from amuse.units import units from amuse.units import nbody_system from amuse import datamodel """ fileformat: =========== diskstep # diskstep is used to number out, should be 0 for input dat N # number of particles time # current time, usually starts with 0.0 index mass x y z vx vy vz # N data lines where # index is a running particle index starting at 0! # mass is the mass of a particle # x y z are the x-, y-, and z- positions # vx vy vz are velocities components """ LINEFORMAT16 = "{particle_index:8d} {mass:0.16E} {x: 0.16E} {y: 0.16E} {z: 0.16E} {vx: 0.16E} {vy: 0.16E} {vz: 0.16E}\n" LINEFORMAT8 = "{particle_index:8d} {mass:0.8E} {x: 0.8E} {y: 0.8E} {z: 0.8E} {vx: 0.8E} {vy: 0.8E} {vz: 0.8E}\n" HEADER = "0\n{no_particles:d}\n{current_time}:f\n" class Particles2Inp(object): def __init__(self): self.string = "" def __str__(self): return self.string def convert_to_inp(self, Particles, filename): self.no_particles = len(Particles) self.string += HEADER.format(no_particles=self.no_particles, current_time=0.0) masses = Particles.mass.value_in(nbody_system.mass) velocities = Particles.velocity.value_in(nbody_system.speed) positions = Particles.position.value_in(nbody_system.length) for i in range(self.no_particles): self.string += LINEFORMAT16.format(particle_index = i, mass = masses[i], x = positions[i][0], y = positions[i][1], z = positions[i][2], vx = velocities[i][0], vy = velocities[i][1], vz = velocities[i][2]) f = open(filename, 'w') f.write(self.string) f.close() class Inp2Particles(object): def __init__(self): pass def parse_int_from_group(self): pass def get_values_from_phase_line(self, line): """ The regexp is grouping, therefore we add strings in the following code.. """ values = re.findall('([-+])?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?',line) args = () n = int(values[0][1]) m = float(values[1][1]+values[1][3]) x = float(values[2][0]+values[2][1]+values[2][3]) y = float(values[3][0]+values[3][1]+values[3][3]) z = float(values[4][0]+values[4][1]+values[4][3]) vx = float(values[5][0]+values[5][1]+values[5][3]) vy = float(values[6][0]+values[6][1]+values[6][3]) vz = float(values[7][0]+values[7][1]+values[7][3]) return n, m, x, y, z, vx, vy, vz def read_to_ram(self, inputfile): f = open(inputfile,'r') lines = f.readlines() f.close() N_particles = int(lines[1]) Particles = datamodel.Particles(N_particles) for i, line in enumerate(lines): if i<3: pass#handle header else: n, m, x, y, z, vx, vy, vz = self.get_values_from_phase_line(line) Particles[n].mass = m | nbody_system.mass Particles[n].x = x |nbody_system.length Particles[n].y = y |nbody_system.length Particles[n].z = z |nbody_system.length Particles[n].vx = vx |nbody_system.speed Particles[n].vy = vy |nbody_system.speed Particles[n].vz = vz |nbody_system.speed return Particles def convert_to_particles(self, inputfile, converter = None): self.Particles = self.read_to_ram(inputfile) if not converter==None: self.Particles=datamodel.ParticlesWithUnitsConverted(self.Particles, converter.as_converter_from_si_to_generic())
4,241
37.563636
126
py
amuse
amuse-main/src/amuse/io/fi_io.py
import struct import numpy from collections import namedtuple from amuse.io import base from amuse.units import units from amuse.units import nbody_system from amuse.support.core import late from amuse import datamodel ioversion=2 nheader=8 nihead=32 nrhead=32 nphead=64 # name - type - index in phead - target particle type - unit variables=[ [ "mass", 'd', 1, "all", nbody_system.mass], [ "x", 'd', 2, "all", nbody_system.length], [ "y", 'd', 2, "all", nbody_system.length], [ "z",'d',2,"all", nbody_system.length], [ "vx",'d',3,"all", nbody_system.speed], [ "vy",'d',3,"all", nbody_system.speed], [ "vz",'d',3,"all", nbody_system.speed], [ "radius",'d',4,"all", nbody_system.length], [ "tform",'d',5,"all", nbody_system.time], [ "accx",'d',6,"all", nbody_system.acceleration], [ "accy",'d',6,"all", nbody_system.acceleration], [ "accz",'d',6,"all", nbody_system.acceleration], [ "rho",'d',10,"gas", nbody_system.mass / nbody_system.length ** 3], [ "ethermal",'d',11,"gas", nbody_system.speed**2], [ "entropy",'d',12,"gas", units.none], # not sure about this unit [ "h_smooth",'d',13,"gas", nbody_system.length], [ "fuvheat",'d',14,"gas", units.none], # special case -> units of Habing field [ "esnthdt",'d',15,"gas", nbody_system.speed**2/nbody_system.time], [ "tcollaps",'d',16,"gas", nbody_system.time], [ "temperat",'d',17,"gas", units.K], [ "elecfrac",'d',18,"gas", units.none], [ "csound",'d',19,"gas", nbody_system.speed], [ "pressure",'d',20,"gas", nbody_system.mass/nbody_system.length/nbody_system.time**2], [ "hsmdivv",'d',21,"gas", nbody_system.speed], [ "mumaxdvh",'d',22,"gas", nbody_system.speed], [ "hsmcurlv",'d',23,"gas", nbody_system.speed], [ "vdisp",'d',24,"gas", nbody_system.speed], [ "h2frac",'d',25,"gas", units.none], [ "dethdt",'d',26,"gas", nbody_system.speed**2/nbody_system.time], [ "dentdt",'d',27,"gas", units.none], # not sure about this unit [ "starfuv",'d',34,"stars", units.erg/units.s], # special case [ "snentropy",'d',35,"stars", units.none], # not sure about this unit [ "pot", 'd', 40, "all", nbody_system.speed**2], [ "extpot", 'd', 41, "all", nbody_system.speed**2], [ "id", 'i', 42, "all", units.none], [ "timestep", 'i', 43, "all", units.none] ] class FiFileFormatProcessor(base.FortranFileFormatProcessor): def load_header(self,file): self.ioversion = self.read_fortran_block_ints(file)[0] if self.ioversion != ioversion: raise Exception self.header=self.read_fortran_block_ints(file) self.ihead=self.read_fortran_block_ints(file) self.rhead=self.read_fortran_block_doubles(file) self.phead=self.read_fortran_block_ints(file) self.ngas=self.ihead[1] self.ndm=self.ihead[2] self.nstar=self.ihead[3] self.unitm_in_msun= self.rhead[16] self.unitl_in_kpc= self.rhead[17]/3.086e21 if self.unitm_in_msun==0. or self.unitl_in_kpc==0.: self.unitm_in_msun= 1.e9 self.unitl_in_kpc= 1.0 self.convert=nbody_system.nbody_to_si( self.unitm_in_msun | units.MSun, self.unitl_in_kpc | units.kpc) print(self.unitl_in_kpc,numpy.log10(self.unitl_in_kpc)) self.flxscale=-41.282-2*numpy.log10(self.unitl_in_kpc) self.heatconst=2.0693e14*self.unitl_in_kpc**2.5/self.unitm_in_msun**1.5 def load_body(self,file): self.gas=datamodel.Particles(self.ngas) self.dark=datamodel.Particles(self.ndm) self.star=datamodel.Particles(self.nstar) for name, type, index, part, unit in variables: if self.phead[index - 1] == 1: if type == 'd': tmp = self.read_fortran_block_doubles(file) if type == 'i': tmp = self.read_fortran_block_ints(file) # special cases: if index == 14: tmp = tmp / self.heatconst if index == 34: tmp = tmp / self.heatconst / 10 ** self.flxscale if part == "all": if self.ngas > 0: setattr(self.gas, name, self.convert.to_si(unit.new_quantity(tmp[0:self.ngas]))) if self.ndm > 0: setattr(self.dark, name, self.convert.to_si(unit.new_quantity(tmp[self.ngas:self.ngas + self.ndm]))) if self.nstar > 0: setattr(self.star, name, self.convert.to_si(unit.new_quantity(tmp[self.ngas + self.ndm:self.ngas + self.ndm + self.nstar]))) if part == "gas": if self.ngas > 0: setattr(self.gas, name, self.convert.to_si(unit.new_quantity(tmp[0:self.ngas]))) if part == "stars": if self.nstar > 0: setattr(self.star, name, self.convert.to_si(unit.new_quantity(tmp[self.ngas + self.ndm:self.ngas + self.ndm + self.nstar]))) def load_file(self, file): self.load_header(file) self.load_body(file) return self.gas,self.dark,self.star def parse_old_runinfo_file(path): """parses the old runinfo file and returns its contents as a dict""" dict_ret = dict() for i, line in enumerate(open(path)): line = line.strip() if len(line) == 0 or line[0] == 'C': continue if i == 1: continue if i == 2: key = 'datadir' value = line if i >= 3: lineSplt = line.split() if ' - ' in line: if '..' not in line: value = True key = ''.join(lineSplt[3::]) else: continue else: value = lineSplt[0] key = '-'.join(lineSplt[1::]) print(value, key) dict_ret[key] = value return dict_ret if __name__=="__main__": p=base.read_set_from_file("test2",format=FiFileFormatProcessor) print(p[0]) print(len(p[0]),len(p[1]),len(p[2]))
6,347
35.482759
141
py