diff --git a/TODO.org b/TODO.org index d97a105f00188320fed74afd391368ea58c68ce8..7104038c6ef1370addcea51cfa3279a98b896b0c 100644 --- a/TODO.org +++ b/TODO.org @@ -17,7 +17,8 @@ ** Features: *** Help functionality -**** TODO Add help functionality to the module by calling the binary_c help api +**** DONE Add help functionality to the module by calling the binary_c help api + CLOSED: [2019-12-16 Mon 00:20] **** TODO Add help_all functionality: to have binary_c return the whole set of parameter descriptions *** Floors Stroopwafel diff --git a/binarycpython/__init__.py b/binarycpython/__init__.py index 4e61002d8790367b28495e2049dc1e1951af7651..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/binarycpython/__init__.py +++ b/binarycpython/__init__.py @@ -1,2 +0,0 @@ -def ding(): - print("ding") diff --git a/binarycpython/utils/custom_logging_functions.py b/binarycpython/utils/custom_logging_functions.py index cd37988bc1f86ab8cfb1516389c2aa5f02bf0fb0..9f58b705a291e39df188765ba9b286a3b27bddff 100644 --- a/binarycpython/utils/custom_logging_functions.py +++ b/binarycpython/utils/custom_logging_functions.py @@ -5,6 +5,7 @@ import socket import tempfile import ctypes + def autogen_C_logging_code(logging_dict): """ Function that autogenerates PRINTF statements for binaryc. intput is a dictionary where the key is the header of that logging line and items which are lists of parameters\ @@ -206,7 +207,6 @@ def return_compilation_dict(verbose=False): ] libs = "{} {}".format(" ".join(library_paths), " ".join(non_library_paths)) - if verbose: print( "Building shared library for custom logging with (binary_c.h) at {} on {}\n".format( diff --git a/binarycpython/utils/functions.py b/binarycpython/utils/functions.py index 6d89b63ff1bd59ae3b8484bead10de5260847254..c65ca92db015fcacef934a4e1a67a28a69caa6a2 100644 --- a/binarycpython/utils/functions.py +++ b/binarycpython/utils/functions.py @@ -16,6 +16,7 @@ def create_arg_string(arg_dict): arg_string = arg_string.strip() return arg_string + def get_defaults(): """ Function that calls the binaryc get args function and cast it into a dictionary @@ -42,7 +43,8 @@ def get_arg_keys(): return get_defaults().keys() -def get_help(param_name, return_dict): + +def get_help(param_name, return_dict=False): """ Function that returns the help info for a given parameter. @@ -64,44 +66,57 @@ def get_help(param_name, return_dict): if param_name in available_arg_keys: help_info = binary_c_python_api.return_help(param_name) - cleaned = [el for el in help_info.split('\n') if not el==''] + cleaned = [el for el in help_info.split("\n") if not el == ""] # Get line numbers - did_you_mean_nr = [i for i, el in enumerate(cleaned) if el.startswith('Did you mean')] - parameter_line_nr = [i for i, el in enumerate(cleaned) if el.startswith('binary_c help')] - default_line_nr = [i for i, el in enumerate(cleaned) if el.startswith('Default')] - macros_line_nr = [i for i, el in enumerate(cleaned) if el.startswith('Available')] + did_you_mean_nr = [ + i for i, el in enumerate(cleaned) if el.startswith("Did you mean") + ] + parameter_line_nr = [ + i for i, el in enumerate(cleaned) if el.startswith("binary_c help") + ] + default_line_nr = [ + i for i, el in enumerate(cleaned) if el.startswith("Default") + ] + macros_line_nr = [ + i for i, el in enumerate(cleaned) if el.startswith("Available") + ] help_info_dict = {} # Get alternatives if did_you_mean_nr: - alternatives = cleaned[did_you_mean_nr[0]+1: parameter_line_nr[0]] + alternatives = cleaned[did_you_mean_nr[0] + 1 : parameter_line_nr[0]] alternatives = [el.strip() for el in alternatives] - help_info_dict['alternatives'] = alternatives + help_info_dict["alternatives"] = alternatives # Information about the parameter parameter_line = cleaned[parameter_line_nr[0]] - parameter_name = parameter_line.split(":")[1].strip().split(' ')[0] - parameter_value_input_type = ' '.join(parameter_line.split(":")[1].strip().split(' ')[1:]).replace('<', '').replace('>', '') + parameter_name = parameter_line.split(":")[1].strip().split(" ")[0] + parameter_value_input_type = ( + " ".join(parameter_line.split(":")[1].strip().split(" ")[1:]) + .replace("<", "") + .replace(">", "") + ) - help_info_dict['parameter_name'] = parameter_name - help_info_dict['parameter_value_input_type'] = parameter_value_input_type + help_info_dict["parameter_name"] = parameter_name + help_info_dict["parameter_value_input_type"] = parameter_value_input_type - description_line = ' '.join(cleaned[parameter_line_nr[0]+1 : default_line_nr[0]]) - help_info_dict['description'] = description_line + description_line = " ".join( + cleaned[parameter_line_nr[0] + 1 : default_line_nr[0]] + ) + help_info_dict["description"] = description_line - # Default: + # Default: default_line = cleaned[default_line_nr[0]] - default_value = default_line.split(':')[-1].strip() + default_value = default_line.split(":")[-1].strip() - help_info_dict['default'] = default_value + help_info_dict["default"] = default_value # Get Macros: if macros_line_nr: - macros = cleaned[macros_line_nr[0]+1:] - help_info_dict['macros'] = macros - + macros = cleaned[macros_line_nr[0] + 1 :] + help_info_dict["macros"] = macros for key in help_info_dict.keys(): print("{}:\n\t{}".format(key, help_info_dict[key])) @@ -110,9 +125,17 @@ def get_help(param_name, return_dict): return help_info_dict else: - print("{} is not a valid parameter name. Please choose from the following parameters:\n\t{}".format(param_name, list(available_arg_keys))) + print( + "{} is not a valid parameter name. Please choose from the following parameters:\n\t{}".format( + param_name, list(available_arg_keys) + ) + ) return None + +get_help("RLOF_method") + + def run_system(**kwargs): """ Wrapper to run a system with settings @@ -197,11 +220,11 @@ def run_system_with_log(**kwargs): # print(arg_string) # Run it and get output - buffer = "" output = binary_c_python_api.run_binary_with_logfile(arg_string) return output + def parse_output(output, selected_header): """ Function that parses output of binary_c: @@ -216,8 +239,8 @@ def parse_output(output, selected_header): TODO: Think about exporting to numpy array or pandas instead of a defaultdict """ - value_dicts = [] - val_lists = [] + value_dicts = [] + val_lists = [] # split output on newlines for i, line in enumerate(output.split("\n")): @@ -234,14 +257,16 @@ def parse_output(output, selected_header): if header == selected_header: # Check if the line contains '=' symbols: value_dict = {} - if all('=' in el for el in values_list): + if all("=" in el for el in values_list): for el in values_list: key, val = el.split("=") value_dict[key.strip()] = val.strip() value_dicts.append(value_dict) else: - if any('=' in el for el in values_list): - raise ValueError('Caught line contains some = symbols but not all of them do. aborting run') + if any("=" in el for el in values_list): + raise ValueError( + "Caught line contains some = symbols but not all of them do. aborting run" + ) else: for i, val in enumerate(values_list): value_dict[i] = val @@ -264,9 +289,8 @@ def parse_output(output, selected_header): return final_values_dict - def load_logfile(logfile): - with open(logfile, 'r') as f: + with open(logfile, "r") as f: logfile_data = f.readlines() time_list = [] @@ -296,6 +320,6 @@ def load_logfile(logfile): ecc_list.append(split_line[6]) rel_r1_list.append(split_line[7]) rel_r2_list.append(split_line[8]) - event_list.append(' '.join(split_line[9:])) + event_list.append(" ".join(split_line[9:])) - print(event_list) \ No newline at end of file + print(event_list) diff --git a/docs/source/conf.py b/docs/source/conf.py index a7ec7ab840e67b77ca37f58c1b891d79b34e491c..e9df5d4be59ee15b89a4eae8f408b62d022fe1ad 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -14,20 +14,20 @@ import os import sys # Include paths for python code -sys.path.insert(0, os.path.abspath('.')) -sys.path.insert(0, os.path.abspath('../../binarycpython')) +sys.path.insert(0, os.path.abspath(".")) +sys.path.insert(0, os.path.abspath("../../binarycpython")) # sys.path.insert(0, os.path.abspath('../../examples')) -sys.path.insert(0, os.path.abspath('../../binarycpython/utils')) +sys.path.insert(0, os.path.abspath("../../binarycpython/utils")) sys.path.insert(0, os.path.join(os.getenv("BINARY_C"), "src/API/")) # include paths for c code -cautodoc_root = os.path.abspath('../../') +cautodoc_root = os.path.abspath("../../") # -- Project information ----------------------------------------------------- -project = 'binary_c-python' -copyright = '2019, Jeff Andrews, Robert Izzard, David Hendriks' -author = 'Jeff Andrews, Robert Izzard, David Hendriks' +project = "binary_c-python" +copyright = "2019, Jeff Andrews, Robert Izzard, David Hendriks" +author = "Jeff Andrews, Robert Izzard, David Hendriks" # -- General configuration --------------------------------------------------- @@ -36,16 +36,16 @@ author = 'Jeff Andrews, Robert Izzard, David Hendriks' # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.doctest', - 'hawkmoth', - 'm2r', + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "hawkmoth", + "m2r", ] -source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -58,9 +58,9 @@ exclude_patterns = [] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -html_theme = 'alabaster' +html_theme = "alabaster" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] diff --git a/examples/examples.py b/examples/examples.py index ab728b6e4679484d265be8068ed00d8ca4fe2dbf..e81878fd70a8f62d9bd345453d93ed25f7e85fc4 100644 --- a/examples/examples.py +++ b/examples/examples.py @@ -45,6 +45,7 @@ def run_example_binary(): output = binary_c_python_api.run_binary(argstring) print(output) + run_example_binary() @@ -83,7 +84,6 @@ def run_example_binary_with_run_system(): # Or put them into a pandas array - # Cast the data into a dataframe. # This example automatically catches the column names because the binary_c output line is constructed as 'example_header_1 time=<number>..' df = pd.DataFrame.from_dict(result_example_header_1, dtype=np.float64) @@ -91,7 +91,7 @@ def run_example_binary_with_run_system(): # This example has column headers which are numbered, but we can override that with custom headers. df2 = pd.DataFrame.from_dict(result_example_header_2, dtype=np.float64) - df2.columns=['time', 'mass_1', 'mass_2', 'st1', 'st2', 'sep', 'ecc'] + df2.columns = ["time", "mass_1", "mass_2", "st1", "st2", "sep", "ecc"] print(df2) # print(df) @@ -100,8 +100,10 @@ def run_example_binary_with_run_system(): # Some routine to plot. + run_example_binary_with_run_system() + def run_example_binary_with_custom_logging(): """ Function that will use a automatically generated piece of logging code. Compile it, load it @@ -143,8 +145,10 @@ def run_example_binary_with_custom_logging(): # Do whatever you like with the dataframe. print(df) + run_example_binary_with_custom_logging() + def run_example_binary_with_writing_logfile(): """ Same as above but when giving the log_filename argument the log filename will be written @@ -161,7 +165,7 @@ def run_example_binary_with_writing_logfile(): separation=0, orbital_period=100000000000, log_filename=tempfile.gettempdir() + "/test_log.txt", - ) -run_example_binary_with_writing_logfile() \ No newline at end of file + +run_example_binary_with_writing_logfile() diff --git a/setup.py b/setup.py index 9e97e0f499f50bd70ca9917da1818511cc0b08f1..cd1c0651982b182a6337e32bdb0f2cda244020c9 100644 --- a/setup.py +++ b/setup.py @@ -1,4 +1,5 @@ from distutils.core import setup, Extension + # from setuptools import find_packages # from setuptools import setup, find_packages, Extension import os @@ -88,10 +89,12 @@ binary_c_python_api_module = Extension( language="C", ) + def readme(): - with open('README.md') as f: + with open("README.md") as f: return f.read() + setup( name="binarycpython", version="0.1", @@ -101,22 +104,18 @@ setup( long_description=readme(), url="https://gitlab.eps.surrey.ac.uk/ri0005/binary_c-python", license="", - package_dir = { - 'binarycpython': 'binarycpython', - 'binarycpython.utils': 'binarycpython/utils', + package_dir={ + "binarycpython": "binarycpython", + "binarycpython.utils": "binarycpython/utils", # 'binarycpython.core': 'lib', }, packages=[ - 'binarycpython', - 'binarycpython.utils', + "binarycpython", + "binarycpython.utils", # 'binarycpython.core', ], - # package_data={ # 'binarycpython.core': ['libbinary_c_api.so'], # }, - - ext_modules=[ - binary_c_python_api_module - ], # binary_c must be loaded + ext_modules=[binary_c_python_api_module], # binary_c must be loaded ) diff --git a/tests/python_API_test.py b/tests/python_API_test.py index 18c9ad8a002c7c82637578f4cdb980a8138d219e..e24a7906ee2bf516bd3d953d0969689b369ec8be 100755 --- a/tests/python_API_test.py +++ b/tests/python_API_test.py @@ -14,6 +14,7 @@ import tempfile # Test script for the api functions ############################################################ + def test_run_binary(): m1 = 15.0 # Msun m2 = 14.0 # Msun @@ -37,14 +38,17 @@ def test_run_binary(): print("\n\nBinary_c output:") print(output) + def test_return_help(): - out = binary_c_python_api.return_help('M_1') + out = binary_c_python_api.return_help("M_1") print(out) + def test_return_arglines(): out = binary_c_python_api.return_arglines() print(out) + def test_run_binary_with_log(): m1 = 15.0 # Msun m2 = 14.0 # Msun @@ -55,7 +59,7 @@ def test_run_binary_with_log(): max_evolution_time = 15000 log_filename = tempfile.gettempdir() + "/test_log.txt" - api_log_filename_prefix = tempfile.gettempdir()+'/test_log' + api_log_filename_prefix = tempfile.gettempdir() + "/test_log" argstring = "binary_c M_1 {0:g} M_2 {1:g} separation {2:g} orbital_period {3:g} eccentricity {4:g} metallicity {5:g} max_evolution_time {6:g} log_filename {7:s} api_log_filename_prefix {8:s}".format( m1, @@ -73,6 +77,7 @@ def test_run_binary_with_log(): print("\n\nBinary_c output:") print(output) + def test_run_binary_with_custom_logging(): """ """ @@ -111,13 +116,14 @@ def test_run_binary_with_custom_logging(): out = binary_c_python_api.run_binary_custom_logging(argstring, func_memaddr) print(out) + #### # test_run_binary() -test_run_binary_with_log() +# test_run_binary_with_log() # test_return_help() # test_return_arglines() -# test_run_binary_with_custom_logging() \ No newline at end of file +# test_run_binary_with_custom_logging()