From 989586dadd8fe94fcecca3460ce46a2f62a9791c Mon Sep 17 00:00:00 2001
From: David Hendriks <davidhendriks93@gmail.com>
Date: Tue, 10 Sep 2019 15:37:33 +0100
Subject: [PATCH] added tests and output parsing

---
 {utils => binaryc_python_utils}/defaults.py   |  0
 binaryc_python_utils/functions.py             | 84 +++++++++++++++++++
 .../stellar_types.py                          |  0
 examples/full_evolution_with_plot.py          |  3 -
 tests_david/test_david.py                     |  2 +-
 tests_david/test_import.py                    |  5 --
 tests_david/test_noteboo.ipynb                | 41 ---------
 tests_david/testing_automatic_log_readout.py  | 40 +++++++--
 utils/functions.py                            | 12 ---
 9 files changed, 117 insertions(+), 70 deletions(-)
 rename {utils => binaryc_python_utils}/defaults.py (100%)
 create mode 100644 binaryc_python_utils/functions.py
 rename {utils => binaryc_python_utils}/stellar_types.py (100%)
 delete mode 100644 tests_david/test_import.py
 delete mode 100644 tests_david/test_noteboo.ipynb
 delete mode 100644 utils/functions.py

diff --git a/utils/defaults.py b/binaryc_python_utils/defaults.py
similarity index 100%
rename from utils/defaults.py
rename to binaryc_python_utils/defaults.py
diff --git a/binaryc_python_utils/functions.py b/binaryc_python_utils/functions.py
new file mode 100644
index 000000000..2cf2ed3a3
--- /dev/null
+++ b/binaryc_python_utils/functions.py
@@ -0,0 +1,84 @@
+import binary_c
+
+from collections import defaultdict
+from binaryc_python_utils.defaults import physics_defaults
+
+def create_arg_string(arg_dict):
+    """
+    Function that creates the arg string
+    """
+
+    arg_string = '' 
+    for key in arg_dict.keys():
+        arg_string += "{key} {value} ".format(key=key, value=arg_dict[key])
+    arg_string = arg_string.strip()
+    return arg_string
+
+def run_system(**kwargs):
+    """
+    Wrapper to run a system with settings 
+    """
+
+    # Load args
+    physics_args = physics_defaults.copy()
+
+    # For example
+    # physics_args['M_1'] = 20
+    # physics_args['separation'] = 0 # 0 = ignored, use period
+    # physics_args['orbital_period'] = 100000000000 # To make it single
+
+    # Use kwarg value to override defaults and add new args
+    for key in kwargs.keys():
+        physics_args[key] = kwargs[key]
+
+    # Construct arguments string and final execution string
+    arg_string = create_arg_string(physics_args)
+    arg_string = f'binary_c {arg_string}' 
+
+    # Run it and get output
+    buffer = ""
+    output = binary_c.run_binary(arg_string)
+
+    return output
+
+
+def parse_output(output, selected_header):
+    """
+    Function that parses output of binaryc when it is construction like this:
+    DAVID_SINGLE_ANALYSIS t=0 mass=20 
+
+    You can give a 'selected_header' to catch any line that starts with that. 
+    Then the values will be put into a 
+    """
+    value_dicts = []
+    val_lists = []
+
+    # split output on newlines
+    for i, line in enumerate(output.split('\n')):
+        # Skip any blank lines
+        if not line=='':
+            split_line = line.split()
+
+            # Select parts
+            header = split_line[0]
+            value_array = split_line[1:]
+
+            # Catch line starting with selected header
+            if header==selected_header:
+                # print(value_array)
+                # Make a dict 
+                value_dict = {}
+                for el in value_array:
+                    key, val = el.split('=')
+                    value_dict[key] = val
+                value_dicts.append(value_dict)
+
+    keys = value_dicts[0].keys()
+
+    # Construct final dict.
+    final_values_dict = defaultdict(list)
+    for value_dict in value_dicts:
+        for key in keys:
+            final_values_dict[key].append(value_dict[key])
+
+    return final_values_dict
\ No newline at end of file
diff --git a/utils/stellar_types.py b/binaryc_python_utils/stellar_types.py
similarity index 100%
rename from utils/stellar_types.py
rename to binaryc_python_utils/stellar_types.py
diff --git a/examples/full_evolution_with_plot.py b/examples/full_evolution_with_plot.py
index 6f0dff1e2..a966e7c3e 100644
--- a/examples/full_evolution_with_plot.py
+++ b/examples/full_evolution_with_plot.py
@@ -4,10 +4,7 @@ import matplotlib.pyplot as plt
 # Append root dir of this project to include functionality
 sys.path.append(os.path.dirname(os.getcwd()))
 import binary_c
-<<<<<<< HEAD
-=======
 
