# Running individual systems with binarycpython

This notebook will show you how to run single systems and analyze their results.

It can be useful to have some functions to quickly run a single system to e.g. inspect what evolutionary steps a specific system goes through, to plot the mass loss evolution of a single star, etc.

## Single system with run_wrapper

The simplest method to run a single system is to use the run_system wrapper. This function deals with setting up the argument string, makes sure all the required parameters are included and handles setting and cleaning up the custom logging functionality (see notebook_custom_logging).

As arguments to this function we can add any of the parameters that binary_c itself actually knows, as well as: - custom_logging_code: string containing a print statement that binary_c can use to print information - log_filename: path of the logfile that binary_c generates - parse_function: function that handles parsing the output of binary-c

    [1]:

    import os
    from binarycpython.utils.functions import temp_dir
    TMP_DIR = temp_dir("notebooks", "notebook_individual_systems")

    [2]:

    from binarycpython.utils.run_system_wrapper import run_system
    # help(run_system) # Uncomment to see the docstring

    [3]:

    output = run_system(M_1=1)
    print(output)

    SINGLE_STAR_LIFETIME 1 12461.9

Lets try adding a log filename now:

    [4]:

    log_filename = os.path.join(TMP_DIR, 'test_logfile.txt')
    output = run_system(M_1=1, log_filename=log_filename, api_log_filename_prefix=TMP_DIR)
    with open(log_filename, 'r') as f:
        print(f.read())

          TIME      M1       M2   K1  K2           SEP      PER    ECC  R1/ROL1 R2/ROL2  TYPE RANDOM_SEED=17089 RANDOM_COUNT=0
         0.0000    1.000    0.000  1  15            -1       -1  -1.00   0.000   0.000  "INITIAL "
     11003.1302    1.000    0.000  2  15            -1       -1  -1.00   0.000   0.000  "OFF_MS"
     11003.1302    1.000    0.000  2  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     11582.2424    1.000    0.000  3  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     12325.1085    0.817    0.000  4  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     12457.1301    0.783    0.000  5  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     12460.9983    0.716    0.000  6  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     12460.9983    0.716    0.000  6  15            -1       -1  -1.00   0.000   0.000  "shrinkAGB"
     12461.9458    0.518    0.000 11  15            -1       -1  -1.00   0.000   0.000  "TYPE_CHNGE"
     15000.0000    0.518    0.000 11  15            -1       -1  -1.00   0.000   0.000  "MAX_TIME"

To get more useful output we can include a custom_logging snippet (see notebook_custom_logging):

    [5]:

    from binarycpython.utils.custom_logging_functions import binary_c_log_code

    # Create the print statement
    custom_logging_print_statement = """
    Printf("EXAMPLE_MASSLOSS %30.12e %g %g %d\\n",
        //
        stardata->model.time, // 1
        stardata->star[0].mass, //2
        stardata->common.zero_age.mass[0], //4

        stardata->star[0].stellar_type //5
    );
    """

    # Generate entire shared lib code around logging lines
    custom_logging_code = binary_c_log_code(custom_logging_print_statement)

    output = run_system(M_1=1, custom_logging_code=custom_logging_code, api_log_filename_prefix=TMP_DIR)
    print('\n'.join(output.splitlines()[:4]))

    EXAMPLE_MASSLOSS             0.000000000000e+00 1 1 1
    EXAMPLE_MASSLOSS             0.000000000000e+00 1 1 1
    EXAMPLE_MASSLOSS             1.000000000000e-06 1 1 1
    EXAMPLE_MASSLOSS             2.000000000000e-06 1 1 1

Now we have some actual output, it is time to create a parse_function which parses the output. Adding a parse_function to the run_system will make run_system run the output of binary_c through the parse_function.

    [6]:

    def parse_function(output):
        """
        Example function to parse the output of binary_c
        """

        #
        column_names = ['time', 'mass', 'initial_mass', 'stellar_type']
        value_lines = [column_names]

        # Loop over output
        for line in output.splitlines():

            # Select the lines starting with the header we chose
            if line.startswith("EXAMPLE_MASSLOSS"):

            # Split the output and fetch the data
                split_line = line.split()
                values = [float(el) for el in split_line[1:]]
                value_lines.append(values)

        return value_lines

    # Catch output
    output = run_system(M_1=1, custom_logging_code=custom_logging_code, parse_function=parse_function)
    print(output[:3])

    [['time', 'mass', 'initial_mass', 'stellar_type'], [0.0, 1.0, 1.0, 1.0], [0.0, 1.0, 1.0, 1.0]]

