From 22f07b8a31dab843d58073f9b3da63a5f40b852b Mon Sep 17 00:00:00 2001 From: David Hendriks <davidhendriks93@gmail.com> Date: Mon, 26 Jul 2021 12:46:38 +0100 Subject: [PATCH] Fixed documentation spelling --- .../utils/custom_logging_functions.py | 26 +-- binarycpython/utils/distribution_functions.py | 201 +++++++++--------- binarycpython/utils/functions.py | 58 ++--- binarycpython/utils/grid.py | 185 ++++++++-------- binarycpython/utils/grid_options_defaults.py | 74 +++---- binarycpython/utils/hpc_functions.py | 2 +- binarycpython/utils/plot_functions.py | 8 +- binarycpython/utils/run_system_wrapper.py | 10 +- binarycpython/utils/useful_funcs.py | 9 +- 9 files changed, 286 insertions(+), 287 deletions(-) diff --git a/binarycpython/utils/custom_logging_functions.py b/binarycpython/utils/custom_logging_functions.py index a17fcbb7a..51c87068e 100644 --- a/binarycpython/utils/custom_logging_functions.py +++ b/binarycpython/utils/custom_logging_functions.py @@ -15,11 +15,11 @@ from binarycpython.utils.functions import temp_dir, remove_file, verbose_print def autogen_C_logging_code(logging_dict: dict, verbose: int = 0) -> Optional[str]: """ - Function that autogenerates PRINTF statements for binaryc. + Function that auto-generates PRINTF statements for binaryc. Input is a dictionary where the key is the header of that logging line and items which are lists of parameters that will be put in that logging line - The list elements are all appended to 'stardata->' in the autogenerated code. + The list elements are all appended to 'stardata->' in the auto-generated code. Example: Input dictionary should look like this:: @@ -35,7 +35,7 @@ def autogen_C_logging_code(logging_dict: dict, verbose: int = 0) -> Optional[str Args: logging_dict: Dictionary containing lists of parameters that binary_c has to output. The keys are used by binary_c as start of the sentence. - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. Returns: string containing C printf statement built to output the parameters given as input. @@ -114,7 +114,7 @@ def binary_c_log_code(code: str, verbose: int = 0) -> str: Args: code: Exact c-statement to output information in binary_c. Can be wrapped in logical statements. - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. Returns: string containing the custom logging code. This includes all the includes and other definitions. This code will be used as the shared library @@ -165,7 +165,7 @@ def binary_c_write_log_code(code: str, filename: str, verbose: int = 0) -> None: Args: code: string containing the custom logging code to write to a file. filename: target filename. - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. """ # TODO: change this. I don't like the cwd @@ -212,13 +212,13 @@ def return_compilation_dict(verbose: int = 0) -> dict: """ Function to build the compile command for the shared library - Inspired by binary_c_inline_config command in perl + Inspired by binary_c_inline_config command in Perl - TODO: this function still has some cleaning up to do wrt default values for the compile command + TODO: this function still has some cleaning up to do w.r.t. default values for the compile command # https://developers.redhat.com/blog/2018/03/21/compiler-and-linker-flags-gcc/ Args: - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. Returns: string containing the command to build the shared library @@ -320,7 +320,7 @@ def compile_shared_lib( code: string containing the custom logging code sourcefile_name: name of the file that will contain the code outfile_name: name of the file that will be the shared library - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. """ # Write code to file @@ -344,7 +344,7 @@ def compile_shared_lib( ) ) - # remove extra whitespaces: + # remove extra white spaces: command = " ".join(command.split()) # Execute compilation and create the library @@ -378,10 +378,10 @@ def create_and_load_logging_function( Args: custom_logging_code: string containing the custom logging code - verbose: Level of verbosity. Defaults to zero if not set explicilty. + verbose: Level of verbosity. Defaults to zero if not set explicitly. Returns: - memory adress of the custom logging function in a int type. + memory address of the custom logging function in a capsule. """ # @@ -392,7 +392,7 @@ def create_and_load_logging_function( custom_logging_dir = os.path.join(tmp_dir, "custom_logging") - # Create the subdir for the custom_logging code + # Create the sub dir for the custom_logging code os.makedirs(custom_logging_dir, exist_ok=True) # diff --git a/binarycpython/utils/distribution_functions.py b/binarycpython/utils/distribution_functions.py index 65880d59e..01c8b136b 100644 --- a/binarycpython/utils/distribution_functions.py +++ b/binarycpython/utils/distribution_functions.py @@ -12,12 +12,12 @@ There are distributions for the following parameters: Tasks: - TODO: make some things globally present? rob does this in his module..i guess it saves - calculations but not sure if im gonna do that now + calculations but not sure if I'm gonna do that now - TODO: add eccentricity distribution: thermal - TODO: Add SFH distributions depending on redshift - TODO: Add metallicity distributions depending on redshift - TODO: Add initial rotational velocity distributions - - TODO: make an n-part powerlaw thats general enough to fix the three part and the 4 part + - TODO: make an n-part power law that's general enough to fix the three part and the 4 part """ import gc @@ -37,7 +37,7 @@ from binarycpython.utils.grid_options_defaults import ( ### # File containing probability distributions -# Mostly copied from the perl modules +# Mostly copied from the Perl modules LOG_LN_CONVERTER = 1.0 / math.log(10.0) distribution_constants = {} # To store the constants in @@ -46,10 +46,10 @@ def prepare_dict(global_dict: dict, list_of_sub_keys: list) -> None: """ Function that makes sure that the global dict is prepared to have a value set there. This dictionary will store values and factors for the distribution functions, - so that they dont have to be calculated each time. + so that they don't have to be calculated each time. Args: - global_dict: globablly acessible dictionary where factors are stored in + global_dict: globally accessible dictionary where factors are stored in list_of_sub_keys: List of keys that must become be(come) present in the global_dict """ @@ -140,17 +140,17 @@ def powerlaw_constant( min_val: Union[int, float], max_val: Union[int, float], k: Union[int, float] ) -> Union[int, float]: """ - Function that returns the constant to normalise a powerlaw + Function that returns the constant to normalise a power law TODO: what if k is -1? Args: min_val: lower bound of the range max_val: upper bound of the range - k: powerlaw slope + k: power law slope Returns: - constant to normalize the given powerlaw between the min_val and max_val range + constant to normalise the given power law between the min_val and max_val range """ k1 = k + 1.0 @@ -171,11 +171,11 @@ def powerlaw( x: Union[int, float], ) -> Union[int, float]: """ - Single powerlaw with index k at x from min to max + Single power law with index k at x from min to max Args: - min_val: lower bound of the powerlaw - max_val: upper bound of the powerlaw + min_val: lower bound of the power law + max_val: upper bound of the power law k: slope of the power law x: position at which we want to evaluate @@ -194,7 +194,7 @@ def powerlaw( powerlaw_const = powerlaw_constant(min_val, max_val, k) - # powerlaw + # power law prob = powerlaw_const * (x ** k) # print( # "Power law from {} to {}: const = {}, y = {}".format( @@ -214,9 +214,9 @@ def calculate_constants_three_part_powerlaw( p3: Union[int, float], ) -> Union[int, float]: """ - Function to calculate the constants for a three-part powerlaw + Function to calculate the constants for a three-part power law - TODO: use the powerlaw_constant function to calculate all these values + TODO: use the power law_constant function to calculate all these values Args: m0: lower bound mass @@ -287,7 +287,7 @@ def three_part_powerlaw( p3: Union[int, float], ) -> Union[int, float]: """ - Generalized three-part power law, usually used for mass distributions + Generalised three-part power law, usually used for mass distributions Args: m: mass at which we want to evaluate the distribution. @@ -331,19 +331,19 @@ def gaussian_normalizing_const( gmax: Union[int, float], ) -> Union[int, float]: """ - Function to calculate the normalisation constant for the gaussian + Function to calculate the normalisation constant for the Gaussian Args: - mean: mean of the gaussian - sigma: standard deviation of the gaussian + mean: mean of the Gaussian + sigma: standard deviation of the Gaussian gmin: lower bound of the range to calculate the probabilities in gmax: upper bound of the range to calculate the probabilities in Returns: - normalisation constant for the gaussian distribution(mean, sigma) between gmin and gmax + normalisation constant for the Gaussian distribution(mean, sigma) between gmin and gmax """ - # First time; calculate multipllier for given mean and sigma + # First time; calculate multiplier for given mean and sigma ptot = 0 resolution = 1000 d = (gmax - gmin) / resolution @@ -360,15 +360,15 @@ def gaussian_func( x: Union[int, float], mean: Union[int, float], sigma: Union[int, float] ) -> Union[int, float]: """ - Function to evaluate a gaussian at a given point, but this time without any boundaries. + Function to evaluate a Gaussian at a given point, but this time without any boundaries. Args: x: location at which to evaluate the distribution - mean: mean of the gaussian - sigma: standard deviation of the gaussian + mean: mean of the Gaussian + sigma: standard deviation of the Gaussian Returns: - value of the gaussian at x + value of the Gaussian at x """ gaussian_prefactor = 1.0 / math.sqrt(2.0 * math.pi) @@ -389,13 +389,13 @@ def gaussian( Args: x: location at which to evaluate the distribution - mean: mean of the gaussian - sigma: standard deviation of the gaussian + mean: mean of the Gaussian + sigma: standard deviation of the Gaussian gmin: lower bound of the range to calculate the probabilities in gmax: upper bound of the range to calculate the probabilities in Returns: - 'probability' of the gaussian distribution between the boundaries, evaluated at x + 'probability' of the Gaussian distribution between the boundaries, evaluated at x """ # # location (X value), mean and sigma, min and max range @@ -404,7 +404,7 @@ def gaussian( if (x < gmin) or (x > gmax): prob = 0 else: - # normalize over given range + # normalise over given range # TODO: add loading into global var normalisation = gaussian_normalizing_const(mean, sigma, gmin, gmax) prob = gaussian_func(x, mean, sigma) / normalisation @@ -419,7 +419,7 @@ def gaussian( def Kroupa2001(m: Union[int, float], newopts: dict = None) -> Union[int, float]: """ - Probability distribution function for kroupa 2001 IMF, where the default values to the + Probability distribution function for Kroupa 2001 IMF, where the default values to the three_part_powerlaw are: default = {"m0": 0.1, "m1": 0.5, "m2": 1, "mmax": 100, "p1": -1.3, "p2": -2.3,"p3": -2.3} Args: @@ -430,7 +430,7 @@ def Kroupa2001(m: Union[int, float], newopts: dict = None) -> Union[int, float]: 'probability' of distribution function evaluated at m """ - # Default params and override them + # Default parameters and override them default = { "m0": 0.1, "m1": 0.5, @@ -535,7 +535,7 @@ def ktg93(m: Union[int, float], newopts: dict = None) -> Union[int, float]: def imf_tinsley1980(m: Union[int, float]) -> Union[int, float]: """ - Probability distribution function for tinsley 1980 IMF (defined up until 80Msol): three_part_powerlaw(m, 0.1, 2.0, 10.0, 80.0, -2.0, -2.3, -3.3) + Probability distribution function for Tinsley 1980 IMF (defined up until 80Msol): three_part_powerlaw(m, 0.1, 2.0, 10.0, 80.0, -2.0, -2.3, -3.3) Args: m: mass to evaluate the distribution at @@ -562,7 +562,7 @@ def imf_scalo1986(m: Union[int, float]) -> Union[int, float]: def imf_scalo1998(m: Union[int, float]) -> Union[int, float]: """ - From scalo 1998 + From Scalo 1998 Probability distribution function for Scalo 1998 IMF (defined up until 80Msol): three_part_powerlaw(m, 0.1, 1.0, 10.0, 80.0, -1.2, -2.7, -2.3) @@ -712,7 +712,7 @@ def sana12( amax: maximum separation of the distribution (upper bound of the range) x0: log of minimum period of the distribution (lower bound of the range) x1: log of maximum period of the distribution (upper bound of the range) - p: slope of the distributoon + p: slope of the distribution Returns: 'probability' of orbital period P given the other parameters @@ -725,7 +725,7 @@ def sana12( p1 = 1.0 + p # For more details see the LyX document of binary_c for this distribution - # where the variables and normalizations are given + # where the variables and normalisations are given # we use the notation x=log(P), xmin=log(Pmin), x0=log(P0), ... to determine the x = LOG_LN_CONVERTER * math.log(P) xmin = LOG_LN_CONVERTER * math.log(calc_period_from_sep(M1, M2, amin)) @@ -815,10 +815,10 @@ def Izzard2012_period_distribution( # save mass input and limit mass used (M1 from now on) to fitted range Mwas = M1 M1 = max(1.15, min(16.3, M1)) - # print("Izzard2012 called for M={} (trunc'd to {}), P={}\n".format(Mwas, M1, P)) + # print("Izzard2012 called for M={} (truncated to {}), P={}\n".format(Mwas, M1, P)) # Calculate the normalisations - # need to normalize the distribution for this mass + # need to normalise the distribution for this mass # (and perhaps secondary mass) prepare_dict(distribution_constants, ["Izzard2012", M1]) if not distribution_constants["Izzard2012"][M1].get(log10Pmin): @@ -827,13 +827,13 @@ def Izzard2012_period_distribution( ] = 1 # To prevent this loop from going recursive N = 200.0 # Resolution for normalisation. I hope 1000 is enough dlP = (10.0 - log10Pmin) / N - C = 0 # normalisation const. + C = 0 # normalisation constant. for lP in np.arange(log10Pmin, 10, dlP): C += dlP * Izzard2012_period_distribution(10 ** lP, M1, log10Pmin) distribution_constants["Izzard2012"][M1][log10Pmin] = 1.0 / C # print( - # "Normalization constant for Izzard2012 M={} (log10Pmin={}) is\ + # "Normalisation constant for Izzard2012 M={} (log10Pmin={}) is\ # {}\n".format( # M1, log10Pmin, distribution_constants["Izzard2012"][M1][log10Pmin] # ) @@ -924,7 +924,7 @@ def cosmic_SFH_madau_dickinson2014(z): z: redshift Returns: - Cosmic star formation rate in Solarmass year^-1 megaparsec^-3 + Cosmic star formation rate in Solar mass year^-1 mega parsec^-3 """ CSFH = 0.015 * ((1 + z) ** 2.7) / (1 + (((1 + z) / 2.9) ** 5.6)) @@ -947,8 +947,8 @@ def cosmic_SFH_madau_dickinson2014(z): # # TODO: Solve the memory issues that are present. # Are the interpolators not cleaned? -# TODO: Parallellize the setting up of the interpolators -# TODO: Generalize the code such that we can input other/newer tables +# TODO: Parallelize the setting up of the interpolators +# TODO: Generalise the code such that we can input other/newer tables ######################################################################## @@ -959,7 +959,7 @@ Moecache = {} def poisson(lambda_val, n, nmax=None, verbosity=0): """ - Function that calculates the poisson value and normalizes + Function that calculates the Poisson value and normalises TODO: improve the description """ @@ -981,7 +981,7 @@ def poisson(lambda_val, n, nmax=None, verbosity=0): # Poisson distribution : note, n can be zero # - # nmax is the truncation : if set, we normalize + # nmax is the truncation : if set, we normalise # correctly. p_val = _poisson(lambda_val, n) @@ -1006,7 +1006,7 @@ def poisson(lambda_val, n, nmax=None, verbosity=0): def _poisson(lambda_val, n): """ - Function to return the poisson value + Function to return the Poisson value """ return (lambda_val ** n) * np.exp(-lambda_val) / (1.0 * math.factorial(n)) @@ -1064,7 +1064,7 @@ def merge_multiplicities(result_array, max_multiplicity, verbosity=0): def normalize_dict(result_dict, verbosity=0): """ - Function to normalize a dictionary + Function to normalise a dictionary """ sum_result = sum([result_dict[key] for key in result_dict.keys()]) @@ -1072,11 +1072,10 @@ def normalize_dict(result_dict, verbosity=0): result_dict[key] = result_dict[key] / sum_result return result_dict -def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): +def Moe_di_Stefano_2017_multiplicity_fractions(options, verbosity=0): """ Function that creates a list of probability fractions and - normalizes and merges them according to the users choice. - + normalises and merges them according to the users choice. TODO: make an extrapolation functionality in this. log10(1.6e1) is low, we can probably go a bit further @@ -1135,7 +1134,7 @@ def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): full_fractions_array = full_fractions_array/np.sum(full_fractions_array) verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: using model {}: full_fractions_array: {}".format("Poisson", full_fractions_array), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: using model {}: full_fractions_array: {}".format("Poisson", full_fractions_array), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1156,7 +1155,7 @@ def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): # Set last value full_fractions_array[3] = 0.0 # no quadruples verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: using model {}: full_fractions_array: {}".format("data", full_fractions_array), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: using model {}: full_fractions_array: {}".format("data", full_fractions_array), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1165,7 +1164,7 @@ def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): if options["normalize_multiplicities"] == "raw": # Don't multiply by the multiplicity_array, but do give a fractions array verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: Not normalizing (using raw results): results: {}".format(full_fractions_array), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: Not normalising (using raw results): results: {}".format(full_fractions_array), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1175,11 +1174,11 @@ def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): # Multiply the full_multiplicity_fraction array by the multiplicity_multiplier_array, creating a weighted fractions array weighted_fractions_array = full_fractions_array * multiplicity_modulator_array - # Normalize this so it is intotal 1: + # Normalise this so it is in total 1: result = weighted_fractions_array/np.sum(weighted_fractions_array) verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: Normalizing with {}. result: {}".format("norm", result), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: Normalising with {}. result: {}".format("norm", result), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1189,17 +1188,17 @@ def Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity=0): # (i.e. not multiplied by multiplier) and do the merging result = merge_multiplicities(full_fractions_array, max_multiplicity, verbosity=verbosity) - # Then normalize to be sure + # Then normalise to be sure result = result/np.sum(result) verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: Normalizing with {}, max_multiplicity={} result={}".format("merge", max_multiplicity, result), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: Normalising with {}, max_multiplicity={} result={}".format("merge", max_multiplicity, result), verbosity, _MS_VERBOSITY_LEVEL, ) verbose_print( - "\tM&S: Moe_de_Stefano_2017_multiplicity_fractions: {}".format(str(result)), + "\tM&S: Moe_di_Stefano_2017_multiplicity_fractions: {}".format(str(result)), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1227,7 +1226,7 @@ def build_q_table(options, m, p, verbosity=0): # Since the information from the table for M&S is independent of any choice we make, # we need to take into account that for example our choice of minimum mass leads to # a minimum q_min that is not the same as in the table - # We should ignore those parts of the table and renormalize. + # We should ignore those parts of the table and renormalise. # If we are below the lowest value of qmin in the table we need to extrapolate the data # # Anyway, the goal of this function is to provide some extrapolated values for q when we should sample outside of the boundaries @@ -1309,7 +1308,7 @@ def build_q_table(options, m, p, verbosity=0): require_extrapolation["low"] = 0 require_extrapolation[ "high" - ] = 1 # TODO: shouldnt the extrapolation need to happen if qmax > 0.95 + ] = 1 # TODO: shouldn't the extrapolation need to happen if qmax > 0.95 qdata[qmin] = Moecache["rinterpolator_q"].interpolate( [np.log10(options[m]), np.log10(options[p]), qmin] )[0] @@ -1412,7 +1411,7 @@ def build_q_table(options, m, p, verbosity=0): ) continue elif method == "flat": - # use the end value value and extrapolate it + # use the end value and extrapolate it # with zero slope qdata[qlimit] = qdata[qs[end_index]] verbose_print( @@ -1465,7 +1464,7 @@ def build_q_table(options, m, p, verbosity=0): _MS_VERBOSITY_LEVEL, ) elif method=="poly": - # TODO: consider implementing the poly method (see perl version) + # TODO: consider implementing the poly method (see Perl version) raise ValueError("M&S: build_q_table: Method 'poly' not implemented") else: @@ -1499,16 +1498,16 @@ def build_q_table(options, m, p, verbosity=0): if can_renormalize: verbose_print( - "\tM&S: build_q_table: Renormalizing table", + "\tM&S: build_q_table: Renormalising table", verbosity, _MS_VERBOSITY_LEVEL, ) - # now we integrate and renormalize (if the table is not all zero) + # now we integrate and renormalise (if the table is not all zero) I = get_integration_constant_q(q_interpolator, tmp_table, qdata, verbosity=verbosity) if I > 0: - # normalize to 1.0 by dividing the data by 1.0/$I + # normalise to 1.0 by dividing the data by 1.0/$I q_interpolator.multiply_table_column(1, 1.0 / I) # test this @@ -1542,7 +1541,7 @@ def build_q_table(options, m, p, verbosity=0): def powerlaw_extrapolation_q(qdata, qs, indices, verbosity=0): """ - Function to do the powerlaw extrapolation at the lower end of the q range + Function to do the power law extrapolation at the lower end of the q range """ newq = 0.05 @@ -1596,7 +1595,7 @@ def get_integration_constant_q(q_interpolator, tmp_table, qdata, verbosity=0): Function to integrate the q interpolator and return the integration constant """ - dq = 1e-3 # resolution of the integration/renormalization + dq = 1e-3 # resolution of the integration/renormalisation I = 0 # integrate: note that the value of the integral is @@ -1625,7 +1624,7 @@ def get_integration_constant_q(q_interpolator, tmp_table, qdata, verbosity=0): def fill_data(sample_values, data_dict): """ - Function that returns the normalized array of values for given logmass and logperiod + Function that returns the normalised array of values for given logmass and logperiod used for the e and q values TODO: make sure we do the correct thing with the dstep @@ -1642,7 +1641,7 @@ def fill_data(sample_values, data_dict): data[sample_value] = val I += val - # Normalize the data + # Normalise the data for sample_value in sample_values: data[sample_value] = data[sample_value] / I @@ -1655,7 +1654,7 @@ def calc_e_integral( """ Function to calculate the P integral - We need to renormalize this because min_per > 0, and not all periods should be included + We need to renormalise this because min_per > 0, and not all periods should be included """ global Moecache @@ -1706,7 +1705,7 @@ def calc_P_integral( """ Function to calculate the P integral - We need to renormalize this because min_per > 0, and not all periods should be included + We need to renormalise this because min_per > 0, and not all periods should be included """ global Moecache @@ -1759,9 +1758,9 @@ def calc_total_probdens(prob_dict): return prob_dict -def Moe_de_Stefano_2017_pdf(options, verbosity=0): +def Moe_di_Stefano_2017_pdf(options, verbosity=0): """ - Moe & distefano function to calculate the probability density. + Moe & diStefano function to calculate the probability density. takes a dictionary as input (in options) with options: @@ -1774,7 +1773,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): """ verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf with options:\n\t\t{}".format( + "\tM&S: Moe_di_Stefano_2017_pdf with options:\n\t\t{}".format( json.dumps(options) ), verbosity, @@ -1786,7 +1785,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Get the multiplicity from the options, and if its not there, calculate it based on the # TODO: the function below makes no sense. We NEED to pass the multiplicity in the if not options.get("multiplicity", None): - msg = "\tM&S: Moe_de_Stefano_2017_pdf: Did not find a multiplicity value in the options dictionary" + msg = "\tM&S: Moe_di_Stefano_2017_pdf: Did not find a multiplicity value in the options dictionary" verbose_print( msg, verbosity, @@ -1802,7 +1801,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Immediately return 0 if the multiplicity modulator is 0 if options["multiplicity_modulator"][multiplicity - 1] == 0: verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: returning 0 because of the multiplicity modulator being 0", + "\tM&S: Moe_di_Stefano_2017_pdf: returning 0 because of the multiplicity modulator being 0", verbosity, _MS_VERBOSITY_LEVEL, ) @@ -1810,12 +1809,12 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ############################################################ # multiplicity fraction - # Calculate the probabilty, or rather, fraction, of stars that belong to this mass + # Calculate the probability, or rather, fraction, of stars that belong to this mass - multiplicity_probability = Moe_de_Stefano_2017_multiplicity_fractions(options, verbosity)[multiplicity - 1] + multiplicity_probability = Moe_di_Stefano_2017_multiplicity_fractions(options, verbosity)[multiplicity - 1] prob_dict['multiplicity'] = multiplicity_probability verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended multiplicity (mass1 = {}) probability ({}) to the prob dict ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended multiplicity (mass1 = {}) probability ({}) to the prob dict ({})".format( options["M_1"], prob_dict['multiplicity'], prob_dict ), verbosity, @@ -1828,12 +1827,12 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # NB multiply by M1 to convert dN/dM to dN/dlnM # (dlnM = dM/M, so 1/dlnM = M/dM) - # TODO: Create an n-part-powerlaw method that can have breakpoints and slopes. I'm using a three-part powerlaw now. - # TODO: is this actually the correct way? putting the M1 in there? Do we sample in logspace? + # TODO: Create an n-part-powerlaw method that can have breakpoints and slopes. I'm using a three-part power law now. + # TODO: is this actually the correct way? putting the M1 in there? Do we sample in log space? M1_probability = Kroupa2001(options["M_1"]) * options["M_1"] prob_dict['M_1'] = M1_probability verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended Mass (m={}) probability ({}) to the prob dict ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended Mass (m={}) probability ({}) to the prob dict ({})".format( options["M_1"], prob_dict['M_1'], prob_dict ), verbosity, @@ -1861,7 +1860,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): verbosity=verbosity - (_MS_VERBOSITY_INTERPOLATOR_LEVEL - 1), ) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Created new period interpolator: {}".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Created new period interpolator: {}".format( Moecache["rinterpolator_log10P"] ), verbosity, @@ -1878,7 +1877,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): verbosity=verbosity - (_MS_VERBOSITY_INTERPOLATOR_LEVEL - 1), ) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Created new q interpolator: {}".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Created new q interpolator: {}".format( Moecache["rinterpolator_q"] ), verbosity, @@ -1896,7 +1895,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): verbosity=verbosity - (_MS_VERBOSITY_INTERPOLATOR_LEVEL - 1), ) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Created new e interpolator: {}".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Created new e interpolator: {}".format( Moecache["rinterpolator_e"] ), verbosity, @@ -1928,7 +1927,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): p_val = p_val / Moecache["P_integrals"][options["M_1"]] prob_dict['P'] = p_val verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended period (m={}, P={}) probability ({}) to the prob list ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended period (m={}, P={}) probability ({}) to the prob list ({})".format( options["M_1"], options["P"], prob_dict['P'], prob_dict ), verbosity, @@ -1954,7 +1953,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Construct the q table build_q_table(options, m_label, p_label, verbosity=verbosity) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Created q_table ({}) for m={} p={}".format(Moecache[ + "\tM&S: Moe_di_Stefano_2017_pdf: Created q_table ({}) for m={} p={}".format(Moecache[ "rinterpolator_q_given_{}_log10{}".format(m_label, p_label) ], options[m_label], options[p_label]), verbosity, @@ -1967,7 +1966,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ].interpolate([secondary_mass / primary_mass])[0] prob_dict['q'] = q_prob verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: appended mass ratio (M={} P={} q={}) probability ({}) to the prob list ({}) ".format( + "\tM&S: Moe_di_Stefano_2017_pdf: appended mass ratio (M={} P={} q={}) probability ({}) to the prob list ({}) ".format( options["M_1"], options["P"], options["M_2"] / options["M_1"], @@ -1994,14 +1993,14 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ) mass_period_string = "{}_{}".format(options["M_1"], options["P"]) - # Set probabilty for ecc + # Set probability for ecc ecc_val = Moecache["rinterpolator_e"].interpolate( [np.log10(options["M_1"]), np.log10(options["P"]), options["ecc"]] )[0] ecc_val = ecc_val / Moecache["ecc_integrals"][mass_period_string] prob_dict['ecc'] = ecc_val verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended eccentricity (m={}, P={}, ecc={}) probability ({}) to the prob list ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended eccentricity (m={}, P={}, ecc={}) probability ({}) to the prob list ({})".format( options["M_1"], options["P"], options["ecc"], prob_dict['ecc'], prob_dict ), verbosity, @@ -2034,7 +2033,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # period is too short : system is not hierarchical prob_dict['P2'] = 0 verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: period2 is too short: {} < {}, system is not hierarchichal. Added 0 to probability list".format( + "\tM&S: Moe_di_Stefano_2017_pdf: period2 is too short: {} < {}, system is not hierarchical. Added 0 to probability list".format( options["P1"], min_P2 ), verbosity, @@ -2069,7 +2068,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): p_val = p_val / Moecache["P2_integrals"][options["M_1+M_2"]] prob_dict['P2'] = p_val verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended period2 (m1={} m2={}, P2={}) probability ({}) to the prob list ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended period2 (m1={} m2={}, P2={}) probability ({}) to the prob list ({})".format( options["M_1"], options["M_2"], options["P2"], prob_dict['P2'], prob_dict ), verbosity, @@ -2094,7 +2093,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Build q table build_q_table(options, m_label, p_label, verbosity=verbosity) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Called build_q_table", + "\tM&S: Moe_di_Stefano_2017_pdf: Called build_q_table", verbosity, _MS_VERBOSITY_LEVEL, ) @@ -2105,7 +2104,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ].interpolate([secondary_mass / primary_mass])[0] prob_dict['q2'] = q2_val verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: appended mass ratio (M_1+M_2={} M_3={} P={} q={}) probability ({}) to the prob list ({}) ".format( + "\tM&S: Moe_di_Stefano_2017_pdf: appended mass ratio (M_1+M_2={} M_3={} P={} q={}) probability ({}) to the prob list ({}) ".format( options["M_1+M_2"], options["M_3"], options["P"], @@ -2123,7 +2122,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # TODO: Implement ecc2 calculation if multiplicity == 4: # quadruple system. - # TODO: Ask Rob about the strructure of the quadruple. Is this only double binary quadrupples? + # TODO: Ask Rob about the structure of the quadruple. Is this only double binary quadruples? ############################################################ # orbital period 3 @@ -2156,7 +2155,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): p_val = p_val / Moecache["P2_integrals"][options["M_1+M_2"]] prob_dict['P3'] = p_val verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Appended period2 (M=4) (M_1={} M_2={}, P2={}) probability ({}) to the prob list ({})".format( + "\tM&S: Moe_di_Stefano_2017_pdf: Appended period2 (M=4) (M_1={} M_2={}, P2={}) probability ({}) to the prob list ({})".format( options["M_1"], options["M_2"], options["P2"], prob_dict['P3'], prob_dict ), verbosity, @@ -2182,7 +2181,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Calculate new q table build_q_table(options, m_label, p_label, verbosity=verbosity) verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: Created q_table ".format(), + "\tM&S: Moe_di_Stefano_2017_pdf: Created q_table ".format(), verbosity, _MS_VERBOSITY_LEVEL, ) @@ -2193,7 +2192,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ].interpolate([secondary_mass / primary_mass])[0] prob_dict['q3'] = q3_prob verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: appended mass ratio (M_1+M_2={} M_3={} P={} q={}) probability ({}) to the prob list ({}) ".format( + "\tM&S: Moe_di_Stefano_2017_pdf: appended mass ratio (M_1+M_2={} M_3={} P={} q={}) probability ({}) to the prob list ({}) ".format( options["M_1+M_2"], options["M_3"], options["P"], @@ -2212,7 +2211,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # check for input of multiplicity elif multiplicity not in range(1, 5): - msg = "\tM&S: Moe_de_Stefano_2017_pdf: Unknown multiplicity {}".format( + msg = "\tM&S: Moe_di_Stefano_2017_pdf: Unknown multiplicity {}".format( multiplicity ) verbose_print( @@ -2228,7 +2227,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): # Some info if multiplicity == 1: verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: M_1={} q=N/A log10P=N/A ({}): {} -> {}\n".format( + "\tM&S: Moe_di_Stefano_2017_pdf: M_1={} q=N/A log10P=N/A ({}): {} -> {}\n".format( options["M_1"], len(prob_dict), str(prob_dict), @@ -2239,7 +2238,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ) elif multiplicity == 2: verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} ({}): {} -> {}\n".format( + "\tM&S: Moe_di_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} ({}): {} -> {}\n".format( options["M_1"], options["M_2"] / options["M_1"] if options.get("M_2", None) else "N/A", np.log10(options["P"]), @@ -2253,7 +2252,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ) elif multiplicity == 3: verbose_print( - "\tM&S: Moe_de_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} M_3={} log10P2={} ecc2={} ({}): {} -> {}".format( + "\tM&S: Moe_di_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} M_3={} log10P2={} ecc2={} ({}): {} -> {}".format( options["M_1"], options["M_2"] / options["M_1"] if options.get("M_2", None) else "N/A", np.log10(options["P"]), @@ -2270,7 +2269,7 @@ def Moe_de_Stefano_2017_pdf(options, verbosity=0): ) elif multiplicity == 4: verbose_print( - "M&S: Moe_de_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} M_3={} log10P2={} ecc2={} M_4={} log10P3={} ecc3={} ({}) : {} -> {}".format( + "M&S: Moe_di_Stefano_2017_pdf: M_1={} q={} log10P={} ecc={} M_3={} log10P2={} ecc2={} M_4={} log10P3={} ecc3={} ({}) : {} -> {}".format( options["M_1"], options["M_2"] / options["M_1"] if options.get("M_2", None) else "N/A", np.log10(options["P"]), diff --git a/binarycpython/utils/functions.py b/binarycpython/utils/functions.py index 4eceb3b62..4ac89ca02 100644 --- a/binarycpython/utils/functions.py +++ b/binarycpython/utils/functions.py @@ -84,7 +84,7 @@ def subtract_dicts(dict_1: dict, dict_2: dict) -> dict: - If the types are of numerical type: subtract the value at dict 2 from dict 1. - If the types are both dictionaries: call this function with the subdicts - WHen the keys are not of the same type: + When the keys are not of the same type: - if the keys are all of numerical types For the unique keys: @@ -213,9 +213,9 @@ def subtract_dicts(dict_1: dict, dict_2: dict) -> dict: return new_dict -def get_moe_distefano_dataset(options, verbosity=0): +def get_moe_di_stefano_dataset(options, verbosity=0): """ - Function to get the default moe and Distefano dataset or accept a userinput. + Function to get the default moe and di Stefano dataset or accept a user input. """ if not options.get("file", None): @@ -246,7 +246,7 @@ def get_moe_distefano_dataset(options, verbosity=0): ) else: - # Read input data and Clean up the data if there are whitespaces around the keys + # Read input data and Clean up the data if there are white spaces around the keys with open(options["file"], "r") as data_filehandle: datafile_data = data_filehandle.read() datafile_data = datafile_data.replace('" ', '"') @@ -363,11 +363,11 @@ def remove_file(file: str, verbosity: int = 0) -> None: Function to remove files but with verbosity Args: - file: full filepath to the file that will be removed. + file: full file path to the file that will be removed. verbosity: current verbosity level (Optional) Returns: - the path of a subdirectory called binary_c_python in the TMP of the filesystem + the path of a sub directory called binary_c_python in the TMP of the file system """ @@ -393,7 +393,7 @@ def remove_file(file: str, verbosity: int = 0) -> None: def temp_dir(*args: str) -> str: """ - Function to create directory within the TMP directory of the filesystem + Function to create directory within the TMP directory of the file system Makes use of os.makedirs exist_ok which requires python 3.2+ @@ -401,7 +401,7 @@ def temp_dir(*args: str) -> str: function arguments: str input where each next input will be a child of the previous full_path. e.g. temp_dir('tests', 'grid') will become '/tmp/binary_c_python/tests/grid' Returns: - the path of a subdirectory called binary_c_python in the TMP of the filesystem + the path of a sub directory called binary_c_python in the TMP of the file system """ tmp_dir = tempfile.gettempdir() @@ -424,7 +424,7 @@ def create_hdf5(data_dir: str, name: str) -> None: - settings file is selected by checking on files ending on settings - data files are selected by checking on files ending with .dat - TODO: fix missing settingsfiles + TODO: fix missing settings files Args: data_dir: directory containing the data files and settings file @@ -507,7 +507,7 @@ def return_binary_c_version_info(parsed: bool = False) -> Union[str, dict]: found_prev = False if "BINARY_C_MACRO_HEADER" in os.environ: - # the envvar is already present. lets save that and put that back later + # the env var is already present. lets save that and put that back later found_prev = True prev_value = os.environ["BINARY_C_MACRO_HEADER"] @@ -623,7 +623,7 @@ def parse_binary_c_version_info(version_info_string: str) -> dict: version_info_dict["isotopes"] = isotope_dict if isotope_dict else None ########################## - # Argpairs: + # Arg pairs: # Split off argpairs = set([el for el in cleaned if el.startswith("ArgPair")]) cleaned = cleaned - argpairs @@ -747,7 +747,7 @@ def parse_binary_c_version_info(version_info_string: str) -> dict: ########################## # miscellaneous: - # All those that I didnt catch with the above filters. Could try to get some more out though. + # All those that I didn't catch with the above filters. Could try to get some more out though. # TODO: filter a bit more. misc_dict = {} @@ -803,7 +803,7 @@ def parse_binary_c_version_info(version_info_string: str) -> dict: def output_lines(output: str) -> list: """ - Function that outputs the lines that were recieved from the binary_c run, but now as an iterator. + Function that outputs the lines that were received from the binary_c run, but now as an iterator. Args: output: raw binary_c output @@ -825,7 +825,7 @@ def example_parse_output(output: str, selected_header: str) -> dict: This function works in two cases: if the caught line contains output like 'example_header time=12.32 mass=0.94 ..' or if the line contains output like 'example_header 12.32 0.94' - Please dont the two cases. + Please don't the two cases. You can give a 'selected_header' to catch any line that starts with that. Then the values will be put into a dictionary. @@ -879,7 +879,7 @@ def example_parse_output(output: str, selected_header: str) -> dict: if len(value_dicts) == 0: print( - "Sorry, didnt find any line matching your header {}".format(selected_header) + "Sorry, didn't find any line matching your header {}".format(selected_header) ) return None @@ -946,7 +946,7 @@ def filter_arg_dict(arg_dict: dict) -> dict: This function is called by get_defaults() Args: - arg_dict: dictionary containing the argument + default keypairs of binary_c + arg_dict: dictionary containing the argument + default key pairs of binary_c Returns: filtered dictionary (pairs with NULL and Function values are removed) @@ -1116,10 +1116,10 @@ def get_help( def get_help_all(print_help: bool = True) -> dict: """ - Function that reads out the output of the return_help_all api call to binary_c. This return_help_all binary_c returns all the information for the parameters, their descriptions and other properties. The output is categorized in sections. + Function that reads out the output of the return_help_all API call to binary_c. This return_help_all binary_c returns all the information for the parameters, their descriptions and other properties. The output is categorised in sections. Args: - print_help: (optional, default = Tru) prints all the parameters and their descriptions. + print_help: (optional, default = True) prints all the parameters and their descriptions. Returns: returns a dictionary containing dictionaries per section. These dictionaries contain the parameters and descriptions etc for all the parameters in that section @@ -1165,7 +1165,7 @@ def get_help_all(print_help: bool = True) -> dict: for split_param in split_params: split_param_info = split_param.split(" : ") if not len(split_param_info) == 3: - # there are ocassions where the semicolon + # there are occasions where the semicolon # is used in the description text itself. if len(split_param_info) == 4: split_param_info = [ @@ -1174,7 +1174,7 @@ def get_help_all(print_help: bool = True) -> dict: split_param_info[3], ] - # other occassions? + # other occasions? # Put the information in a dict param_name = split_param_info[0] @@ -1329,7 +1329,7 @@ def write_binary_c_parameter_descriptions_to_rst_file(output_file: str) -> None: this document Args: - output_file: name of the output .rst faile containing the ReStructuredText formatted output + output_file: name of the output .rst file containing the ReStructuredText formatted output of all the binary_c parameters. """ @@ -1381,13 +1381,13 @@ def write_binary_c_parameter_descriptions_to_rst_file(output_file: str) -> None: ######################################################## -# logfile functions +# log file functions ######################################################## def load_logfile(logfile: str) -> None: """ - Experimental function that parses the generated logfile of binary_c. + Experimental function that parses the generated log file of binary_c. This function is not finished and shouldn't be used yet. @@ -1395,7 +1395,7 @@ def load_logfile(logfile: str) -> None: - TODO: Args: - - logfile: filename of the logfile you want to parse + - logfile: filename of the log file you want to parse Returns: @@ -1783,7 +1783,7 @@ def custom_sort_dict(input_dict): if not type(key) in all_types_keys: all_types_keys.append(type(key)) - # If there are multiple types, then we loop over them and do a piecewise sort + # If there are multiple types, then we loop over them and do a piece wise sort if len(all_types_keys) > 1: msg = "Different types in the same dictionary key set" @@ -1838,7 +1838,7 @@ def extract_ensemble_json_from_string(binary_c_output: str) -> dict: binary_c_output: raw binary_c output string Returns: - json dictionary with the parsed ENSEMBLE_JSON data + JSON dictionary with the parsed ENSEMBLE_JSON data """ json_dict = None @@ -1920,7 +1920,7 @@ class BinaryCEncoder(json.JSONEncoder): def default(self, o): """ - Converting function. Well, could be more precise. look at the json module + Converting function. Well, could be more precise. look at the JSON module """ try: str_repr = str(o) @@ -1935,13 +1935,13 @@ class BinaryCEncoder(json.JSONEncoder): def binaryc_json_serializer(obj: Any) -> Any: """ - Custom serializer for binary_c to use when functions are present in the dictionary + Custom serialiser for binary_c to use when functions are present in the dictionary that we want to export. Function objects will be turned into str representations of themselves Args: - obj: The object that might not be serializable + obj: The object that might not be serialisable Returns: Either string representation of object if the object is a function, or the object itself diff --git a/binarycpython/utils/grid.py b/binarycpython/utils/grid.py index 27d32cc9f..3e23b29da 100644 --- a/binarycpython/utils/grid.py +++ b/binarycpython/utils/grid.py @@ -45,7 +45,7 @@ import py_rinterpolate from binarycpython.utils.grid_options_defaults import ( grid_options_defaults_dict, - moe_distefano_default_options, + moe_di_stefano_default_options, _MS_VERBOSITY_LEVEL, ) @@ -65,7 +65,7 @@ from binarycpython.utils.functions import ( merge_dicts, update_dicts, extract_ensemble_json_from_string, - get_moe_distefano_dataset, + get_moe_di_stefano_dataset, recursive_change_key_to_float, custom_sort_dict, recursive_change_key_to_string, @@ -88,7 +88,7 @@ from binarycpython.utils.distribution_functions import ( get_max_multiplicity, Arenou2010_binary_fraction, raghavan2010_binary_fraction, - Moe_de_Stefano_2017_multiplicity_fractions, + Moe_di_Stefano_2017_multiplicity_fractions, ) from binarycpython import _binary_c_bindings @@ -345,7 +345,7 @@ class Population: def last_grid_variable(self): """ - Functon that returns the last grid variable + Function that returns the last grid variable (i.e. the one with the highest grid_variable_number) """ @@ -376,7 +376,7 @@ class Population: """ Function to add grid variables to the grid_options. - The execution of the grid generation will be through a nested forloop. + The execution of the grid generation will be through a nested for loop. Each of the grid variables will get create a deeper for loop. The real function that generates the numbers will get written to a new file in the TMP_DIR, @@ -426,7 +426,7 @@ class Population: Examples: precode = 'M_1=math.exp(lnm1);' probdist: - FUnction determining the probability that gets asigned to the sampled parameter + Function determining the probability that gets assigned to the sampled parameter Examples: probdist = 'Kroupa2001(M_1)*M_1' @@ -445,8 +445,7 @@ class Population: (steps starting at lower edge + 0.5 * stepsize). """ - # TODO: Add check for the gridtype input value - # TODO: add functionality for branchpoint + # TODO: Add check for the grid type input value # Add grid_variable grid_variable = { @@ -481,7 +480,7 @@ class Population: """ Function that returns all the options that have been set. - Can be combined with json to make a nice file. + Can be combined with JSON to make a nice file. Returns: dictionary containing "bse_options", "grid_options", "custom_options" @@ -571,14 +570,14 @@ class Population: include_binary_c_help_all: bool = True, ) -> Union[str, None]: """ - Function that exports the all_info to a json file + Function that exports the all_info to a JSON file Tasks: - - TODO: if any of the values in the dicts here is of a not-serializable form, then we + - TODO: if any of the values in the dicts here is of a not-serialisable form, then we need to change that to a string or something so, use a recursive function that goes over the all_info dict and finds those that fit - TODO: Fix to write things to the directory. which options do which etc - - TODO: theres flawed logic here. rewrite this part pls + - TODO: there's flawed logic here. rewrite this part pls - TODO: consider actually just removing the whole 'output to file' part and let the user do this. @@ -591,7 +590,7 @@ class Population: version info (see return_binary_c_version_info) include_binary_c_help_all: whether to include a dict containing all the information about the binary_c parameters (see get_help_all) - use_datadir: boolean whether to use the custom_options['data_dir'] to write the file to. + use_datadir: Boolean whether to use the custom_options['data_dir'] to write the file to. If the custom_options["base_filename"] is set, the output file will be called <custom_options["base_filename"]>_settings.json. Otherwise a file called simulation_<date+time>_settings.json will be created @@ -681,7 +680,7 @@ class Population: verbose=self.grid_options["verbosity"], ) - # Load memory adress + # Load memory address ( self.grid_options["custom_logging_func_memaddr"], self.grid_options["_custom_logging_shared_library_file"], @@ -703,7 +702,7 @@ class Population: logging_line, verbose=self.grid_options["verbosity"] ) - # Load memory adress + # Load memory address ( self.grid_options["custom_logging_func_memaddr"], self.grid_options["_custom_logging_shared_library_file"], @@ -733,13 +732,13 @@ class Population: def evolve(self) -> None: """ - Entrypoint function of the whole object. From here, based on the settings, + Entry point function of the whole object. From here, based on the settings, we set up a SLURM or CONDOR grid, or if no setting is given we go straight to evolving the population There are no direct arguments to this function, rather it is based on the grid_options settings: - grid_options['slurm']: integer boolean whether to use a slurm_grid evolution - grid_options['condor']: integer boolean whether to use a condor_grid evolution + grid_options['slurm']: integer Boolean whether to use a slurm_grid evolution + grid_options['condor']: integer Boolean whether to use a condor_grid evolution If neither of the above is set, we continue without using HPC routines (that doesn't mean this cannot be run on a server with many cores) @@ -753,7 +752,7 @@ class Population: # Check which type: if self.grid_options["slurm"] == 1: - # Execute slurm subroutines + # Execute Slurm subroutines self._slurm_grid() elif self.grid_options["condor"] == 1: @@ -916,7 +915,7 @@ class Population: generator = self.grid_options["_system_generator"](self, print_results=False) # TODO: build in method to handle with the HPC. - # Continously fill the queue + # Continuously fill the queue for system_number, system_dict in enumerate(generator): # Put job in queue job_queue.put((system_number, system_dict)) @@ -979,13 +978,13 @@ class Population: """ Function that handles running the population using multiprocessing. - First we set uip the multiprocessing manager and the job and result queue. + First we set up the multiprocessing manager and the job and result queue. Then we spawn <self.grid_options["amt_cores"]> amount of process instances, and signal them to start. While the processes are waiting for their instructions, we start the queue filler, - which goes over the gridcode and puts all the tasks in a queue until its full. + which goes over the grid code and puts all the tasks in a queue until its full. The processes take these jobs, evolve the and store results. @@ -997,7 +996,7 @@ class Population: # Set process name setproctitle.setproctitle('binarycpython parent process') - setproctitle.setthreadtitle("binarycpyhon parent thread") + setproctitle.setthreadtitle("binarycpython parent thread") # Set up the manager object that can share info between processes manager = multiprocessing.Manager() @@ -1174,9 +1173,9 @@ class Population: 0, ) - # Set the ensemble memaddr + # Set the ensemble memory address if self.bse_options.get("ensemble", 0) == 1: - # set persistent data memaddr if necessary. + # set persistent data memory address if necessary. persistent_data_memaddr = ( _binary_c_bindings.return_persistent_data_memaddr() ) @@ -1243,7 +1242,7 @@ class Population: # they match the keys known to binary_c. # Won't do that every system cause that is a bit of a waste of computing time. if number_of_systems_run == 0: - # TODO: Put this someplace else and wrap in a functioncall + # TODO: Put this someplace else and wrap in a function call for key in full_system_dict.keys(): if not key in self.available_keys: # Deal with special keys @@ -1362,7 +1361,7 @@ class Population: ensemble_json = {} # Make sure it exists already if self.bse_options.get("ensemble", 0) == 1: verbose_print( - "Process {}: is freeing ensemble output (using persisten_data memaddr {})".format( + "Process {}: is freeing ensemble output (using persistent_data memaddr {})".format( ID, self.persistent_data_memory_dict[self.process_ID] ), self.grid_options["verbosity"], @@ -1417,7 +1416,7 @@ class Population: ) ) - # free store mem: + # free store memory: _binary_c_bindings.free_store_memaddr(self.grid_options["_store_memaddr"]) # Return a set of results and errors @@ -1501,7 +1500,7 @@ class Population: # Clean up the interpolators if they exist # TODO: make a cleanup function for the individual threads - # TODO: make sure this is necessary. Actually its probably not, because we have a centralized queue + # TODO: make sure this is necessary. Actually its probably not, because we have a centralised queue return @@ -1536,7 +1535,7 @@ class Population: population=0, ) - # TODO: add call to function that cleans up the temp customlogging dir, + # TODO: add call to function that cleans up the temp custom logging dir, # and unloads the loaded libraries. # TODO: make a switch to turn this off @@ -1605,14 +1604,14 @@ class Population: [key.startswith("ensemble_filter_") for key in self.bse_options] ): verbose_print( - "Warning: Running the ensemble without any filter requires alot of available RAM", + "Warning: Running the ensemble without any filter requires a lot of available RAM", self.grid_options["verbosity"], 0, ) if self.bse_options.get("ensemble_filters_off", 0) != 1: verbose_print( - "Warning: Running the ensemble without any filter requires alot of available RAM", + "Warning: Running the ensemble without any filter requires a lot of available RAM", self.grid_options["verbosity"], 0, ) @@ -1620,7 +1619,7 @@ class Population: if self.grid_options["combine_ensemble_with_thread_joining"] == False: if not self.custom_options.get("data_dir", None): verbose_print( - "Error: chosen to write the ensemble output directly to files but data_dir isnt set", + "Error: chosen to write the ensemble output directly to files but data_dir isn't set", self.grid_options["verbosity"], 0, ) @@ -1634,7 +1633,7 @@ class Population: # Put in check if len(self.grid_options["_grid_variables"]) == 0: - print("Error: you havent defined any grid variables! Aborting") + print("Error: you haven't defined any grid variables! Aborting") raise ValueError # Set up the grid code with a dry run option to see total probability @@ -1744,7 +1743,7 @@ class Population: del Moecache[key] ################################################### - # Gridcode functions + # Grid code functions # # Function below are used to run populations with # a variable grid @@ -1762,13 +1761,13 @@ class Population: # TODO: Add correct logging everywhere # TODO: add part to handle separation if orbital_period is added. Idea. use default values # for orbital parameters and possibly overwrite those or something. - # TODO: add centering center left right for the spacing. + # TODO: add centre left right for the spacing. # TODO: add sensible description to this function. # TODO: Check whether all the probability and phasevol values are correct. # TODO: import only the necessary packages/functions # TODO: Put all the masses, eccentricities and periods in there already - # TODO: Put the certain blocks that are repeated in some subfunctions - # TODO: make sure running systems with multicplity 3+ is also possible. + # TODO: Put the certain blocks that are repeated in some sub functions + # TODO: make sure running systems with multiplicity 3+ is also possible. Results in a generated file that contains a system_generator function. """ @@ -1872,8 +1871,8 @@ class Population: grid_variable = grid_variable_el[1] ######################### - # Setting up the forloop - # Add comment for forloop + # Setting up the for loop + # Add comment for for loop code_string += ( indent * depth + "# for loop for {}".format(grid_variable["parameter_name"]) @@ -1927,7 +1926,7 @@ class Population: ) ################################################################################# - # Check condition and generate forloop + # Check condition and generate for loop # If the grid variable has a condition, write the check and the action if grid_variable["condition"]: @@ -1955,7 +1954,7 @@ class Population: ) code_string += indent * (depth + 2) + "continue" + "\n" - # Add some whiteline + # Add some white line code_string += indent * (depth + 1) + "\n" ##############3 @@ -1976,7 +1975,7 @@ class Population: ) code_string += indent * (depth + 2) + "continue" + "\n" - # Add some whiteline + # Add some white line code_string += indent * (depth + 1) + "\n" ######################### @@ -2068,7 +2067,7 @@ class Population: # The final parts of the code, where things are returned, are within the deepest loop, # but in some cases code from a higher loop needs to go under it again - # SO I think its better to put an ifstatement here that checks + # SO I think its better to put an if statement here that checks # whether this is the last loop. if loopnr == len(self.grid_options["_grid_variables"]) - 1: @@ -2106,7 +2105,7 @@ class Population: ) # Set phasevol - # TODO: fix. this isnt supposed to be the value that we give it here. discuss + # TODO: fix. this isn't supposed to be the value that we give it here. discuss code_string += indent * (depth + 1) + "phasevol /= phasevol_{}\n".format( grid_variable["name"] ) @@ -2176,7 +2175,7 @@ class Population: ################################################################################# # Stop of code generation. Here the code is saved and written - # Save the gridcode to the grid_options + # Save the grid code to the grid_options verbose_print( "Saving grid code to grid_options", self.grid_options["verbosity"], 1 ) @@ -2320,7 +2319,7 @@ class Population: def _load_grid_function(self): """ - Functon that loads the script containing the grid code. + Function that loads the script containing the grid code. TODO: Update this description Test function to run grid stuff. mostly to test the import @@ -2392,10 +2391,10 @@ class Population: print(info_string) ################################################### - # Montecarlo functions + # Monte Carlo functions # # Functions below are used to run populations with - # Monte carlo + # Monte Carlo ################################################### ################################################### @@ -2438,7 +2437,7 @@ class Population: minimal_verbosity=1, ) - # We can choose to perform a check on the sourcefile, which checks if the lines start with 'binary_c' + # We can choose to perform a check on the source file, which checks if the lines start with 'binary_c' if check: source_file_check_filehandle = open( self.grid_options["source_file_filename"], "r" @@ -2463,7 +2462,7 @@ class Population: def _dict_from_line_source_file(self, line): """ - Function that creates a dict from a binary_c argline + Function that creates a dict from a binary_c arg line """ if line.startswith("binary_c "): @@ -2962,18 +2961,16 @@ class Population: include_defaults: bool = False, ) -> None: """ - Function that loops over the gridcode and writes the generated parameters to a file. - In the form of a commandline call + Function that loops over the grid code and writes the generated parameters to a file. + In the form of a command line call - Only useful when you have a variable grid as system_generator. MC wouldnt be that useful + Only useful when you have a variable grid as system_generator. MC wouldn't be that useful Also, make sure that in this export there are the basic parameters like m1,m2,sep, orb-per, ecc, probability etc. On default this will write to the datadir, if it exists - WARNING; dont use yet. not fully tested. - Tasks: - TODO: test this function - TODO: make sure the binary_c_python .. output file has a unique name @@ -2981,7 +2978,7 @@ class Population: Args: output_dir: (optional, default = None) directory where to write the file to. If custom_options['data_dir'] is present, then that one will be used first, and then the output_dir output_filename: (optional, default = None) filename of the output. If not set it will be called "binary_c_calls.txt" - include_defaults: (optional, default = None) whether to include the defaults of binary_c in the lines that are written. Beware that this will result in very long lines, and it might be better to just export the binary_c defaults and keep them in a seperate file. + include_defaults: (optional, default = None) whether to include the defaults of binary_c in the lines that are written. Beware that this will result in very long lines, and it might be better to just export the binary_c defaults and keep them in a separate file. """ # Check if there is no compiled grid yet. If not, lets try to build it first. @@ -3000,7 +2997,7 @@ class Population: # Put in check if len(self.grid_options["_grid_variables"]) == 0: - print("Error: you havent defined any grid variables! Aborting") + print("Error: you haven't defined any grid variables! Aborting") raise ValueError # @@ -3014,7 +3011,7 @@ class Population: # Check if there is an output dir configured if self.custom_options.get("data_dir", None): binary_c_calls_output_dir = self.custom_options["data_dir"] - # otherwise check if theres one passed to the function + # otherwise check if there's one passed to the function else: if not output_dir: print( @@ -3023,7 +3020,7 @@ class Population: raise ValueError binary_c_calls_output_dir = output_dir - # check if theres a filename passed to the function + # check if there's a filename passed to the function if output_filename: binary_c_calls_filename = output_filename # otherwise use default value @@ -3098,7 +3095,7 @@ class Population: # TODO: Unset custom logging code - # TODO: Unset function memory adress + # TODO: Unset function memory address # print(self.grid_options["custom_logging_func_memaddr"]) # remove shared library files @@ -3116,7 +3113,7 @@ class Population: ) # TODO: make sure that these also work. not fully sure if necessary tho. - # whether its a single file, or a dict of files/memaddresses + # whether its a single file, or a dict of files/mem addresses if evol_type == "MC": pass @@ -3139,7 +3136,7 @@ class Population: Function to set the loggers for the execution of the grid """ - # Set logfile + # Set log file binary_c_logfile = self.grid_options["log_file"] # Create directory @@ -3157,7 +3154,7 @@ class Population: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) - # Make and add filehandlers + # Make and add file handlers # make handler for output to file handler_file = logging.FileHandler(filename=os.path.join(binary_c_logfile)) handler_file.setFormatter(log_formatter) @@ -3233,7 +3230,7 @@ class Population: # If not, write the failing systems to files unique to each process else: - # Write arglines to file + # Write arg lines to file argstring = self._return_argline(system_dict) with open( os.path.join( @@ -3251,9 +3248,9 @@ class Population: 2, ) - def set_moe_distefano_settings(self, options=None): + def set_moe_di_stefano_settings(self, options=None): """ - Function to set user input configurations for the moe & distefano methods + Function to set user input configurations for the moe & di Stefano methods If nothing is passed then we just use the default options """ @@ -3268,14 +3265,14 @@ class Population: with open(os.path.join(os.path.join(self.grid_options["tmp_dir"], "moe_distefano"), "moeopts.dat"), "w") as f: f.write(json.dumps(self.grid_options['m&s_options'], indent=4)) - def _load_moe_distefano_data(self): + def _load_moe_di stefano_data(self): """ - Function to load the moe & distefano data + Function to load the moe & di stefano data """ - # Only if the grid is loaded and moecache contains information + # Only if the grid is loaded and Moecache contains information if (not self.grid_options['_loaded_ms_data']) and not Moecache: - # Load the json data + # Load the JSON data json_data = get_moe_distefano_dataset(self.grid_options['m&s_options'], verbosity=self.grid_options['verbosity']) # entry of log10M1 is a list containing 1 dict. We can take the dict out of the list @@ -3286,7 +3283,7 @@ class Population: if not logmasses: msg = "The table does not contain masses." verbose_print( - "\tMoe_de_Stefano_2017: {}".format(msg), + "\tMoe_di_Stefano_2017: {}".format(msg), self.grid_options["verbosity"], 0, ) @@ -3309,7 +3306,7 @@ class Population: if not (logperiods == current_logperiods): msg = "Period values are not consistent throughout the dataset" verbose_print( - "\tMoe_de_Stefano_2017: {}".format(msg), + "\tMoe_di_Stefano_2017: {}".format(msg), self.grid_options["verbosity"], 0, ) @@ -3325,7 +3322,7 @@ class Population: ): msg = "Period spacing is not consistent throughout the dataset" verbose_print( - "\tMoe_de_Stefano_2017: {}".format(msg), + "\tMoe_di_Stefano_2017: {}".format(msg), self.grid_options["verbosity"], 0, ) @@ -3427,7 +3424,7 @@ class Population: # qs = sorted(json_data["log10M1"][logmass]["logP"][logperiod]["q"]) - # Fill the data and 'normalize' + # Fill the data and 'normalise' qdata = fill_data( qs, json_data["log10M1"][logmass]["logP"][logperiod]["q"] ) @@ -3445,7 +3442,7 @@ class Population: # eccentricity distributions as a function of mass, period, ecc eccs = sorted(json_data["log10M1"][logmass]["logP"][logperiod]["e"]) - # Fill the data and 'normalize' + # Fill the data and 'normalise' ecc_data = fill_data( eccs, json_data["log10M1"][logmass]["logP"][logperiod]["e"] ) @@ -3485,35 +3482,35 @@ class Population: ) verbose_print( - "\tMoe_de_Stefano_2017: Length period_distributions table: {}".format( + "\tMoe_di_Stefano_2017: Length period_distributions table: {}".format( len(Moecache["period_distributions"]) ), self.grid_options["verbosity"], _MS_VERBOSITY_LEVEL, ) verbose_print( - "\tMoe_de_Stefano_2017: Length multiplicity table: {}".format( + "\tMoe_di_Stefano_2017: Length multiplicity table: {}".format( len(Moecache["multiplicity_table"]) ), self.grid_options["verbosity"], _MS_VERBOSITY_LEVEL, ) verbose_print( - "\tMoe_de_Stefano_2017: Length q table: {}".format( + "\tMoe_di_Stefano_2017: Length q table: {}".format( len(Moecache["q_distributions"]) ), self.grid_options["verbosity"], _MS_VERBOSITY_LEVEL, ) verbose_print( - "\tMoe_de_Stefano_2017: Length ecc table: {}".format( + "\tMoe_di_Stefano_2017: Length ecc table: {}".format( len(Moecache["ecc_distributions"]) ), self.grid_options["verbosity"], _MS_VERBOSITY_LEVEL, ) - # Write to logfile + # Write to log file os.makedirs(os.path.join(self.grid_options["tmp_dir"], "moe_distefano"), exist_ok=True) with open(os.path.join(os.path.join(self.grid_options["tmp_dir"], "moe_distefano"), "moecache.json"), "w") as cache_filehandle: cache_filehandle.write(json.dumps(Moecache, indent=4)) @@ -3521,9 +3518,9 @@ class Population: # Signal that the data has been loaded self.grid_options['_loaded_ms_data'] = True - def _set_moe_distefano_distributions(self): + def _set_moe_di_stefano_distributions(self): """ - Function to set the moe & distefano distribution + Function to set the Moe & di Stefano distribution """ ############################################################ @@ -3532,7 +3529,7 @@ class Population: max_multiplicity = get_max_multiplicity(self.grid_options['m&s_options']["multiplicity_modulator"]) verbose_print( - "\tMoe_de_Stefano_2017: Max multiplicity = {}".format(max_multiplicity), + "\tMoe_di_Stefano_2017: Max multiplicity = {}".format(max_multiplicity), self.grid_options["verbosity"], _MS_VERBOSITY_LEVEL, ) @@ -3582,7 +3579,7 @@ class Population: gridtype="centred", dphasevol="dlnm1", precode='M_1 = np.exp(lnm1); options["M_1"]=M_1', - probdist="Moe_de_Stefano_2017_pdf({{{}, {}, {}}}, verbosity=self.grid_options['verbosity'])['total_probdens'] if multiplicity == 1 else 1".format( + probdist="Moe_di_Stefano_2017_pdf({{{}, {}, {}}}, verbosity=self.grid_options['verbosity'])['total_probdens'] if multiplicity == 1 else 1".format( str(dict(self.grid_options['m&s_options']))[1:-1], "'multiplicity': multiplicity", "'M_1': M_1" ), ) @@ -3844,7 +3841,7 @@ eccentricity3=0 # Now we are at the last part. # Here we should combine all the information that we calculate and update the options - # dictionary. This will then be passed to the Moe_de_Stefano_2017_pdf to calculate + # dictionary. This will then be passed to the Moe_di_Stefano_2017_pdf to calculate # the real probability. The trick we use is to strip the options_dict as a string # and add some keys to it: @@ -3863,7 +3860,7 @@ eccentricity3=0 '"ecc3": eccentricity3', ) - probdist_addition = "Moe_de_Stefano_2017_pdf({}, verbosity=self.grid_options['verbosity'])['total_probdens']".format( + probdist_addition = "Moe_di_Stefano_2017_pdf({}, verbosity=self.grid_options['verbosity'])['total_probdens']".format( updated_options ) @@ -3878,7 +3875,7 @@ eccentricity3=0 # ] += "; self.grid_options['m&s_ensemble_options'] = {}".format(o) verbose_print( - "\tMoe_de_Stefano_2017: Added final call to the pdf function".format( + "\tMoe_di_Stefano_2017: Added final call to the pdf function".format( max_multiplicity ), self.grid_options["verbosity"], @@ -3889,16 +3886,16 @@ eccentricity3=0 self.grid_options['_set_ms_grid'] = True ################################################################################################ - def Moe_de_Stefano_2017(self, options=None): + def Moe_di_Stefano_2017(self, options=None): """ Function to handle setting the user input settings, set up the data and load that into interpolators and - and then set the distribution functions + then set the distribution functions Takes a dictionary as its only argument """ - # Set the userinput + # Set the user input self.set_moe_distefano_settings(options=options) # Load the data @@ -3911,7 +3908,7 @@ eccentricity3=0 """ Function to clean up the interpolators after a run - We look in the MoeCache global variable for items that are interpolators. + We look in the Moecache global variable for items that are interpolators. Should be called by the general cleanup function AND the thread cleanup function """ @@ -3976,7 +3973,7 @@ eccentricity3=0 msg = "The M&S options do not seem to be set properly. The value is {}".format(self.grid_options['m&s_options']) raise ValueError(msg) - # Second: is the moecache filled. + # Second: is the Moecache filled. if not Moecache: verbose_print( "_calculate_multiplicity_fraction: Moecache is empty. It needs to be filled with the data for the interpolators. Loading the data now", @@ -3994,7 +3991,7 @@ eccentricity3=0 self.grid_options['m&s_options']['M_1'] = system_dict['M_1'] # Calculate the multiplicity fraction - multiplicity_fraction_list = Moe_de_Stefano_2017_multiplicity_fractions(self.grid_options['m&s_options'], self.grid_options["verbosity"]) + multiplicity_fraction_list = Moe_di_Stefano_2017_multiplicity_fractions(self.grid_options['m&s_options'], self.grid_options["verbosity"]) # Turn into dict multiplicity_fraction_dict = {el+1:multiplicity_fraction_list[el] for el in range(len(multiplicity_fraction_list))} diff --git a/binarycpython/utils/grid_options_defaults.py b/binarycpython/utils/grid_options_defaults.py index 5d9240ecb..35e6eefc5 100644 --- a/binarycpython/utils/grid_options_defaults.py +++ b/binarycpython/utils/grid_options_defaults.py @@ -28,11 +28,11 @@ grid_options_defaults_dict = { # general (or unordered..) ########################## "amt_cores": 1, # total amount of cores used to evolve the population - "parse_function": None, # FUnction to parse the output with. + "parse_function": None, # Function to parse the output with. "multiplicity_fraction_function": 0, # Which multiplicity fraction function to use. 0: None, 1: Arenou 2010, 2: Rhagavan 2010, 3: M&S 2017 "tmp_dir": temp_dir(), # Setting the temp dir of the program "_main_pid": -1, # Placeholder for the main process id of the run. - "combine_ensemble_with_thread_joining": True, # Flag on whether to combine everything and return it to the user or if false: write it to data_dir/ensemble_output_{popuation_id}_{thread_id}.json + "combine_ensemble_with_thread_joining": True, # Flag on whether to combine everything and return it to the user or if false: write it to data_dir/ensemble_output_{population_id}_{thread_id}.json "_commandline_input": "", "log_runtime_systems": 0, # whether to log the runtime of the systems (1 file per thread. stored in the tmp_dir) "_actually_evolve_system": True, # Whether to actually evolve the systems of just act as if. for testing. used in _process_run_population_grid @@ -69,17 +69,17 @@ grid_options_defaults_dict = { ########################## # Custom logging ########################## - "C_auto_logging": None, # Should contain a dictionary where the kes are they headers + "C_auto_logging": None, # Should contain a dictionary where the keys are they headers # and the values are lists of parameters that should be logged. - # This will get parsed by autogen_C_logging_code in custom_loggion_functions.py + # This will get parsed by autogen_C_logging_code in custom_logging_functions.py "C_logging_code": None, # Should contain a string which holds the logging code. "custom_logging_func_memaddr": -1, # Contains the custom_logging functions memory address "_custom_logging_shared_library_file": None, # file containing the .so file ########################## # Store pre-loading: ########################## - "_store_memaddr": -1, # Contains the store object memory adress, useful for preloading. - # defaults to -1 and isnt used if thats the default then. + "_store_memaddr": -1, # Contains the store object memory address, useful for pre loading. + # defaults to -1 and isn't used if that's the default then. ########################## # Log args: logging of arguments ########################## @@ -92,7 +92,7 @@ grid_options_defaults_dict = { "evolution_type": "grid", # Flag for type of population evolution "_evolution_type_options": [ "grid", - ], # available choices for type of population evolution. # TODO: fill later with monte carlo, sourcefile + ], # available choices for type of population evolution. # TODO: fill later with Monte Carlo, source file "_system_generator": None, # value that holds the function that generates the system # (result of building the grid script) "source_file_filename": None, # filename for the source @@ -444,14 +444,14 @@ grid_options_descriptions = { "_binary_c_shared_library": "Full path to the libbinary_c file. This options is not used in the population object", "verbosity": "Verbosity of the population code. Default is 0, by which only errors will be printed. Higher values will show more output, which is good for debugging.", "binary": "Set this to 1 if the population contains binaries. Input: int", # TODO: write what effect this has. - "amt_cores": "The amount of cores that the population grid will use. The multiprocessing is useful but make sure to figure out how many logical cores the machine has. The core is multiprocessed, not multithreaded, and will gain no extra speed when amt_cores exceeds the amount of logical cores. Input: int", + "amt_cores": "The amount of cores that the population grid will use. The multiprocessing is useful but make sure to figure out how many logical cores the machine has. The core is multi processed, not multi threaded, and will gain no extra speed when amt_cores exceeds the amount of logical cores. Input: int", "_start_time_evolution": "Variable storing the start timestamp of the population evolution. Set by the object itself.", # TODO: make sure this is logged to a file "_end_time_evolution": "Variable storing the end timestamp of the population evolution. Set by the object itself", # TODO: make sure this is logged to a file "_total_starcount": "Variable storing the total amount of systems in the generator. Used and set by the population object.", "_custom_logging_shared_library_file": "filename for the custom_logging shared library. Used and set by the population object", - "_errors_found": "Variable storing a boolean flag whether errors by binary_c are encountered.", - "_errors_exceeded": "Variable storing a boolean flag whether the amount of errors was higher than the set threshold (failed_systems_threshold). If True, then the commandline arguments of the failing systems will not be stored in the failed_system_log files.", - "source_file_filename": "Variable containing the source file containing lines of binary_c commandline calls. These all have to start with binary_c.", # TODO: Expand + "_errors_found": "Variable storing a Boolean flag whether errors by binary_c are encountered.", + "_errors_exceeded": "Variable storing a Boolean flag whether the amount of errors was higher than the set threshold (failed_systems_threshold). If True, then the command line arguments of the failing systems will not be stored in the failed_system_log files.", + "source_file_filename": "Variable containing the source file containing lines of binary_c command line calls. These all have to start with binary_c.", # TODO: Expand "C_auto_logging": "Dictionary containing parameters to be logged by binary_c. The structure of this dictionary is as follows: the key is used as the headline which the user can then catch. The value at that key is a list of binary_c system parameters (like star[0].mass)", "C_logging_code": "Variable to store the exact code that is used for the custom_logging. In this way the user can do more complex logging, as well as putting these logging strings in files.", "_failed_count": "Variable storing the amount of failed systems.", @@ -461,31 +461,31 @@ grid_options_descriptions = { "_grid_variables": "Dictionary storing the grid_variables. These contain properties which are accessed by the _generate_grid_code function", "_population_id": "Variable storing a unique 32-char hex string.", "_commandline_input": "String containing the arguments passed to the population object via the command line. Set and used by the population object.", - "_system_generator": "Function object that contains the system generator function. This can be from a grid, or a source file, or a montecarlo grid.", + "_system_generator": "Function object that contains the system generator function. This can be from a grid, or a source file, or a Monte Carlo grid.", "gridcode_filename": "Filename for the grid code. Set and used by the population object. TODO: allow the user to provide their own function, rather than only a generated function.", "log_args": "Boolean to log the arguments. Unused ", # TODO: fix the functionality for this and describe it properly "log_args_dir": "Directory to log the arguments to. Unused", # TODO: fix the functionality for this and describe it properly "log_file": "Log file for the population object. Unused", # TODO: fix the functionality for this and describe it properly - "custom_logging_func_memaddr": "Memory adress where the custom_logging_function is stored. Input: int", + "custom_logging_func_memaddr": "Memory address where the custom_logging_function is stored. Input: int", "_count": "Counter tracking which system the generator is on.", "_probtot": "Total probability of the population.", # TODO: check whether this is used properly throughout "_main_pid": "Main process ID of the master process. Used and set by the population object.", - "_store_memaddr": "Memory adress of the store object for binary_c.", - "failed_systems_threshold": "Variable storing the maximum amount of systems that are allowed to fail before logging their commandline arguments to failed_systems log files", + "_store_memaddr": "Memory address of the store object for binary_c.", + "failed_systems_threshold": "Variable storing the maximum amount of systems that are allowed to fail before logging their command line arguments to failed_systems log files", "parse_function": "Function that the user can provide to handle the output the binary_c. This function has to take the arguments (self, output). Its best not to return anything in this function, and just store stuff in the grid_options['results'] dictionary, or just output results to a file", "condor": "Int flag whether to use a condor type population evolution. Not implemented yet.", # TODO: describe this in more detail - "slurm": "Int flag whether to use a slurm type population evolution.", # TODO: describe this in more detail - "weight": "Weight factor for each system. The calculated probability is mulitplied by this. If the user wants each system to be repeated several times, then this variable should not be changed, rather change the _repeat variable instead, as that handles the reduction in probability per system. This is useful for systems that have a process with some random element in it.", # TODO: add more info here, regarding the evolution splitting. + "slurm": "Int flag whether to use a Slurm type population evolution.", # TODO: describe this in more detail + "weight": "Weight factor for each system. The calculated probability is multiplied by this. If the user wants each system to be repeated several times, then this variable should not be changed, rather change the _repeat variable instead, as that handles the reduction in probability per system. This is useful for systems that have a process with some random element in it.", # TODO: add more info here, regarding the evolution splitting. "repeat": "Factor of how many times a system should be repeated. Consider the evolution splitting binary_c argument for supernovae kick repeating.", # TODO: make sure this is used. "evolution_type": "Variable containing the type of evolution used of the grid. Multiprocessing or linear processing", - "combine_ensemble_with_thread_joining": "BOolean flag on whether to combine everything and return it to the user or if false: write it to data_dir/ensemble_output_{popuation_id}_{thread_id}.json", - "log_runtime_systems": "Whether to log the runtime of the systems . Each systems run by the thread is logged to a file and is stored in the tmp_dir. (1 file per thread). Don't use this if you are planning to run alot of systems. This is mostly for debugging and finding systems that take long to run. Integer, default = 0. if value is 1 then the systems are logged", + "combine_ensemble_with_thread_joining": "Boolean flag on whether to combine everything and return it to the user or if false: write it to data_dir/ensemble_output_{population_id}_{thread_id}.json", + "log_runtime_systems": "Whether to log the runtime of the systems . Each systems run by the thread is logged to a file and is stored in the tmp_dir. (1 file per thread). Don't use this if you are planning to run a lot of systems. This is mostly for debugging and finding systems that take long to run. Integer, default = 0. if value is 1 then the systems are logged", "_total_mass_run": "To count the total mass that thread/process has ran", "_total_probability_weighted_mass_run": "To count the total mass * probability for each system that thread/process has ran", "_actually_evolve_system": "Whether to actually evolve the systems of just act as if. for testing. used in _process_run_population_grid", "max_queue_size": "Maximum size of the queue that is used to feed the processes. Don't make this too big! Default: 1000. Input: int", "_set_ms_grid": "Internal flag whether the M&S grid has been loaded", - "run_zero_probability_system": "Whether to run the zero probability systems. Default: True. Input: boolean", + "run_zero_probability_system": "Whether to run the zero probability systems. Default: True. Input: Boolean", "_zero_prob_stars_skipped": "Internal counter to track how many systems are skipped because they have 0 probability", "ensemble_factor_in_probability_weighted_mass": "Flag to multiply all the ensemble results with 1/probability_weighted_mass", "multiplicity_fraction_function": "Which multiplicity fraction function to use. 0: None, 1: Arenou 2010, 2: Rhagavan 2010, 3: M&S 2017", @@ -496,8 +496,8 @@ grid_options_descriptions = { ### # -# Default options for the Moe & Distefano grid -moe_distefano_default_options = { +# Default options for the Moe & di Stefano grid +moe_di_stefano_default_options = { "resolutions": { "M": [ 20, # M1 @@ -534,7 +534,7 @@ moe_distefano_default_options = { # multiplicity model (as a function of log10M1) # - # You can use 'Poisson' which uses the system multiplicty + # You can use 'Poisson' which uses the system multiplicity # given by Moe and maps this to single/binary/triple/quad # fractions. # @@ -557,16 +557,16 @@ moe_distefano_default_options = { 0, # triple 0, # quadruple ], - # given a mix of multiplities, you can either (noting that + # given a mix of multiplicities, you can either (noting that # here (S,B,T,Q) = appropriate modulator * model(S,B,T,Q) ) # - # 'norm' : normalize so the whole population is 1.0 + # 'norm' : normalise so the whole population is 1.0 # after implementing the appropriate fractions # S/(S+B+T+Q), B/(S+B+T+Q), T/(S+B+T+Q), Q/(S+B+T+Q) # # 'raw' : stick to what is predicted, i.e. # S/(S+B+T+Q), B/(S+B+T+Q), T/(S+B+T+Q), Q/(S+B+T+Q) - # without normalization + # without normalisation # (in which case the total probability < 1.0 unless # all you use single, binary, triple and quadruple) # @@ -581,7 +581,7 @@ moe_distefano_default_options = { # # # note: if you only set one multiplicity_modulator - # to 1, and all the others to 0, then normalizing + # to 1, and all the others to 0, then normalising # will mean that you effectively have the same number # of stars as single, binary, triple or quad (whichever # is non-zero) i.e. the multiplicity fraction is ignored. @@ -593,14 +593,14 @@ moe_distefano_default_options = { "q_high_extrapolation_method": "linear", } -moe_distefano_default_options_description = { +moe_di_stefano_default_options_description = { "resolutions": "", "ranges": "", "Mmin": "Minimum stellar mass", "multiplicity_model": """ multiplicity model (as a function of log10M1) -You can use 'Poisson' which uses the system multiplicty +You can use 'Poisson' which uses the system multiplicity given by Moe and maps this to single/binary/triple/quad fractions. @@ -617,13 +617,13 @@ e.g. [1,0,0,0] for single stars only defaults to [1,1,0,0] i.e. singles and binaries """, "normalize_multiplicities": """ -'norm': normalize so the whole population is 1.0 +'norm': normalise so the whole population is 1.0 after implementing the appropriate fractions S/(S+B+T+Q), B/(S+B+T+Q), T/(S+B+T+Q), Q/(S+B+T+Q) - given a mix of multiplities, you can either (noting that + given a mix of multiplicities, you can either (noting that here (S,B,T,Q) = appropriate modulator * model(S,B,T,Q) ) note: if you only set one multiplicity_modulator - to 1, and all the others to 0, then normalizing + to 1, and all the others to 0, then normalising will mean that you effectively have the same number of stars as single, binary, triple or quad (whichever is non-zero) i.e. the multiplicity fraction is ignored. @@ -632,7 +632,7 @@ defaults to [1,1,0,0] i.e. singles and binaries 'raw' : stick to what is predicted, i.e. S/(S+B+T+Q), B/(S+B+T+Q), T/(S+B+T+Q), Q/(S+B+T+Q) - without normalization + without normalisation (in which case the total probability < 1.0 unless all you use single, binary, triple and quadruple) @@ -672,7 +672,7 @@ def grid_options_help(option: str) -> dict: option: which option you want to have the description of returns: - dict containg the option, the description if its there, otherwise empty string. And if the key doesnt exist, the dict is empty + dict containing the option, the description if its there, otherwise empty string. And if the key doesnt exist, the dict is empty """ option_keys = grid_options_defaults_dict.keys() @@ -735,7 +735,7 @@ def write_grid_options_to_rst_file(output_file: str) -> None: Function that writes the descriptions of the grid options to a rst file Tasks: - TODO: seperate things into private and public options + TODO: separate things into private and public options Args: output_file: target file where the grid options descriptions are written to @@ -781,12 +781,12 @@ def write_grid_options_to_rst_file(output_file: str) -> None: "The following options are meant to be changed by the user.", ) - # Moe & Distefano options: + # Moe & di Stefano options: print_option_descriptions( f, moe_distefano_default_options, moe_distefano_default_options_description, - "Moe & Distefano sampler options", + "Moe & di Stefano sampler options", "The following options are meant to be changed by the user.", ) diff --git a/binarycpython/utils/hpc_functions.py b/binarycpython/utils/hpc_functions.py index 248f41942..87d3fe8b9 100644 --- a/binarycpython/utils/hpc_functions.py +++ b/binarycpython/utils/hpc_functions.py @@ -1,7 +1,7 @@ """ File containing functions for HPC computing, distributed tasks on clusters etc. -Functions that the slurm and condor subroutines of the population object use. +Functions that the Slurm and Condor subroutines of the population object use. Mainly divided in 2 sections: Slurm and Condor """ diff --git a/binarycpython/utils/plot_functions.py b/binarycpython/utils/plot_functions.py index fd4f440c7..002b4272b 100644 --- a/binarycpython/utils/plot_functions.py +++ b/binarycpython/utils/plot_functions.py @@ -9,12 +9,12 @@ Structure of file: plotting functions master function: plot_system -All the loose components here can ofcourse be used in other routines if you want. +All the loose components here can of course be used in other routines if you want. -There is no preloaded matplotlib rc, you should do that yourself +There is no pre loaded matplotlib rc, you should do that yourself -These plotting routines are designed for binary systems, and admittingly they are here mostly for -inspirational purposes, since one would problably want to customize the plots. +These plotting routines are designed for binary systems, and admittedly they are here mostly for +inspirational purposes, since one would probably want to customise the plots. Regardless, having some plotting routines in here seemed like a nice idea Tasks diff --git a/binarycpython/utils/run_system_wrapper.py b/binarycpython/utils/run_system_wrapper.py index c81237a4f..56f58379a 100644 --- a/binarycpython/utils/run_system_wrapper.py +++ b/binarycpython/utils/run_system_wrapper.py @@ -24,7 +24,7 @@ def run_system(**kwargs): Examples: - run_system(M_1=10): will run a system with ZAMS mass 1 = 10 - run_system(M_1=10, log_filename="~/example_log.txt"): Will run a system - and write the logfile too + and write the log file too - run_system(M_1=10, parse_function=fancy_parsing_function) Tasks: @@ -37,9 +37,9 @@ def run_system(**kwargs): Kwargs: custom_logging_code: Should contain a string containing the c-code for the shared library. If this is provided binary_c will use that custom logging code to output its data - log_filename: Should contain name of the binary_c system logfile. + log_filename: Should contain name of the binary_c system log file. Passing this will make sure that the filename gets written for a run - (its default behaviour is NOT to write a logfile for a system) + (its default behaviour is NOT to write a log file for a system) parse_function (function): should contain a function that parses the output. The parse function should take 1 required parameter: the output of the binaryc run Passing this will call the parse_function by passing it the output of the binary_c call @@ -58,7 +58,7 @@ def run_system(**kwargs): func_memaddr = -1 write_logfile = 0 - # Create dict to pass as argstring + # Create dict to pass as arg string binary_c_args = {} # Check which binary_c arguments have been passed and put them into a dict @@ -70,7 +70,7 @@ def run_system(**kwargs): else: if not key in other_keywords: print( - "The following keyword was not recognized and wont be used:\n\t{}".format( + "The following keyword was not recognised and wont be used:\n\t{}".format( key ) ) diff --git a/binarycpython/utils/useful_funcs.py b/binarycpython/utils/useful_funcs.py index 8e9901053..546d8b9c7 100644 --- a/binarycpython/utils/useful_funcs.py +++ b/binarycpython/utils/useful_funcs.py @@ -10,10 +10,13 @@ Functions: - ZAMS_collision(m1, m2, e, sep, z) returns 1 if stars collide on the ZAMS - roche_lobe(q): returns roche lobe radius in units of separation - ragb(m, z): radius at first thermal pulse + - minimum_period_for_RLOF(M1, M2, metallicity, store_memaddr=-1): function to calculate the minimum period that leads to RLOF on ZAMS + - minimum_separation_for_RLOF(M1, M2, metallicity, store_memaddr=-1): function to calculate the minimum period that leads to RLOF on ZAMS + - maximum_mass_ratio_for_RLOF(M1, orbital_period, store_memaddr=None): Function to calculate the maximum mass ratio that leads to RLOF on ZAMS Tasks: - TODO: check whether these functions are correct - - TODO: add unittest for maximum_mass_ratio_for_RLOF + - TODO: add unit test for maximum_mass_ratio_for_RLOF """ import math @@ -31,13 +34,13 @@ def minimum_period_for_RLOF(M1, M2, metallicity, store_memaddr=-1): """ Wrapper function for _binary_c_bindings.return_minimum_orbit_for_RLOF - Handles the output and returns the minimum orbital period at which RLOF just does not occur at zams + Handles the output and returns the minimum orbital period at which RLOF just does not occur at ZAMS Args: M1: Primary mass in solar mass M2: Secondary mass in solar mass metallicity: metallicity - store_memaddr (optional): store memory adress + store_memaddr (optional): store memory address Returns: minimum orbital_period that just does not cause a RLOF at ZAMS -- GitLab