Пример #1
0
    def addMultipleRandomPuffs(self):
        nSites = self.getValue('nSites')

        if self.currentWin == None:
            g.alert('First select window')
            return

        #select current ROI
        self.currentROI = self.currentWin.currentROI

        if self.currentWin.currentROI == None:
            g.alert('First draw an ROI')
            return
        bounds = self.currentROI.parentBounds()

        topLeft_x = bounds.topLeft().x()
        topLeft_y = bounds.topLeft().y()

        bottomRight_x = bounds.bottomRight().x()
        bottomRight_y = bounds.bottomRight().y()

        print('adding puffs to {} sites from {},{} to {},{}'.format(
            nSites, topLeft_x, topLeft_y, bottomRight_x, bottomRight_y))

        sites = self.getRandomSites(topLeft_x, bottomRight_x, topLeft_y,
                                    bottomRight_y, nSites)

        for site in sites:
            print("Puff site: ", self.siteNumber)
            self.addRandomPuffs(singleSite=False, x=site[0], y=site[1])
            self.siteNumber += 1

        print('Finished adding sites')

        return
Пример #2
0
 def make_cluster_im(self):
     print('Generating Cluster Movie')
     mt, mx, my=self.movieShape
     try:
         cluster_im=np.zeros((mt,mx,my,4),dtype=np.float16)
     except MemoryError:
         g.alert('There is not enough memory to create the image of clusters (error in function clusters.make_cluster_im).')
         return None
     for i, cluster in enumerate(self.clusters):
         color = cmap(int(((i%5)*255./6)+np.random.randint(255./12)))
         pos = self.idxs[cluster]
         cluster_im[pos[:, 0], pos[:, 1], pos[:, 2], :] = color
     return cluster_im
Пример #3
0
    def exportTimes(self):
        if self.getValue('active_window') == None:
            g.alert('First select window')
            return

        if self.randomPuffsAdded == False:
            g.alert('Add puffs first')
            return

        #set export path
        savePath, _ = QFileDialog.getSaveFileName(None, "Save file", "",
                                                  "Text Files (*.csv)")

        #write file
        self.timesAdded.to_csv(savePath)
        print('List of times saved to: {}'.format(savePath))
Пример #4
0
    def exportTimes(self):
        if self.randommeppsAdded == False:
            g.alert('Add MEPPs first')
            return

        #set export path
        savePath, _ = QFileDialog.getSaveFileName(None, "Save file", "",
                                                  "Text Files (*.csv)")

        #write file
        try:
            # opening the csv file in 'w+' mode
            file = open(savePath, 'w+', newline='')

            # writing the data into the file
            with file:
                write = csv.writer(file)
                write.writerows(map(lambda x: [x], self.timesAdded))

            print('List of times saved to: {}'.format(savePath))
        except BaseException as e:
            print(e)
            print('Export of times failed, printing times to console')
            print(self.timesAdded)