->>>>>>> 19cf329fcbd85a0dff06eaec60030d6bf3ebc0b0
 from utils.defaults import physics_defaults
 from utils.functions import create_arg_string
 
diff --git a/tests_david/test_david.py b/tests_david/test_david.py
index 3b9509991..eff9b19fd 100644
--- a/tests_david/test_david.py
+++ b/tests_david/test_david.py
@@ -3,7 +3,7 @@ import os
 import binary_c
 import matplotlib.pyplot as plt
 
-from utils.defaults import physics_defaults
+from binaryc_python_utils.defaults import physics_defaults
 
 ############################################################
 # Test script to run a binary using the binary_c Python
diff --git a/tests_david/test_import.py b/tests_david/test_import.py
deleted file mode 100644
index 848cfc72e..000000000
--- a/tests_david/test_import.py
+++ /dev/null
@@ -1,5 +0,0 @@
-import os, sys
-import binary_c
-# sys.path.append(os.path.dirname(file)) 
-print(os.getenv('PYTHONPATH'))
-#paths = os.getenv('PYTHONPATH').split(':' if os.name=='posix' else ';')
\ No newline at end of file
diff --git a/tests_david/test_noteboo.ipynb b/tests_david/test_noteboo.ipynb
deleted file mode 100644
index 6592ec55f..000000000
--- a/tests_david/test_noteboo.ipynb
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "cells": [
-  {
-   "cell_type": "code",
-   "execution_count": 2,
-   "metadata": {},
-   "outputs": [],
-   "source": [
-    "import binary_c"
-   ]
-  },
-  {
-   "cell_type": "code",
-   "execution_count": null,
-   "metadata": {},
-   "outputs": [],
-   "source": []
-  }
- ],
- "metadata": {
-  "kernelspec": {
-   "display_name": "Python 3",
-   "language": "python",
-   "name": "python3"
-  },
-  "language_info": {
-   "codemirror_mode": {
-    "name": "ipython",
-    "version": 3
-   },
-   "file_extension": ".py",
-   "mimetype": "text/x-python",
-   "name": "python",
-   "nbconvert_exporter": "python",
-   "pygments_lexer": "ipython3",
-   "version": "3.6.4"
-  }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
diff --git a/tests_david/testing_automatic_log_readout.py b/tests_david/testing_automatic_log_readout.py
index cbd50cfdb..941fd595c 100644
--- a/tests_david/testing_automatic_log_readout.py
+++ b/tests_david/testing_automatic_log_readout.py
@@ -1,13 +1,37 @@
-import os, sys
-import matplotlib.pyplot as plt
+import os, sys, time
 
-# # Append root dir of this project to include functionality
-# sys.path.append(os.path.dirname(os.getcwd()))
-# print(sys.path)
-# quit()
+import matplotlib.pyplot as plt
+from collections import defaultdict
+import numpy as np
+import pandas as pd
 
 import binary_c
-from utils.defaults import physics_defaults
-from utils.functions import create_arg_string
+from binaryc_python_utils.defaults import physics_defaults
+from binaryc_python_utils.functions import create_arg_string, parse_output, run_system
+
+"""
+Script to test some auto reading out.
+
+todo: make to hdf5
+"""
+
+start = time.time()
+output = run_system(M_1=10, M_2=20, separation=0, orbital_period=100000000000)
+result = parse_output(output, 'DAVID_SINGLE_ANALYSIS')
+stop = time.time()
+print("Took {:.2f}s to run single system".format(stop-start))
+print("The following keys are present in the results:\n{}".format(result.keys()))
+
+#### Now do whatever you want with it: 
+#t_res = np.asarray(result['t'], dtype=np.float64, order='C')
+#m_res = np.asarray(result['mass'], dtype=np.float64, order='C')
 
+# Cast the data into a dataframe. 
+df = pd.DataFrame.from_dict(result, dtype=np.float64)
+sliced_df = df[df.t < 1000] # Cut off late parts of evolution
+print(sliced_df["t"])
 
+plt.plot(sliced_df['t'], sliced_df['radius'])
+plt.xlabel('Time (Myr)')
+plt.ylabel('Radius (Rsol)')
+plt.show()
\ No newline at end of file
diff --git a/utils/functions.py b/utils/functions.py
deleted file mode 100644
index 2d4a479ea..000000000
--- a/utils/functions.py
+++ /dev/null
@@ -1,12 +0,0 @@
-def create_arg_string(arg_dict):
-    """
-    Function that creates the arg string
-    """
-
-    arg_string = '' 
-    for key in arg_dict.keys():
-        arg_string += "{key} {value} ".format(key=key, value=arg_dict[key])
-    arg_string = arg_string.strip()
-    return arg_string
-
-
-- 
GitLab