From 6964bdbfc8d21acd93e91eaded048d686130f47a Mon Sep 17 00:00:00 2001
From: Jan Grewe <jan.grewe@g-node.org>
Date: Sun, 27 Sep 2020 17:16:24 +0200
Subject: [PATCH] more plotting

---
 chirp_stimulation.py         |  5 ++--
 chirps_as_probing_signals.md |  2 +-
 plots.py                     | 56 ++++++++++++++++++++++--------------
 response_discriminability.py |  2 --
 4 files changed, 38 insertions(+), 27 deletions(-)

diff --git a/chirp_stimulation.py b/chirp_stimulation.py
index 08ffb71..94271d6 100644
--- a/chirp_stimulation.py
+++ b/chirp_stimulation.py
@@ -18,7 +18,7 @@ def despine(axis, spines=None, hide_ticks=True):
         axis.yaxis.set_ticks([])
 
 
-def create_chirp(*,eodf=500, chirpsize=100, chirpduration=0.015, ampl_reduction=0.05, chirptimes=[0.05, 0.2], kurtosis=1.0, duration=1., dt=0.00001):
+def create_chirp(eodf=500, chirpsize=100, chirpduration=0.015, ampl_reduction=0.05, chirptimes=[0.05, 0.2], kurtosis=1.0, duration=1., dt=0.00001):
     """create a fake fish eod that contains chirps at the given times. EOF is a simple sinewave. Chirps are modeled with Gaussian profiles in amplitude reduction and frequency ecxcursion.
 
     Args:
@@ -110,8 +110,7 @@ def plot_simulation():
     combined_signal = sender_eod + receiver_eod
 
     ylims = [-np.ceil(np.max(combined_signal)), np.ceil(np.max(combined_signal))]
-    embed()
-    exit()
+   
     fig = plt.figure()
     eod1_ax = fig.add_subplot(321)
     eod1_ax.plot(time, sender_eod)
diff --git a/chirps_as_probing_signals.md b/chirps_as_probing_signals.md
index 2869b82..4943425 100644
--- a/chirps_as_probing_signals.md
+++ b/chirps_as_probing_signals.md
@@ -42,7 +42,7 @@ Won't do, this is trivial?!
 ### 3. Does the chirp increase the detectablility of another animal?
 
 * Work out the difference between baseline activity and a foreign chirp response: --> done
-    * calculate the discriminability between the baseline (no-other fish present) and the another fish is present for each contrast
+* calculate the discriminability between the baseline (no-other fish present) and the another fish is present for each contrast -> done
 * Work out the difference between the soliloquy and the response to self generated chirp in a communication context -> done
 * Compare to the beat alone parts of the responses. -> done
 * What kernels to use? -> done
diff --git a/plots.py b/plots.py
index 6a0cb5e..fa2ef23 100644
--- a/plots.py
+++ b/plots.py
@@ -177,26 +177,30 @@ def create_response_plot(filename, current_df=20, figure_name=None):
             ax.set_ylabel("frequency [Hz]", va="center")
             ax.yaxis.set_label_coords(-0.45, 3.5)
         
-    name = figure_name if figure_name is not None else "chirp_responses.pdf"
-    name = (name + ".pdf") if ".pdf" not in name else name
-    plt.savefig(os.path.join(figure_folder, name))
+    plt.savefig(figure_name)
     plt.close()
     nf.close()
 
 
-def response_examples():
-    filename = sorted(glob.glob(os.path.join(data_folder, "*.nix")))[0]
-    fig_name = filename.split(os.path.sep)[-1].split(".nix")[0] + "_df_20Hz.pdf"
-    create_response_plot(filename, 20, figure_name=fig_name)
-    fig_name = filename.split(os.path.sep)[-1].split(".nix")[0] + "_df_-100Hz.pdf"
-    create_response_plot(filename, -100, figure_name=fig_name)
+def response_examples(args):
+    files = sorted(glob.glob(args.cell + "*"))
+    if len(files) < 1:
+        raise ValueError("Cell data with name %s not found" % args.cell)
+    filename = files[0]
+    create_response_plot(filename, args.deltaf, figure_name=args.outfile)
 
 
-def plot_detection_results(data_frame, df, kernel_width, cell, figure_name=None):
+def plot_detection_results(data_frame, df, kernel_width, cell=None, figure_name=None):
+    if cell is None:
+        cell = data_frame.cell.unique()[0]
+    dfs = np.sort(data_frame.df.unique())
+    if df not in dfs:
+        raise ValueError("requested deltaf not present, valid choices are: " + str(dfs))
     cell_results = data_frame[(data_frame.cell == cell) & (data_frame.df == df)]
     conditions = sorted(cell_results.detection_task.unique())
     kernels = sorted(cell_results.kernel_width.unique())
-
+    if kernel_width not in kernels:
+        raise ValueError("requested kernel not present, valid choices are: " + str(kernels))
     fig = plt.figure(figsize=(6.5, 5.5))
     fig_grid = (8, 7)
     for i, c in enumerate(conditions):
@@ -240,20 +244,18 @@ def plot_detection_results(data_frame, df, kernel_width, cell, figure_name=None)
         if i == 0:
             auc_ax.legend(ncol=2, fontsize=6, handletextpad=0.4, columnspacing=1.0, labelspacing=0.25, frameon=False, loc="lower center")
         auc_ax.plot([min(contrasts), max(contrasts)], [0.5, 0.5], lw=0.5, ls="--", zorder=0)
-    name = figure_name if figure_name is not None else "foreign_fish_detection.pdf"
-    name = (name + ".pdf") if ".pdf" not in name else name
-    fig.savefig(os.path.join(figure_folder, name))
 
+    fig.savefig(figure_name)
 
-def foreign_fish_detection_example_plot(): 
+
+def foreign_fish_detection_example_plot(args): 
     files = glob.glob(os.path.join(data_folder, "*discriminations.h5"))
     if len(files) == 0:
         raise ValueError("no discrimination results found!")
     store = pd.HDFStore(files[0])
-    data_frame = store.get("discrimination_results")
-    embed()
-    plot_detection_results(data_frame, 20, 0.001, )
-    pass
+    data_frame = store.get("discrimination_results")   
+    plot_detection_results(data_frame, args.deltaf, args.kernel_width, figure_name=args.outfile)
+    store.close()
 
 
 def performance_plot(args):
@@ -330,6 +332,12 @@ def main():
     comp_parser.add_argument("-o", "--outfile", default=os.path.join(figure_folder, "comparisons.pdf"), help="filename of the plot")
     comp_parser.set_defaults(func=plot_comparisons)
 
+    roc_parser = subparsers.add_parser("roc", help="plot roc analysis of example cell")
+    roc_parser.add_argument("-o", "--outfile", default=os.path.join(figure_folder, "roc_analysis.pdf"), help="filename of the plot")
+    roc_parser.add_argument("-d", "--deltaf", type=int, default=20, help="deltaf for individual plot")
+    roc_parser.add_argument("-k", "--kernel_width", type=float, default=0.001, help="Kernel width to choose for plotting, defaults to 0.001s")
+    roc_parser.set_defaults(func=foreign_fish_detection_example_plot)
+    
     perf_parser = subparsers.add_parser("discrimination", help="plot discrimination performance across all cells")
     perf_parser.add_argument("-o", "--outfile", default=os.path.join(figure_folder, "discrimination_performances.pdf"), help="filename of the plot")
     perf_parser.add_argument("-k", "--kernel_width", type=float, default=0.001, help="Kernel width to choose for plotting")
@@ -337,10 +345,16 @@ def main():
     perf_parser.add_argument("-c", "--contrasts", type=float, nargs="+", default=[5, 10, 20], help="stimulus contrast for individual plot")
     perf_parser.set_defaults(func=performance_plot)
 
+    resps_parser = subparsers.add_parser("responses", help="plot responses from and example cell")
+    resps_parser.add_argument("-o", "--outfile", default=os.path.join(figure_folder, "response_example.pdf"), help="filename of the plot")
+    resps_parser.add_argument("-d", "--deltaf", type=int, default=20, help="deltaf for individual plot")
+    dflt_cell = os.path.join(data_folder, "cell_2010-11-08-al")
+    resps_parser.add_argument("-c", "--cell", type=str, default=dflt_cell, help="cell name, defaults to %s" %dflt_cell)
+    resps_parser.set_defaults(func=response_examples)
+
     args = parser.parse_args()
     args.func(args)
-   
-   
+
 
 if __name__ == "__main__":
     main()
diff --git a/response_discriminability.py b/response_discriminability.py
index b78a1a4..9d9173c 100644
--- a/response_discriminability.py
+++ b/response_discriminability.py
@@ -210,8 +210,6 @@ def foreign_fish_detection_chirp(block_map, df, all_contrasts, all_conditions, k
     return detection_performances
 
 
-
-
 def foreign_fish_detection(block_map, all_dfs, all_contrasts, all_conditions, current_df=None, cell_name="", store_roc=False):
     dfs = [current_df] if current_df is not None else all_dfs 
     kernels = [0.00025, 0.0005, 0.001, 0.0025]