Пример #5
0
    def addRandomPuffs(self, singleSite=True, x=None, y=None):
        if self.getValue('active_window') == None:
            g.alert('First select window')
            return

        mean = self.getValue('meanExp')
        #nPuffs = self.getValue('nPuffs')

        puffsAdded = 0
        puffsOutsideOfRange = 0

        # add first puff
        try:
            if self.randomDuration.isChecked():
                startTime = int(
                    np.random.exponential(scale=mean, size=1) +
                    self.getValue('startFrame'))
                duration = float(
                    np.random.exponential(scale=self.getValue('meanDuration'),
                                          size=1)[0])
                self.addPuff(time=startTime,
                             singleSite=singleSite,
                             x=x,
                             y=y,
                             duration=duration)

            else:
                startTime = int(
                    np.random.exponential(scale=mean, size=1) +
                    self.getValue('startFrame'))
                duration = self.getValue('nFrames')
                self.addPuff(time=startTime, singleSite=singleSite, x=x, y=y)

            if self.getValue('puffsSequential'):
                endTime = startTime + duration
            else:
                endTime = startTime

        except Exception as e:
            print(e)
            puffsOutsideOfRange += 1
            print('{} puffs added, {} puffs out of range'.format(
                puffsAdded, puffsOutsideOfRange))
            print('1st puff outside of range, aborting')
            return

        # add puff after each time selection untill end of stack
        # rounding the exponential continous value to an int to select frame
        while startTime < self.dt - self.getValue('nFrames'):
            try:
                startTime = int(endTime +
                                np.random.exponential(scale=mean, size=1))

                #if random duration
                if self.randomDuration.isChecked():
                    #print('original time: ', startTime)
                    duration = np.random.exponential(
                        scale=self.getValue('meanDuration'), size=1)
                    startTime = startTime + ceil(duration)
                    #print('time: ', startTime)
                    #print('duration: ', duration)
                    #add puff at time
                    self.addPuff(time=startTime,
                                 singleSite=singleSite,
                                 x=x,
                                 y=y,
                                 duration=duration)

                    #if sequental, add puff duration to time
                    if self.getValue('puffsSequential'):
                        endTime = startTime + duration
                    else:
                        endTime = startTime
                #else use duration from GUI
                else:
                    startTime = startTime + self.getValue('nFrames')
                    duration = self.getValue('nFrames')
                    #add puff at time
                    self.addPuff(time=startTime,
                                 singleSite=singleSite,
                                 x=x,
                                 y=y)

                    #if sequental, add puff duration to time
                    if self.getValue('puffsSequential'):
                        endTime = startTime + duration
                    else:
                        endTime = startTime

                #update puff time log
                self.timesAdded = self.timesAdded.append(
                    {
                        'time of puff': startTime,
                        'duration': duration,
                        'site': int(self.siteNumber)
                    },
                    ignore_index=True)

                puffsAdded += 1
            except:
                puffsOutsideOfRange += 1

        print('{} puffs added, {} puffs out of range'.format(
            puffsAdded, puffsOutsideOfRange))

        if self.plotHistoTimes.isChecked():
            plt.hist(self.timesAdded)
            plt.xlabel('Time puff added (frames)')
            plt.ylabel('Number of puffs added')
            plt.show()

        self.randomPuffsAdded = True
        if singleSite:
            self.siteNumber += 1

        return
Пример #6
0
    def addPuff(self,
                time=False,
                singleSite=True,
                x=None,
                y=None,
                duration=False):
        '''add synthetic blip to image stack'''
        #select window
        self.currentWin = self.getValue('active_window')
        if self.currentWin == None:
            g.alert('First select window')
            return

        #generate blip
        sigma = self.getValue('sigma')
        amp = self.getValue('puffAmplitude')

        if self.randomDuration.isChecked():
            #get random duration
            if duration == False:
                duration = float(
                    np.random.exponential(scale=self.getValue('meanDuration'),
                                          size=1)[0])

        else:
            duration = self.getValue('nFrames')

        #scale puff amplitude to account for durations <1 frame
        if duration < 1:
            amp = amp * duration
            duration = ceil(duration)

        else:
            #round duration to nearest integer number of frames
            duration = ceil(duration)

        blip = generateBlip(sigma=sigma, amplitude=amp, duration=duration)

        blip_time, blip_x_size, blip_y_size = blip.shape

        x_size = int(blip_x_size / 2)
        y_size = int(blip_y_size / 2)

        #add blip to stack
        if time == False:
            t = self.getValue('startFrame')
        else:
            t = time

        if singleSite:
            x = self.getValue('x')
            y = self.getValue('y')

        tt = np.arange(t, t + duration, dtype=np.int)
        xx = np.arange(x - x_size - 1, x + x_size, dtype=np.int)
        yy = np.arange(y - y_size - 1, y + y_size, dtype=np.int)

        if time == False:
            try:
                self.data[np.ix_(tt, xx,
                                 yy)] = self.data[np.ix_(tt, xx, yy)] + blip
            except:
                g.alert(
                    'Error - Puff might be too large, too long or too close to edge'
                )
        else:
            self.data[np.ix_(tt, xx,
                             yy)] = self.data[np.ix_(tt, xx, yy)] + blip

        frame = self.currentWin.currentIndex
        self.currentWin.imageview.setImage(self.data)
        self.currentWin.image = self.data
        self.currentWin.setIndex(frame)

        print(
            'Puff added at time: {}, x: {}, y: {} with duration: {}, sigma: {}, amplitude:{}'
            .format(t, x, y, duration, sigma, amp))

        return
