From 01f20e58c98fe9dbe1d1541050c55170df452f2a Mon Sep 17 00:00:00 2001 From: dh00601 <dh00601@surrey.ac.uk> Date: Sat, 8 Jan 2022 12:14:32 +0000 Subject: [PATCH] fixing docs --- binarycpython/utils/functions.py | 109 +++++++++++------- .../distribution_functions.py | 24 ++-- .../spacing_functions.py | 23 ++-- 3 files changed, 93 insertions(+), 63 deletions(-) diff --git a/binarycpython/utils/functions.py b/binarycpython/utils/functions.py index 3da4c50ba..26c1ba91b 100644 --- a/binarycpython/utils/functions.py +++ b/binarycpython/utils/functions.py @@ -36,28 +36,30 @@ from binarycpython.utils.dicts import filter_dict_through_values ######################################################## -def now(now_object=None, style=None, specifier=None): +def now(now_object=None, style=None, custom_format=None): """ - convenience function to return a string of the current time, - using the format "%m/%d/%Y %H:%M:%S" + convenience function to return a string of the current time, using the format ``%m/%d/%Y %H:%M:%S`` Args: - style : if "nospace" then return the date/time with the format - "%Y%m%d_%H%M%S" + style : if "nospace" then return the date/time with the format ``%Y%m%d_%H%M%S``, else use format ``%m/%d/%Y %H:%M:%S`` - specifier: if set, uses this as a specifier rather than whatever is set by default or in the style variable + custom_format: if set, uses this as a format rather than whatever is set by default or in the style variable """ + if not now_object: now_object = datetime.datetime.now() - if not specifier: + + if not custom_format: if style == "nospace": # special case - specifier = "%Y%m%d_%H%M%S" + date_format = "%Y%m%d_%H%M%S" else: # our default - specifier = "%m/%d/%Y %H:%M:%S" + date_format = "%m/%d/%Y %H:%M:%S" + else: + date_format = custom_format - return datetime.datetime.strftime(now_object, specifier) + return datetime.datetime.strftime(now_object, date_format) def format_number(number): @@ -147,7 +149,9 @@ def get_ANSI_colours(): def mem_use(): """ - Return current process memory use in MB. (Takes no arguments) Note: this is per-thread only. + Return current process memory use in MB. (Takes no arguments) + + Note: this is per-thread only. """ return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0 @@ -155,11 +159,19 @@ def mem_use(): def trem(dt, count, dn, n): """ - Estimate time remaining (seconds) given a differential time and count (i.e. progress = $count/$n). $dt is the time since the last call, $count is the current progress count, $dn is the number run since the last call, and $n is the total number required. + Estimate time remaining (seconds) given a differential time and count (i.e. ``progress = count/n``). + + Args: + dt: is the time since the last call. + count: is the current progress count. + dn: is the number run since the last call. + n: is the total number required. """ + tpr = dt / max(1, dn) etasecs = tpr * (n - count) (eta, units) = conv_time_units(etasecs) + return (eta, units, tpr, etasecs) @@ -180,9 +192,16 @@ def conv_time_units(t): def bin_data(value, binwidth): """ - Function that bins the data + Function that bins the data using the absolute value of binwidth using the following formula:: + + ((0.5 if value > 0.0 else -0.5) + int(value / abs(binwidth))) * abs(binwidth) + + Args: + value: value that we want to bin + binwidth: width of the binning - Uses the absolute value of binwidth + Returns: + binned value """ return ((0.5 if value > 0.0 else -0.5) + int(value / abs(binwidth))) * abs(binwidth) @@ -214,6 +233,7 @@ def get_size(obj, seen=None): obj_id = id(obj) if obj_id in seen: return 0 + # Important mark as seen *before* entering recursion to gracefully handle # self-referential objects seen.add(obj_id) @@ -237,20 +257,26 @@ def imports(): yield val.__name__ -def isfloat(x): +def isfloat(x: Union[str, float, int]): """ - Return True if the "number" x, which could be a string, is a float, otherwise return False. + Function to return `True` if the "number" x, which could be a string, is an float, otherwise return `False`. + + Args: + x: string float or int that we will attempt to convert to an `float` value. """ + try: _ = float(x) return True except ValueError: return False - -def isint(x): +def isint(x: Union[str, float, int]): """ - Return True if the "number" x, which could be a string, is an int, otherwise return False. + Function to return `True` if the "number" x, which could be a string, is an int, otherwise return `False`. + + Args: + x: string float or int that we will attempt to convert to an `int` value. """ try: @@ -275,11 +301,13 @@ def convfloat(x): def datalinedict(line: str, parameters: list): """ Convert a line of data to a more convenient dictionary. + Arguments: line = a line of data as a string parameters = a list of the parameter names - Note: if the parameter is a floating point number, it will be converted to Python's float type. + Note: + If the parameter is a floating point number, it will be converted to Python's float type. """ return {param: convfloat(value) for param, value in zip(parameters, line.split())} @@ -288,6 +316,10 @@ def datalinedict(line: str, parameters: list): def pad_output_distribution(dist: dict, binwidth: float): """ Given a distribution, dist (a dictionary), which should be binned every binwidth (float), fill the distribution with zeros when there is no data. Note: this changes the data in place. + + Args: + dist: dictionary containing the distribution data. + binwidth: binwidth that is used to fill the distribution with 0 in places where there is no value/key. """ # sorted list of the keys @@ -355,11 +387,11 @@ def call_binary_c_config(argument): """ Function to interface with the binary_c config file - input: - - argument: argument for the binary_c config + Args: + argument: argument for the binary_c config Returns: - - raw output of binary_c-config + raw output of binary_c-config """ BINARY_C_DIR = os.getenv("BINARY_C", None) @@ -383,21 +415,18 @@ def call_binary_c_config(argument): # utility functions ######################################################## - def verbose_print( message: str, verbosity: int, minimal_verbosity: int, newline: str = "\n" ) -> None: """ Function that decides whether to print a message based on the current verbosity - and its minimum verbosity - - if verbosity is equal or higher than the minimum, then we print + and its minimum verbosity. If verbosity is equal or higher than the minimum, then we print. Args: - message: message to print - verbosity: current verbosity level - minimal_verbosity: threshold verbosity above which to print - newline: newline character (or set of characters), defaults to "\n" but "\x0d" (carriage return) might be useful. + message: message to print. + verbosity: current verbosity level. + minimal_verbosity: threshold verbosity above which to print. + newline: newline character (or set of characters), defaults to ``\\n`` but ``\\x0d`` (carriage return) might be useful. """ if verbosity >= minimal_verbosity: @@ -449,14 +478,14 @@ def get_username(): return psutil.Process().username() -def temp_dir(*args: str) -> str: +def temp_dir(*child_dirs: str) -> str: """ - Function to create directory within the TMP directory of the file system + Function to create directory within the TMP directory of the file system, starting with `/<TMP>/binary_c_python-<username>` Makes use of os.makedirs exist_ok which requires python 3.2+ Args: - 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' + *child_dirs: 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-<username>/tests/grid'`` Returns: the path of a sub directory called binary_c_python in the TMP of the file system @@ -467,8 +496,8 @@ def temp_dir(*args: str) -> str: path = os.path.join(tmp_dir, "binary_c_python-{}".format(username)) # loop over the other paths if there are any: - if args: - for extra_dir in args: + if child_dirs: + for extra_dir in child_dirs: path = os.path.join(path, extra_dir) # @@ -756,7 +785,7 @@ def get_help( Will check whether it is a valid parameter. - Binary_c will output things in the following order; + Binary_c will output things in the following order: - Did you mean? - binary_c help for variable - default @@ -772,8 +801,8 @@ def get_help( parameter isn't valid Returns: - Dictionary containing the help info. This dictionary contains 'parameter_name', - 'parameter_value_input_type', 'description', optionally 'macros' + Dictionary containing the help info. This dictionary contains `parameter_name`, + `parameter_value_input_type`, `description`, optionally `macros` """ available_arg_keys = get_arg_keys() @@ -1097,7 +1126,7 @@ def write_binary_c_parameter_descriptions_to_rst_file(output_file: str) -> None: argdict = arguments_dict[el]["parameters"][arg] print("| **Parameter**: {}".format(argdict["param_name"]), file=f) - print("| **Description**: {}".format(argdict["description"]), file=f) + print("| **Description**: {}".format(argdict["description"].replace("|Rout/Rin-1|", "abs(Rout/Rin-1)")), file=f) if "parameter_value_input_type" in argdict: print( "| **Parameter input type**: {}".format( diff --git a/binarycpython/utils/population_extensions/distribution_functions.py b/binarycpython/utils/population_extensions/distribution_functions.py index dfe114047..c26c929e6 100644 --- a/binarycpython/utils/population_extensions/distribution_functions.py +++ b/binarycpython/utils/population_extensions/distribution_functions.py @@ -409,17 +409,19 @@ class distribution_functions: self, m: Union[int, float], newopts: dict = None ) -> Union[int, float]: """ - 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 - } + Probability distribution function for Kroupa 2001 IMF. + + The (default) values for this is:: + + default = { + "m0": 0.1, + "m1": 0.5, + "m2": 1, + "mmax": 100, + "p1": -1.3, + "p2": -2.3, + "p3": -2.3 + } Args: m: mass to evaluate the distribution at diff --git a/binarycpython/utils/population_extensions/spacing_functions.py b/binarycpython/utils/population_extensions/spacing_functions.py index d7792601a..e2161e502 100644 --- a/binarycpython/utils/population_extensions/spacing_functions.py +++ b/binarycpython/utils/population_extensions/spacing_functions.py @@ -91,13 +91,13 @@ class spacing_functions: Example: The following allocates 10 stars between 0.1 and 0.65, 20 stars between 0.65 - and 0.85, and 10 stars between 0.85 and 10.0 Msun. + and 0.85, and 10 stars between 0.85 and 10.0 Msun:: - samplerfunc="const_ranges((({},{},{}),({},{},{}),({},{},{})))".format( - 0.1,0.65,10, - 0.65,0.85,20, - 0.85,10.0,10 - ), + samplerfunc="const_ranges((({},{},{}),({},{},{}),({},{},{})))".format( + 0.1, 0.65, 10, + 0.65, 0.85, 20, + 0.85, 10.0, 10 + ) """ @@ -209,14 +209,13 @@ class spacing_functions: Array of masses. Example: - # these are lines set as options to Population.add_grid_value(...) + these are lines set as options to Population.add_grid_value(...):: - # linear time bins of 1Gyr - samplerfunc="self.const_dt(self,dt=1000,nres=100,mmin=0.07,mmax=2.0,showtable=True)" + # linear time bins of 1Gyr + samplerfunc="self.const_dt(self,dt=1000,nres=100,mmin=0.07,mmax=2.0,showtable=True)" - # logarithmic spacing in time, generally suitable for Galactic - # chemical evolution yield grids. - samplerfunc="self.const_dt(self,dlogt=0.1,nres=100,mmin=0.07,mmax=80.0,maxdm=((0.07,1.0,0.1),(1.0,10.0,1.0),(10.0,80.0,2.0)),showtable=True,logspacing=True,fsample=1.0/4.0)" + # logarithmic spacing in time, generally suitable for Galactic chemical evolution yield grids. + samplerfunc="self.const_dt(self,dlogt=0.1,nres=100,mmin=0.07,mmax=80.0,maxdm=((0.07,1.0,0.1),(1.0,10.0,1.0),(10.0,80.0,2.0)),showtable=True,logspacing=True,fsample=1.0/4.0)" """ -- GitLab