Exemplo n.º 1
0
def get_pc_metrics(ops, use_red=False):
    ''' computes registration metrics using top PCs of registered movie
        movie saved as binary file ops['reg_file']
        metrics saved to ops['regPC'] and ops['X']
    '''
    nsamp    = min(5000, ops['nframes']) # n frames to pick from full movie
    if ops['Ly'] > 700:
        nsamp = min(2500, nsamp)
    nPC      = 30 # n PCs to compute motion for
    nlowhigh = np.minimum(300,int(ops['nframes']/2)) # n frames to average at ends of PC coefficient sortings
    ix   = np.linspace(0,ops['nframes']-1,nsamp).astype('int')
    if use_red and 'reg_file_chan2' in ops:
        mov  = utils.sample_frames(ops, ix, ops['reg_file_chan2'])
    else:
        mov  = utils.sample_frames(ops, ix, ops['reg_file'])

    pclow, pchigh, sv, v = pclowhigh(mov, nlowhigh, nPC)
    if 'block_size' not in ops:
        ops['block_size']   = [128, 128]
    if 'maxregshiftNR' not in ops:
        ops['maxregshiftNR'] = 5
    X    = pc_register(pclow, pchigh, ops['refImg'],
                       ops['smooth_sigma'], ops['block_size'], ops['maxregshift'], ops['maxregshiftNR'], ops['1Preg'])
    ops['regPC'] = np.concatenate((pclow[np.newaxis, :,:,:], pchigh[np.newaxis, :,:,:]), axis=0)
    ops['regDX'] = X
    ops['tPC'] = v

    return ops
Exemplo n.º 2
0
def get_pc_metrics(ops, use_red=False):
    """ computes registration metrics using top PCs of registered movie

        movie saved as binary file ops['reg_file']
        metrics saved to ops['regPC'] and ops['X']
        'regDX' is nPC x 3 where X[:,0] is rigid, X[:,1] is average nonrigid, X[:,2] is max nonrigid shifts
        'regPC' is average of top and bottom frames for each PC
        'tPC' is PC across time frames

        Parameters
        ----------
        ops : dict
            requires 'nframes', 'Ly', 'Lx', 'reg_file' (if use_red=True, 'reg_file_chan2')
        use_red : :obj:`bool`, optional
            default False, whether to use 'reg_file' or 'reg_file_chan2'

        Returns
        -------
            ops : dict
                adds 'regPC' and 'tPC' and 'regDX'

    """
    nsamp    = min(5000, ops['nframes']) # n frames to pick from full movie
    if ops['nframes'] < 5000:
        nsamp = min(2000, ops['nframes'])
    if ops['Ly'] > 700 or ops['Lx'] > 700:
        nsamp = min(2000, nsamp)
    nPC      = 30 # n PCs to compute motion for
    nlowhigh = np.minimum(300,int(ops['nframes']/2)) # n frames to average at ends of PC coefficient sortings
    ix   = np.linspace(0,ops['nframes']-1,nsamp).astype('int')
    if use_red and 'reg_file_chan2' in ops:
        mov  = sample_frames(ops, ix, ops['reg_file_chan2'])
    else:
        mov  = sample_frames(ops, ix, ops['reg_file'])

    pclow, pchigh, sv, v = pclowhigh(mov, nlowhigh, nPC)
    if 'block_size' not in ops:
        ops['block_size']   = [128, 128]
    if 'maxregshiftNR' not in ops:
        ops['maxregshiftNR'] = 5
    if 'smooth_sigma' not in ops:
        ops['smooth_sigma'] = 1.15
    if 'maxregshift' not in ops:
        ops['maxregshift'] = 0.1
    if '1Preg' not in ops:
        ops['1Preg'] = False
    if 'refImg' in ops:
        refImg = ops['refImg']

    else:
        refImg = mov.mean(axis=0)
    X    = pc_register(pclow, pchigh, refImg,
                       ops['smooth_sigma'], ops['block_size'], ops['maxregshift'], ops['maxregshiftNR'], ops['1Preg'])
    ops['regPC'] = np.concatenate((pclow[np.newaxis, :,:,:], pchigh[np.newaxis, :,:,:]), axis=0)
    ops['regDX'] = X
    ops['tPC'] = v

    return ops