Пример #7
0
def load_file_gui():
    prompt = 'Open file'
    filetypes = '*'
    filename = open_file_gui(prompt=prompt, filetypes=filetypes)

    ext = os.path.splitext(filename)[-1]

    print(ext)

    if ext == '.flika':
        msg = "To open .flika files use puff detector plugin"
        g.alert(msg)
        if filename in g.settings['recent_files']:
            g.settings['recent_files'].remove(filename)
        # make_recent_menu()
        return

    elif ext in ['.tif', '.stk', '.tiff', '.ome']:
        open_file(str(filename))
        return

    elif ext == '.nd2':
        g.m.statusBar().showMessage(
            'Reading {} using python-bioformats'.format(
                os.path.basename(filename)))
        A = read_image_series(filename)
        g.m.statusBar().showMessage('Array shape {} '.format(A.shape))
        print('Array shape {} '.format(A.shape))
        mt = A.shape[0]
        channels = A.shape[1]
        mXX = A.shape[2]  #not sure what this dimension is...
        mx = A.shape[3]
        my = A.shape[4]

        if channels > 1 or mXX > 1:
            g.alert('Array shape not supported')
            return

        A = A.reshape(mt, mx, my)
        Window(A)
        g.m.statusBar().showMessage('Successfully loaded {} '.format(
            os.path.basename(filename)))

    # elif ext == '.nd2':
    #     import nd2reader
    #     nd2 = nd2reader.ND2Reader(str(filename))
    #     axes = nd2.axes
    #     print(axes)
    #     mx = nd2.metadata['width']
    #     my = nd2.metadata['height']
    #     mt = nd2.metadata['total_images_per_channel']

    #     print(nd2.metadata['width'], nd2.metadata['height'], nd2.metadata['total_images_per_channel'])

    #     A = np.zeros((mt, mx, my))
    #     percent = 0
    #     for frame in range(mt):
    #         A[frame] = nd2[frame].T
    #         if percent < int(100 * float(frame) / mt):
    #             percent = int(100 * float(frame) / mt)
    #             g.m.statusBar().showMessage('Loading file {}%'.format(percent))
    #             QtWidgets.qApp.processEvents()
    #     metadata = nd2.metadata

    elif ext == '.py':
        from ..app.script_editor import ScriptEditor
        ScriptEditor.importScript(filename)
        return

    elif ext == '.whl':
        # first, remove trailing (1) or (2)
        newfilename = re.sub(r' \([^)]*\)', '', filename)
        try:
            os.rename(filename, newfilename)
        except FileExistsError:
            pass
        filename = newfilename
        result = subprocess.call(
            [sys.executable, '-m', 'pip', 'install', '{}'.format(filename)])
        if result == 0:
            g.alert('Successfully installed {}'.format(filename))
        else:
            g.alert('Install of {} failed'.format(filename))
        return

    elif ext == '.jpg' or ext == '.png':
        import skimage.io
        A = skimage.io.imread(filename)
        if len(A.shape) == 3:
            perm = get_permutation_tuple(['y', 'x', 'c'], ['x', 'y', 'c'])
            A = np.transpose(A, perm)
            metadata['is_rgb'] = True

    else:
        msg = "Could not open.  Filetype for '{}' not recognized".format(
            filename)
        g.alert(msg)
        if filename in g.settings['recent_files']:
            g.settings['recent_files'].remove(filename)
        # make_recent_menu()
        return