This output can now be turned into e.g. an Numpy array or Pandas dataframe (my favorite: makes querying the data very easy)

    [7]:

    import pandas as pd

    # Load data into dataframe
    example_df = pd.DataFrame(output)

    # Fix column headers
    example_df.columns = example_df.iloc[0]
    example_df = example_df.drop(example_df.index[0])

    print(example_df)

    0        time      mass initial_mass stellar_type
    1           0         1            1            1
    2           0         1            1            1
    3       1e-06         1            1            1
    4       2e-06         1            1            1
    5       3e-06         1            1            1
    ...       ...       ...          ...          ...
    1617  12461.8  0.546683            1            6
    1618  12461.9  0.517749            1           11
    1619  13461.9  0.517749            1           11
    1620  14461.9  0.517749            1           11
    1621    15000  0.517749            1           11

    [1621 rows x 4 columns]

## Single system via population object

When setting up your population object (see notebook_population), and configuring all the parameters, it is possible to run a single system using that same configuration. It will use the parse_function if set, and running a single system is a good method to test if everything works accordingly.

    [8]:

    from binarycpython.utils.grid import Population
    # help(Population) # Uncomment to see the docstring

First, let’s try this without any custom logging or parsing functionality

    [9]:

    # Create the population object
    example_pop = Population()

    # Set some parameters
    example_pop.set(
        verbosity=1,
        api_log_filename_prefix=TMP_DIR
    )
    example_pop.set(
        M_1=10
    )

    # get output and print
    output = example_pop.evolve_single()
    print(output)

    adding: api_log_filename_prefix=/tmp/binary_c_python/notebooks/notebook_individual_systems to BSE_options
    adding: M_1=10 to BSE_options
    Creating and loading custom logging functionality
    Running binary_c M_1 10 api_log_filename_prefix /tmp/binary_c_python/notebooks/notebook_individual_systems
    Cleaning up the custom logging stuff. type: single
    SINGLE_STAR_LIFETIME 10 28.4838

Now lets add some actual output with the custom logging

    [10]:

    custom_logging_print_statement = """
    Printf("EXAMPLE_MASSLOSS %30.12e %g %g %g %d\\n",
        //
        stardata->model.time, // 1
        stardata->star[0].mass, //2
        stardata->previous_stardata->star[0].mass, //3
        stardata->common.zero_age.mass[0], //4

        stardata->star[0].stellar_type //5
    );
    """

    example_pop.set(C_logging_code=custom_logging_print_statement)

    # get output and print
    output = example_pop.evolve_single()
    print('\n'.join(output.splitlines()[:4]))

    adding: C_logging_code=
    Printf("EXAMPLE_MASSLOSS %30.12e %g %g %g %d\n",
        //
        stardata->model.time, // 1
        stardata->star[0].mass, //2
        stardata->previous_stardata->star[0].mass, //3
        stardata->common.zero_age.mass[0], //4

        stardata->star[0].stellar_type //5
    );
     to grid_options
    Creating and loading custom logging functionality
    Running binary_c M_1 10 api_log_filename_prefix /tmp/binary_c_python/notebooks/notebook_individual_systems
    Cleaning up the custom logging stuff. type: single
    Removed /tmp/binary_c_python/custom_logging/libcustom_logging_8967553693ac4e11a49c42d4eef773e8.so
    EXAMPLE_MASSLOSS             0.000000000000e+00 10 0 10 1
    EXAMPLE_MASSLOSS             0.000000000000e+00 10 10 10 1
    EXAMPLE_MASSLOSS             1.000000000000e-06 10 10 10 1
    EXAMPLE_MASSLOSS             2.000000000000e-06 10 10 10 1

Lastly we can add a parse_function to handle parsing the output again.

Because the parse_function will now be part of the population object, it can access information of the object. We need to make a new parse function that is fit for an object: we the arguments now need to be (self, output). Returning the data is useful when running evolve_single(), but won’t be used in a population evolution.

    [11]:

    import os
    import json
    import numpy as np

    def object_parse_function(self, output):
        """
        Example parse function that can be added to the population object
        """

        # We can access object instance information now.
        # In this way we can store the results in a file for example.
        output_file = os.path.join(self.custom_options['output_dir'], 'example_output.json')

        #
        column_names = ['time', 'mass', 'initial_mass', 'stellar_type']
        value_lines = [column_names]

        # Loop over output
        for line in output.splitlines():

            # Select the lines starting with the header we chose
            if line.startswith("EXAMPLE_MASSLOSS"):

            # Split the output and fetch the data
                split_line = line.split()
                values = [float(el) for el in split_line[1:]]
                value_lines.append(values)

        # Turn into an array
        values_array = np.array(value_lines[1:])

        # make dict and fill
        output_dict = {}
        for i in range(len(column_names)):
            output_dict[column_names[i]] = list(values_array[:,i])

        # Write to file
        with open(output_file, 'w') as f:
            f.write(json.dumps(output_dict, indent=4))

        # Return something anyway
        return value_lines

    [12]:

    example_pop.set(
        parse_function=object_parse_function,
        output_dir=TMP_DIR,
        api_log_filename_prefix=TMP_DIR
    )
    output = example_pop.evolve_single()
    print(output[:4])

    # Example of loading the data that was written
    with open(os.path.join(example_pop.custom_options['output_dir'], 'example_output.json')) as f:
        written_data = json.loads(f.read())

    print(written_data.keys())

    adding: parse_function=<function object_parse_function at 0x7fb4d41ebbf8> to grid_options
    <<<< Warning: Key does not match previously known parameter:                     adding: output_dir=/tmp/binary_c_python/notebooks/notebook_individual_systems to custom_options >>>>
    adding: api_log_filename_prefix=/tmp/binary_c_python/notebooks/notebook_individual_systems to BSE_options
    Creating and loading custom logging functionality
    Running binary_c M_1 10 api_log_filename_prefix /tmp/binary_c_python/notebooks/notebook_individual_systems
    Cleaning up the custom logging stuff. type: single
    Removed /tmp/binary_c_python/custom_logging/libcustom_logging_5d7779e8190e4b79b10c7e6a44cb0e7e.so
    [['time', 'mass', 'initial_mass', 'stellar_type'], [0.0, 10.0, 0.0, 10.0, 1.0], [0.0, 10.0, 10.0, 10.0, 1.0], [1e-06, 10.0, 10.0, 10.0, 1.0]]
    dict_keys(['time', 'mass', 'initial_mass', 'stellar_type'])

## Single system via API functionality

It is possible to construct your own functionality to run a single system by directly calling the API function to run a system. Under the hood all the other functions and wrappers actually use this API.

There are less failsafes for this method, so this make sure the input is correct and binary_c knows all the arguments you pass in.

for more details on this API function see `notebook_api_functions`

First we must construct the argument string that we pass to binary_c

    [13]:

    # For a binary system we need to pass in these arguments
    M_1 = 15.0  # Msun
    M_2 = 14.0  # Msun
    separation = 0  # 0 = ignored, use period
    orbital_period = 4530.0  # days
    eccentricity = 0.0
    metallicity = 0.02
    max_evolution_time = 15000  # Myr. You need to include this argument.
    api_log_filename_prefix = TMP_DIR

    # Here we set up the argument string that is passed to the bindings
    argstring = """
    binary_c M_1 {M_1} M_2 {M_2} separation {separation} orbital_period {orbital_period} eccentricity {eccentricity} metallicity {metallicity} max_evolution_time {max_evolution_time} api_log_filename_prefix {api_log_filename_prefix}
    """.format(
        M_1=M_1,
        M_2=M_2,
        separation=separation,
        orbital_period=orbital_period,
        eccentricity=eccentricity,
        metallicity=metallicity,
        max_evolution_time=max_evolution_time,
        api_log_filename_prefix=TMP_DIR
    ).strip()

    from binarycpython import _binary_c_bindings

    output = _binary_c_bindings.run_system(argstring)
    print(output)

    SINGLE_STAR_LIFETIME 15 14.9947

As we can see above, the output is rather empty. But if SINGLE_STAR_LIFETIME is printed we know we caught the output correctly. To get actual output we should have timesteps printed in the `log_every_timestep.c` in binary_c, or add some custom_logging (see notebook_custom_logging).