Skip to content
Snippets Groups Projects
examples.py 7.4 KiB
Newer Older
#!/usr/bin/python3
import os
import sys

David Hendriks's avatar
David Hendriks committed
from binarycpython import _binary_c_bindings
David Hendriks's avatar
David Hendriks committed
from binarycpython.utils.functions import example_parse_output
from binarycpython.utils.custom_logging_functions import (
    autogen_C_logging_code,
    binary_c_log_code,
from binarycpython.utils.run_system_wrapper import run_system

"""
Very basic scripts to run a binary system and print the output.

Use these as inspiration/base.
def run_example_binary():
    """
David Hendriks's avatar
David Hendriks committed
    Function to run a binary system. Very basic approach which directly adresses the run_system(..) python-c wrapper function.
    m1 = 15.0  # Msun
    m2 = 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.
    argstring = "binary_c M_1 {m1} M_2 {m2} separation {separation} orbital_period {orbital_period} \
        eccentricity {eccentricity} metallicity {metallicity} \
        max_evolution_time {max_evolution_time}".format(
        m1=m1,
        m2=m2,
        separation=separation,
        orbital_period=orbital_period,
        eccentricity=eccentricity,
        metallicity=metallicity,
        max_evolution_time=max_evolution_time,
    )
David Hendriks's avatar
David Hendriks committed
    output = _binary_c_bindings.run_system(argstring)
def run_example_binary_with_run_system():
    """
David Hendriks's avatar
David Hendriks committed
    This function serves as an example on the function run_system and parse_output.
    There is more functionality with this method and several tasks are done behind the scene.

    Requires pandas, numpy to run.

    run_system: mostly just makes passing arguments to the function easier. It also loads all the necessary defaults in the background
David Hendriks's avatar
David Hendriks committed
    parse_output: Takes the raw output of binary_c and selects those lines that start with the given header.
    Note, if you dont use the custom_logging functionality binary_c should be configured to have output that starts with that given header
David Hendriks's avatar
David Hendriks committed
    The parsing of the output only works correctly if either all of the values are described inline like `mass=<number>' or none of them are.
    """

    import pandas as pd
    import numpy as np

    # Run system. all arguments can be given as optional arguments.
    output = run_system(M_1=10, M_2=20, separation=0, orbital_period=100000000000)

    # Catch results that start with a given header. (Mind that binary_c has to be configured to print them if your not using a custom logging function)
David Hendriks's avatar
David Hendriks committed
    result_example_header_1 = example_parse_output(
        output, selected_header="example_header_1"
    )
    result_example_header_2 = example_parse_output(
        output, selected_header="example_header_2"
    )

    # print(result_example_header_1)
    #### Now do whatever you want with it:
    # Put it in numpy arrays
    # t_res = np.asarray(result_example_header['t'], dtype=np.float64, order='C')
    # m_res = np.asarray(result_example_header['mass'], dtype=np.float64, order='C')
    # 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)
    print(df)

    # 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"]
    # sliced_df = df[df.t < 1000] # Cut off late parts of evolution
    # print(sliced_df[["t","m1"]])

    # Some routine to plot.

def run_example_custom_logging_autogenerated():
    """
    This is an example function for the autogeneration of logging codes that binary_c uses.
    """

    # generate logging lines
    logging_line = autogen_C_logging_code(
        {
            "MY_STELLAR_DATA": ["model.time", "star[0].mass"],
            "my_sss2": ["model.time", "star[1].mass"],
        }
    )

    # Generate code around logging lines
    custom_logging_code = binary_c_log_code(logging_line)

    # Generate library and get memaddr
    func_memaddr, shared_lib_filename = create_and_load_logging_function(
        custom_logging_code
    )

    #
    m1 = 15.0  # Msun
    m2 = 14.0  # Msun
    separation = 0  # 0 = ignored, use period
    orbital_period = 4530.0  # days
    eccentricity = 0.0
    metallicity = 0.02
    max_evolution_time = 15000
    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}".format(
        m1,
        m2,
        separation,
        orbital_period,
        eccentricity,
        metallicity,
        max_evolution_time,
David Hendriks's avatar
David Hendriks committed
    output = _binary_c_bindings.run_system(
        argstring, custom_logging_func_memaddr=func_memaddr
    )
# run_example_custom_logging_autogenerated()
def run_example_binary_with_custom_logging():
    """
David Hendriks's avatar
David Hendriks committed
    Function that will use a automatically generated piece of logging code. Compile it, load it
    into memory and run a binary system. See run_system on how several things are done in the background here.
    """

    import pandas as pd
    import numpy as np

    # generate logging lines. Here you can choose whatever you want to have logged, and with what header
    # this generates working print statements
    logging_line = autogen_C_logging_code(
David Hendriks's avatar
David Hendriks committed
        {
            "MY_STELLAR_DATA": ["model.time", "star[0].mass"],
        }
    )
    # OR
    # You can also decide to `write` your own logging_line, which allows you to write a more complex logging statement with conditionals.
    logging_line = 'Printf("MY_STELLAR_DATA time=%g mass=%g\\n", stardata->model.time, stardata->star[0].mass)'

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

    # Run system. all arguments can be given as optional arguments. the custom_logging_code is one of them and will be processed automatically.
    output = run_system(
        M_1=1,
        metallicity=0.002,
        M_2=0.1,
        separation=0,
        orbital_period=100000000000,
        custom_logging_code=custom_logging_code,
    )
    # Catch results that start with a given header. (Mind that binary_c has to be configured to print them if your not using a custom logging function)
    # DOESNT WORK YET if you have the line autogenerated.
    result_example_header = parse_output(output, "MY_STELLAR_DATA")
    # Cast the data into a dataframe.
    df = pd.DataFrame.from_dict(result_example_header, dtype=np.float64)

    # 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
    """

    import pandas as pd
    import numpy as np
    import tempfile

    # Run system. all arguments can be given as optional arguments.
    output = run_system(
        M_1=10,
        M_2=20,
        separation=0,
        orbital_period=100000000000,
        log_filename=tempfile.gettempdir() + "/test_log.txt",
David Hendriks's avatar
David Hendriks committed
run_example_binary_with_writing_logfile()