Exemple #1
0
    def plot_LFP_example(self, rds=(95,4,1), scan_number=22, margin=2.0):
        """Plot example LFP traces showing theta power during a head scan
        """
        data = SessionData.get(rds)
        scan_table = get_node('/behavior', 'scans')
        scan = get_unique_row(scan_table,
            data.session_query + '&(number==%d)'%scan_number)

        t_scan = { k: data.T_(scan[k]) for k in ScanPoints }
        window = t_scan['downshift'] - margin, t_scan['upshift'] + margin

        plt.ioff()
        f = self.new_figure('scan_LFP_example',
            'Scan LFP Example: Rat %d, Day %d, M%d @ t=%.2f'%(rds + (window[0],)))

        theta_tt = find_theta_tetrode(rds[:2], condn='(EEG==True)&(area=="CA1")')[0]
        ts, EEG = get_eeg_timeseries(rds, theta_tt)
        t_EEG = data.T_(ts)

        data_file = self.get_data_file()
        session = get_unique_row(data_file.root.sessions, data.session_query)
        t_theta, x_theta = Theta.timeseries(t_EEG, EEG)
        ZP_theta = Z(Theta.power(x_theta, filtered=True)) #data_file.getNode('/arrays', session['ZP_theta'])
        f_theta = data_file.getNode('/arrays', session['f_theta'])

        traj = data.trajectory
        t_traj = data.T_(traj.ts)
        s_traj = time_slice(t_traj, start=window[0], end=window[1])
        s_EEG = time_slice(t_EEG, start=window[0], end=window[1])
        s_theta = time_slice(t_theta, start=window[0], end=window[1])

        y = 0
        dy = -2
        norm = lambda x: (x - np.mean(x)) / (1.1 * float(np.max(np.abs((x - np.mean(x))))))
        ax = f.add_subplot(111)
        ax.axhline(y, c='k', ls='-', zorder=0)
        ax.plot(t_traj[s_traj], y + norm(traj.radius[s_traj]), 'b-', lw=2, zorder=1); y += dy
        ax.plot(t_EEG[s_EEG], y + norm(EEG[s_EEG]), 'k-', lw=1, zorder=1); y += dy
        ax.plot(t_theta[s_theta], y + norm(x_theta[s_theta]), 'k-', lw=1, zorder=1); y += dy
        ax.plot(t_theta[s_theta], y + norm(ZP_theta[s_theta]), 'k-', lw=1, zorder=1); y += dy
        ax.plot(t_theta[s_theta], y + norm(f_theta[s_theta]), 'k-', lw=1, zorder=1); y += dy

        ax.axvspan(t_scan['downshift'], t_scan['start'], lw=0, fc='g', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['start'], t_scan['max'], lw=0, fc='m', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['max'], t_scan['return'], lw=0, fc='y', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['return'], t_scan['end'], lw=0, fc='m', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['end'], t_scan['upshift'], lw=0, fc='g', alpha=0.3, zorder=-2)

        ax.set_yticks([0, -2, -4, -6, -8])
        ax.set_yticklabels(['r', 'EEG', 'theta', 'ZP_theta', 'f_theta'])
        ax.set_ylim(-8.75, 1.25)
        ax.set_xlim(*window)
        ax.tick_params(top=False, right=False)

        plt.ion()
        plt.show()
