Skip to content
Snippets Groups Projects
Commit 6759fe09 authored by David Hendriks's avatar David Hendriks
Browse files

made better examples and fixed run_system code

parent f464d2ff
No related branches found
No related tags found
No related merge requests found
Showing with 300 additions and 816 deletions
......@@ -3,6 +3,7 @@ import textwrap
import subprocess
import socket
import tempfile
import ctypes
# Functions for the automatic logging of stuff
def autogen_C_logging_code(logging_dict):
......@@ -245,4 +246,31 @@ def temp_custom_logging_dir():
#
os.makedirs(path, exist_ok=True)
return path
\ No newline at end of file
return path
def create_and_load_logging_function(custom_logging_code):
"""
Function to automatically compile the shared library with the given custom logging code and load it with ctypes
returns:
memory adress of the custom logging function in a int type.
"""
#
compile_shared_lib(custom_logging_code,
sourcefile_name=os.path.join(temp_custom_logging_dir(), 'custom_logging.c'),
outfile_name=os.path.join(temp_custom_logging_dir(), 'libcustom_logging.so')
)
# Loading library
dll1 = ctypes.CDLL('libgslcblas.so', mode=ctypes.RTLD_GLOBAL)
dll2 = ctypes.CDLL('libgsl.so', mode=ctypes.RTLD_GLOBAL)
dll3 = ctypes.CDLL('libbinary_c.so', mode=ctypes.RTLD_GLOBAL)
libmean = ctypes.CDLL(os.path.join(temp_custom_logging_dir(), 'libcustom_logging.so'),
mode=ctypes.RTLD_GLOBAL) # loads the shared library
# Get memory adress of function. mimicking a pointer
func_memaddr = ctypes.cast(libmean.custom_output_function, ctypes.c_void_p).value
return func_memaddr
# WARNING DEPRECATED FROM 11-aug-2019
# File containing physics_defaults
physics_defaults = {
# internal buffering and compression level
'internal_buffering': 0,
'internal_buffering_compression': 0,
# log filename
'log_filename': '/dev/null',
'metallicity': 0.02, # metallicity (default 0.02, solar)
'max_evolution_time': 13700.0, # max evol time in Myr (default WMAP result)
# stellar evolution parameters
'max_tpagb_core_mass': 1.38,
'chandrasekhar_mass': 1.44,
'max_neutron_star_mass': 1.8,
'minimum_mass_for_carbon_ignition': 1.6,
'minimum_mass_for_neon_ignition': 2.85,
'AGB_core_algorithm': 0,
'AGB_radius_algorithm': 0,
'AGB_luminosity_algorithm': 0,
'AGB_3dup_algorithm': 0,
# dredge up calibration (either automatic, or not)
'delta_mcmin': 0.0,
'lambda_min': 0.0,
'minimum_envelope_mass_for_third_dredgeup': 0.5,
# minimum timestep (1yr = 1e-6 is the default)
'minimum_timestep': 1e-6,
# maximum timestep (1 Gyr = 1e3 is the default)
'maximum_timestep': 1e3,
# orbit
'eccentricity': 0.0,
# tidally induced mass loss
'CRAP_parameter': 0.0,
# tidal strength factor
'tidal_strength_factor': 1.0,
# E2 tidal prescription. 0 = H02, 1 = Siess+2013
'E2_prescription': 1,
# gravitational radiation model
# 0 = H02 model (Eggleton) for J and e
# 1 = H02 when R<RL for both stars for J and e
# 2 = None
# 3 = Landau and Lifshitz (1951) model for J (e is not changed)
# 4 = Landau and Lifshitz (1951) model for J when R<RL only (e is not changed)
'gravitational_radiation_model': 0,
# magnetic braking multiplier
'magnetic_braking_factor': 1.0,
############################################################
### Mass-loss prescriptions
############################################################
# turn wind mass loss on or off
'wind_mass_loss': 1,
# massive stars
'wr_wind': 0, # default hurley et al wind
'wr_wind_fac': 1.0, # factor applied to WR stars
# TPAGB wind details
'tpagbwind': 0, # default to 0 (Karakas et al 2002)
'superwind_mira_switchon': 500.0,
'tpagb_reimers_eta': 1.0,
# eta for Reimers-like GB mass loss
'gb_reimers_eta': 0.5,
# VW93 alterations
'vw93_mira_shift': 0.0,
'vw93_multiplier': 1.0,
# systemic wind angular momentum loss prescription
'wind_angular_momentum_loss': 0,
'lw': 1.0,
# enhanced mass loss due to rotation
# 0 = none = ROTATION_ML_NONE
# 1 = Langer+ formula (in mass-loss rate calculation,
# warning: can be unstable
# = ROTATION_ML_FORMULA)
# 2 = remove material in a decretion disc until J<Jcrit
# (ROTATION_ML_ANGMOM)
# 3 = 1 + 2 (not recommended!)
'rotationally_enhanced_mass_loss': 2,
'rotationally_enhanced_exponent': 1.0,
# timestep modulator
'timestep_modulator': 1.0,
# initial rotation rates (0=automatic, >0 = in km/s)
'vrot1': 0.0,
'vrot2': 0.0,
########################################
# Supernovae and kicks
########################################
# Black hole masses:
# 0: H02=0
# 1: Belczynski
# 2: Spera+ 2015
# 3: Fryer 2012 (delayed)
# 4: Fryer 2012 (rapid)
'BH_prescription': 2,
'post_SN_orbit_method': 0,
'wd_sigma': 0.0,
'wd_kick_direction': 0,
'wd_kick_pulse_number': 0,
'wd_kick_when': 0,
# sn_kick_distribution and
# sn_kick_dispersion are only defined
# for SN types that leave a remnant
'sn_kick_distribution_II': 1,
'sn_kick_dispersion_II': 190.0,
'sn_kick_distribution_IBC': 1,
'sn_kick_dispersion_IBC': 190.0,
'sn_kick_distribution_GRB_COLLAPSAR': 1,
'sn_kick_dispersion_GRB_COLLAPSAR': 190.0,
'sn_kick_distribution_ECAP': 1,
'sn_kick_dispersion_ECAP': 190.0,
'sn_kick_distribution_NS_NS': 0,
'sn_kick_dispersion_NS_NS': 0.0,
'sn_kick_distribution_TZ': 0,
'sn_kick_dispersion_TZ': 0.0,
'sn_kick_distribution_BH_BH': 0,
'sn_kick_dispersion_BH_BH': 0.0,
'sn_kick_distribution_BH_NS': 0,
'sn_kick_dispersion_BH_NS': 0.0,
'sn_kick_distribution_AIC_BH': 0,
'sn_kick_dispersion_AIC_BH': 0.0,
'sn_kick_companion_IA_He': 0,
'sn_kick_companion_IA_ELD': 0,
'sn_kick_companion_IA_CHAND': 0,
'sn_kick_companion_AIC': 0,
'sn_kick_companion_ECAP': 0,
'sn_kick_companion_IA_He_Coal': 0,
'sn_kick_companion_IA_CHAND_Coal': 0,
'sn_kick_companion_NS_NS': 0,
'sn_kick_companion_GRB_COLLAPSAR': 0,
'sn_kick_companion_HeStarIa': 0,
'sn_kick_companion_IBC': 0,
'sn_kick_companion_II': 0,
'sn_kick_companion_IIa': 0,
'sn_kick_companion_WDKICK': 0,
'sn_kick_companion_TZ': 0,
'sn_kick_companion_AIC_BH': 0,
'sn_kick_companion_BH_BH': 0,
'sn_kick_companion_BH_NS': 0,
# evolution run splitting
'evolution_splitting': 0,
'evolution_splitting_sn_n': 10,
'evolution_splitting_maxdepth': 1,
########################################
#### Mass transfer
########################################
# critical mass ratio for unstable RLOF
#
# qc = m (donor) / m (accretor) :
# if q>qc mass transfer is unstable
#
# H02 = Hurley et al. (2002)
# C14 = Claeys et al. (2014)
# non-degenerate accretors
'qcrit_LMMS': 0.6944, # de Mink et al 2007 suggests 1.8, C14 suggest 1/1.44 = 0.694
'qcrit_MS': 1.6, # C14 suggest 1.6
'qcrit_HG': 4.0, # H02 sect. 2.6.1 gives 4.0
'qcrit_GB': -1, # -1 is the H02 prescription for giants
'qcrit_CHeB': 3.0,
'qcrit_EAGB': -1, # -1 is the H02 prescription for giants
'qcrit_TPAGB': -1, # -1 is the H02 prescription for giants
'qcrit_HeMS': 3,
'qcrit_HeHG': 0.784, # as in H02 2.6.1
'qcrit_HeGB': 0.784, # as in H02 2.6.1
'qcrit_HeWD': 3, # H02
'qcrit_COWD': 3, # H02
'qcrit_ONeWD': 3, # H02
'qcrit_NS': 3, # H02
'qcrit_BH': 3, # H02
# degenerate accretors
'qcrit_degenerate_LMMS': 1.0, # C14
'qcrit_degenerate_MS': 1.0, # C14
'qcrit_degenerate_HG': 4.7619, # C14
'qcrit_degenerate_GB': 1.15, # C14 (based on Hachisu)
'qcrit_degenerate_CHeB': 3, # not used
'qcrit_degenerate_EAGB': 1.15, # as GB
'qcrit_degenerate_TPAGB': 1.15, # as GB
'qcrit_degenerate_HeMS': 3,
'qcrit_degenerate_HeHG': 4.7619, # C14
'qcrit_degenerate_HeGB': 1.15, # C14
'qcrit_degenerate_HeWD': 0.625, # C14
'qcrit_degenerate_COWD': 0.625, # C14
'qcrit_degenerate_ONeWD': 0.625, # C14
'qcrit_degenerate_NS': 0.625, # C14
'qcrit_degenerate_BH': 0.625, # C14
# disk wind for SNeIa
'hachisu_disk_wind': 0, # 0
'hachisu_qcrit': 1.15, # 1.15
# ELD accretion mass
'mass_accretion_for_eld': 0.15, # 0.15, or 100(off)
# mergers have the critical angular momentum
# multiplied by this factor
'merger_angular_momentum_factor': 1.0,
# RLOF rate method : 0=H02, 1=Adaptive R=RL, 3=Claeys et al 2014
'RLOF_method': 3,
'RLOF_mdot_factor': 1.0,
# RLOF time interpolation method
# 0 = binary_c (forward in time only), 1 = BSE (backwards allowed)
'RLOF_interpolation_method': 0,
# Angular momentum in RLOF transfer model
# 0 : H02 (including disk treatment)
# 1 : Conservative
'jorb_RLOF_transfer_model': 0,
# ang mom factor for non-conservative mass loss
# -2 : a wind from the secondary (accretor), i.e. gamma=Md/Ma (default in C14)
# -1 : donor (alternative in C14), i.e. gamma=Ma/Md
# >=0 : the specific angular momentum of the orbit multiplied by gamma
#
# (NB if Hachisu's disk wind is active, or loss is because of
# super-Eddington accretion or novae, material lost through the
# disk wind automatically gets gamma=-2 i.e. the Jaccretor)
'nonconservative_angmom_gamma': -2,
# Hachisu's disc wind
'hachisu_disk_wind': 0,
'hachisu_qcrit': -1.0,
# donor rate limiters
'donor_limit_thermal_multiplier': 1.0,
'donor_limit_dynamical_multiplier': 1.0,
# RLOF assumes circular orbit (0) or at periastron (1)
'rlperi': 0,
# general accretion limits
'accretion_limit_eddington_multiplier': 1.0, # eddington limit factor
'accretion_limit_dynamical_multiplier': 1.0, # dynamical limit factor
'accretion_limit_thermal_multiplier': 1.0, # thermal limit on MS,HG and CHeB star factor
'accretion_rate_novae_upper_limit': 1.03e-7,
'accretion_rate_soft_xray_upper_limit': 2.71e-7,
# novae
'nova_retention_method': 0,
'nova_retention_fraction': 1e-3,
'individual_novae': 0,
'beta_reverse_nova': -1,
'nova_faml_multiplier': 1.0,
'nova_irradiation_multiplier': 0.0,
########################################
# common envelope evolution
########################################
'comenv_prescription': 0, # 0=H02, 1=nelemans, 2=Nandez+Ivanova2016
'alpha_ce': 1.0,
'lambda_ce': -1, # -1 = automatically set
'lambda_ionisation': 0.0,
'lambda_enthalpy': 0.0,
'comenv_splitmass': 0.0,
'comenv_ms_accretion_mass': 0.0,
'nelemans_minq': 0.0, # 0.0 min q for nelemans
'nelemans_max_frac_j_change': 1.0, # 1.0
'nelemans_gamma': 1.0, # 1.0
'nelemans_n_comenvs': 1, # 1
'comenv_merger_spin_method': 2,
'comenv_ejection_spin_method': 1,
'comenv_post_eccentricity': 0.0,
'comenv_splitmass': 1.01,
# comenv accretion
'comenv_ns_accretion_fraction': 0.0,
'comenv_ns_accretion_mass': 0.0,
# #################################################
# circumbinary disc
# #################################################
# 'comenv_disc_mass_fraction' : 0.0,
# 'comenv_disc_angmom_fraction' : 0.0,
# 'cbdisc_gamma' : 1.6666666666,
# 'cbdisc_alpha' : 1e-6,
# 'cbdisc_kappa' : 1e-2,
# 'cbdisc_torquef' : 1.0,
# 'cbdisc_mass_loss_constant_rate' : 0.0,
# 'cbdisc_mass_loss_inner_viscous_accretion_method' : 1,
# 'cbdisc_mass_loss_inner_viscous_multiplier' : 1.0,
# 'cbdisc_mass_loss_inner_L2_cross_multiplier' : 0.0,
# 'cbdisc_mass_loss_ISM_ram_pressure_multiplier' : 0.0,
# 'cbdisc_mass_loss_ISM_pressure' : 3000.0,
# 'cbdisc_mass_loss_FUV_multiplier' : 0.0,
# 'cbdisc_mass_loss_Xray_multiplier' : 1.0,
# 'cbdisc_viscous_photoevaporation_coupling' : 1,
# 'cbdisc_inner_edge_stripping' : 1,
# 'cbdisc_outer_edge_stripping' : 1,
# 'cbdisc_minimum_luminosity' : 1e-4,
# 'cbdisc_minimum_mass' : 1e-6,
# 'cbdisc_eccentricity_pumping_method' : 1,
# 'cbdisc_resonance_multiplier' : 1.0,
# 'comenv_post_eccentricity' : 1e-5,
##################################################
# wind accretion
##################################################
# Bondi-Hoyle accretion multiplier
'Bondi_Hoyle_accretion_factor': 1.5,
# Wind-RLOF method: 0=none, 1=q-dependent, 2=quadratic
# (See Abate et al. 2012,13,14 series of papers)
'WRLOF_method': 0,
# pre-main sequence evolution
'pre_main_sequence': 0,
'pre_main_sequence_fit_lobes': 0,
########################################
# Nucleosynthesis
########################################
# lithium
'lithium_hbb_multiplier': 1.0,
'lithium_GB_post_1DUP': 0.0,
'lithium_GB_post_Heflash': 0.0,
########################################
# Yields vs time (GCE)
########################################
'yields_dt': 100000,
'escape_velocity': 1e9, # if wind v < this, ignore the yield
# and assume it is lost to the IGM
'escape_fraction': 0.0, # assume all yield is kept in the population
# minimum sep/per for RLOF on the ZAMS
'minimum_separation_for_instant_RLOF': 0,
'minimum_orbital_period_for_instant_RLOF': 0,
}
import binary_c
from collections import defaultdict
from binaryc_python_utils.defaults import physics_defaults
import binary_c
from binaryc_python_utils.custom_logging_functions import create_and_load_logging_function
def create_arg_string(arg_dict):
"""
......@@ -41,33 +41,60 @@ def get_arg_keys():
def run_system(**kwargs):
"""
Wrapper to run a system with settings
This function determines which underlying python-c api function will be called based upon the arguments that are passed via kwargs.
- if custom_logging_code or custom_logging_dict is included in the kwargs then it will
- if
"""
# Load default args
args = get_defaults()
# args = {}
if 'custom_logging_code' in kwargs:
# Use kwarg value to override defaults and add new args
for key in kwargs.keys():
if not key=='custom_logging_code':
args[key] = kwargs[key]
# For example
# physics_args['M_1'] = 20
# physics_args['separation'] = 0 # 0 = ignored, use period
# physics_args['orbital_period'] = 100000000000 # To make it single
# Generate library and get memaddr
func_memaddr = create_and_load_logging_function(kwargs['custom_logging_code'])
# Use kwarg value to override defaults and add new args
for key in kwargs.keys():
args[key] = kwargs[key]
# Construct arguments string and final execution string
arg_string = create_arg_string(args)
arg_string = 'binary_c {}'.format(arg_string)
# Construct arguments string and final execution string
arg_string = create_arg_string(args)
arg_string = f'binary_c {arg_string}'
# Run it and get output
output = binary_c.run_binary_custom_logging(arg_string, func_memaddr)
return output
# print(arg_string)
elif 'log_filename' in kwargs:
# Use kwarg value to override defaults and add new args
for key in kwargs.keys():
args[key] = kwargs[key]
# Run it and get output
buffer = ""
output = binary_c.run_binary(arg_string)
# Construct arguments string and final execution string
arg_string = create_arg_string(args)
arg_string = 'binary_c {}'.format(arg_string)
return output
# Run it and get output
output = binary_c.run_binary_with_logfile(arg_string)
return output
else: # run the plain basic type
# Use kwarg value to override defaults and add new args
for key in kwargs.keys():
args[key] = kwargs[key]
# Construct arguments string and final execution string
arg_string = create_arg_string(args)
arg_string = 'binary_c {}'.format(arg_string)
# Run it and get output
output = binary_c.run_binary(arg_string)
return output
def run_system_with_log(**kwargs):
"""
......@@ -89,7 +116,7 @@ def run_system_with_log(**kwargs):
# Construct arguments string and final execution string
arg_string = create_arg_string(args)
arg_string = f'binary_c {arg_string}'
arg_string = 'binary_c {}'.format(arg_string)
# print(arg_string)
......@@ -105,7 +132,9 @@ def parse_output(output, selected_header):
DAVID_SINGLE_ANALYSIS t=0 mass=20
You can give a 'selected_header' to catch any line that starts with that.
Then the values will be put into a
Then the values will be put into a dictionary.
TODO: Think about exporting to numpy array or pandas
"""
value_dicts = []
val_lists = []
......
This diff is collapsed.
......@@ -2,7 +2,7 @@ import ctypes
import tempfile
import os
from binaryc_python_utils.custom_logging_functions import autogen_C_logging_code, binary_c_log_code, compile_shared_lib, temp_custom_logging_dir
from binaryc_python_utils.custom_logging_functions import autogen_C_logging_code, binary_c_log_code, compile_shared_lib, temp_custom_logging_dir, create_and_load_logging_function
import binary_c
# generate logging lines
......@@ -16,21 +16,8 @@ logging_line = autogen_C_logging_code(
# Generate code around logging lines
custom_logging_code = binary_c_log_code(logging_line)
#
compile_shared_lib(created_code,
sourcefile_name=os.path.join(temp_custom_logging_dir(), 'custom_logging.c'),
outfile_name=os.path.join(temp_custom_logging_dir(), 'libcustom_logging.so')
)
# Loading library
dll1 = ctypes.CDLL('libgslcblas.so', mode=ctypes.RTLD_GLOBAL)
dll2 = ctypes.CDLL('libgsl.so', mode=ctypes.RTLD_GLOBAL)
dll3 = ctypes.CDLL('libbinary_c.so', mode=ctypes.RTLD_GLOBAL)
libmean = ctypes.CDLL(os.path.join(temp_custom_logging_dir(), 'libcustom_logging.so'),
mode=ctypes.RTLD_GLOBAL) # loads the shared library
# Get memory adress of function. mimicking a pointer
mem = ctypes.cast(libmean.custom_output_function, ctypes.c_void_p).value
# Generate library and get memaddr
func_memaddr = create_and_load_logging_function(custom_logging_code)
#
m1 = 15.0 # Msun
......@@ -40,10 +27,6 @@ orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000
buffer = ""
argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g} ".format(m1,m2,separation,orbital_period,eccentricity,metallicity,max_evolution_time)
output = binary_c.run_binary_custom_logging(argstring, mem)
# output = binary_c.run_binary(argstring)
print (output)
argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g}".format(m1,m2,separation,orbital_period,eccentricity,metallicity,max_evolution_time)
output = binary_c.run_binary_custom_logging(argstring, func_memaddr)
print(output)
\ No newline at end of file
#!/usr/bin/python3
import os
import sys
import binary_c
from binaryc_python_utils.functions import run_system, parse_output
from binaryc_python_utils.custom_logging_functions import autogen_C_logging_code, binary_c_log_code
"""
Very basic scripts to run a binary system and print the output.
Use these as inspiration/base
"""
def run_example_binary():
"""
Function to run a binary system. Very basic approach which directly adresses the run_binary(..) python-c wrapper function.
"""
m1 = 15.0 # Msun
m2 = 14.0 # Msun
separation = 0 # 0 = ignored, use period
orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000 # Myr. You need to include this argument.
#
argstring = "binary_c M_1 {m1} M_2 {m2} separation {separation} orbital_period {orbital_period} \
eccentricity {eccentricity} metallicity {metallicity} \
max_evolution_time {max_evolution_time}".format(m1=m1, m2=m2, separation=separation, orbital_period=orbital_period, eccentricity=eccentricity, metallicity=metallicity, max_evolution_time=max_evolution_time)
output = binary_c.run_binary(argstring)
print (output)
# run_example_binary()
def run_example_binary_with_run_system():
"""
This function serves as an example on the function run_system and parse_output.
There is more functionality with this method and several tasks are done behind the scene.
Requires pandas, numpy to run.
run_system: mostly just makes passing arguments to the function easier. It also loads all the necessary defaults in the background
parse_output: Takes the raw output of binary_c and selects those lines that start with the given header.
Note, if you dont use the custom_logging functionality binary_c should be configured to have output that starts with that given header
"""
import pandas as pd
import numpy as np
# Run system. all arguments can be given as optional arguments.
output = run_system(M_1=10, M_2=20, separation=0, orbital_period=100000000000)
# Catch results that start with a given header. (Mind that binary_c has to be configured to print them if your not using a custom logging function)
result_example_header = parse_output(output, 'example_header')
#### Now do whatever you want with it:
# Put it in numpy arrays
#t_res = np.asarray(result_example_header['t'], dtype=np.float64, order='C')
#m_res = np.asarray(result_example_header['mass'], dtype=np.float64, order='C')
# Cast the data into a dataframe.
df = pd.DataFrame.from_dict(result_example_header, dtype=np.float64)
# print(df)
# sliced_df = df[df.t < 1000] # Cut off late parts of evolution
# print(sliced_df[["t","m1"]])
# Some routine to plot.
# run_example_binary_with_run_system()
def run_example_binary_with_custom_logging():
"""
Function that will use a automatically generated piece of logging code. Compile it, load it
into memory and run a binary system. See run_system on how several things are done in the background here.
"""
import pandas as pd
import numpy as np
# generate logging lines. Here you can choose whatever you want to have logged, and with what header
# this generates working print statements
logging_line = autogen_C_logging_code(
{
'MY_STELLAR_DATA': ['model.time', 'star[0].mass'],
}
)
# OR
# You can also decide to `write` your own logging_line, which allows you to write a more complex logging statement with conditionals.
logging_line = 'Printf("MY_STELLAR_DATA time=%g mass=%g\\n", stardata->model.time, stardata->star[0].mass)'
# Generate entire shared lib code around logging lines
custom_logging_code = binary_c_log_code(logging_line)
# Run system. all arguments can be given as optional arguments. the custom_logging_code is one of them and will be processed automatically.
output = run_system(M_1=1, metallicity=0.002, M_2=0.1, separation=0, orbital_period=100000000000, custom_logging_code=custom_logging_code)
# Catch results that start with a given header. (Mind that binary_c has to be configured to print them if your not using a custom logging function)
# DOESNT WORK YET if you have the line autogenerated.
result_example_header = parse_output(output, 'MY_STELLAR_DATA')
# Cast the data into a dataframe.
df = pd.DataFrame.from_dict(result_example_header, dtype=np.float64)
# Do whatever you like with the dataframe.
print(df)
# run_example_binary_with_custom_logging()
def run_example_binary_with_writing_logfile():
"""
Same as above but when giving the log_filename argument the log filename will be written
"""
import pandas as pd
import numpy as np
# Run system. all arguments can be given as optional arguments.
output = run_system(M_1=10, M_2=20, separation=0, orbital_period=100000000000, log_filename=os.getcwd()+'/test_log.txt')
# Catch results that start with a given header. (Mind that binary_c has to be configured to print them if your not using a custom logging function)
result_example_header = parse_output(output, 'example_header')
#### Now do whatever you want with it:
# Put it in numpy arrays
#t_res = np.asarray(result_example_header['t'], dtype=np.float64, order='C')
#m_res = np.asarray(result_example_header['mass'], dtype=np.float64, order='C')
# Cast the data into a dataframe.
df = pd.DataFrame.from_dict(result_example_header, dtype=np.float64)
# print(df)
# sliced_df = df[df.t < 1000] # Cut off late parts of evolution
# print(sliced_df[["t","m1"]])
# Some routine to plot.
# run_example_binary_with_writing_logfile()
\ No newline at end of file
TIME M1 M2 K1 K2 SEP ECC R1/ROL1 R2/ROL2 TYPE RANDOM_SEED=21708 RANDOM_COUNT=0
0.0000 10.000 20.000 1 1 2.8176e+08 0.00 0.000 0.000 INITIAL
8.8656 9.980 19.203 1 2 2.8966e+08 0.00 0.000 0.000 TYPE_CHNGE
8.8814 9.980 19.185 1 4 2.8983e+08 0.00 0.000 0.000 TYPE_CHNGE
9.8724 9.977 10.122 1 5 4.2066e+08 0.00 0.000 0.000 TYPE_CHNGE
9.8834 9.977 9.974 1 5 4.2379e+08 0.00 0.000 0.000 q-inv
9.8901 9.977 1.621 1 13 -592.56 -1.00 0.000 0.000 Randbuf=35834 - d48r(0)=0.500757 - d48r(1)=0.0445977 - d48r(2)=0.55466 - d48r(3)=0.342924 - d48r(4)=0.230728
9.8901 9.977 1.621 1 13 -592.56 -1.00 0.000 0.000 SN kick II (SN type 12 12, pre-explosion M=8.50996 Mc=6.81718 type=5) -> kick 1(190) vk=61.1258 vr=0.0878271 omega=1.44971 phi=-0.319563 -> vn=61.1158 ; final sep -592.558 ecc -1 (random count 0) - Runaway v=(0,0,0) |v|=0 : companion v=(0,0,0), |v|=0 ; - , dm(exploder) = 6.88872, dm(companion) = 0
9.8901 9.977 1.621 1 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
9.8901 9.977 1.621 1 13 -592.56 -1.00 0.000 0.000 DISRUPT
9.8901 9.977 1.621 1 13 -592.56 -1.00 0.000 0.000 SN
24.4615 9.890 1.621 2 13 -592.56 -1.00 0.000 0.000 OFF_MS
24.4615 9.890 1.621 2 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
24.5257 9.887 1.621 3 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
24.5353 9.886 1.621 4 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
27.3558 9.424 1.621 5 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
27.4616 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 d48r(5)=0.770697 - d48r(6)=0.689651 - d48r(7)=0.21307 - d48r(8)=0.709486
27.4616 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 SN kick II (SN type 12 12, pre-explosion M=9.30206 Mc=2.87012 type=5) -> kick 1(190) vk=327.76 vr=0 omega=4.45783 phi=-0.61121 -> vn=327.76 ; final sep -592.558 ecc -1 (random count 5) - Runaway v=(0,0,0) |v|=0 : companion v=(0,0,0), |v|=0 ; - , dm(exploder) = 7.96389, dm(companion) = 0
27.4616 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 TYPE_CHNGE
27.4616 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 q-inv
27.4616 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 SN
15000.0000 1.338 1.621 13 13 -592.56 -1.00 0.000 0.000 MAX_TIME
Probability : 1
TIME M1 M2 K1 K2 SEP ECC R1/ROL1 R2/ROL2 TYPE RANDOM_SEED=55045 RANDOM_COUNT=0
0.0000 10.000 20.000 1 1 2.8176e+08 0.00 0.000 0.000 INITIAL
8.8656 9.980 19.203 1 2 2.8966e+08 0.00 0.000 0.000 TYPE_CHNGE
8.8814 9.980 19.185 1 4 2.8983e+08 0.00 0.000 0.000 TYPE_CHNGE
9.8724 9.977 10.122 1 5 4.2066e+08 0.00 0.000 0.000 TYPE_CHNGE
9.8834 9.977 9.974 1 5 4.2379e+08 0.00 0.000 0.000 q-inv
9.8901 9.977 1.621 1 13 -16.809 -1.00 0.000 0.000 Randbuf=37809 - d48r(0)=0.335316 - d48r(1)=0.610765 - d48r(2)=0.984646 - d48r(3)=0.74651 - d48r(4)=0.897875
9.8901 9.977 1.621 1 13 -16.809 -1.00 0.000 0.000 SN kick II (SN type 12 12, pre-explosion M=8.50996 Mc=6.81718 type=5) -> kick 1(190) vk=362.928 vr=0.0878271 omega=5.64151 phi=0.515558 -> vn=362.867 ; final sep -16.809 ecc -1 (random count 0) - Runaway v=(0,0,0) |v|=0 : companion v=(0,0,0), |v|=0 ; - , dm(exploder) = 6.88872, dm(companion) = 0
9.8901 9.977 1.621 1 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
9.8901 9.977 1.621 1 13 -16.809 -1.00 0.000 0.000 DISRUPT
9.8901 9.977 1.621 1 13 -16.809 -1.00 0.000 0.000 SN
24.4615 9.890 1.621 2 13 -16.809 -1.00 0.000 0.000 OFF_MS
24.4615 9.890 1.621 2 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
24.5257 9.887 1.621 3 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
24.5353 9.886 1.621 4 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
27.3558 9.424 1.621 5 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
27.4616 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 d48r(5)=0.306812 - d48r(6)=0.0954943 - d48r(7)=0.00699521 - d48r(8)=0.980772
27.4616 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 SN kick II (SN type 12 12, pre-explosion M=9.30206 Mc=2.87012 type=5) -> kick 1(190) vk=164.187 vr=0 omega=6.16237 phi=-1.40333 -> vn=164.187 ; final sep -16.809 ecc -1 (random count 5) - Runaway v=(0,0,0) |v|=0 : companion v=(0,0,0), |v|=0 ; - , dm(exploder) = 7.96389, dm(companion) = 0
27.4616 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 TYPE_CHNGE
27.4616 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 q-inv
27.4616 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 SN
15000.0000 1.338 1.621 13 13 -16.809 -1.00 0.000 0.000 MAX_TIME
Probability : 1
import os, sys
import matplotlib.pyplot as plt
# Append root dir of this project to include functionality
sys.path.append(os.path.dirname(os.getcwd()))
import binary_c
from utils.defaults import physics_defaults
from utils.functions import create_arg_string
"""
This script is intended to have the logfile of a binary system being outputted to a given directory so that we can use that logfile for other purposes
Like plotting/visualizing the general evolution of that system using e.g. Mirons script
"""
def example_with_loading_default_args():
"""
Example function loading the default physics args for a binary_c system. Got
it from the binary_grid2 perl module
This function works if binary_c is set to log something every timestep so that we can plot the evolution of a system
"""
# Load args
physics_args = physics_defaults.copy()
# Manually set M_1, M_2, orbital_period and separation values:
physics_args['M_1'] = 20
physics_args['M_2'] = 15
physics_args['separation'] = 0 # 0 = ignored, use period
physics_args['orbital_period'] = 4530.0
physics_args['log_filename'] = os.path.join(os.getcwd(), 'test.log')
print(physics_args['log_filename'])
arg_string = create_arg_string(physics_args)
arg_string = f'binary_c {arg_string}'
buffer = ""
print(arg_string)
output = binary_c.run_binary(arg_string)
example_with_loading_default_args()
\ No newline at end of file
import os, sys
import matplotlib.pyplot as plt
# Append root dir of this project to include functionality
sys.path.append(os.path.dirname(os.getcwd()))
import binary_c
from utils.defaults import physics_defaults
from utils.functions import create_arg_string
"""
This script is an example of running a group of binary systems using a loop. For big grids this is not wise, the grid functionality will be built later
I made this script to with the logging of binaryc set to log only one line per system (when a certain requirement is met).
You can either capture the data and print it, or write it to a file
"""
def run_simple_loop_binary():
# Some simple function with a loop
# This function assumes a single output line
m2 = 14.0 # Msun
separation = 0 # 0 = ignored, use period
orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000
buffer = ""
print ("Binary_c grid output:")
mass_1 = []
time = []
initial_m1 = []
# Set up for loop. Beware: this is only a proof of concept example. big grid should not be run in this way. rather one should use a queueing/threading system.
for m1 in range(15, 20):
argstring = f"binary_c M_1 {m1} M_2 {m2} separation {separation} orbital_period {orbital_period} eccentricity {eccentricity} metallicity {metallicity} max_evolution_time {max_evolution_time}"
# Get the output string
output = binary_c.run_binary(argstring)
# split output on newlines
for line in output.split('\n'):
# Example of splitting off certain lines of output
if line.startswith('TESTLOG_BINARY_POP'):
value_array = line.split()[1:]
# print(value_array)
# Either save the results in arrays or lists
mass_1.append(value_array[1])
time.append(value_array[0])
initial_m1.append(value_array[2])
# write headers. can be cleaner
if not os.path.isfile("test_output.txt"):
with open("test_output.txt", "a") as f:
f.write('time M1 M1_zams\n')
# Or write them to a file with a file:
with open("test_output.txt", "a") as myfile:
myfile.write(' '.join(value_array[:3])+'\n')
print('mass1:', mass_1)
print('zams_mass1:' ,initial_m1)
print('time:', time)
\ No newline at end of file
#!/usr/bin/python3
import os
import sys
# Append root dir of this project to include functionality
sys.path.append(os.path.dirname(os.getcwd()))
import binary_c
from utils.defaults import physics_defaults
from utils.functions import create_arg_string
def run_test_binary():
m1 = 15.0 # Msun
m2 = 14.0 # Msun
separation = 0 # 0 = ignored, use period
orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000
buffer = ""
# argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g} ".format(m1,m2,separation,orbital_period,eccentricity,metallicity,max_evolution_time)
argstring = f"binary_c M_1 {m1} M_2 {m2} separation {separation} orbital_period {orbital_period} eccentricity {eccentricity} metallicity {metallicity} max_evolution_time {max_evolution_time}"
output = binary_c.run_binary(argstring)
# print ("Binary_c output:\n\n")
print (output)
run_test_binary()
import os, sys
# Append root dir of this project to include functionality
sys.path.append(os.path.dirname(os.getcwd()))
import binary_c
"""
Example script for running a single system. This is a very simple set up.
For a different way of inputting arg strings:
from utils.defaults import physics_defaults
from utils.functions import create_arg_string
physics_args = physics_defaults.copy()
physics_args['orbital_period'] = 4530.0
arg_string = create_arg_string(physics_args)
arg_string = f'binary_c {arg_string}'
Other examples can be found using this method
"""
def run_test_binary():
m1 = 15.0 # Msun
m2 = 14.0 # Msun
separation = 0 # 0 = ignored, use period
orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000
buffer = ""
# argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g} ".format(m1,m2,separation,orbital_period,eccentricity,metallicity,max_evolution_time)
argstring = f"binary_c M_1 {m1} M_2 {m2} separation {separation} orbital_period {orbital_period} eccentricity {eccentricity} metallicity {metallicity} max_evolution_time {max_evolution_time}"
output = binary_c.run_binary(argstring)
# print ("Binary_c output:\n\n")
print (output)
\ No newline at end of file
#!/usr/bin/python3
import binary_c
############################################################
# Test script to run a binary using the binary_c Python
# module.
############################################################
def run_test_binary():
m1 = 15.0 # Msun
m2 = 14.0 # Msun
separation = 0 # 0 = ignored, use period
orbital_period = 4530.0 # days
eccentricity = 0.0
metallicity = 0.02
max_evolution_time = 15000
buffer = ""
argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g} ".format(m1,m2,separation,orbital_period,eccentricity,metallicity,max_evolution_time)
output = binary_c.run_binary(argstring)
print ("\n\nBinary_c output:\n\n")
print (output)
binary_star=binary_c.new_system()
print(dir(binary_c))
# print(binary_star)
run_test_binary()
ding = binary_c.return_arglines()
print(ding)
\ No newline at end of file
#!/usr/bin/python3
import os
import binary_c
import matplotlib.pyplot as plt
from binaryc_python_utils.defaults import physics_defaults
############################################################
# Test script to run a binary using the binary_c Python
# module.
############################################################
print(binary_c)
# print("Current binary_c object class functions: ")
# print(dir(binary_c))
# print("Current binary_c.new_system object class functions: ")
# print(dir(binary_c.new_system()))
## WHat is the use of new_system?
# print("Current binary_c.run_binary object class functions: ")
# print(dir(binary_c.run_binary()))
# binary_star=binary_c.new_system()
# print(binary_star)
# print(dir(binary_star))
# Test single system
# run_test_binary()
# Test grid-like
# run_simple_loop_binary()
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment