Beispiel #1
0
 def __init__(self, exp_id, drive="H:"):
     exp_path      = get_exp_path(exp_id,drive)
     timeline_path = get_timeline_path(exp_path)
     trials        = get_trials_in_recording(exp_path,ignore_dprime=True,
                                      use_sparse=True)
     licks = get_lick_times(timeline_path)
     
     self.fig,ax = plt.subplots(ncols=2,figsize=[8,5])
     for idx,trial in enumerate(trials):
         trial_licks = licks-trial.start_stimulus
         trial_licks = trial_licks[np.logical_and(trial_licks>0,trial_licks<5)]
         ax[0 if trial.isgo else 1].plot(
             trial_licks,
             np.full(trial_licks.shape,idx),
             'o',markersize=2,
             color="k")
         
 
     for a in ax:
         ymin,ymax = a.get_ylim()
         a.vlines((0,1,3),ymin,ymax,linestyles='dashed',color = 'k')
         for name,pos in zip(('Tone','Stimulus','Response'),(0,1,3)):
                 a.text(pos+0.1,ymax,name,
                     horizontalalignment='left',
                     verticalalignment='bottom')
                 a.set_xlabel(r'$\Delta$t from trial onset (s)')
                 a.set_xlim((-1,5))
     ax[0].set_title("Go Trials")
     ax[1].set_title("No-Go Trials")
     ax[0].set_ylabel('Trial Number')
Beispiel #2
0
 def __init__(self,df,signature,dic,name,drive = "H://"):
     ls_of_recordings = dic[signature]
     self.recordings = ls_of_recordings
     self.df = df
     recording_paths = list(map(lambda p:get_exp_path(p,drive),
                                     self.recordings))
     psychstims = [get_psychstim_path(r) for r in recording_paths]
     self.dprimes = [calc_d_prime(r) for r in psychstims]
     self.df_repr = pd.DataFrame((self.recordings,self.dprimes)).transpose()
     self.df_repr.columns = ["recording_id","dprime"]
     self.df_repr[self.df_repr==np.inf] = np.nan
     self.df_repr = self.df_repr[self.df_repr.dprime>1]
     self.recordings = self.df_repr.recording_id.values
     subset = self.df[self.df.recording_id.isin(self.recordings)]
     self.pooled_stats = get_count_and_stats(subset,subsetting=False)
     self.name = name
     self.signature = signature
     self.drive = drive
     self.recording_paths = list(map(lambda p:get_exp_path(p,drive),
                                     self.recordings))
def dataframe_from_ls_of_ROIs(ls):
    return pd.DataFrame.from_records(ROI.to_dict() for ROI in ls)


def flat_dataframe_from_ls_of_ROIs(ls):
    records = []
    for roi in ls:
        records.extend(roi.to_unrolled_records())
    return pd.DataFrame(records)


def load_all_trials(path):
    all_trials = []
    with open(path, 'rb') as file:
        while True:
            try:
                all_trials.append(pkl.load(file))
            except EOFError:
                break
    return all_trials


if __name__ == "__main__":
    from accdatatools.Observations.trials import get_trials_in_recording
    from accdatatools.Utils.path import get_exp_path
    trials = get_trials_in_recording(
        get_exp_path("2016-11-01_03_CFEB027", "D:\\"))
    rois = ls_of_ROIs_from_ls_of_Trials(trials)
    del trials
    plotter = ROIActivitySummaryFactory(rois)
@author: viviani
"""

import os

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import pearsonr

from accdatatools.Utils.path import get_exp_path
from accdatatools.Observations.recordings import Recording
from accdatatools.Timing.synchronisation import (get_neural_frame_times,
                                                 get_lick_state_by_frame)

experiment_ID = "2016-10-07_03_CFEB027"
experiment_path = get_exp_path(experiment_ID, "H:\\")

suite2p_path = os.path.join(experiment_path, "suite2p", "plane0")

timeline_path = os.path.join(experiment_path,
                             "2016-10-07_03_CFEB027_Timeline.mat")

exp_recording = Recording(suite2p_path)

frame_times = get_neural_frame_times(timeline_path,
                                     exp_recording.ops["nframes"])

licking = get_lick_state_by_frame(timeline_path, frame_times)

corrs = [pearsonr(x, licking)[0] for x in exp_recording.dF_on_F]
corrs_isort = np.argsort(corrs)
    def __init__(self,
                 mouse_id=None,
                 drive="H://",
                 ls_of_exp_ids=None,
                 ls_of_exp_paths=None):
        if sum((not mouse_id, not ls_of_exp_ids, not ls_of_exp_paths)) != 2:
            raise ValueError("Supply exactly one of a mouse_id, a list of " +
                             "exp_ids or a list of exp_paths!")
        seaborn.set_style("dark")
        if mouse_id:
            experiment_paths = []
            animal_path = get_mouse_path(mouse_id, drive)

            for experiment in os.listdir(animal_path):
                try:
                    experiment_paths.append(get_exp_path(experiment, drive))
                except FileNotFoundError:
                    pass
        elif ls_of_exp_ids:
            experiment_paths = [
                get_exp_path(id, drive) for id in ls_of_exp_ids
            ]
        elif ls_of_exp_paths:
            experiment_paths = ls_of_exp_paths
        mean_images = {}
        self.ls_of_exp_paths = []
        for experiment_path in experiment_paths:
            try:
                ops_path = os.path.join(experiment_path, "suite2p", "plane0",
                                        "ops.npy")
                ops = np.load(ops_path, allow_pickle=True).item()
                mean_image = ops["meanImgE"]
                mean_images[experiment_path] = mean_image
                self.ls_of_exp_paths.append(experiment_path)
            except FileNotFoundError:
                pass
        n_exps = len(mean_images)

        for width in range(ceil(sqrt(n_exps)), 1, -1):
            if n_exps % width == 0:
                height = n_exps // width
                break
        else:
            width = ceil(sqrt(n_exps))
            height = width

        self.fig = plt.figure(figsize=(2 * width + 1, 2 * height + 1))
        self.ax = np.empty((width, height), dtype=object)
        gs = gridspec.GridSpec(width,
                               height,
                               wspace=0.0,
                               hspace=0.0,
                               top=1. - 0.5 / (height + 1),
                               bottom=0.5 / (height + 1),
                               left=0.5 / (width + 1),
                               right=1 - 0.5 / (width + 1))

        iterator = iter(mean_images.items())
        im_idx = 0
        for i in range(width):
            for j in range(height):
                try:
                    experiment, im = next(iterator)
                except StopIteration:
                    break

                self.ax[i][j] = plt.subplot(gs[i, j])
                self.ax[i][j].imshow(im)
                self.ax[i][j].text(0.5,
                                   0.5,
                                   str(im_idx),
                                   horizontalalignment='center',
                                   verticalalignment='center',
                                   transform=self.ax[i][j].transAxes,
                                   size=16,
                                   color='k')
                self.ax[i][j].set_xticklabels([])
                self.ax[i][j].set_yticklabels([])
                im_idx += 1
        self.canvas = self.fig.canvas
        self.show = self.fig.show
        self.draw = self.fig.draw