From 619c1ae9887b35feea4441e82f7ab2f0d477d5f9 Mon Sep 17 00:00:00 2001
From: Gregory Ashton <gregory.ashton@ligo.org>
Date: Tue, 26 Feb 2019 21:04:04 -0800
Subject: [PATCH 1/2] Adds a results-file command line interface

---
 cli_bilby/bilby_result.py | 78 +++++++++++++++++++++++++++++++++++++++
 setup.py                  |  3 +-
 2 files changed, 80 insertions(+), 1 deletion(-)
 create mode 100644 cli_bilby/bilby_result.py

diff --git a/cli_bilby/bilby_result.py b/cli_bilby/bilby_result.py
new file mode 100644
index 000000000..419a190f2
--- /dev/null
+++ b/cli_bilby/bilby_result.py
@@ -0,0 +1,78 @@
+""" A command line interface to ease the process of batch jobs on result files
+
+Examples
+--------
+To convert all the JSON result files in `outdir` to hdf5 format:
+
+    $ bilby_result -r outdir/*json -c hdf5
+
+Note, by default this will save the new files in the outdir defined within the
+results files. To give a new location, use the `--outdir` argument.
+
+To print the version and `log_evidence` for all the result files in outdir:
+
+    $ bilby_result -r outdir/*json --print version log_evidence
+
+To generate a corner plot for all the files in outdir
+
+    $ bilby_result -r outdir/*json --call plot_corner
+
+This is effectively calling `plot_corner()` on each of the result files
+individually. Note that passing extra commands in is not yet implemented.
+
+"""
+import argparse
+import pandas as pd
+
+
+def setup_command_line_args():
+    parser = argparse.ArgumentParser(
+        description="Helper tool for bilby result files")
+    parser.add_argument("-r", "--results", nargs='+',
+                        help="List of results files.")
+    parser.add_argument("-c", "--convert", type=str, choices=['json', 'hdf5'],
+                        help="Convert all results.", default=False)
+    parser.add_argument("-o", "--outdir", type=str, default=None,
+                        help="Output directory.")
+    parser.add_argument("-b", "--bayes", action='store_true',
+                        help="Print all Bayes factors.")
+    parser.add_argument("-p", "--print", nargs='+', default=None,
+                        help="Result dictionary keys to print.")
+    parser.add_argument("--call", nargs='+', default=None,
+                        help="Result dictionary methods to call (no argument passing available).")
+    args, _ = parser.parse_known_args()
+
+    return args
+
+
+def print_bayes_factors(results):
+    print("\nPrinting Bayes factors:")
+    N = len(results)
+    for i, res in enumerate(results):
+        print("For label={}".format(res.label))
+        index = ['noise'] + [results[j].label for j in range(i + 1, N)]
+        data = [res.log_bayes_factor]
+        data += [res.log_evidence - results[j].log_evidence for j in range(i + 1, N)]
+        series = pd.Series(data=data, index=index, name=res.label)
+        print(series)
+
+
+def main():
+    args = setup_command_line_args()
+    import bilby
+    results = [bilby.core.result.read_in_result(filename=r)
+               for r in args.results]
+    if args.convert:
+        for r in results:
+            r.save_to_file(extension=args.convert, outdir=args.outdir)
+    if args.print is not None:
+        for r in results:
+            print("\nResult file: {}/{}".format(r.outdir, r.label))
+            for key in args.print:
+                print("  {}: {}".format(key, getattr(r, key, 'None')))
+    if args.call is not None:
+        for r in results:
+            for call in args.call:
+                getattr(r, call)()
+    if args.bayes:
+        print_bayes_factors(results)
diff --git a/setup.py b/setup.py
index 20f5e5577..441db8deb 100644
--- a/setup.py
+++ b/setup.py
@@ -85,7 +85,8 @@ setup(name='bilby',
           'pandas',
           'scipy'],
       entry_points={'console_scripts':
-                    ['bilby_plot=cli_bilby.plot_multiple_posteriors:main']
+                    ['bilby_plot=cli_bilby.plot_multiple_posteriors:main',
+                     'bilby_result=cli_bilby.bilby_result:main']
                     },
       classifiers=[
           "Programming Language :: Python :: 2.7",
-- 
GitLab


From 2f13912ccc0bad92285c2d66f422f05f12946adc Mon Sep 17 00:00:00 2001
From: Gregory Ashton <gregory.ashton@ligo.org>
Date: Fri, 1 Mar 2019 10:25:58 +1100
Subject: [PATCH 2/2] Fix formatting issues and add --ipython option

---
 cli_bilby/bilby_result.py | 49 ++++++++++++++++++++++++++++-----------
 1 file changed, 35 insertions(+), 14 deletions(-)

diff --git a/cli_bilby/bilby_result.py b/cli_bilby/bilby_result.py
index 419a190f2..aa0ea0f18 100644
--- a/cli_bilby/bilby_result.py
+++ b/cli_bilby/bilby_result.py
@@ -24,11 +24,14 @@ individually. Note that passing extra commands in is not yet implemented.
 import argparse
 import pandas as pd
 
+import bilby
+
 
 def setup_command_line_args():
     parser = argparse.ArgumentParser(
-        description="Helper tool for bilby result files")
-    parser.add_argument("-r", "--results", nargs='+',
+        description="Helper tool for bilby result files",
+        epilog=print(__doc__))
+    parser.add_argument("-r", "--results", nargs='+', required=True,
                         help="List of results files.")
     parser.add_argument("-c", "--convert", type=str, choices=['json', 'hdf5'],
                         help="Convert all results.", default=False)
@@ -40,39 +43,57 @@ def setup_command_line_args():
                         help="Result dictionary keys to print.")
     parser.add_argument("--call", nargs='+', default=None,
                         help="Result dictionary methods to call (no argument passing available).")
