diff --git a/binarycpython/utils/population_extensions/distribution_functions.py b/binarycpython/utils/population_extensions/distribution_functions.py index 42992407358fa9dad93f60e70390945594f60f61..ae1c0e875ed815d56fcc0c8cb052f95ae5546398 100644 --- a/binarycpython/utils/population_extensions/distribution_functions.py +++ b/binarycpython/utils/population_extensions/distribution_functions.py @@ -33,7 +33,7 @@ import cachetools import numpy as np import py_rinterpolate -from binarycpython.utils.dicts import prepare_dict +from binarycpython.utils.dicts import normalize_dict, prepare_dict from binarycpython.utils.functions import verbose_print from binarycpython.utils.population_extensions.grid_options_defaults import ( _MOE2017_VERBOSITY_INTERPOLATOR_LEVEL, @@ -693,9 +693,7 @@ class distribution_functions: raise ValueError(msg) # To make sure we normalize the dictionary - multiplicity_fraction_dict = normalize_dict( - multiplicity_fraction_dict - ) + multiplicity_fraction_dict = normalize_dict(multiplicity_fraction_dict) return multiplicity_fraction_dict @@ -1226,10 +1224,6 @@ class distribution_functions: """ return (lambda_val**n) * np.exp(-lambda_val) / (1.0 * math.factorial(n)) - - - - def build_q_table(self, options, m, p, verbosity=0): """ Build an interpolation table for q, given a mass and diff --git a/binarycpython/utils/population_extensions/monte_carlo_sampling.py b/binarycpython/utils/population_extensions/monte_carlo_sampling.py index c3f11652f1d63a730c46c1939fdeefca6243f36f..c9b4ab10e6b3017ad2b0cc55cb8e8bd84801245c 100644 --- a/binarycpython/utils/population_extensions/monte_carlo_sampling.py +++ b/binarycpython/utils/population_extensions/monte_carlo_sampling.py @@ -9,27 +9,13 @@ TODO: build CDFS in a nested dict fashing where the parameter the current parame import datetime import importlib - -# pylint: disable=E1101 import os -from binarycpython.utils.functions import calculate_total_mass_system - - -import os -import datetime import numpy as np -import importlib - -from binarycpython.utils.functions import verbose_print -from binarycpython.utils.dicts import normalize_dict -from binarycpython.utils.population_extensions.distribution_functions import ( - Moecache, -) -from binarycpython import Population -from types import MethodType +from binarycpython.utils.functions import calculate_total_mass_system +# pylint: disable=E1101 _numba = False comment_line = "###########\n" @@ -83,12 +69,9 @@ class monte_carlo_sampling: # raise NotImplementedError("Functionality in not implemented") pass - - - ############## # Generator functions - + # Management def _monte_carlo_sampling_get_generator_filename(self): """ @@ -141,7 +124,6 @@ class monte_carlo_sampling: # Write some info in the function "# Grid code generated on {}\n".format(datetime.datetime.now().isoformat()), "# This function generates the systems that will be evolved with binary_c\n\n", - # Set some values in the generated code: "# Set initial values\n", "_total_starcount = 0\n", @@ -151,9 +133,7 @@ class monte_carlo_sampling: # Add method for the pre-calculation of the arrays if self.grid_options["monte_carlo_use_pre_calculated_distributions"]: - self._add_code( - "self.handle_pre_calc(self)\n" - ) + self._add_code("self.handle_pre_calc(self)\n") ######### # Set up the loop and yield calls @@ -167,9 +147,7 @@ class monte_carlo_sampling: # Increase indent_depth self._increment_indent_depth(+1) - self._add_code( - "system_dict = copy.copy(default_system_dict)\n\n" - ) + self._add_code("system_dict = copy.copy(default_system_dict)\n\n") ######### # Run loop of sampling variable setup @@ -183,9 +161,7 @@ class monte_carlo_sampling: ######### # Generate parameter lines - self._monte_carlo_sampling_write_generator_parameter( - sampling_variable - ) + self._monte_carlo_sampling_write_generator_parameter(sampling_variable) ######### # Generate yield call if branchpoint @@ -237,7 +213,7 @@ class monte_carlo_sampling: if branchcode: self._add_code( "# Branch code\n", - "if {branchcode}:\n".format(branchcode=branchcode) + "if {branchcode}:\n".format(branchcode=branchcode), ) self._increment_indent_depth(+1) @@ -278,21 +254,20 @@ class monte_carlo_sampling: """ self.verbose_print( - "Constructing/adding: {}".format(sampling_variable['parameter_name']), + "Constructing/adding: {}".format(sampling_variable["parameter_name"]), self.grid_options["verbosity"], 2, - ) + ) #################### # Write comment self._add_code( - comment_line, - "# Sampling variable {}\n\n".format(sampling_variable['name']) + comment_line, "# Sampling variable {}\n\n".format(sampling_variable["name"]) ) self.verbose_print( "Writing sampling variable {} to monte-carlo sampling generator".format( - sampling_variable['parameter_name'] + sampling_variable["parameter_name"] ), self.grid_options["verbosity"], 1, @@ -311,8 +286,24 @@ class monte_carlo_sampling: # Generate call to pdf-cdf function to generate the parameter value self._add_code( comment_line, - "{} = self.handle_calc_sampled_value(self, sampling_variable={}{})\n".format(sampling_variable['parameter_name'], sampling_variable, ', ' + ','.join(['{}={}'.format(dependency_variable, dependency_variable) for dependency_variable in sampling_variable['dependency_variables']]) if sampling_variable['dependency_variables'] else ''), - "system_dict['{}'] = {}\n\n".format(sampling_variable['parameter_name'], sampling_variable['parameter_name']) + "{} = self.handle_calc_sampled_value(self, sampling_variable={}{})\n".format( + sampling_variable["parameter_name"], + sampling_variable, + ", " + + ",".join( + [ + "{}={}".format(dependency_variable, dependency_variable) + for dependency_variable in sampling_variable[ + "dependency_variables" + ] + ] + ) + if sampling_variable["dependency_variables"] + else "", + ), + "system_dict['{}'] = {}\n\n".format( + sampling_variable["parameter_name"], sampling_variable["parameter_name"] + ), ) #################### @@ -320,7 +311,7 @@ class monte_carlo_sampling: if sampling_variable["bottomcode"]: self._add_code( comment_line, - sampling_variable["bottomcode"]+"\n\n", + sampling_variable["bottomcode"] + "\n\n", ) ############## @@ -348,7 +339,9 @@ class monte_carlo_sampling: # Code to load the generator code self.verbose_print( message="Load monte-carlo sampling functions from {file}".format( - file=self.grid_options["_monte_carlo_sampling_sampling_functions_filename"] + file=self.grid_options[ + "_monte_carlo_sampling_sampling_functions_filename" + ] ), verbosity=self.grid_options["verbosity"], minimal_verbosity=1, @@ -357,7 +350,9 @@ class monte_carlo_sampling: # Load the module from file and the functions in it. spec = importlib.util.spec_from_file_location( "binary_c_python_monte_carlo_sampling_functions", - os.path.join(self.grid_options["_monte_carlo_sampling_sampling_functions_filename"]), + os.path.join( + self.grid_options["_monte_carlo_sampling_sampling_functions_filename"] + ), ) monte_carlo_sampling_functions_file = importlib.util.module_from_spec(spec) spec.loader.exec_module(monte_carlo_sampling_functions_file) @@ -368,30 +363,36 @@ class monte_carlo_sampling: # Create dictionary to hold the calc_sampled_value functions self.monte_carlo_calc_sampled_value_functions = {} for obj in dir(monte_carlo_sampling_functions_file): - if obj.startswith('calc_sampled_value'): + if obj.startswith("calc_sampled_value"): # Set function as class function setattr(self, obj, getattr(monte_carlo_sampling_functions_file, obj)) # Add to dict - self.monte_carlo_calc_sampled_value_functions[obj.replace('calc_sampled_value_', '')] = getattr(monte_carlo_sampling_functions_file, obj) + self.monte_carlo_calc_sampled_value_functions[ + obj.replace("calc_sampled_value_", "") + ] = getattr(monte_carlo_sampling_functions_file, obj) # Create dictionary to hold the calc_pdf_cdf_value_array_dict functions self.monte_carlo_calc_pdf_cdf_value_array_dict_functions = {} for obj in dir(monte_carlo_sampling_functions_file): - if obj.startswith('calc_pdf_cdf_value_array_dict'): + if obj.startswith("calc_pdf_cdf_value_array_dict"): # Set function as class function setattr(self, obj, getattr(monte_carlo_sampling_functions_file, obj)) # Add to dict - self.monte_carlo_calc_pdf_cdf_value_array_dict_functions[obj.replace('calc_pdf_cdf_value_array_dict_', '')] = getattr(monte_carlo_sampling_functions_file, obj) + self.monte_carlo_calc_pdf_cdf_value_array_dict_functions[ + obj.replace("calc_pdf_cdf_value_array_dict_", "") + ] = getattr(monte_carlo_sampling_functions_file, obj) # Load handler function for obj in dir(monte_carlo_sampling_functions_file): - if obj.startswith('handle_calc_sampled_value'): - self.handle_calc_sampled_value = getattr(monte_carlo_sampling_functions_file, obj) + if obj.startswith("handle_calc_sampled_value"): + self.handle_calc_sampled_value = getattr( + monte_carlo_sampling_functions_file, obj + ) break # Load handler function for obj in dir(monte_carlo_sampling_functions_file): - if obj.startswith('handle_pre_calc'): + if obj.startswith("handle_pre_calc"): self.handle_pre_calc = getattr(monte_carlo_sampling_functions_file, obj) # setattr(self, obj, getattr(monte_carlo_sampling_functions_file, obj)) # MethodType(func, obj) @@ -429,11 +430,15 @@ class monte_carlo_sampling: ###################### # Call to function to write the calc_sample_value function - self._monte_carlo_sampling_write_calc_pdf_cdf_value_array_dict_function(sampling_variable) + self._monte_carlo_sampling_write_calc_pdf_cdf_value_array_dict_function( + sampling_variable + ) ###################### # Call to function to write the calc_sample_value function - self._monte_carlo_sampling_write_calc_sampled_value_function(sampling_variable) + self._monte_carlo_sampling_write_calc_sampled_value_function( + sampling_variable + ) ###################### # Call to function to write the pre_calc_sample_value function @@ -491,7 +496,9 @@ class monte_carlo_sampling: # Set up lists self._add_code( comment_line, - "value_array = {}\n".format(sampling_variable['samplerfunc']), # Line for the sampler func value array sampling (not the same as parameter value array) + "value_array = {}\n".format( + sampling_variable["samplerfunc"] + ), # Line for the sampler func value array sampling (not the same as parameter value array) "parameter_value_array = []\n", "probability_array = [0]\n\n", ) @@ -500,18 +507,22 @@ class monte_carlo_sampling: # Set up first parameter value array adding self._add_code( comment_line, - "{} = value_array[0]\n".format(sampling_variable['name']), - "{}\n".format(sampling_variable['precode'].replace( - "\n", "\n" + self._indent_block(0) - )) if sampling_variable['precode'] else "\n", - "parameter_value_array.append({})\n\n".format(sampling_variable['parameter_name']) + "{} = value_array[0]\n".format(sampling_variable["name"]), + "{}\n".format( + sampling_variable["precode"].replace("\n", "\n" + self._indent_block(0)) + ) + if sampling_variable["precode"] + else "\n", + "parameter_value_array.append({})\n\n".format( + sampling_variable["parameter_name"] + ), ) ####### # Set up loop for sampling the distribution function self._add_code( comment_line, - "for {} in value_array[1:]:\n".format(sampling_variable['name']), + "for {} in value_array[1:]:\n".format(sampling_variable["name"]), ) self._increment_indent_depth(+1) @@ -519,17 +530,21 @@ class monte_carlo_sampling: # Set up conversion with precode self._add_code( comment_line, - "{}\n".format(sampling_variable['precode'].replace( - "\n", "\n" + self._indent_block(0) - )) if sampling_variable['precode'] else "\n", - "parameter_value_array.append({})\n\n".format(sampling_variable['parameter_name']) + "{}\n".format( + sampling_variable["precode"].replace("\n", "\n" + self._indent_block(0)) + ) + if sampling_variable["precode"] + else "\n", + "parameter_value_array.append({})\n\n".format( + sampling_variable["parameter_name"] + ), ) ####### # Set up calculation of probability self._add_code( comment_line, - "probability = {}\n".format(sampling_variable['probdist']), + "probability = {}\n".format(sampling_variable["probdist"]), "probability_array.append(probability)\n\n", ) self._increment_indent_depth(-1) @@ -560,7 +575,7 @@ class monte_carlo_sampling: "def bin(parameter_value_array, parameter_value):\n", " index = np.digitize(parameter_value, bins=parameter_value_array, right=False)-1\n", " center_value = (parameter_value_array[index+1]+parameter_value_array[index])/2\n", - " return center_value\n" + " return center_value\n", ) def _monte_carlo_sampling_write_center_function(self): @@ -573,7 +588,7 @@ class monte_carlo_sampling: "def center(sampling_func):\n", " value_array = sampling_func\n", " center_value_array = (value_array[1:]+value_array[:-1])/2\n", - " return center_value_array\n" + " return center_value_array\n", ) def _monte_carlo_sampling_write_handle_pre_calc_function(self): @@ -588,7 +603,6 @@ class monte_carlo_sampling: ) self._increment_indent_depth(+1) - ####### # Initialise dict self._add_code( @@ -602,23 +616,26 @@ class monte_carlo_sampling: self.grid_options["_sampling_variables"].items(), key=lambda x: x[1]["sampling_variable_number"], ) - ): + ): sampling_variable = sampling_variable_el[1] ####### # Write call to specific functions to pre-calculate each pdf/cdf dict self._add_code( - "self.pre_calculated_pdf_cdf_value_array_dicts['{}'] = pre_calculate_pdf_cdf_value_array_dict_{}(self)\n".format(sampling_variable['parameter_name'], sampling_variable['parameter_name']), + "self.pre_calculated_pdf_cdf_value_array_dicts['{}'] = pre_calculate_pdf_cdf_value_array_dict_{}(self)\n".format( + sampling_variable["parameter_name"], + sampling_variable["parameter_name"], + ), ) ####### # De-dent and padd self._increment_indent_depth(-1) - self._add_code( - "\n\n" - ) + self._add_code("\n\n") - def _monte_carlo_sampling_write_calc_sampled_value_function(self, sampling_variable): + def _monte_carlo_sampling_write_calc_sampled_value_function( + self, sampling_variable + ): """ Function to write the calc_sampled_value call """ @@ -626,7 +643,20 @@ class monte_carlo_sampling: ####### # Construct function self._add_code( - "def calc_sampled_value_{}(self{}):\n".format(sampling_variable['parameter_name'], ', '+ ','.join(['{}'.format(dependency_variable) for dependency_variable in sampling_variable['dependency_variables']]) if sampling_variable['dependency_variables'] else ''), + "def calc_sampled_value_{}(self{}):\n".format( + sampling_variable["parameter_name"], + ", " + + ",".join( + [ + "{}".format(dependency_variable) + for dependency_variable in sampling_variable[ + "dependency_variables" + ] + ] + ) + if sampling_variable["dependency_variables"] + else "", + ), ) self._increment_indent_depth(+1) @@ -639,28 +669,64 @@ class monte_carlo_sampling: ###### # Add calls to the dependency variable's pre-calculated parameter_value_array - if sampling_variable['dependency_variables']: - for dependency_variable in sampling_variable['dependency_variables']: + if sampling_variable["dependency_variables"]: + for dependency_variable in sampling_variable["dependency_variables"]: # Create string for getting the parameter value array - string = "self.pre_calculated_pdf_cdf_value_array_dicts['{}']".format(dependency_variable) + string = "self.pre_calculated_pdf_cdf_value_array_dicts['{}']".format( + dependency_variable + ) - if self.grid_options['_sampling_variables_parameter_names'][dependency_variable]['dependency_variables']: - for depth in range(0, len(self.grid_options['_sampling_variables_parameter_names'][dependency_variable]['dependency_variables'])): - string += "['{{:.6f}}'.format(binned_{})]".format(sampling_variable['dependency_variables'][depth]) + if self.grid_options["_sampling_variables_parameter_names"][ + dependency_variable + ]["dependency_variables"]: + for depth in range( + 0, + len( + self.grid_options["_sampling_variables_parameter_names"][ + dependency_variable + ]["dependency_variables"] + ), + ): + string += "['{{:.6f}}'.format(binned_{})]".format( + sampling_variable["dependency_variables"][depth] + ) # Add code to get the binned value of the current dependency value self._add_code( " binned_{} = bin({}['parameter_value_array'], {})\n".format( - dependency_variable, - string, - dependency_variable + dependency_variable, string, dependency_variable ) ) self._add_code( - " pdf_cdf_value_array_dict = self.pre_calculated_pdf_cdf_value_array_dicts['{}']{}\n".format(sampling_variable['parameter_name'], ''.join(["['{{:.6f}}'.format(binned_{})]".format(dependency_variable) for dependency_variable in sampling_variable['dependency_variables']]) if sampling_variable['dependency_variables'] else ''), + " pdf_cdf_value_array_dict = self.pre_calculated_pdf_cdf_value_array_dicts['{}']{}\n".format( + sampling_variable["parameter_name"], + "".join( + [ + "['{{:.6f}}'.format(binned_{})]".format(dependency_variable) + for dependency_variable in sampling_variable[ + "dependency_variables" + ] + ] + ) + if sampling_variable["dependency_variables"] + else "", + ), "else:\n", - " pdf_cdf_value_array_dict = self.monte_carlo_calc_pdf_cdf_value_array_dict_functions['{}'](self{})\n\n".format(sampling_variable['parameter_name'], ', '+ ','.join(['{}'.format(dependency_variable) for dependency_variable in sampling_variable['dependency_variables']]) if sampling_variable['dependency_variables'] else ''), + " pdf_cdf_value_array_dict = self.monte_carlo_calc_pdf_cdf_value_array_dict_functions['{}'](self{})\n\n".format( + sampling_variable["parameter_name"], + ", " + + ",".join( + [ + "{}".format(dependency_variable) + for dependency_variable in sampling_variable[ + "dependency_variables" + ] + ] + ) + if sampling_variable["dependency_variables"] + else "", + ), comment_line, "cdf_array = pdf_cdf_value_array_dict['cdf_array']\n", "value_array = pdf_cdf_value_array_dict['value_array']\n", @@ -683,7 +749,7 @@ class monte_carlo_sampling: ) ####### - # Get probabilities of bin-edges and set + # Get probabilities of bin-edges and set self._add_code( comment_line, "left_cdf = cdf_array[left_index]\n", @@ -692,7 +758,7 @@ class monte_carlo_sampling: ) ####### - # Get values of bin-edges and set + # Get values of bin-edges and set self._add_code( comment_line, "left_value = parameter_value_array[left_index]\n", @@ -706,33 +772,34 @@ class monte_carlo_sampling: comment_line, "dvalue_dcdf = dvalue/dcdf\n", "dist_to_left = random_sample - left_cdf\n", - "{} = left_value + (dvalue_dcdf) * dist_to_left\n\n".format(sampling_variable['parameter_name']), + "{} = left_value + (dvalue_dcdf) * dist_to_left\n\n".format( + sampling_variable["parameter_name"] + ), ) ####### # Turn the new point into the actual parameter if we have post-code - if sampling_variable['postcode']: + if sampling_variable["postcode"]: self._add_code( comment_line, - sampling_variable['postcode']+"\n\n", - ) + sampling_variable["postcode"] + "\n\n", + ) ####### # return value self._add_code( comment_line, - "return {}[0]\n".format(sampling_variable['parameter_name']), - ) - + "return {}[0]\n".format(sampling_variable["parameter_name"]), + ) ####### # De-dent and padd self._increment_indent_depth(-1) - self._add_code( - "\n\n" - ) + self._add_code("\n\n") - def _monte_carlo_sampling_write_calc_pdf_cdf_value_array_dict_function(self, sampling_variable): + def _monte_carlo_sampling_write_calc_pdf_cdf_value_array_dict_function( + self, sampling_variable + ): """ Function to write the calc_pdf_cdf_value_array_dict_function call """ @@ -740,7 +807,20 @@ class monte_carlo_sampling: ####### # Construct function self._add_code( - "def calc_pdf_cdf_value_array_dict_{}(self{}):\n".format(sampling_variable['parameter_name'], ', '+ ','.join(['{}'.format(dependency_variable) for dependency_variable in sampling_variable['dependency_variables']]) if sampling_variable['dependency_variables'] else ''), + "def calc_pdf_cdf_value_array_dict_{}(self{}):\n".format( + sampling_variable["parameter_name"], + ", " + + ",".join( + [ + "{}".format(dependency_variable) + for dependency_variable in sampling_variable[ + "dependency_variables" + ] + ] + ) + if sampling_variable["dependency_variables"] + else "", + ), ) self._increment_indent_depth(+1) @@ -757,9 +837,7 @@ class monte_carlo_sampling: ####### # De-dent and pad self._increment_indent_depth(-1) - self._add_code( - "\n\n" - ) + self._add_code("\n\n") def _monte_carlo_sampling_write_handle_calc_sampled_value_function(self): """ @@ -778,15 +856,13 @@ class monte_carlo_sampling: self._add_code( "calc_sampled_value_function = self.monte_carlo_calc_sampled_value_functions[sampling_variable['parameter_name']]\n", "sampled_value = calc_sampled_value_function(self, **kwargs)\n\n", - "return sampled_value\n" + "return sampled_value\n", ) ####### # De-dent and padd self._increment_indent_depth(-1) - self._add_code( - "\n\n" - ) + self._add_code("\n\n") def _monte_carlo_sampling_write_pre_calc_function(self, sampling_variable): """ @@ -796,13 +872,15 @@ class monte_carlo_sampling: ####### # Construct function self._add_code( - "def pre_calculate_pdf_cdf_value_array_dict_{}(self):\n".format(sampling_variable['parameter_name']), + "def pre_calculate_pdf_cdf_value_array_dict_{}(self):\n".format( + sampling_variable["parameter_name"] + ), ) self._increment_indent_depth(+1) ####### # Handle construction if we have dependency variables - if sampling_variable['dependency_variables']: + if sampling_variable["dependency_variables"]: ####### # Construct nested pdf cdf dict @@ -811,59 +889,98 @@ class monte_carlo_sampling: "nested_pdf_cdf_value_array_dict = {}\n\n", ) - sampling_variable_dict_based_on_parameter_name = {sampling_variable_el['parameter_name']: sampling_variable_el for sampling_variable_el in self.grid_options['_sampling_variables'].values()} - dependency_variable_list = [sampling_variable_dict_based_on_parameter_name[dependency_variable_key] for dependency_variable_key in sampling_variable['dependency_variables']] + sampling_variable_dict_based_on_parameter_name = { + sampling_variable_el["parameter_name"]: sampling_variable_el + for sampling_variable_el in self.grid_options[ + "_sampling_variables" + ].values() + } + dependency_variable_list = [ + sampling_variable_dict_based_on_parameter_name[dependency_variable_key] + for dependency_variable_key in sampling_variable["dependency_variables"] + ] ####### # Loop over all dependency variables - for dependency_variable_i, dependency_variable_key in enumerate(sampling_variable['dependency_variables']): - dependency_variable = sampling_variable_dict_based_on_parameter_name[dependency_variable_key] + for dependency_variable_i, dependency_variable_key in enumerate( + sampling_variable["dependency_variables"] + ): + dependency_variable = sampling_variable_dict_based_on_parameter_name[ + dependency_variable_key + ] ################ # Create dict if we are in - if (not dependency_variable_i == len(sampling_variable['dependency_variables'])) and (not dependency_variable_i == 0): + if ( + not dependency_variable_i + == len(sampling_variable["dependency_variables"]) + ) and (not dependency_variable_i == 0): self._add_code( comment_line, - "nested_pdf_cdf_value_array_dict['{{:.6f}}'.format({})] = {{}}\n".format(sampling_variable['dependency_variables'][dependency_variable_i-1]), + "nested_pdf_cdf_value_array_dict['{{:.6f}}'.format({})] = {{}}\n".format( + sampling_variable["dependency_variables"][ + dependency_variable_i - 1 + ] + ), ) ####### - # Construct the loop over the + # Construct the loop over the self._add_code( comment_line, - "value_array_{} = {}\n\n".format(dependency_variable['name'], dependency_variable['samplerfunc']), + "value_array_{} = {}\n\n".format( + dependency_variable["name"], dependency_variable["samplerfunc"] + ), ) ####### # Set up loop for sampling the distribution function self._add_code( comment_line, - "for {} in center(value_array_{}):\n\n".format(dependency_variable['name'], dependency_variable['name']), + "for {} in center(value_array_{}):\n\n".format( + dependency_variable["name"], dependency_variable["name"] + ), ) self._increment_indent_depth(+1) self._add_code( - "{}\n".format(dependency_variable['precode'].replace( - "\n", "\n" + self._indent_block(0) - )) if dependency_variable['precode'] else "\n") + "{}\n".format( + dependency_variable["precode"].replace( + "\n", "\n" + self._indent_block(0) + ) + ) + if dependency_variable["precode"] + else "\n" + ) ####### # Construct parts to build the pdf cdf function - self._monte_carlo_sampling_write_pdf_cdf_value_array_block(sampling_variable) + self._monte_carlo_sampling_write_pdf_cdf_value_array_block( + sampling_variable + ) ####### # Write code to store the dict in the nested dict - nested_dict_calls = "".join(["['{{:.6f}}'.format({})]".format(cur_dependency_variable['parameter_name']) for cur_dependency_variable in dependency_variable_list]) + nested_dict_calls = "".join( + [ + "['{{:.6f}}'.format({})]".format( + cur_dependency_variable["parameter_name"] + ) + for cur_dependency_variable in dependency_variable_list + ] + ) self._add_code( comment_line, "nested_pdf_cdf_value_array_dict{} = pdf_cdf_value_array_dict\n\n".format( nested_dict_calls - ) + ), ) ####### # de-dent the code - for dependency_variable_i, dependency_variable_key in enumerate(sampling_variable['dependency_variables'][::-1]): + for dependency_variable_i, dependency_variable_key in enumerate( + sampling_variable["dependency_variables"][::-1] + ): self._increment_indent_depth(-1) ####### @@ -877,21 +994,20 @@ class monte_carlo_sampling: else: ####### # Construct parts to build the pdf cdf function - self._monte_carlo_sampling_write_pdf_cdf_value_array_block(sampling_variable) + self._monte_carlo_sampling_write_pdf_cdf_value_array_block( + sampling_variable + ) ####### - # Write return statement + # Write return statement self._add_code( "return pdf_cdf_value_array_dict\n", ) - ####### # De-dent and padd self._increment_indent_depth(-1) - self._add_code( - "\n\n" - ) + self._add_code("\n\n") # Misc def _sample_multiplicity(self, system_dict): @@ -909,7 +1025,9 @@ class monte_carlo_sampling: # TODO: this can probably be a oneliner multiplicity_list, probability_list = [], [] - for multiplicity, probability in sorted(multiplicity_dict.items(), key=lambda x: x[0]): + for multiplicity, probability in sorted( + multiplicity_dict.items(), key=lambda x: x[0] + ): multiplicity_list.append(multiplicity) probability_list.append(probability) multiplicity_array = np.array(multiplicity_list) @@ -984,13 +1102,10 @@ class monte_carlo_sampling: ############## # misc - ############## # Writing binary_c calls to file: def monte_carlo_sampling_write_binary_c_calls_to_file( - self, - output_file, - include_defaults + self, output_file, include_defaults ): """ Function to write the generated grid to a file. @@ -1007,9 +1122,7 @@ class monte_carlo_sampling: # then if the _system_generator is present, we go through it if generator: # Write to file - with self.open( - output_file, "w", encoding="utf-8" - ) as file: + with self.open(output_file, "w", encoding="utf-8") as file: # Get defaults and clean them, then overwrite them with the set values. if include_defaults: # TODO: make sure that the defaults here are cleaned up properly @@ -1027,7 +1140,9 @@ class monte_carlo_sampling: # Handle monte-carlo threshold based on evolved mass if self.grid_options["evolution_type"] == "monte_carlo": # Check based on mass threshold - self._monte_carlo_sampling_check_mass_threshold(full_system_dict) + self._monte_carlo_sampling_check_mass_threshold( + full_system_dict + ) ###### # Check if evolution threshold is reached. @@ -1041,4 +1156,4 @@ class monte_carlo_sampling: print("Error. No grid function found!") raise ValueError - return output_file \ No newline at end of file + return output_file