def smooth(x, isosbestic, calcium, **kwargs): """Function that smooths the raw data and displays it in a plot. Args : x (arr) = The time data in X isosbestic (arr) = The adjusted isosbestic signal (time fitted to the video) calcium (arr) = The adjusted calcium signal (time fitted to the video) kwargs (dict) = Dictionnary with the parameters Returns : x (arr) = The new time data in X isosbestic_smoothed (arr) = The smoothed isosbestic signal calcium_smoothed (arr) = The smoothed calcium signal """ print("\nStarting smoothing for Isosbestic and Calcium signals !") isosbestic_smoothed = smooth_signal(isosbestic, window_len=kwargs["smoothing_window"])[:-kwargs["smoothing_window"]+1] calcium_smoothed = smooth_signal(calcium, window_len=kwargs["smoothing_window"])[:-kwargs["smoothing_window"]+1] x_max = x[-1] # print("Data length : {0}".format(ut.h_m_s(x_max, add_tags=True))) if kwargs["photometry_pp"]["plots_to_display"]["smoothing"]: xticks, xticklabels, unit = utils.generate_xticks_and_labels(x_max) fig = plt.figure(figsize=(10, 5), dpi=200.) ax0 = plt.subplot(211) p, = ax0.plot(x, isosbestic_smoothed, alpha=0.8, c=kwargs["photometry_pp"]["purple_laser"], lw=kwargs["lw"]) ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(isosbestic_smoothed, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("mV", fontsize=kwargs["fsl"]) ax0.legend(handles=[p], labels=["isosbestic"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title("Smoothed Isosbestic and Calcium signals", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) ax1 = plt.subplot(212, sharex=ax0) b, = ax1.plot(x, calcium_smoothed, alpha=0.8, c=kwargs["photometry_pp"]["blue_laser"], lw=kwargs["lw"]) ax1.set_xticks(xticks) ax1.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax1.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(calcium_smoothed, 0.1) ax1.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax1.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax1.set_ylim(y_min, y_max) ax1.set_ylabel("mV", fontsize=kwargs["fsl"]) ax1.legend(handles=[b], labels=["calcium"], loc=2, fontsize=kwargs["fsl"]) ax1.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) ax1.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["photometry_pp"]["multicursor"]: multi = MultiCursor(fig.canvas, [ax0, ax1], color='r', lw=1, vertOn=[ax0, ax1]) # FIXME: unused if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "Smoothed_Signals.{0}".format(kwargs["extension"])), dpi=200.) return x, isosbestic_smoothed, calcium_smoothed
def dFF(x, isosbestic, calcium, **kwargs): """Function that computes the dF/F of the fitted isosbestic and standardized (or not) calcium signals and displays it in a plot. Args : x (arr) = The time data in X isosbestic (arr) = The fitted isosbestic signal calcium (arr) = The standardized (or not) calcium signal kwargs (dict) = Dictionnary with the parameters Returns : dFF (arr) = Relative changes of fluorescence over time """ print("\nStarting the computation of dF/F !") df_f = calcium - isosbestic # computing dF/F max_x = x[-1] # print("Data length : {0}".format(ut.h_m_s(max_x, add_tags=True))) if kwargs["photometry_pp"]["plots_to_display"]["dFF"]: xticks, xticklabels, unit = utils.generate_xticks_and_labels(max_x) fig = plt.figure(figsize=(10, 3), dpi=200.) ax0 = plt.subplot(111) g, = ax0.plot(x, df_f, alpha=0.8, c="green", lw=kwargs["lw"]) ax0.plot((0, x[-1]), (0, 0), "--", color="black", lw=kwargs["lw"]) #Creates a horizontal dashed line at y = 0 to signal the baseline ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, max_x) ax0.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) if kwargs["photometry_pp"]["standardize"]: y_min, y_max, round_factor = utils.generate_yticks(df_f, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel(r"z-score $\Delta$F/F", fontsize=kwargs["fsl"]) ax0.legend(handles=[g], labels=[r"z-score $\Delta$F/F"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title(r"z-score $\Delta$F/F", fontsize=kwargs["fst"]) else: y_min, y_max, round_factor = utils.generate_yticks(df_f, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*100], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel(r"$\Delta$F/F", fontsize=kwargs["fsl"]) ax0.legend(handles=[g], labels=[r"$\Delta$F/F"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title(r"$\Delta$F/F", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "dFF.{0}".format(kwargs["extension"])), dpi=200.) return df_f
def align_channels(x, isosbestic, calcium, **kwargs): """Function that performs the alignement of the fitted isosbestic and standardized (or not) calcium signals and displays it in a plot. Args : x (arr) = The time data in X isosbestic (arr) = The fitted isosbestic signal calcium (arr) = The standardized (or not) calcium signal kwargs (dict) = Dictionnary with the parameters """ x_max = x[-1] if kwargs["photometry_pp"]["plots_to_display"]["channel_alignement"]: fig = plt.figure(figsize=(10, 3), dpi=200.) # FIXME: unused ax0 = plt.subplot(111) b, = ax0.plot(x, calcium, alpha=0.8, c=kwargs["photometry_pp"]["blue_laser"], lw=kwargs["lw"], zorder=0) p, = ax0.plot(x, isosbestic, alpha=0.8, c=kwargs["photometry_pp"]["purple_laser"], lw=kwargs["lw"], zorder=1) ax0.plot((0, x[-1]), (0, 0), "--", color="black", lw=kwargs["lw"]) #Creates a horizontal dashed line at y = 0 to signal the baseline xticks, xticklabels, unit = utils.generate_xticks_and_labels(x_max) ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, x_max) ax0.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) if kwargs["photometry_pp"]["standardize"]: y_min, y_max, round_factor = utils.generate_yticks(np.concatenate((isosbestic, calcium)), 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("z-score", fontsize=kwargs["fsl"]) else: y_min, y_max, round_factor = utils.generate_yticks(np.concatenate((isosbestic, calcium)), 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*100], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("Change in signal (%)", fontsize=kwargs["fsl"]) ax0.legend(handles=[p, b], labels=["isosbestic", "calcium"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title("Alignement of Isosbestic and Calcium signals", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "Alignement.{0}".format(kwargs["extension"])), dpi=200.)
def check_dF_with_behavior(position_bouts, length_bouts, color=("blue"), name="dF_&_behavioral_overlay", **kwargs): """Function that plots the pre-processed photometry data and overlays the behavior data. Args : position_bouts (arr) = list of start and end of each behavioral bout length_bouts (list) = list of the length of each behavioral bout color (list) = color(s) of the behavioral overlay(s) kwargs (dict) = dictionnary with additional parameters """ fig = plt.figure(figsize=(10, 3), dpi=200.) # FIXME: unused ax0 = plt.subplot(111) n = 0 handles = [] if len(position_bouts) == 1: labels = [kwargs["behavior_to_segment"]] else: labels = [kwargs["behavior_to_segment"], "Excluded"] ax0.plot(kwargs["photometry_data"]["dFF"]["x"], kwargs["photometry_data"]["dFF"]["dFF"], color="green", lw=kwargs["lw"]) ax0.plot( 0, kwargs["video_end"] - kwargs["photometry_data"]["time_lost"], (0, 0), "--", color="blue", lw=kwargs["lw"] ) #Creates a horizontal dashed line at y = 0 to signal the baseline xticks, xticklabels, unit = utils.generate_xticks_and_labels( kwargs["photometry_data"]["dFF"]["x"][-1]) ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, kwargs["photometry_data"]["dFF"]["x"][-1]) ax0.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) y_min, y_max, round_factor = utils.generate_yticks( kwargs["photometry_data"]["dFF"]["dFF"], 0.1) ax0.set_yticks(np.arange(y_min, y_max + round_factor, round_factor)) ax0.set_ylim(y_min, y_max) if kwargs["photometry_pp"]["standardize"]: ax0.set_yticklabels([ "{:.0f}".format(i) for i in np.arange(y_min, y_max + round_factor, round_factor) ], fontsize=kwargs["fsl"]) else: ax0.set_yticklabels([ "{:.0f}".format(i) for i in np.arange(y_min, y_max + round_factor, round_factor) * 100 ], fontsize=kwargs["fsl"]) for P, L in zip(position_bouts, length_bouts): patch = patches.Rectangle((0, 0), 1, 1, alpha=0.3, color=color[n], lw=0, edgecolor=None) handles.append(patch) for p, l in zip(P, L): patch = patches.Rectangle( (p[0], y_min + y_min * 0.1), l, (y_max + y_max * 0.1) - (y_min + y_min * 0.1), alpha=0.3, color=color[n], lw=0, edgecolor=None) ax0.add_patch(patch) n += 1 ax0.legend(handles=handles, labels=labels, loc=2, fontsize=kwargs["fsl"]) plt.tight_layout() if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "{0}.{1}".format(name, kwargs["extension"])), dpi=200.)
def peri_event_plot(data_around_major_bouts, length_major_bouts, cmap="inferno", **kwargs): """Function that plots the peri-event photometry data in two different formats. First a line plot showing the average signal before and after initiation of the behavior, Second a heatmap showing each individual signal traces before and after initiation of the behavior. Args : data_around_major_bouts (arr) = list of the pre-processed photometry data before and after initiation of the behavior length_major_bouts (list) = list of the length of each behavioral bout cmap (str) = colormap used for the heatmap kwargs (dict) = dictionnary with additional parameters """ mean_data_around_bouts = np.mean( data_around_major_bouts, axis=0) # Computes the mean for the peri-event photometry data std_data_around_bouts = np.std( data_around_major_bouts, axis=0 ) # Computes the standard deviation for the peri-event photometry data fig = plt.figure(figsize=(5, 5), dpi=200.) # Creates a figure # ============================================================================= # First Plot # ============================================================================= ax0 = plt.subplot(2, 1, 1) # Creates a subplot for the first figure x_range = np.linspace(0, len(mean_data_around_bouts), len(mean_data_around_bouts)) ax0.plot(x_range, mean_data_around_bouts, color="green", alpha=1., lw=kwargs["lw"] + 1, zorder=1) # Plots the average signal if kwargs["peri_event"][ "style"] == "individual": # If individual traces are to be displayed in the line plot for l in data_around_major_bouts: if kwargs["peri_event"]["individual_color"]: ax0.plot(l, alpha=0.5, lw=kwargs["lw"], zorder=0) # Plots individual traces else: ax0.plot(l, color="gray", alpha=0.5, lw=kwargs["lw"], zorder=0) # Plots individual traces ax0.plot(x_range, mean_data_around_bouts + std_data_around_bouts, color="green", alpha=0.5, lw=kwargs["lw"], zorder=1) ax0.plot(x_range, mean_data_around_bouts - std_data_around_bouts, color="green", alpha=0.5, lw=kwargs["lw"], zorder=1) ax0.fill_between(x_range, mean_data_around_bouts, (mean_data_around_bouts + std_data_around_bouts), color="green", alpha=0.1) ax0.fill_between(x_range, mean_data_around_bouts, (mean_data_around_bouts - std_data_around_bouts), color="green", alpha=0.1) y_min, y_max, round_factor = utils.generate_yticks( data_around_major_bouts.flatten(), 0.2) y_range = y_max - y_min ax0.set_yticks(np.arange(y_min, y_max + round_factor, round_factor)) ax0.set_yticklabels([ "{:.0f}".format(i) for i in np.arange(y_min, y_max + round_factor, round_factor) ], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) elif kwargs["peri_event"]["style"] == "average": ax0.plot(x_range, mean_data_around_bouts + std_data_around_bouts, color="green", alpha=0.3, lw=kwargs["lw"]) ax0.plot(x_range, mean_data_around_bouts - std_data_around_bouts, color="green", alpha=0.3, lw=kwargs["lw"]) ax0.fill_between(x_range, mean_data_around_bouts, (mean_data_around_bouts + std_data_around_bouts), color="green", alpha=0.1) ax0.fill_between(x_range, mean_data_around_bouts, (mean_data_around_bouts - std_data_around_bouts), color="green", alpha=0.1) y_min, y_max, round_factor = utils.generate_yticks( np.concatenate((mean_data_around_bouts + std_data_around_bouts, mean_data_around_bouts - std_data_around_bouts)), 0.2) y_range = y_max - y_min ax0.set_yticks(np.arange(y_min, y_max + round_factor, round_factor)) ax0.set_yticklabels([ "{:.0f}".format(i) for i in np.arange(y_min, y_max + round_factor, round_factor) ], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) # Creates a gray square on the line plot that represents the average length of a behavioral bout patch = patches.Rectangle( ((kwargs["peri_event"]["graph_distance_pre"] + 0.5) * kwargs["recording_sampling_rate"], -y_range * 0.1), width=np.mean(length_major_bouts) * kwargs["recording_sampling_rate"], height=y_range * 0.1, color="gray", lw=0, alpha=0.7) ax0.add_patch(patch) # Adds the patch to the plot ax0.plot( (0, len(mean_data_around_bouts)), (0, 0), "--", color="black", lw=kwargs["lw"] ) # Creates a horizontal dashed line at y = 0 to signal the baseline vline = ax0.axvline( x=(kwargs["peri_event"]["graph_distance_pre"] + 0.5) * kwargs["recording_sampling_rate"], color='red', linestyle='--', lw=kwargs["lw"] ) # Creates a vertical dashed line at x = 0 to signal the begining of the behavioral bout ax0.set_xticks( np.linspace(0, ((kwargs["peri_event"]["graph_distance_pre"] + kwargs["peri_event"]["graph_distance_post"] + 1) * kwargs["recording_sampling_rate"]), 5)) #Generates ticks for the x axis ax0.set_xticklabels( np.linspace(-kwargs["peri_event"]["graph_distance_pre"], kwargs["peri_event"]["graph_distance_post"], 5), fontsize=kwargs["fsl"]) # Generates labels for the x axis ax0.set_xlim(0, len(mean_data_around_bouts)) # Sets the limits for the x axis # ax0.set_xlabel("Time (s)", fontsize=kwargs["fsl"]) #Displays the label for the x axis ax0.legend( handles=[vline, patch], labels=["Begining of bout", "Average behavioral bout length"], loc=2, fontsize=kwargs["fsl"]) # Displays the legend of the first figure # ============================================================================= # Second Plot # ============================================================================= ax1 = plt.subplot(2, 1, 2) # Creates a subplot for the second figure if not kwargs["peri_event"]["normalize_heatmap"]: heatmap = ax1.imshow(data_around_major_bouts, cmap=cmap, aspect="auto", interpolation="none") else: heatmap = ax1.imshow( data_around_major_bouts, cmap=cmap, aspect="auto", norm=col.LogNorm(), interpolation="none") # norm=matplotlib.colors.LogNorm() ax1.axvline(x=(kwargs["peri_event"]["graph_distance_pre"] + 0.5) * kwargs["recording_sampling_rate"], color='red', linestyle='--', lw=kwargs["lw"]) ax1.set_xticks( np.linspace(0, ((kwargs["peri_event"]["graph_distance_pre"] + kwargs["peri_event"]["graph_distance_post"] + 1) * kwargs["recording_sampling_rate"]), 5)) #Generates ticks for the x axis ax1.set_xticklabels( np.linspace(-kwargs["peri_event"]["graph_distance_pre"], kwargs["peri_event"]["graph_distance_post"], 5), fontsize=kwargs["fsl"]) #Generates labels for the x axis ax1.set_xlim(0, len(mean_data_around_bouts)) # Sets the limits for the x axis ax1.set_xlabel("Time (s)", fontsize=kwargs["fsl"]) # Displays the label for the x axis ax1.set_yticks([]) ax1.set_ylim(-0.5, len(data_around_major_bouts) - 0.5) ax1.set_ylabel("Duration of individual bouts (s)", fontsize=kwargs["fsl"], labelpad=20) # Displays the label for the x axis for n, l in enumerate(length_major_bouts): ax1.text(-len(mean_data_around_bouts) * 0.01, n, l, ha="right", va="center", fontsize=kwargs["fsl"]) plt.gca().invert_yaxis() cax = fig.add_axes([1, 0.1, 0.02, 0.35]) cb = plt.colorbar(heatmap, ax=ax1, cax=cax) cb.ax.tick_params(labelsize=kwargs["fsl"]) cb.ax.get_yaxis().labelpad = 8 if kwargs["photometry_pp"]["standardize"]: ax0.set_ylabel( r"$\Delta$F/F (Z-Score)", fontsize=kwargs["fsl"]) #Displays the label for the y axis ax0.set_title( r"$\Delta$F/F (Z-Score) in function of time before & after {0} initiation" .format(kwargs["behavior_to_segment"]), fontsize=kwargs["fst"]) #Displays the titel for the first figure ax1.set_title( r"Individual $\Delta$F/F (Z-Score) in function of time before & after {0} initiation" .format(kwargs["behavior_to_segment"]), fontsize=kwargs["fst"]) cb.ax.set_ylabel(r"$\Delta$F/F (Z-Score)", rotation=270, fontsize=kwargs["fsl"]) else: ax0.set_ylabel( r"$\Delta$F/F (%)", fontsize=kwargs["fsl"]) #Displays the label for the y axis ax0.set_title( r"$\Delta$F/F (%) in function of time before & after {0} initiation" .format(kwargs["behavior_to_segment"]), fontsize=kwargs["fst"]) #Displays the titel for the first figure ax1.set_title( r"Individual $\Delta$F/F (%) in function of time before & after {0} initiation" .format(kwargs["behavior_to_segment"]), fontsize=kwargs["fst"]) cb.ax.set_ylabel(r"$\Delta$F/F (%)", rotation=270, fontsize=kwargs["fsl"]) plt.tight_layout() if kwargs["save"]: plt.savefig(os.path.join( kwargs["save_dir"], "Peri_Event_Plot.{0}".format(kwargs["extension"])), dpi=200., bbox_inches='tight')
def standardization(x, isosbestic, calcium, **kwargs): """Function that performs the standardization of the corrected signals and displays it in a plot. Args : x (arr) = The time data in X isosbestic (arr) = The baseline corrected isosbestic signal calcium (arr) = The baseline corrected calcium signal kwargs (dict) = Dictionnary with the parameters Returns : isosbestic_standardized (arr) = The standardized isosbestic signal calcium_standardized (arr) = The standardized calcium signal """ if kwargs["photometry_pp"]["standardize"]: print("\nStarting standardization for Isosbestic and Calcium signals !") isosbestic_standardized = (isosbestic - np.median(isosbestic)) / np.std(isosbestic) # standardization correction for isosbestic calcium_standardized = (calcium - np.median(calcium)) / np.std(calcium) # standardization for calcium x_max = x[-1] if kwargs["photometry_pp"]["plots_to_display"]["standardization"]: xticks, xticklabels, unit = utils.generate_xticks_and_labels(x_max) fig = plt.figure(figsize=(10, 5), dpi=200.) ax0 = plt.subplot(211) p, = ax0.plot(x, isosbestic_standardized, alpha=0.8, c=kwargs["photometry_pp"]["purple_laser"], lw=kwargs["lw"]) ax0.plot((0, x[-1]), (0, 0), "--", color="black", lw=kwargs["lw"]) #Creates a horizontal dashed line at y = 0 to signal the baseline ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(isosbestic_standardized, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("z-score", fontsize=kwargs["fsl"]) ax0.legend(handles=[p], labels=["isosbestic"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title("Standardization of Isosbestic and Calcium signals", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) ax1 = plt.subplot(212, sharex=ax0) b, = ax1.plot(x, calcium_standardized, alpha=0.8, c=kwargs["photometry_pp"]["blue_laser"], lw=kwargs["lw"]) ax1.plot((0, x[-1]), (0, 0), "--", color="black", lw=kwargs["lw"]) #Creates a horizontal dashed line at y = 0 to signal the baseline ax1.set_xticks(xticks) ax1.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax1.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(calcium_standardized, 0.1) ax1.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax1.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)], fontsize=kwargs["fsl"]) ax1.set_ylim(y_min, y_max) ax1.set_ylabel("z-score", fontsize=kwargs["fsl"]) ax1.legend(handles=[b], labels=["calcium"], loc=2, fontsize=kwargs["fsl"]) ax1.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) ax1.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["photometry_pp"]["multicursor"]: multi = MultiCursor(fig.canvas, [ax0, ax1], color='r', lw=1, vertOn=[ax0, ax1]) # FIXME: unused if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "Standardization.{0}".format(kwargs["extension"])), dpi=200.) else: utils.print_in_color("\nThe standardization step in skipped." " Parameter plot_args['photometry_pp']['standardize'] == False", "RED") isosbestic_standardized = isosbestic # standardization skipped calcium_standardized = calcium # standardization skipped return isosbestic_standardized, calcium_standardized
def find_baseline_and_crop(x, isosbestic, calcium, method="als", **kwargs): """Function that estimates the baseline of the smoothed signals and displays it in a plot. Args : x (arr) = The time data in X isosbestic (arr) = The smoothed isosbestic signal (time fitted to the video) calcium (arr) = The smoothed calcium signal (time fitted to the video) kwargs (dict) = Dictionnary with the parameters Returns : x (arr) = The time data in X isosbestic (arr) = The cropped isosbestic signal calcium (arr) = The cropped calcium signal isosbestic_fc (arr) = The baseline for the isosbestic signal calcium_fc (arr) = The baseline for the calcium signal """ print("\nStarting baseline computation for Isosbestic and Calcium signals !") if method == "als": x = crop_signal(x, int(kwargs["cropping_window"])) x = x - x[0] isosbestic = crop_signal(isosbestic, int(kwargs["cropping_window"])) calcium = crop_signal(calcium, int(kwargs["cropping_window"])) isosbestic_fc = baseline_asymmetric_least_squares_smoothing(isosbestic, kwargs["lambda"], kwargs["p"]) calcium_fc = baseline_asymmetric_least_squares_smoothing(calcium, kwargs["lambda"], kwargs["p"]) elif method == "ma": x = crop_signal(x, int(kwargs["moving_average_window"]/2)) x = x - x[0] isosbestic, isosbestic_fc = centered_moving_average(isosbestic, window=kwargs["moving_average_window"]) #moving average for isosbestic data calcium, calcium_fc = centered_moving_average(calcium, window=kwargs["moving_average_window"]) #moving average for calcium data x_max = x[-1] # print("Data length : {0}".format(ut.h_m_s(x_max, add_tags=True))) if kwargs["photometry_pp"]["plots_to_display"]["baseline_determination"]: xticks, xticklabels, unit = utils.generate_xticks_and_labels(x_max) fig = plt.figure(figsize=(10, 5), dpi=200.) ax0 = plt.subplot(211) p, = ax0.plot(x, isosbestic, alpha=0.8, c=kwargs["photometry_pp"]["purple_laser"], lw=kwargs["lw"]) ma, = ax0.plot(x, isosbestic_fc, alpha=0.8, c="orange", lw=2) ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(isosbestic, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("mV", fontsize=kwargs["fsl"]) ax0.legend(handles=[p, ma], labels=["isosbestic", "baseline"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title("Smoothed Isosbestic and Calcium signals with respective baselines", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) ax1 = plt.subplot(212, sharex=ax0) b, = ax1.plot(x, calcium, alpha=0.8, c=kwargs["photometry_pp"]["blue_laser"], lw=kwargs["lw"]) ma, = ax1.plot(x, calcium_fc, alpha=0.8, c="orange", lw=2) ax1.set_xticks(xticks) ax1.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax1.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(calcium, 0.1) ax1.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax1.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax1.set_ylim(y_min, y_max) ax1.set_ylabel("mV", fontsize=kwargs["fsl"]) ax1.legend(handles=[b, ma], labels=["calcium", "baseline"], loc=2, fontsize=kwargs["fsl"]) ax1.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) ax1.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["photometry_pp"]["multicursor"]: multi = MultiCursor(fig.canvas, [ax0, ax1], color='r', lw=1, vertOn=[ax0, ax1]) # FIXME: unused if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "Baseline_Determination.{0}" .format(kwargs["extension"])), dpi=200.) return x, isosbestic, calcium, isosbestic_fc, calcium_fc
def extract_raw_data(file, **kwargs): """Function that extracts the raw data from the csv file and displays it in a plot. Args : file (str) = The input photometry file for analysis kwargs (dict) = Dictionnary with the parameters Returns : x (arr) = The time data in X isosbestic_adjusted (arr) = The adjusted isosbestic signal (time fitted to the video) calcium_adjusted (arr) = The adjusted calcium signal (time fitted to the video) """ print("\nExtracting raw data for Isosbestic and Calcium recordings !") photometry_data = np.load(file) # Load the NPY file x = photometry_data[0] # time to be extracted isosbestic_adjusted = photometry_data[1] # data compressed in time calcium_adjusted = photometry_data[2] # data compressed in time x_max = x[-1] # print("Data length : {0}".format(ut.h_m_s(x_max, add_tags=True))) if kwargs["photometry_pp"]["plots_to_display"]["raw_data"]: xticks, xticklabels, unit = utils.generate_xticks_and_labels(x_max) fig = plt.figure(figsize=(10, 5), dpi=200.) ax0 = plt.subplot(211) p, = ax0.plot(x, isosbestic_adjusted, alpha=0.8, c=kwargs["photometry_pp"]["purple_laser"], lw=kwargs["lw"]) ax0.set_xticks(xticks) ax0.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax0.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(isosbestic_adjusted, 0.1) ax0.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax0.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax0.set_ylim(y_min, y_max) ax0.set_ylabel("mV", fontsize=kwargs["fsl"]) ax0.legend(handles=[p], labels=["isosbestic"], loc=2, fontsize=kwargs["fsl"]) ax0.set_title("Raw Isosbestic and Calcium signals", fontsize=kwargs["fst"]) ax0.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) ax1 = plt.subplot(212, sharex=ax0) b, = ax1.plot(x, calcium_adjusted, alpha=0.8, c=kwargs["photometry_pp"]["blue_laser"], lw=kwargs["lw"]) ax1.set_xticks(xticks) ax1.set_xticklabels(xticklabels, fontsize=kwargs["fsl"]) ax1.set_xlim(0, x_max) y_min, y_max, round_factor = utils.generate_yticks(calcium_adjusted, 0.1) ax1.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) ax1.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)*1000], fontsize=kwargs["fsl"]) ax1.set_ylim(y_min, y_max) ax1.set_ylabel("mV", fontsize=kwargs["fsl"]) ax1.legend(handles=[b], labels=["calcium"], loc=2, fontsize=kwargs["fsl"]) ax1.set_xlabel("Time ({0})".format(unit), fontsize=kwargs["fsl"]) ax1.tick_params(axis='both', which='major', labelsize=kwargs["fsl"]) plt.tight_layout() if kwargs["photometry_pp"]["multicursor"]: multi = MultiCursor(fig.canvas, [ax0, ax1], color='r', lw=1, vertOn=[ax0, ax1]) # FIXME: unused if kwargs["save"]: plt.savefig(os.path.join(kwargs["save_dir"], "Raw_Signals.{0}".format(kwargs["extension"])), dpi=200.) return x, isosbestic_adjusted, calcium_adjusted
def live_video_plot(video_clip, x_data, y_data, **kwargs): def make_frame_mpl(t): i = int(t) if i < kwargs["video_photometry"]["display_threshold"]*kwargs["video_photometry"]["plot_acceleration"]: try: behavior_plot.set_data(x_data[0:i], y_data[0][0:i]) df_plot.set_data(x_data[0:i], y_data[1][0:i]) except : print("Oups a problem occured") last_frame = mplfig_to_npimage(live_figure) return last_frame else: delta = (i/kwargs["video_photometry"]["plot_acceleration"]) - kwargs["video_photometry"]["display_threshold"] live_ax0.set_xlim(x_data[0]+delta, x_data[0]+(i/kwargs["video_photometry"]["plot_acceleration"])) live_ax1.set_xlim(x_data[0]+delta, x_data[0]+(i/kwargs["video_photometry"]["plot_acceleration"])) try: behavior_plot.set_data(x_data[0:i], y_data[0][0:i]) df_plot.set_data(x_data[0:i], y_data[1][0:i]) except: print("Oups a problem occured") last_frame = mplfig_to_npimage(live_figure) return last_frame number_subplots = len([x for x in y_data if x != []]) plt.style.use("dark_background") live_figure = plt.figure(figsize=(10, 6), facecolor='black') gs = live_figure.add_gridspec(nrows=number_subplots, ncols=1) # ============================================================================= # First live axis # ============================================================================= live_ax0 = live_figure.add_subplot(gs[0, :]) live_ax0.set_title("Behavior bouts : {0}".format(kwargs["behavior_to_segment"]), fontsize=10.) live_ax0.set_xlim([x_data[0], x_data[0]+kwargs["video_photometry"]["display_threshold"]]) live_ax0.set_yticks([0, 1]) live_ax0.set_yticklabels(["Not behaving", "Behaving"], fontsize=10.) live_ax0.set_ylim(-0.1, 1.1) behavior_plot, = live_ax0.plot(x_data[0], y_data[0][0], '-', color="red", alpha=0.8, ms=1., lw=3.) # ============================================================================= # Second live axis # ============================================================================= live_ax1 = live_figure.add_subplot(gs[1, :]) live_ax1.set_title(r"$\Delta$F/F", fontsize=kwargs["fst"]) live_ax1.set_xlim([x_data[0], x_data[0]+kwargs["video_photometry"]["display_threshold"]]) live_ax1.set_xlabel("Time (s)", fontsize=10.) y_min, y_max, round_factor = utils.generate_yticks(y_data[1], 0.1) live_ax1.set_yticks(np.arange(y_min, y_max+round_factor, round_factor)) live_ax1.set_yticklabels(["{:.0f}".format(i) for i in np.arange(y_min, y_max+round_factor, round_factor)], fontsize=10.) live_ax1.set_ylim(y_min, y_max) df_plot, = live_ax1.plot(x_data[0], y_data[1][0], '-', color="green", alpha=1., ms=1., lw=3.) plt.tight_layout() animation = mpy.VideoClip(make_frame_mpl, duration=(kwargs["video_duration"] * kwargs["video_photometry"]["plot_acceleration"])) clips = [clip.margin(2, color=[0, 0, 0]) for clip in [(video_clip.resize(kwargs["video_photometry"]["resize_video"]).speedx(kwargs["video_photometry"]["global_acceleration"])),\ animation.speedx(kwargs["video_photometry"]["global_acceleration"]).speedx(kwargs["video_photometry"]["plot_acceleration"])]] final_clip = clips_array([[clips[0]], [clips[1]]], bg_color=[0, 0, 0]) final_clip.write_videofile(os.path.join(kwargs["save_dir"],"Live_Video_Plot.mp4"), fps=kwargs["video_photometry"]["live_plot_fps"]) # final_clip = final_clip.subclip(t_start=0, t_end=final_clip.duration-5) # final_clip.write_gif(os.path.join(kwargs["save_dir"],"Live_Video_Plot.gif"), fps=kwargs["video_photometry"]["live_plot_fps"]) plt.style.use("default")