Exemplo n.º 3
0
def get_metrics(ops):
    nsamp    = min(10000, ops['nframes']) # n frames to pick from full movie
    nPC      = 50 # n PCs to compute motion for
    nlowhigh = 500 # n frames to average at ends of PC coefficient sortings
    ix   = np.linspace(0,ops['nframes']-1,nsamp).astype('int')
    mov  = utils.sample_frames(ops, ix)
    #mov = mov[:, ops['yrange'][0]:ops['yrange'][-1], ops['xrange'][0]:ops['xrange'][-1]]

    pclow, pchigh,sv = utils.pclowhigh(mov, nlowhigh, nPC)
    if 'block_size' not in ops:
        ops['block_size']   = [128, 128]
    if 'maxregshiftNR' not in ops:
        ops['maxregshiftNR'] = 5
    X    = utils.metric_register(pclow, pchigh, ops['do_phasecorr'], ops['smooth_sigma'], ops['block_size'], ops['maxregshift'], ops['maxregshiftNR'])
    ops['regPC'] = np.concatenate((pclow[np.newaxis, :,:,:], pchigh[np.newaxis, :,:,:]), axis=0)
    ops['regDX'] = X
    return ops
Exemplo n.º 4
0
    def openCombined(self, fileName):
        try:
            ops1 = np.load(fileName, allow_pickle=True)
            basefolder = ops1[0]['save_path0']
            #opsCombined = np.load(os.path.join(basefolder, 'suite2p/combined/ops.npy'), allow_pickle=True).item()
            #self.LY = opsCombined['Ly']
            #self.LX = opsCombined['Lx']
            self.LY = 0
            self.LX = 0
            self.reg_loc = []
            self.reg_file = []
            self.Ly = []
            self.Lx = []
            self.dy = []
            self.dx = []
            self.yrange = []
            self.xrange = []
            self.ycrop = []
            self.xcrop = []
            # check that all binaries still exist
            for ipl, ops in enumerate(ops1):
                #if os.path.isfile(ops['reg_file']):
                if os.path.isfile(ops['reg_file']):
                    reg_file = ops['reg_file']
                else:
                    reg_file = os.path.join(os.path.dirname(fileName),
                                            'plane%d' % ipl, 'data.bin')
                print(reg_file, os.path.isfile(reg_file))
                self.reg_loc.append(reg_file)
                self.reg_file = open(self.reg_loc[-1], 'rb')
                self.reg_file.close()
                self.Ly.append(ops['Ly'])
                self.Lx.append(ops['Lx'])
                self.dy.append(ops['dy'])
                self.dx.append(ops['dx'])
                self.xrange.append(
                    np.arange(self.dx[-1], self.dx[-1] + self.Lx[-1], 1, int))
                self.yrange.append(
                    np.arange(self.dy[-1], self.dy[-1] + self.Ly[-1], 1, int))
                xrange = ops['xrange']
                yrange = ops['yrange']
                xcrop = np.zeros((ops['Lx'], ), dtype=np.bool)
                xcrop[np.arange(xrange[0], xrange[1], 1, int)] = True
                self.xcrop.append(xcrop.nonzero()[0])
                ycrop = np.zeros((ops['Ly'], ), dtype=np.bool)
                ycrop[np.arange(yrange[0], yrange[1], 1, int)] = True
                self.ycrop.append(ycrop.nonzero()[0])
                self.xrange[-1] = self.xrange[-1][xcrop]
                self.yrange[-1] = self.yrange[-1][ycrop]
                self.LY = np.maximum(self.LY, self.Ly[-1] + self.dy[-1])
                self.LX = np.maximum(self.LX, self.Lx[-1] + self.dx[-1])
            #if os.path.isfile(os.path.join(basefolder, 'suite2p/combined/','F.npy')):
            #    self.Fcell = np.load(os.path.join(basefolder, 'suite2p/combined/','F.npy'))
            #    self.stat =  np.load(os.path.join(basefolder, 'suite2p/combined/','stat.npy'))
            #    self.Floaded = True
            #else:
            self.Floaded = False
            if self.Floaded:
                ncells = len(self.stat)
                for n in range(0, ncells):
                    ypix = self.stat[n]['ypix'].flatten()
                    xpix = self.stat[n]['xpix'].flatten()
                    iext = fig.boundary(ypix, xpix)
                    yext = ypix[iext]
                    xext = xpix[iext]
                    #yext = np.hstack((yext,yext+1,yext+1,yext-1,yext-1))
                    #xext = np.hstack((xext,xext+1,xext-1,xext+1,xext-1))
                    goodi = (yext >= 0) & (xext >= 0) & (yext < self.LY) & (
                        xext < self.LX)
                    self.stat[n]['yext'] = yext[goodi]
                    self.stat[n]['xext'] = xext[goodi]
            good = True
        except Exception as e:
            print("ERROR: incorrect ops1.npy or missing binaries")
            good = False
        if good:
            # only show registered even if raw exists
            self.wraw = False
            self.wred = False
            self.wraw_wred = False
            self.p1.clear()
            self.p2.clear()
            self.ichosen = 0
            self.ROIedit.setText('0')
            # get scaling from 100 random frames
            frames = utils.sample_frames(
                ops,
                np.linspace(0, ops['nframes'] - 1,
                            np.minimum(ops['nframes'], 100)).astype(int),
                self.reg_loc[-1])
            self.srange = frames.mean() + frames.std() * np.array([-1, 5])
            self.srange[0] = max(0, self.srange[0])
            self.reg_file = []
            self.nbytesread = []
            for n in range(len(self.reg_loc)):
                self.reg_file.append(open(self.reg_loc[n], 'rb'))
                self.nbytesread.append(2 * self.Ly[n] * self.Lx[n])

            #aspect ratio
            if 'aspect' in ops:
                self.xyrat = ops['aspect']
            elif 'diameter' in ops and (type(ops["diameter"]) is not int) and (
                    len(ops["diameter"]) > 1):
                self.xyrat = ops["diameter"][0] / ops["diameter"][1]
            else:
                self.xyrat = 1.0
            self.p0.setAspectLocked(lock=True, ratio=self.xyrat)

            self.movieLabel.setText(self.reg_loc[0])
            self.nframes = ops['nframes']
            self.time_step = 1. / ops['fs'] * 1000 / 5  # 5x real-time
            self.frameDelta = int(np.maximum(5, self.nframes / 200))
            self.frameSlider.setSingleStep(self.frameDelta)
            self.currentMovieDirectory = QtCore.QFileInfo(fileName).path()
            if self.nframes > 0:
                self.updateFrameSlider()
                self.updateButtons()

            # plot ops X-Y offsets for the last plane
            if 'yoff' in ops:
                self.yoff = ops['yoff']
                self.xoff = ops['xoff']
            else:
                self.yoff = np.zeros((ops['nframes'], ))
                self.xoff = np.zeros((ops['nframes'], ))
            self.p1.plot(self.yoff, pen='g')
            self.p1.plot(self.xoff, pen='y')
            self.p1.setRange(xRange=(0, self.nframes),
                             yRange=(np.minimum(self.yoff.min(),
                                                self.xoff.min()),
                                     np.maximum(self.yoff.max(),
                                                self.xoff.max())),
                             padding=0.0)
            self.p1.setLimits(xMin=0, xMax=self.nframes)
            self.scatter1 = pg.ScatterPlotItem()
            self.p1.addItem(self.scatter1)
            self.scatter1.setData(
                [self.cframe, self.cframe],
                [self.yoff[self.cframe], self.xoff[self.cframe]],
                size=10,
                brush=pg.mkBrush(255, 0, 0))
            if self.Floaded:
                self.cell_mask()
                self.ft = self.Fcell[self.ichosen, :]
                self.p2.plot(self.ft, pen='b')
                self.p2.setRange(xRange=(0, self.nframes),
                                 yRange=(self.ft.min(), self.ft.max()),
                                 padding=0.0)
                self.p2.setLimits(xMin=0, xMax=self.nframes)
                self.scatter2 = pg.ScatterPlotItem()
                self.p2.addItem(self.scatter2)
                self.scatter2.setData([self.cframe], [self.ft[self.cframe]],
                                      size=10,
                                      brush=pg.mkBrush(255, 0, 0))
                self.p2.setXLink('plot1')
            self.cframe = -1
            self.loaded = True
            self.next_frame()