Exemple #2
0
    def plot_scan_example(self, rds=(95,4,1), scan_number=22, margin=1.0):
        """Plot example scan with relevant behavior variables and scan phases
        """
        data = SessionData.get(rds)
        scan_table = get_node('/behavior', 'scans')
        scan = get_unique_row(scan_table,
            data.session_query + '&(number==%d)'%scan_number)

        t_scan = { k: data.T_(scan[k]) for k in ScanPoints }
        window = t_scan['downshift'] - margin, t_scan['upshift'] + margin

        plt.ioff()
        f = self.new_figure('scan_example',
            'Scan Example: Rat %d, Day %d, M%d @ t=%.2f'%(rds + (window[0],)))

        traj = data.trajectory
        t = data.T_(traj.ts)
        s = time_slice(t, start=window[0], end=window[1])
        scan_slice = time_slice(t, start=t_scan['start'], end=t_scan['end'])

        y = 0
        dy = -2
        norm = lambda x: x / np.max(np.abs(x))
        ax = f.add_subplot(111)
        ax.axhline(y, c='k', ls='-', zorder=0)
        ax.plot(t[s], y + norm(traj.radius[s]), 'b-', lw=2, zorder=1); y += dy
        ax.axhline(y, c='k', ls='-', zorder=0)
        ax.plot(t[s], y + norm(traj.radial_velocity[s]), 'b-', lw=2, zorder=1); y += dy
        ax.axhline(y, c='k', ls='-', zorder=0)
        ax.plot(t[s], y + norm(traj.forward_velocity[s]), 'b-', lw=2, zorder=1); y += dy

        ax.axvspan(t_scan['downshift'], t_scan['start'], lw=0, fc='g', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['start'], t_scan['max'], lw=0, fc='m', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['max'], t_scan['return'], lw=0, fc='y', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['return'], t_scan['end'], lw=0, fc='m', alpha=0.3, zorder=-2)
        ax.axvspan(t_scan['end'], t_scan['upshift'], lw=0, fc='g', alpha=0.3, zorder=-2)

        for k in ScanPoints:
            ax.axvline(t_scan[k], c='k', ls='-', zorder=-1)

        ax.set_yticks([0, -2, -4])
        ax.set_yticklabels(['r', 'rs', 'fwd'])
        ax.set_ylim(-4.75, 1.25)
        ax.set_xlim(*window)
        ax.tick_params(top=False, right=False)

        f = self.new_figure('scan_example_space', 'Scan Example', (4,4))
        ax = f.add_subplot(111)
        ax.plot(traj.x[s], traj.y[s], 'k-', alpha=0.6)
        ax.plot(traj.x[scan_slice], traj.y[scan_slice], 'r-', lw=2)
        ax.axis('equal')
        ax.set_axis_off()
        plot_track_underlay(ax=ax, ls='dotted')

        plt.ion()
        plt.show()
    def collect_data(self, datasets=None):
        """Get head scan table and print out reports

        Keyword arguments:
        datasets -- restrict report to particular datasets specified as a list
            of (rat, day) tuples
        """
        pause_table = get_node('/behavior', 'pauses')
        self.out('Reporting pauses found in %s...' % pause_table._v_pathname)

        fmt = dict(lw=SCAN_LW, solid_capstyle='round', alpha=0.7)
        for rds, lap, ax in self.get_plot(datasets=datasets,
                                          timing_issue=True,
                                          missing_HD=True):
            ts, x, y, hd = get_tracking(*rds)
            lapslice = time_slice(ts, start=lap[0], end=lap[1])
            ax.plot(x[lapslice], y[lapslice], '-', c='0.4', lw=TRAJ_LW)
            plot_track_underlay(ax, lw=0.5, ls='dotted')

            for pause in pause_table.where(
                    '(rat==%d)&(day==%d)&(session==%d)' % rds):
                if not (lap[0] <= pause['start'] <= lap[1]):
                    continue

                tslice = slice(*pause['slice'])
                ax.plot(x[tslice], y[tslice], 'r-', zorder=5, **fmt)

            ax.axis([-50, 50, -48, 48])
            # ax.axis('equal')
            ax.axis('off')
class HeadScanLapReport(BaseLapReport):
    """
    Print a complete by-lap report of head scan events
    """

    label = 'head scan laps'

    def collect_data(self, datasets=None, phasing=True):
        """Get head scan table and print out reports

        Keyword arguments:
        datasets -- restrict report to particular datasets specified as a list
            of (rat, day) tuples
        """
        kfile = get_kdata_file()
        bpath = get_group_path(tree='behavior')

        table_name = CfgData['scan_table']
        try:
            scan_table = kfile.getNode(bpath, table_name)
        except NodeError, e:
            raise e, 'could not find valid scan table'

        self.out('Reporting scans found in %s...' % scan_table._v_pathname)

        colors = dict(prefix=('g', 0),
                      outbound=('r', 2),
                      dwell=('y', 0),
                      inbound=('m', 1),
                      postfix=('g', 0))
        phase_names = colors.keys()

        fmt = dict(lw=SCAN_LW, solid_capstyle='round', alpha=0.7)
        for rds, lap, ax in self.get_plot(datasets=datasets, missing_HD=True):
            ts, x, y, hd = get_tracking(*rds)
            lapslice = time_slice(ts, start=lap[0], end=lap[1])
            ax.plot(x[lapslice],
                    y[lapslice],
                    '-',
                    c='0.4',
                    lw=TRAJ_LW,
                    zorder=-1)
            plot_track_underlay(ax, lw=0.5, ls='dotted')

            for scan in scan_table.where('(rat==%d)&(day==%d)&(session==%d)' %
                                         rds):
                if not (lap[0] <= scan['start'] <= lap[1]):
                    continue

                # Plot the scan on top of trajectory
                if phasing:
                    for phase in phase_names:
                        start, end = ScanPhasePoints[phase]
                        tslice = time_slice(ts,
                                            start=scan[start],
                                            end=scan[end])
                        col, zord = colors[phase]
                        ax.plot(x[tslice],
                                y[tslice],
                                c=col,
                                zorder=zord,
                                **fmt)
                else:
                    tslice = slice(*scan['slice'])
                    ax.plot(x[tslice], y[tslice], 'r-', zorder=5, **fmt)

            ax.axis([-50, 50, -48, 48])
            # ax.axis('equal')
            ax.axis('off')