+    parser.add_argument("--ipython", action='store_true',
+                        help=("For each result given, drops the user into an "
+                              "IPython shell with the result loaded in"))
     args, _ = parser.parse_known_args()
 
     return args
 
 
-def print_bayes_factors(results):
+def read_in_results(filename_list):
+    results_list = []
+    for filename in filename_list:
+        results_list.append(bilby.core.result.read_in_result(filename=filename))
+    return results_list
+
+
+def print_bayes_factors(results_list):
     print("\nPrinting Bayes factors:")
-    N = len(results)
-    for i, res in enumerate(results):
+    N = len(results_list)
+    for i, res in enumerate(results_list):
         print("For label={}".format(res.label))
-        index = ['noise'] + [results[j].label for j in range(i + 1, N)]
+        index = ['noise'] + [results_list[j].label for j in range(i + 1, N)]
         data = [res.log_bayes_factor]
-        data += [res.log_evidence - results[j].log_evidence for j in range(i + 1, N)]
+        data += [res.log_evidence - results_list[j].log_evidence for j in range(i + 1, N)]
         series = pd.Series(data=data, index=index, name=res.label)
         print(series)
 
 
+def drop_to_ipython(results_list):
+    for result in results_list:
+        message = "Opened IPython terminal for result {}".format(result.label)
+        message += "\nBilby result loaded as `result`"
+        import IPython
+        IPython.embed(header=message)
+
+
 def main():
     args = setup_command_line_args()
-    import bilby
-    results = [bilby.core.result.read_in_result(filename=r)
-               for r in args.results]
+    results_list = read_in_results(args.results)
     if args.convert:
-        for r in results:
+        for r in results_list:
             r.save_to_file(extension=args.convert, outdir=args.outdir)
     if args.print is not None:
-        for r in results:
+        for r in results_list:
             print("\nResult file: {}/{}".format(r.outdir, r.label))
             for key in args.print:
                 print("  {}: {}".format(key, getattr(r, key, 'None')))
     if args.call is not None:
-        for r in results:
+        for r in results_list:
             for call in args.call:
                 getattr(r, call)()
     if args.bayes:
-        print_bayes_factors(results)
+        print_bayes_factors(results_list)
+    if args.ipython:
+        drop_to_ipython(results_list)
-- 
GitLab