Exemple #5
0
    def collect_data(self, dataset=(57, 1), lag=0.25):
        """Detect all ripples in dataset and plot EEG, ripple-band, and power
        signals along with detected event boundaries
        """
        ripple_table = get_node('/physiology', 'ripples')
        tetrode_query = '(area=="CA1")&(EEG==True)'
        dataset_query = '(rat==%d)&(day==%d)' % dataset
        pyr_tetrodes = find_pyramidale_tetrodes(dataset, verbose=False)
        rat, day = dataset

        # Initialize accumulators
        time_slices = []
        EEG_slices = []
        power_slices = []
        events = []
        timestamps = []

        Ripple = RippleFilter()

        # Loop through sessions, detecting and storing ripple slices
        for rds in unique_sessions(ripple_table, condn=dataset_query):
            data = SessionData.get(rds)

            self.out('Loading data for rat%03d-%02d-m%d...' % rds)
            ts = None
            EEG = None
            P = None
            for tt in pyr_tetrodes:
                X = get_eeg_timeseries(rds, tt)
                if X is None:
                    continue
                if ts is None:
                    ts = X[0]
                if EEG is None:
                    EEG = X[1]
                else:
                    EEG = np.vstack((EEG, X[1]))
                if P is None:
                    P = Ripple.power(X[1])
                else:
                    P = np.vstack((P, Ripple.power(X[1])))

            if P.ndim == 2:
                P = np.mean(P, axis=0)

            ts_ripples = [(rec['start'], rec['peak'], rec['end'])
                          for rec in ripple_table.where(data.session_query)]
            t = data.T_(ts)

            for timing in ts_ripples:
                start, peak, end = data.T_(timing)
                chunk = time_slice(t, peak - lag, peak + lag)
                time_slices.append(t[chunk] - peak)
                EEG_slices.append(EEG[..., chunk])
                power_slices.append(P[chunk])
                events.append((start - peak, end - peak))
                timestamps.append(timing[1])

        self.out('Plotting EEG traces of ripple events...')
        LW = 0.4
        norm = lambda x: x.astype('d') / float(CLIP)
        for i, ax in self.get_plot(range(len(time_slices))):
            t_chunk = time_slices[i]
            traces = EEG_slices[i]
            if traces.ndim == 1:
                ax.plot(t_chunk,
                        norm(traces),
                        'k-',
                        lw=1.5 * LW,
                        alpha=1,
                        zorder=0)
            else:
                ax.plot(t_chunk,
                        norm(traces).T,
                        'k-',
                        lw=LW,
                        alpha=0.5,
                        zorder=-1)
                ax.plot(t_chunk,
                        norm(np.mean(traces, axis=0)),
                        'k-',
                        lw=LW,
                        alpha=1,
                        zorder=0)
            ax.plot(t_chunk,
                    power_slices[i] / power_slices[i].max(),
                    'b-',
                    lw=1.5 * LW,
                    alpha=1,
                    zorder=1)
            ax.axhline(0, ls='-', c='k', lw=LW, zorder=0)
            ax.axvline(events[i][0], ls='-', c='k', lw=LW, zorder=2)
            ax.axvline(0, ls=':', c='k', lw=LW, zorder=2, alpha=0.5)
            ax.axvline(events[i][1], ls='-', c='k', lw=LW, zorder=2)
            ax.set_xlim(-lag, lag)
            ax.set_ylim(-1, 1)
            ax.set_axis_off()
            quicktitle(ax, '%d' % timestamps[i], size='xx-small')

            self.out.printf('.')
        self.out.printf('\n')