def gui(self):
        self.gui_reset()

        #combobox
        inputChoice = ComboBox()
        inputChoice.addItem('Current Window')
        inputChoice.addItem('Numpy Array')
        inputChoice.addItem('Batch Process')

        #checkbox
        self.keepOriginalWindow = CheckBox()
        self.keepOriginalWindow.setValue(False)

        #populate GUI
        self.items.append({
            'name': 'inputChoice',
            'string': 'Choose Input Data:',
            'object': inputChoice
        })
        self.items.append({
            'name': 'keepOriginalWindow',
            'string': 'Keep Original Window',
            'object': self.keepOriginalWindow
        })
        super().gui()
Пример #2
0
    def gui(self):
        self.gui_reset()
        framerate = pg.SpinBox()

        if hasattr(g.win, 'framerate'):
            framerate.setValue(g.win.framerate)
        elif 'framerate' in g.settings.d.keys():
            framerate.setValue(g.settings['framerate'])

        framerate.setRange(0, 1000000)
        framerate.setDecimals(10)

        show = CheckBox()
        show.setChecked(True)

        #windows
        self.window_button = WindowSelector()

        #self.exportFolder = FolderSelector('*.txt')
        self.items.append({
            'name': 'window',
            'string': 'Select Window',
            'object': self.window_button
        })
        self.items.append({
            'name': 'framerate',
            'string': 'Frame Rate (Hz)',
            'object': framerate
        })
        self.items.append({'name': 'show', 'string': 'Show', 'object': show})
        super().gui()
class VolumeSliderBase(BaseProcess_noPriorWindow):
    """
    Start Volume Slider from differnt sources

        |Select source (current window or saved numpy array)
        
    Returns volumeSlider GUI

    """
    
    def __init__(self):
        if g.settings['volumeSlider'] is None or 'inputChoice' not in g.settings['volumeSlider']:
            s = dict() 
            s['inputChoice'] = 'Current Window'              
            s['keepOriginalWindow'] = False                                  
            g.settings['volumeSlider'] = s
                
        BaseProcess_noPriorWindow.__init__(self)
        
    def __call__(self, inputChoice,keepOriginalWindow,keepSourceWindow=False):
        g.settings['volumeSlider']['inputChoice'] = inputChoice
        g.settings['volumeSlider']['keepOriginalWindow'] = keepOriginalWindow

        g.m.statusBar().showMessage("Starting Volume Slider...")
        
        if inputChoice == 'Current Window':
            camVolumeSlider.startVolumeSlider(keepWindow=keepOriginalWindow)
            
        elif inputChoice == 'Numpy Array':
            A_path = open_file_gui(directory=os.path.expanduser("~/Desktop"),filetypes='*.npy')
            g.m.statusBar().showMessage("Importing Array: " + A_path)
            A = np.load(str(A_path))
            camVolumeSlider.startVolumeSlider(A=A,keepWindow=keepOriginalWindow)
            
        return

    def closeEvent(self, event):
        BaseProcess_noPriorWindow.closeEvent(self, event)

    def gui(self):
        self.gui_reset()
                       
        #combobox
        inputChoice = ComboBox()
        inputChoice.addItem('Current Window')
        inputChoice.addItem('Numpy Array')
        
        #checkbox
        self.keepOriginalWindow = CheckBox()
        self.keepOriginalWindow.setValue(False)          
        
        #populate GUI
        self.items.append({'name': 'inputChoice', 'string': 'Choose Input Data:', 'object': inputChoice}) 
        self.items.append({'name': 'keepOriginalWindow','string':'Keep Original Window','object': self.keepOriginalWindow})                                     
        super().gui()
    def __init__(self, window=None, parent=None):
        super(Volume_Viewer,
              self).__init__(parent)  # Create window with ImageView widget
        g.m.volume_viewer = self
        window.lostFocusSignal.connect(self.hide)
        window.gainedFocusSignal.connect(self.show_wo_focus)
        self.window = window
        self.setWindowTitle('Light Sheet Volume View Controller')
        self.setWindowIcon(QtGui.QIcon(image_path('favicon.png')))
        self.setGeometry(QtCore.QRect(422, 35, 222, 86))
        self.layout = QtWidgets.QVBoxLayout()
        self.vol_shape = window.volume.shape
        mv, mz, mx, my = window.volume.shape
        self.currentAxisOrder = [0, 1, 2, 3]
        self.current_v_Index = 0
        self.current_z_Index = 0
        self.current_x_Index = 0
        self.current_y_Index = 0
        self.formlayout = QtWidgets.QFormLayout()
        self.formlayout.setLabelAlignment(QtCore.Qt.AlignRight)
        self.xzy_position_label = QtWidgets.QLabel('Z position')
        self.zSlider = SliderLabel(0)
        self.zSlider.setRange(0, mz - 1)
        self.zSlider.label.valueChanged.connect(self.zSlider_updated)
        self.zSlider.slider.mouseReleaseEvent = self.zSlider_release_event

        self.sideViewOn = CheckBox()
        self.sideViewOn.setChecked(False)
        self.sideViewOn.stateChanged.connect(self.sideViewOnClicked)

        self.sideViewSide = QtWidgets.QComboBox(self)
        self.sideViewSide.addItem("X")
        self.sideViewSide.addItem("Y")

        self.MaxProjButton = QtWidgets.QPushButton('Max Intenstiy Projection')
        self.MaxProjButton.pressed.connect(self.make_maxintensity)

        self.exportVolButton = QtWidgets.QPushButton('Export Volume')
        self.exportVolButton.pressed.connect(self.export_volume)

        self.formlayout.addRow(self.xzy_position_label, self.zSlider)
        self.formlayout.addRow('Side View On', self.sideViewOn)
        self.formlayout.addRow('Side View Side', self.sideViewSide)
        self.formlayout.addRow('', self.MaxProjButton)
        self.formlayout.addRow('', self.exportVolButton)

        self.layout.addWidget(self.zSlider)
        self.layout.addLayout(self.formlayout)
        self.setLayout(self.layout)
        self.setGeometry(QtCore.QRect(381, 43, 416, 110))
        self.show()
Пример #5
0
    def gui(self):
        s=g.settings['light_sheet_analyzer']
        self.gui_reset()
        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])
        
        self.shift_factor = pg.SpinBox(int=False, step=.1)
        self.shift_factor.setValue(s['shift_factor'])

        self.theta = pg.SpinBox(int=True, step=1)
        self.theta.setValue(s['theta'])

        self.triangle_scan = CheckBox()
        self.triangle_scan.setValue(s['triangle_scan'])

        self.interpolate = CheckBox()
        self.interpolate.setValue(s['interpolate'])

        self.trim_last_frame = CheckBox()
        self.trim_last_frame.setValue(s['trim_last_frame'])

        self.zscan = CheckBox()
        self.zscan.setValue(s['trim_last_frame'])

        
        self.items.append({'name': 'nSteps', 'string': 'Number of steps per volume', 'object': self.nSteps})
        self.items.append({'name': 'shift_factor', 'string': 'Shift Factor', 'object': self.shift_factor})
        self.items.append({'name': 'theta', 'string': 'Theta', 'object': self.theta})
        self.items.append({'name': 'triangle_scan', 'string': 'Trangle Scan', 'object': self.triangle_scan})
        self.items.append({'name': 'interpolate', 'string': 'Interpolate', 'object': self.interpolate})
        self.items.append({'name': 'trim_last_frame', 'string': 'Trim Last Frame', 'object': self.trim_last_frame})
        self.items.append({'name': 'zscan', 'string': 'Z scan', 'object': self.zscan})
        super().gui()
Пример #6
0
    def gui(self):
        s=g.settings['tiff_page_loader']
        self.gui_reset()
        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])
        self.filePath = TiffSelector('*.tiff, *.tif')
        
        self.setSteps = CheckBox()
        self.setSteps.setValue(s['setSteps'])

        self.items.append({'name':'filePath','string':'Tiff file path','object': self.filePath})
        self.items.append({'name': 'nSteps', 'string': 'Number of steps per volume', 'object': self.nSteps})
        self.items.append({'name': 'setSteps', 'string': 'Automatically determine step size from Tiff metadata', 'object': self.setSteps})

        super().gui()
Пример #7
0
 def gui(self):
     text_file = get_text_file()
     self.text = open(text_file, 'r').readlines()
     self.keys = self.text[0].split('\t')
     self.gui_reset()
     x_axis_selection = ComboBox()
     y_axis_selection = ComboBox()
     z_axis_selection = ComboBox()
     epsilon = QDoubleSpinBox()
     epsilon.setDecimals(2)
     epsilon.setSingleStep(1)
     min_neighbors = QDoubleSpinBox()
     min_neighbors.setDecimals(2)
     min_neighbors.setSingleStep(1)
     min_cluster = QDoubleSpinBox()
     min_cluster.setDecimals(2)
     min_cluster.setSingleStep(1)
     simulate_check = CheckBox()
     axis_creator(x_axis_selection,
                  y_axis_selection,
                  z_axis_selection,
                  choices=self.keys)
     self.items.append({
         'name': 'x_axis_selection',
         'string': 'x axis',
         'object': x_axis_selection
     })
     self.items.append({
         'name': 'y_axis_selection',
         'string': 'y axis',
         'object': y_axis_selection
     })
     self.items.append({
         'name': 'z_axis_selection',
         'string': 'z axis',
         'object': z_axis_selection
     })
     self.items.append({
         'name': 'epsilon',
         'string': 'Epsilon',
         'object': epsilon
     })
     self.items.append({
         'name': 'min_neighbors',
         'string': 'Minimum neighbors to consider a point',
         'object': min_neighbors
     })
     self.items.append({
         'name': 'min_cluster',
         'string': 'Minimum Cluster Density',
         'object': min_cluster
     })
     self.items.append({
         'name': 'simulate_check',
         'string': 'Simulate Center Proximities',
         'object': simulate_check
     })
     super().gui()
     self.ui.setGeometry(QRect(150, 50, 150, 130))
Пример #8
0
 def gui(self):
     self.gui_reset()
     window_width = SliderLabel()
     window_width.setRange(1, 2000)
     window_height = SliderLabel()
     window_height.setRange(1, 2000)
     num_points = SliderLabel()
     num_points.setRange(1, 13000)
     pixel_scale = QtWidgets.QDoubleSpinBox()
     pixel_scale.setDecimals(3)
     pixel_scale.setSingleStep(.001)
     load_ROI = CheckBox()
     display_graphs = CheckBox()
     self.items.append({
         'name': 'window_width',
         'string': 'Window Width',
         'object': window_width
     })
     self.items.append({
         'name': 'window_height',
         'string': 'Window Height',
         'object': window_height
     })
     self.items.append({
         'name': 'num_points',
         'string': 'Number of Points',
         'object': num_points
     })
     self.items.append({
         'name': 'pixel_scale',
         'string': 'Microns per Pixel',
         'object': pixel_scale
     })
     self.items.append({
         'name': 'load_ROI',
         'string': 'Load ROI?',
         'object': load_ROI
     })
     self.items.append({
         'name': 'display_graphs',
         'string': 'Display Graphs?',
         'object': display_graphs
     })
     super().gui()
     self.ui.setGeometry(QRect(400, 50, 600, 130))
Пример #9
0
class TiffPageLoader(BaseProcess_noPriorWindow):
    """
    Loads tiff files by page.
    """
    def __init__(self):
        if g.settings['tiff_page_loader'] is None or 'setSteps' not in g.settings['tiff_page_loader']:
            s = dict()
            s['nSteps'] = 1
            s['setSteps'] = True
            g.settings['tiff_page_loader'] = s
            
        #test saved filePath is valid
        
        super().__init__()
        return             
    
    def __call__(self, filePath, nSteps, setSteps):
        g.settings['on_the_fly']['filePath'] = filePath
        g.settings['on_the_fly']['nSteps']=nSteps
        g.settings['on_the_fly']['setSteps']=setSteps
        g.m.statusBar().showMessage("Scanning file ...")
        
        self.mainGUI = MainGUI()
        self.mainGUI.show()

    def closeEvent(self, event):
        BaseProcess_noPriorWindow.closeEvent(self, event)
        
    def gui(self):
        s=g.settings['tiff_page_loader']
        self.gui_reset()
        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])
        self.filePath = TiffSelector('*.tiff, *.tif')
        
        self.setSteps = CheckBox()
        self.setSteps.setValue(s['setSteps'])

        self.items.append({'name':'filePath','string':'Tiff file path','object': self.filePath})
        self.items.append({'name': 'nSteps', 'string': 'Number of steps per volume', 'object': self.nSteps})
        self.items.append({'name': 'setSteps', 'string': 'Automatically determine step size from Tiff metadata', 'object': self.setSteps})

        super().gui()
Пример #10
0
    def gui(self):
        self.gui_reset()
        self.active_window = WindowSelector()

        self.startButton = QPushButton('Start')
        self.startButton.pressed.connect(self.start)

        self.autoscaleX = CheckBox()
        self.autoscaleY = CheckBox()

        self.autoscaleX.setChecked(True)
        self.autoscaleY.setChecked(True)

        self.autoscaleX.stateChanged.connect(self.updateX)
        self.autoscaleY.stateChanged.connect(self.updateY)

        self.items.append({
            'name': 'active_window',
            'string': 'Select Window',
            'object': self.active_window
        })
        self.items.append({
            'name': 'autoScaleX',
            'string': 'Autoscale Histogram X-axis',
            'object': self.autoscaleX
        })
        self.items.append({
            'name': 'autoScaleY',
            'string': 'Autoscale Histogram Y-axis',
            'object': self.autoscaleY
        })
        self.items.append({
            'name': 'start_button',
            'string': 'Click to select current ROI',
            'object': self.startButton
        })

        super().gui()
Пример #11
0
 def gui(self):
     self.gui_reset()
     nFrames = SliderLabel(0)
     nFrames.setRange(0, 10000)
     puffAmplitude = SliderLabel(2)
     puffAmplitude.setRange(0, 10)
     nPuffs = SliderLabel(0)
     nPuffs.setRange(1, 100)
     pointsFile = FileSelector('*.txt')
     mx = SliderLabel(0)
     mx.setRange(1, 10000)
     my = SliderLabel(0)
     my.setRange(1, 10000)
     noisefree = CheckBox()
     self.items.append({
         'name': 'nFrames',
         'string': 'Movie Duration (frames)',
         'object': nFrames
     })
     self.items.append({
         'name': 'puffAmplitude',
         'string': 'Amplitude of puffs (multiples of SNR)',
         'object': puffAmplitude
     })
     self.items.append({
         'name': 'nPuffs',
         'string': 'number of puffs',
         'object': nPuffs
     })
     self.items.append({
         'name': 'pointsFile',
         'string': 'Location to save points',
         'object': pointsFile
     })
     self.items.append({
         'name': 'mx',
         'string': 'Movie Width',
         'object': mx
     })
     self.items.append({
         'name': 'my',
         'string': 'Movie Height',
         'object': my
     })
     self.items.append({
         'name': 'noisefree',
         'string': 'Noise Free',
         'object': noisefree
     })
     super().gui()
Пример #12
0
    def gui(self):
        self.gui_reset()
        self.red_window = WindowSelector()
        self.green_window = WindowSelector()
        self.overlayButton = QPushButton('Overlay')
        self.overlayButton.pressed.connect(self.overlay)
        self.scaleImages = CheckBox()

        self.items.append({'name': 'red_window', 'string': 'Select Red Window', 'object': self.red_window})
        self.items.append({'name': 'green_window', 'string': 'Select Green Window', 'object': self.green_window})
        self.items.append({'name': 'scaleImages', 'string': 'Scale Images', 'object': self.scaleImages})
        self.items.append({'name': 'start_button', 'string': '', 'object': self.overlayButton})

        super().gui()
    def gui(self):
        s = g.settings['on_the_fly']
        self.gui_reset()

        self.batchSize = pg.SpinBox(int=True, step=1)
        self.batchSize.setMinimum(1)
        self.batchSize.setValue(s['batchSize'])

        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])

        self.shift_factor = pg.SpinBox(int=False, step=.1)
        self.shift_factor.setValue(s['shift_factor'])

        self.theta = pg.SpinBox(int=True, step=1)
        self.theta.setValue(s['theta'])

        self.triangle_scan = CheckBox()
        self.triangle_scan.setValue(s['triangle_scan'])

        self.interpolate = CheckBox()
        self.interpolate.setValue(s['interpolate'])

        self.trim_last_frame = CheckBox()
        self.trim_last_frame.setValue(s['trim_last_frame'])

        self.zscan = CheckBox()
        self.zscan.setValue(s['trim_last_frame'])

        self.recordingFolder = FolderSelector('*.txt')
        self.exportFolder = FolderSelector('*.txt')

        self.displaySlice = pg.SpinBox(int=True, step=1)
        self.displaySlice.setMinimum(0)
        self.displaySlice.setValue(s['displaySlice'])

        self.updateRate = pg.SpinBox(int=True, step=1)
        self.updateRate.setMinimum(1)
        self.updateRate.setValue(s['updateRate'])

        self.updateRateVolViewer = pg.SpinBox(int=True, step=1)
        self.updateRateVolViewer.setMinimum(1)
        self.updateRateVolViewer.setValue(s['updateRateVolViewer'])

        self.nChannels = pg.SpinBox(int=True, step=1)
        self.nChannels.setMinimum(1)
        self.nChannels.setMaximum(2)
        self.nChannels.setValue(s['nChannels'])

        self.items.append({
            'name': 'recordingFolder',
            'string': 'Results Folder Location',
            'object': self.recordingFolder
        })
        self.items.append({
            'name': 'exportFolder',
            'string': 'Export Folder Location',
            'object': self.exportFolder
        })
        self.items.append({
            'name': 'batchSize',
            'string': 'Batch Size',
            'object': self.batchSize
        })
        self.items.append({
            'name': 'updateRate',
            'string': 'Update Rate (seconds)',
            'object': self.updateRate
        })
        self.items.append({
            'name': 'updateRateVolViewer',
            'string': 'Volume Viewer Update Rate (seconds)',
            'object': self.updateRateVolViewer
        })
        self.items.append({
            'name': 'nSteps',
            'string': 'Number of Steps Per Volume',
            'object': self.nSteps
        })
        self.items.append({
            'name': 'displaySlice',
            'string': 'Display Slice#',
            'object': self.displaySlice
        })
        self.items.append({
            'name': 'shift_factor',
            'string': 'Shift Factor',
            'object': self.shift_factor
        })
        self.items.append({
            'name': 'theta',
            'string': 'Theta',
            'object': self.theta
        })
        self.items.append({
            'name': 'triangle_scan',
            'string': 'Triangle Scan',
            'object': self.triangle_scan
        })
        self.items.append({
            'name': 'interpolate',
            'string': 'Interpolate',
            'object': self.interpolate
        })
        self.items.append({
            'name': 'trim_last_frame',
            'string': 'Trim Last Frame',
            'object': self.trim_last_frame
        })
        self.items.append({
            'name': 'zscan',
            'string': 'Z Scan',
            'object': self.zscan
        })
        self.items.append({
            'name': 'nChannels',
            'string': 'Number of Channels',
            'object': self.nChannels
        })

        super().gui()
Пример #14
0
    def __init__(self, parent=None):
        super(BatchOptions, self).__init__(parent)

        self.s = g.settings['volumeSlider']

        self.slicesPerVolume = self.s['slicesPerVolume']
        self.baselineValue = self.s['baselineValue']
        self.f0Start = self.s['f0Start']
        self.f0End = self.s['f0End']
        self.f0VolStart = self.s['f0VolStart']
        self.f0VolEnd = self.s['f0VolEnd']
        self.multiplicationFactor = self.s['multiplicationFactor']
        self.currentDataType = self.s['currentDataType']
        self.newDataType = self.s['newDataType']
        self.inputArrayOrder = self.s['inputArrayOrder']
        self.displayArrayOrder = self.s['displayArrayOrder'] = 16
        self.theta = self.s['theta']
        self.shiftFactor = self.s['shiftFactor']
        self.trim_last_frame = self.s['trimLastFrame']

        self.subtractBaseline = False
        self.runDFF0 = False
        self.runMultiplication = False

        self.inputDirectory = ''

        #window geometry
        self.left = 300
        self.top = 300
        self.width = 300
        self.height = 200

        #labels
        self.label_slicesPerVolume = QtWidgets.QLabel("slices per volume:")
        self.label_theta = QtWidgets.QLabel("theta:")
        self.label_baselineValue = QtWidgets.QLabel('baseline Value:')
        self.label_f0Start = QtWidgets.QLabel('f0 Start:')
        self.label_f0End = QtWidgets.QLabel('f0 End:')
        self.label_f0VolStart = QtWidgets.QLabel('f0Vol Start:')
        self.label_f0VolEnd = QtWidgets.QLabel('f0Vol End:')
        self.label_multiplicationFactor = QtWidgets.QLabel(
            'multiplication Factor:')
        self.label_shiftFactor = QtWidgets.QLabel('shift Factor:')
        self.label_trim_last_frame = QtWidgets.QLabel('trim Last Frame:')
        self.label_inputDirectory = QtWidgets.QLabel('input directory:')

        self.label_subtractBaseline = QtWidgets.QLabel('subtract baseline:')
        self.label_runDFF0 = QtWidgets.QLabel('run DF/F0:')
        self.label_runMultiplication = QtWidgets.QLabel(
            'scale by multiplication factor:')

        #spinboxes/comboboxes
        self.volBox = QtWidgets.QSpinBox()
        self.volBox.setRange(0, 10000)
        self.volBox.setValue(self.slicesPerVolume)

        self.thetaBox = QtWidgets.QSpinBox()
        self.thetaBox.setRange(0, 360)
        self.thetaBox.setValue(self.theta)

        self.baselineBox = QtWidgets.QSpinBox()
        self.baselineBox.setRange(0, 100000)
        self.baselineBox.setValue(self.baselineValue)

        self.f0StartBox = QtWidgets.QSpinBox()
        self.f0StartBox.setRange(0, 100000)
        self.f0StartBox.setValue(self.f0Start)

        self.f0EndBox = QtWidgets.QSpinBox()
        self.f0EndBox.setRange(0, 100000)
        self.f0EndBox.setValue(self.f0End)

        self.f0VolStartBox = QtWidgets.QSpinBox()
        self.f0VolStartBox.setRange(0, 100000)
        self.f0VolStartBox.setValue(self.f0VolStart)

        self.f0VolEndBox = QtWidgets.QSpinBox()
        self.f0VolEndBox.setRange(0, 100000)
        self.f0VolEndBox.setValue(self.f0VolEnd)

        self.multiplicationFactorBox = QtWidgets.QSpinBox()
        self.multiplicationFactorBox.setRange(0, 100000)
        self.multiplicationFactorBox.setValue(self.multiplicationFactor)

        self.shiftFactorBox = QtWidgets.QSpinBox()
        self.shiftFactorBox.setRange(0, 100000)
        self.shiftFactorBox.setValue(self.shiftFactor)

        self.trim_last_frame_checkbox = CheckBox()
        self.trim_last_frame_checkbox.setChecked(self.trim_last_frame)

        self.subtractBaseline_checkbox = CheckBox()
        self.subtractBaseline_checkbox.setChecked(self.subtractBaseline)

        self.runDFF0_checkbox = CheckBox()
        self.runDFF0_checkbox.setChecked(self.runDFF0)

        self.runMultiplication_checkbox = CheckBox()
        self.runMultiplication_checkbox.setChecked(self.runMultiplication)

        self.inputDirectory_display = QtWidgets.QLabel(self.inputDirectory)

        #buttons
        self.button_setInputDirectory = QtWidgets.QPushButton("Set Folder")
        self.button_startBatch = QtWidgets.QPushButton("Go")

        #grid layout
        layout = QtWidgets.QGridLayout()
        layout.setSpacing(5)
        layout.addWidget(self.label_slicesPerVolume, 0, 0)
        layout.addWidget(self.volBox, 0, 1)
        layout.addWidget(self.label_theta, 1, 0)
        layout.addWidget(self.thetaBox, 1, 1)
        layout.addWidget(self.label_baselineValue, 2, 0)
        layout.addWidget(self.baselineBox, 2, 1)
        layout.addWidget(self.label_f0Start, 3, 0)
        layout.addWidget(self.f0StartBox, 3, 1)
        layout.addWidget(self.label_f0End, 4, 0)
        layout.addWidget(self.f0EndBox, 4, 1)
        layout.addWidget(self.label_f0VolStart, 5, 0)
        layout.addWidget(self.f0VolStartBox, 5, 1)
        layout.addWidget(self.label_f0VolEnd, 6, 0)
        layout.addWidget(self.f0VolEndBox, 6, 1)
        layout.addWidget(self.label_multiplicationFactor, 7, 0)
        layout.addWidget(self.multiplicationFactorBox, 7, 1)
        layout.addWidget(self.label_shiftFactor, 8, 0)
        layout.addWidget(self.shiftFactorBox, 8, 1)
        layout.addWidget(self.label_trim_last_frame, 9, 0)
        layout.addWidget(self.trim_last_frame_checkbox, 9, 1)

        layout.addWidget(self.label_subtractBaseline, 10, 0)
        layout.addWidget(self.subtractBaseline_checkbox, 10, 1)

        layout.addWidget(self.label_runDFF0, 11, 0)
        layout.addWidget(self.runDFF0_checkbox, 11, 1)
        layout.addWidget(self.label_runMultiplication, 12, 0)
        layout.addWidget(self.runMultiplication_checkbox, 12, 1)

        layout.addWidget(self.label_inputDirectory, 13, 0)
        layout.addWidget(self.inputDirectory_display, 13, 1)
        layout.addWidget(self.button_setInputDirectory, 13, 2)
        layout.addWidget(self.button_startBatch, 14, 2)

        self.setLayout(layout)
        self.setGeometry(self.left, self.top, self.width, self.height)

        #add window title
        self.setWindowTitle("Batch Options")

        #connect spinboxes/comboboxes
        self.volBox.valueChanged.connect(self.set_slicesPerVolume)
        self.thetaBox.valueChanged.connect(self.set_theta)
        self.baselineBox.valueChanged.connect(self.set_baselineValue)
        self.f0StartBox.valueChanged.connect(self.set_f0Start)
        self.f0EndBox.valueChanged.connect(self.set_f0End)
        self.f0VolStartBox.valueChanged.connect(self.set_f0VolStart)
        self.f0VolEndBox.valueChanged.connect(self.set_f0VolEnd)
        self.multiplicationFactorBox.valueChanged.connect(
            self.set_multiplicationFactor)
        self.shiftFactorBox.valueChanged.connect(self.set_shiftFactor)
        self.trim_last_frame_checkbox.stateChanged.connect(
            self.set_trim_last_frame)
        self.subtractBaseline_checkbox.stateChanged.connect(
            self.set_subtractBaseline)
        self.runDFF0_checkbox.stateChanged.connect(self.set_runDFF0)
        self.runMultiplication_checkbox.stateChanged.connect(
            self.set_runMultiplication)
        self.button_setInputDirectory.pressed.connect(
            lambda: self.setInput_button())
        self.button_startBatch.pressed.connect(lambda: self.start_button())
        return
class OnTheFly(BaseProcess_noPriorWindow):
    """
    Continuous light sheet analysis
    """
    def __init__(self):
        if g.settings[
                'on_the_fly'] is None or 'updateRateVolViewer' not in g.settings[
                    'on_the_fly']:
            s = dict()
            s['sliceNumber'] = 0
            s['batchSize'] = 10
            s['updateRate'] = 2  #seconds
            s['updateRateVolViewer'] = 120  #seconds
            s['nSteps'] = 1
            s['displaySlice'] = 0
            s['shift_factor'] = 1
            s['theta'] = 45
            s['triangle_scan'] = False
            s['interpolate'] = False
            s['trim_last_frame'] = False
            s['nChannels'] = 1
            g.settings['on_the_fly'] = s

        BaseProcess_noPriorWindow.__init__(self)

    def __call__(self,
                 recordingFolder,
                 exportFolder,
                 batchSize,
                 updateRate,
                 updateRateVolViewer,
                 nSteps,
                 displaySlice,
                 shift_factor,
                 theta,
                 triangle_scan,
                 interpolate,
                 trim_last_frame,
                 zscan,
                 nChannels,
                 keepSourceWindow=False):
        g.settings['on_the_fly']['recordingFolder'] = recordingFolder
        g.settings['on_the_fly']['exportFolder'] = exportFolder
        g.settings['on_the_fly']['batchSize'] = batchSize
        g.settings['on_the_fly']['updateRate'] = updateRate
        g.settings['on_the_fly']['updateRateVolViewer'] = updateRateVolViewer
        g.settings['on_the_fly']['nSteps'] = nSteps
        g.settings['on_the_fly']['displaySlice'] = displaySlice
        g.settings['on_the_fly']['shift_factor'] = shift_factor
        g.settings['on_the_fly']['theta'] = theta
        g.settings['on_the_fly']['triangle_scan'] = triangle_scan
        g.settings['on_the_fly']['interpolate'] = interpolate
        g.settings['on_the_fly']['trim_last_frame'] = trim_last_frame
        g.settings['on_the_fly']['zscan'] = zscan
        g.settings['on_the_fly']['nChannels'] = nChannels
        g.m.statusBar().showMessage("Starting ...")
        t = time()

        self.mainGUI = MainGUI()
        self.mainGUI.show()

    def closeEvent(self, event):
        BaseProcess_noPriorWindow.closeEvent(self, event)

    def gui(self):
        s = g.settings['on_the_fly']
        self.gui_reset()

        self.batchSize = pg.SpinBox(int=True, step=1)
        self.batchSize.setMinimum(1)
        self.batchSize.setValue(s['batchSize'])

        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])

        self.shift_factor = pg.SpinBox(int=False, step=.1)
        self.shift_factor.setValue(s['shift_factor'])

        self.theta = pg.SpinBox(int=True, step=1)
        self.theta.setValue(s['theta'])

        self.triangle_scan = CheckBox()
        self.triangle_scan.setValue(s['triangle_scan'])

        self.interpolate = CheckBox()
        self.interpolate.setValue(s['interpolate'])

        self.trim_last_frame = CheckBox()
        self.trim_last_frame.setValue(s['trim_last_frame'])

        self.zscan = CheckBox()
        self.zscan.setValue(s['trim_last_frame'])

        self.recordingFolder = FolderSelector('*.txt')
        self.exportFolder = FolderSelector('*.txt')

        self.displaySlice = pg.SpinBox(int=True, step=1)
        self.displaySlice.setMinimum(0)
        self.displaySlice.setValue(s['displaySlice'])

        self.updateRate = pg.SpinBox(int=True, step=1)
        self.updateRate.setMinimum(1)
        self.updateRate.setValue(s['updateRate'])

        self.updateRateVolViewer = pg.SpinBox(int=True, step=1)
        self.updateRateVolViewer.setMinimum(1)
        self.updateRateVolViewer.setValue(s['updateRateVolViewer'])

        self.nChannels = pg.SpinBox(int=True, step=1)
        self.nChannels.setMinimum(1)
        self.nChannels.setMaximum(2)
        self.nChannels.setValue(s['nChannels'])

        self.items.append({
            'name': 'recordingFolder',
            'string': 'Results Folder Location',
            'object': self.recordingFolder
        })
        self.items.append({
            'name': 'exportFolder',
            'string': 'Export Folder Location',
            'object': self.exportFolder
        })
        self.items.append({
            'name': 'batchSize',
            'string': 'Batch Size',
            'object': self.batchSize
        })
        self.items.append({
            'name': 'updateRate',
            'string': 'Update Rate (seconds)',
            'object': self.updateRate
        })
        self.items.append({
            'name': 'updateRateVolViewer',
            'string': 'Volume Viewer Update Rate (seconds)',
            'object': self.updateRateVolViewer
        })
        self.items.append({
            'name': 'nSteps',
            'string': 'Number of Steps Per Volume',
            'object': self.nSteps
        })
        self.items.append({
            'name': 'displaySlice',
            'string': 'Display Slice#',
            'object': self.displaySlice
        })
        self.items.append({
            'name': 'shift_factor',
            'string': 'Shift Factor',
            'object': self.shift_factor
        })
        self.items.append({
            'name': 'theta',
            'string': 'Theta',
            'object': self.theta
        })
        self.items.append({
            'name': 'triangle_scan',
            'string': 'Triangle Scan',
            'object': self.triangle_scan
        })
        self.items.append({
            'name': 'interpolate',
            'string': 'Interpolate',
            'object': self.interpolate
        })
        self.items.append({
            'name': 'trim_last_frame',
            'string': 'Trim Last Frame',
            'object': self.trim_last_frame
        })
        self.items.append({
            'name': 'zscan',
            'string': 'Z Scan',
            'object': self.zscan
        })
        self.items.append({
            'name': 'nChannels',
            'string': 'Number of Channels',
            'object': self.nChannels
        })

        super().gui()
Пример #16
0
    def gui(self):
        self.gui_reset()
        self.nFrames = pg.SpinBox(int=False, step=.01)
        #self.nFrames.setRange(0,10000)
        self.startFrame = SliderLabel(0)
        self.startFrame.setRange(0, 10000)

        self.puffAmplitude = pg.SpinBox(int=False, step=.01)
        self.puffAmplitude.setValue(1.0)
        self.sigma = SliderLabel(0)
        self.sigma.setRange(1, 1000)
        self.x = SliderLabel(0)
        self.x.setRange(1, 10000)
        self.y = SliderLabel(0)
        self.y.setRange(1, 10000)
        self.useROI = CheckBox()
        self.useFrame = CheckBox()
        self.active_window = WindowSelector()
        self.previewButton = QPushButton('Preview Puff')
        self.previewButton.pressed.connect(self.previewPuff)
        self.puffButton = QPushButton('Add Puff')
        self.puffButton.pressed.connect(self.addPuff)

        self.randomPuffsAdded = False

        self.nSites = 10
        columnNames = ['time of puff', 'duration', 'site']
        self.timesAdded = pd.DataFrame(columns=columnNames)
        self.siteNumber = int(0)

        self.nPuffs_slider = SliderLabel(0)
        self.nPuffs_slider.setRange(1, 1000)

        self.meanExp_slider = pg.SpinBox(int=False, step=.01)
        self.meanExp_slider.setValue(5.0)

        self.randomDuration = CheckBox()
        self.randomDuration.setValue(False)

        self.durationMean = 10.0
        self.durationMean_box = pg.SpinBox(int=False, step=.01)
        self.durationMean_box.setRange(0, 10000)
        self.durationMean_box.setValue(self.durationMean)

        self.plotHistoTimes = CheckBox()
        self.plotHistoTimes.setValue(False)

        self.addPuffsSequentially = CheckBox()
        self.addPuffsSequentially.setValue(False)

        self.exportTimes_button = QPushButton('Export times')
        self.exportTimes_button.pressed.connect(self.exportTimes)

        self.randomPuffButton = QPushButton('Add Puffs to site')
        self.randomPuffButton.pressed.connect(self.addRandomPuffs)

        self.multipleRandomPuffButton = QPushButton('Add Puffs inside ROI')
        self.multipleRandomPuffButton.pressed.connect(
            self.addMultipleRandomPuffs)

        self.nSites_box = QSpinBox()
        self.nSites_box.setRange(0, 10000)
        self.nSites_box.setValue(self.nSites)

        self.items.append({
            'name': 'active_window',
            'string': 'Select Window',
            'object': self.active_window
        })
        self.items.append({
            'name': 'nFrames',
            'string': 'Duration (frames)',
            'object': self.nFrames
        })
        self.items.append({
            'name': 'randomDuration',
            'string': 'Use exponentially distributed random duration',
            'object': self.randomDuration
        })
        self.items.append({
            'name': 'meanDuration',
            'string': 'Mean duration',
            'object': self.durationMean_box
        })
        self.items.append({
            'name': 'startFrame',
            'string': 'Start Frame',
            'object': self.startFrame
        })
        #self.items.append({'name': 'useCurrentFrame', 'string': 'Use Current Frame For Start', 'object': self.useFrame})
        self.items.append({
            'name': 'puffAmplitude',
            'string': 'Amplitude',
            'object': self.puffAmplitude
        })
        self.items.append({'name': 'x', 'string': 'x', 'object': self.x})
        self.items.append({'name': 'y', 'string': 'y', 'object': self.y})
        #self.items.append({'name': 'useROI', 'string': 'Use ROI for position', 'object': self.useROI})
        self.items.append({
            'name': 'sigma',
            'string': 'sigma',
            'object': self.sigma
        })
        self.items.append({
            'name': 'preview_Button',
            'string': 'Click to preview Puff',
            'object': self.previewButton
        })
        self.items.append({
            'name': 'puff_Button',
            'string': 'Click to add Puff',
            'object': self.puffButton
        })
        self.items.append({
            'name': 'blank',
            'string': '---------- RANDOM PUFFS ---------------------------',
            'object': None
        })
        #self.items.append({'name': 'nPuffs', 'string': 'Number of puffs to add', 'object': self.nPuffs_slider})
        self.items.append({
            'name': 'meanExp',
            'string': 'Mean of exponential distibution of puff start times',
            'object': self.meanExp_slider
        })
        self.items.append({
            'name': 'puffsSequential',
            'string': 'Wait until puff ends before adding next puff:',
            'object': self.addPuffsSequentially
        })
        self.items.append({
            'name': 'histoTimes',
            'string': 'Plot histogram of puff start times:',
            'object': self.plotHistoTimes
        })
        self.items.append({
            'name': 'random_puff_Button',
            'string': 'Click to add randomly distibuted puffs at one site',
            'object': self.randomPuffButton
        })
        self.items.append({
            'name': 'multipleRandom_puff_Button',
            'string':
            'Click to add randomly distibuted puffs at multiple sites',
            'object': self.multipleRandomPuffButton
        })
        self.items.append({
            'name': 'nSites',
            'string': 'Number of Sites to add',
            'object': self.nSites_box
        })
        self.items.append({
            'name': 'blank',
            'string': '---------- Export Puffs ---------------------------',
            'object': None
        })
        self.items.append({
            'name': 'listTimes',
            'string': 'Export list of puff start times',
            'object': self.exportTimes_button
        })

        super().gui()
Пример #17
0
    def gui(self):
        #get saved settings
        s = g.settings['centerSurroundROI']
        self.surroundWidth = s['surroundWidth']
        self.centerWidth = s['centerWidth']
        self.centerHeight = s['centerHeight']
        self.centerSize = self.centerWidth  #setting size to width at start
        #setup GUI
        self.gui_reset()
        self.active_window = WindowSelector()

        self.displaySurroundButton = QPushButton('Display Surround ROI')
        self.displaySurroundButton.pressed.connect(self.displaySurround)

        self.startButton = QPushButton('Start')
        self.startButton.pressed.connect(self.startROItrace)

        self.width = SliderLabel(0)
        self.width.setRange(1, 20)
        self.width.setValue(self.surroundWidth)
        self.width.valueChanged.connect(self.updateWidth)
        self.width.slider.sliderReleased.connect(self.getSubtract)

        self.widthCenter = SliderLabel(0)
        self.widthCenter.setRange(1, 500)
        self.widthCenter.setValue(self.centerWidth)
        self.widthCenter.valueChanged.connect(self.updateCenterWidth)
        self.widthCenter.slider.sliderReleased.connect(self.getSubtract)

        self.heightCenter = SliderLabel(0)
        self.heightCenter.setRange(1, 500)
        self.heightCenter.setValue(self.centerHeight)
        self.heightCenter.valueChanged.connect(self.updateCenterHeight)
        self.heightCenter.slider.sliderReleased.connect(self.getSubtract)

        self.sizeCenter = SliderLabel(0)
        self.sizeCenter.setRange(1, 500)
        self.sizeCenter.setValue(self.centerSize)
        self.sizeCenter.valueChanged.connect(self.updateCenterSize)
        self.sizeCenter.slider.sliderReleased.connect(self.getSubtract)

        self.scaleImages = CheckBox()

        self.items.append({
            'name': 'active_window',
            'string': 'Select Window',
            'object': self.active_window
        })
        self.items.append({
            'name': 'surroundWidth',
            'string': 'Set Surround Width',
            'object': self.width
        })
        self.items.append({
            'name': 'centerWidth',
            'string': 'Set Center Width',
            'object': self.widthCenter
        })
        self.items.append({
            'name': 'centerHeight',
            'string': 'Set Center Height',
            'object': self.heightCenter
        })
        self.items.append({
            'name': 'centerSize',
            'string': 'Set Center Size (as square)',
            'object': self.sizeCenter
        })
        #self.items.append({'name': 'scaleImages', 'string': 'Scale trace', 'object': self.scaleImages})
        #self.items.append({'name': 'displaySurround_button', 'string': '          ', 'object': self.displaySurroundButton})
        self.items.append({
            'name': 'start_button',
            'string': '          ',
            'object': self.startButton
        })

        super().gui()
Пример #18
0
    def gui(self):
        self.gui_reset()

        #combobox
        inputChoice = ComboBox()
        inputChoice.addItem('Current Window')
        inputChoice.addItem('Load file')
        inputChoice.addItem('Numpy Array')
        inputChoice.addItem('Batch Process')

        #checkbox
        self.keepOriginalWindow = CheckBox()
        self.keepOriginalWindow.setValue(False)

        self.preProcess = CheckBox()
        self.preProcess.setValue(g.settings['volumeSlider']['preProcess'])

        self.framesPerVolume = pg.SpinBox(int=True, step=1)
        self.framesPerVolume.setValue(
            g.settings['volumeSlider']['slicesPerVolume'])

        self.framesRemoved = pg.SpinBox(int=True, step=1)
        self.framesRemoved.setValue(
            g.settings['volumeSlider']['slicesDeletedPerVolume'])

        self.framesRemovedStart = pg.SpinBox(int=True, step=1)
        self.framesRemovedStart.setValue(
            g.settings['volumeSlider']['slicesDeletedPerMovie'])

        self.overlay = CheckBox()
        self.overlay.setValue(g.settings['volumeSlider']['overlay'])

        self.overlayStart = pg.SpinBox(int=True, step=1)
        self.overlayStart.setValue(g.settings['volumeSlider']['overlayStart'])

        #populate GUI
        self.items.append({
            'name': 'inputChoice',
            'string': 'Choose Input Data:',
            'object': inputChoice
        })
        self.items.append({
            'name': 'keepOriginalWindow',
            'string': 'Keep Original Window',
            'object': self.keepOriginalWindow
        })

        self.items.append({
            'name': 'spacer',
            'string': '------------ Preprocessing Options --------------',
            'object': None
        })
        self.items.append({
            'name': 'preProcess',
            'string': 'Preprocess Image Stack',
            'object': self.preProcess
        })
        self.items.append({
            'name': 'slicesPerVolume',
            'string': 'Slices per Volume',
            'object': self.framesPerVolume
        })
        self.items.append({
            'name': 'slicesDeletedPerVolume',
            'string': 'Frames to Remove per Volume',
            'object': self.framesRemoved
        })
        self.items.append({
            'name': 'slicesDeletedPerMovie',
            'string': 'Frames to Remove From Start of Stack',
            'object': self.framesRemovedStart
        })

        self.items.append({
            'name': 'spacer',
            'string': '------------    Overlay Options    --------------',
            'object': None
        })
        self.items.append({
            'name': 'overlay',
            'string': 'Overlay Image in Stack',
            'object': self.overlay
        })
        self.items.append({
            'name': 'overlayStart',
            'string': '1st Frame of Overlay',
            'object': self.overlayStart
        })

        super().gui()
Пример #19
0
class VolumeSliderBase(BaseProcess_noPriorWindow):
    """
    Start Volume Slider from differnt sources

        |Select source (current window or saved numpy array)
        
    Returns volumeSlider GUI

    """
    def __init__(self):
        if g.settings['volumeSlider'] is None or 'UPDATE' not in g.settings[
                'volumeSlider']:
            s = dict()
            s['inputChoice'] = 'Current Window'
            s['keepOriginalWindow'] = False
            s['slicesPerVolume'] = 1
            s['baselineValue'] = 0
            s['f0Start'] = 0
            s['f0End'] = 0
            s['multiplicationFactor'] = 100
            s['currentDataType'] = 0
            s['newDataType'] = 0
            s['theta'] = 45
            s['shiftFactor'] = 1
            s['trimLastFrame'] = False
            s['inputArrayOrder'] = 4
            s['displayArrayOrder'] = 16
            s['f0VolStart'] = 0
            s['f0VolEnd'] = 0
            s['IMS_fname'] = 'IMS_export.ims'
            s['IMS_subsamp'] = '((1, 1, 1), (1, 2, 2))'
            s['IMS_chunks'] = '((16, 128, 128), (64, 64, 64))'
            s['IMS_compression'] = 'gzip'
            s['IMS_thumbsize'] = '256'
            s['IMS_dx'] = 0.1
            s['IMS_dz'] = 0.25
            s['IMS_Unit'] = 'um'
            s['IMS_GammaCorrection'] = 1
            s['IMS_ColorRange'] = '0 255'
            s['IMS_LSMEmissionWavelength'] = 0
            s['IMS_LSMExcitationWavelength'] = 0

            g.settings['volumeSlider'] = s

        BaseProcess_noPriorWindow.__init__(self)

    def __call__(self,
                 inputChoice,
                 keepOriginalWindow,
                 keepSourceWindow=False):
        g.settings['volumeSlider']['inputChoice'] = inputChoice
        g.settings['volumeSlider']['keepOriginalWindow'] = keepOriginalWindow

        g.m.statusBar().showMessage("Starting Volume Slider...")

        if inputChoice == 'Current Window':
            camVolumeSlider.startVolumeSlider(keepWindow=keepOriginalWindow)

        elif inputChoice == 'Numpy Array':
            A_path = open_file_gui(directory=os.path.expanduser("~/Desktop"),
                                   filetypes='*.npy')
            g.m.statusBar().showMessage("Importing Array: " + A_path)
            A = np.load(str(A_path))
            camVolumeSlider.startVolumeSlider(A=A,
                                              keepWindow=keepOriginalWindow)

        elif inputChoice == 'Batch Process':
            g.m.statusBar().showMessage("Starting Batch Processing...")
            camVolumeSlider.startVolumeSlider(batch=True)

        return

    def closeEvent(self, event):
        BaseProcess_noPriorWindow.closeEvent(self, event)

    def gui(self):
        self.gui_reset()

        #combobox
        inputChoice = ComboBox()
        inputChoice.addItem('Current Window')
        inputChoice.addItem('Numpy Array')
        inputChoice.addItem('Batch Process')

        #checkbox
        self.keepOriginalWindow = CheckBox()
        self.keepOriginalWindow.setValue(False)

        #populate GUI
        self.items.append({
            'name': 'inputChoice',
            'string': 'Choose Input Data:',
            'object': inputChoice
        })
        self.items.append({
            'name': 'keepOriginalWindow',
            'string': 'Keep Original Window',
            'object': self.keepOriginalWindow
        })
        super().gui()
class Volume_Viewer(QtWidgets.QWidget):
    closeSignal = QtCore.Signal()

    def show_wo_focus(self):
        self.show()
        self.window.activateWindow()  # for Windows
        self.window.raise_()  # for MacOS

    def __init__(self, window=None, parent=None):
        super(Volume_Viewer,
              self).__init__(parent)  # Create window with ImageView widget
        g.m.volume_viewer = self
        window.lostFocusSignal.connect(self.hide)
        window.gainedFocusSignal.connect(self.show_wo_focus)
        self.window = window
        self.setWindowTitle('Light Sheet Volume View Controller')
        self.setWindowIcon(QtGui.QIcon(image_path('favicon.png')))
        self.setGeometry(QtCore.QRect(422, 35, 222, 86))
        self.layout = QtWidgets.QVBoxLayout()
        self.vol_shape = window.volume.shape
        mv, mz, mx, my = window.volume.shape
        self.currentAxisOrder = [0, 1, 2, 3]
        self.current_v_Index = 0
        self.current_z_Index = 0
        self.current_x_Index = 0
        self.current_y_Index = 0
        self.formlayout = QtWidgets.QFormLayout()
        self.formlayout.setLabelAlignment(QtCore.Qt.AlignRight)
        self.xzy_position_label = QtWidgets.QLabel('Z position')
        self.zSlider = SliderLabel(0)
        self.zSlider.setRange(0, mz - 1)
        self.zSlider.label.valueChanged.connect(self.zSlider_updated)
        self.zSlider.slider.mouseReleaseEvent = self.zSlider_release_event

        self.sideViewOn = CheckBox()
        self.sideViewOn.setChecked(False)
        self.sideViewOn.stateChanged.connect(self.sideViewOnClicked)

        self.sideViewSide = QtWidgets.QComboBox(self)
        self.sideViewSide.addItem("X")
        self.sideViewSide.addItem("Y")

        self.MaxProjButton = QtWidgets.QPushButton('Max Intenstiy Projection')
        self.MaxProjButton.pressed.connect(self.make_maxintensity)

        self.exportVolButton = QtWidgets.QPushButton('Export Volume')
        self.exportVolButton.pressed.connect(self.export_volume)

        self.formlayout.addRow(self.xzy_position_label, self.zSlider)
        self.formlayout.addRow('Side View On', self.sideViewOn)
        self.formlayout.addRow('Side View Side', self.sideViewSide)
        self.formlayout.addRow('', self.MaxProjButton)
        self.formlayout.addRow('', self.exportVolButton)

        self.layout.addWidget(self.zSlider)
        self.layout.addLayout(self.formlayout)
        self.setLayout(self.layout)
        self.setGeometry(QtCore.QRect(381, 43, 416, 110))
        self.show()

    def closeEvent(self, event):
        event.accept()  # let the window close

    def zSlider_updated(self, z_val):
        self.current_v_Index = self.window.currentIndex
        vol = self.window.volume
        testimage = np.squeeze(vol[self.current_v_Index, z_val, :, :])
        viewRect = self.window.imageview.view.targetRect()
        self.window.imageview.setImage(testimage, autoLevels=False)
        self.window.imageview.view.setRange(viewRect, padding=0)
        self.window.image = testimage

    def zSlider_release_event(self, ev):
        vol = self.window.volume
        if self.currentAxisOrder[1] == 1:  # 'z'
            self.current_z_Index = self.zSlider.value()
            image = np.squeeze(vol[:, self.current_z_Index, :, :])
        elif self.currentAxisOrder[1] == 2:  # 'x'
            self.current_x_Index = self.zSlider.value()
            image = np.squeeze(vol[:, self.current_x_Index, :, :])
        elif self.currentAxisOrder[1] == 3:  # 'y'
            self.current_y_Index = self.zSlider.value()
            image = np.squeeze(vol[:, self.current_y_Index, :, :])

        viewRect = self.window.imageview.view.viewRect()
        self.window.imageview.setImage(image, autoLevels=False)
        self.window.imageview.view.setRange(viewRect, padding=0)
        self.window.image = image
        if self.window.imageview.axes['t'] is not None:
            self.window.imageview.setCurrentIndex(self.current_v_Index)
        self.window.activateWindow()  # for Windows
        self.window.raise_()  # for MacOS
        QtWidgets.QSlider.mouseReleaseEvent(self.zSlider.slider, ev)

    def sideViewOnClicked(self, checked):
        self.current_v_Index = self.window.currentIndex
        vol = self.window.volume
        if checked == 2:  #checked=True
            assert self.currentAxisOrder == [0, 1, 2, 3]
            side = self.sideViewSide.currentText()
            if side == 'X':
                vol = vol.swapaxes(1, 2)
                self.currentAxisOrder = [0, 2, 1, 3]
                vol = vol.swapaxes(2, 3)
                self.currentAxisOrder = [0, 2, 3, 1]
            elif side == 'Y':
                vol = vol.swapaxes(1, 3)
                self.currentAxisOrder = [0, 3, 2, 1]
        else:  #checked=False
            if self.currentAxisOrder == [0, 3, 2, 1]:
                vol = vol.swapaxes(1, 3)
                self.currentAxisOrder = [0, 1, 2, 3]
            elif self.currentAxisOrder == [0, 2, 3, 1]:
                vol = vol.swapaxes(2, 3)
                vol = vol.swapaxes(1, 2)
                self.currentAxisOrder = [0, 1, 2, 3]
        if self.currentAxisOrder[1] == 1:  # 'z'
            idx = self.current_z_Index
            self.xzy_position_label.setText('Z position')
            self.zSlider.setRange(0, self.vol_shape[1] - 1)
        elif self.currentAxisOrder[1] == 2:  # 'x'
            idx = self.current_x_Index
            self.xzy_position_label.setText('X position')
            self.zSlider.setRange(0, self.vol_shape[2] - 1)
        elif self.currentAxisOrder[1] == 3:  # 'y'
            idx = self.current_y_Index
            self.xzy_position_label.setText('Y position')
            self.zSlider.setRange(0, self.vol_shape[3] - 1)
        image = np.squeeze(vol[:, idx, :, :])
        self.window.imageview.setImage(image, autoLevels=False)
        self.window.volume = vol
        self.window.imageview.setCurrentIndex(self.current_v_Index)
        self.zSlider.setValue(idx)

    def make_maxintensity(self):
        vol = self.window.volume
        new_vol = np.max(vol, 1)
        if self.currentAxisOrder[1] == 1:  # 'z'
            name = 'Max Z projection'
        elif self.currentAxisOrder[1] == 2:  # 'x'
            name = 'Max X projection'
        elif self.currentAxisOrder[1] == 3:  # 'y'
            name = 'Max Y projection'
        Window(new_vol, name=name)

    def export_volume(self):
        vol = self.window.volume
        export_path = QtWidgets.QFileDialog.getExistingDirectory(
            g.m, "Select a parent folder to save into.", expanduser("~"),
            QtWidgets.QFileDialog.ShowDirsOnly)
        export_path = os.path.join(export_path, 'light_sheet_vols')
        i = 0
        while os.path.isdir(export_path + str(i)):
            i += 1
        export_path = export_path + str(i)
        os.mkdir(export_path)
        for v in np.arange(len(vol)):
            A = vol[v]
            filename = os.path.join(export_path, str(v) + '.tiff')
            if len(A.shape) == 3:
                A = np.transpose(
                    A, (0, 2,
                        1))  # This keeps the x and the y the same as in FIJI
            elif len(A.shape) == 2:
                A = np.transpose(A, (1, 0))
            tifffile.imsave(filename, A)
Пример #21
0
class VolumeSliderBase(BaseProcess_noPriorWindow):
    """
    Start Volume Slider from differnt sources

        |Select source (current window or saved numpy array)
        
    Returns volumeSlider GUI

    """
    def __init__(self):
        if g.settings['volumeSlider'] is None or 'overlay' not in g.settings[
                'volumeSlider']:
            s = dict()
            s['inputChoice'] = 'Current Window'
            s['keepOriginalWindow'] = False
            s['slicesPerVolume'] = 1
            s['slicesDeletedPerVolume'] = 0
            s['slicesDeletedPerMovie'] = 0
            s['baselineValue'] = 0
            s['f0Start'] = 0
            s['f0End'] = 0
            s['multiplicationFactor'] = 100
            s['currentDataType'] = 0
            s['newDataType'] = 0
            s['theta'] = 45
            s['shiftFactor'] = 1
            s['trimLastFrame'] = False
            s['inputArrayOrder'] = 4
            s['displayArrayOrder'] = 16
            s['f0VolStart'] = 0
            s['f0VolEnd'] = 0
            s['IMS_fname'] = 'IMS_export.ims'
            s['IMS_subsamp'] = '((1, 1, 1), (1, 2, 2))'
            s['IMS_chunks'] = '((16, 128, 128), (64, 64, 64))'
            s['IMS_compression'] = 'gzip'
            s['IMS_thumbsize'] = '256'
            s['IMS_dx'] = 0.1
            s['IMS_dz'] = 0.25
            s['IMS_Unit'] = 'um'
            s['IMS_GammaCorrection'] = 1
            s['IMS_ColorRange'] = '0 255'
            s['IMS_LSMEmissionWavelength'] = 0
            s['IMS_LSMExcitationWavelength'] = 0
            s['preProcess'] = False
            s['overlayStart'] = 1
            s['overlay'] = False

            g.settings['volumeSlider'] = s

        BaseProcess_noPriorWindow.__init__(self)

    def __call__(self,
                 inputChoice,
                 keepOriginalWindow,
                 preProcess,
                 slicesPerVolume,
                 slicesDeletedPerVolume,
                 slicesDeletedPerMovie,
                 overlay,
                 overlayStart,
                 keepSourceWindow=False):
        g.settings['volumeSlider']['inputChoice'] = inputChoice
        g.settings['volumeSlider']['keepOriginalWindow'] = keepOriginalWindow
        g.settings['volumeSlider']['preProcess'] = preProcess
        g.settings['volumeSlider']['slicesPerVolume'] = slicesPerVolume
        g.settings['volumeSlider'][
            'slicesDeletedPerVolume'] = slicesDeletedPerVolume
        g.settings['volumeSlider'][
            'slicesDeletedPerMovie'] = slicesDeletedPerMovie
        g.settings['volumeSlider']['overlay'] = overlay
        g.settings['volumeSlider']['overlayStart'] = overlayStart

        g.m.statusBar().showMessage("Starting Volume Slider...")

        if inputChoice == 'Current Window':
            windowName = g.win.filename
            #Get overlay
            if overlay:
                A = np.array(deepcopy(g.win.image))
                print(A.shape)
                endFrame = g.win.mt - 1
                g.win.close()
                #overlayWin =  Window(A[overlayStart:endFrame,:,:],'Overlay')
                dataWin = Window(A[0:overlayStart, :, :], 'Overlay')

            #Trim movie
            if preProcess and slicesDeletedPerMovie != 0:
                trim(0, slicesDeletedPerMovie, delete=True)

            camVolumeSlider.setFileName(windowName)

            #start volumeSlider
            if overlay:
                camVolumeSlider.startVolumeSlider(
                    keepWindow=keepOriginalWindow,
                    preProcess=preProcess,
                    framesPerVol=slicesPerVolume,
                    framesToDelete=slicesDeletedPerVolume,
                    overlayEmbeded=True,
                    A_overlay=A[overlayStart:endFrame, :, :])

            else:
                camVolumeSlider.startVolumeSlider(
                    keepWindow=keepOriginalWindow,
                    preProcess=preProcess,
                    framesPerVol=slicesPerVolume,
                    framesToDelete=slicesDeletedPerVolume)

            #print('loading:',windowName)

        elif inputChoice == 'Numpy Array':
            A_path = open_file_gui(directory=os.path.expanduser("~/Desktop"),
                                   filetypes='*.npy')
            g.m.statusBar().showMessage("Importing Array: " + A_path)
            A = np.load(str(A_path))
            camVolumeSlider.setFileName(A_path)
            camVolumeSlider.startVolumeSlider(A=A,
                                              keepWindow=keepOriginalWindow)

        elif inputChoice == 'Batch Process':
            g.m.statusBar().showMessage("Starting Batch Processing...")
            camVolumeSlider.startVolumeSlider(batch=True)

        elif inputChoice == 'Load file':
            g.m.statusBar().showMessage("Loading file...")
            #Open file using tiff loader
            load_tiff.gui()

            #Get overlay
            if overlay:
                A = np.array(deepcopy(g.win.image))
                print(A.shape)
                endFrame = g.win.mt - 1
                g.win.close()
                #overlayWin =  Window(A[overlayStart:endFrame,:,:],'Overlay')
                dataWin = Window(A[0:overlayStart, :, :], 'Overlay')

            #Trim movie
            if preProcess and slicesDeletedPerMovie != 0:
                trim(0, slicesDeletedPerMovie, delete=True)

            #start volumeSlider
            camVolumeSlider.setFileName(load_tiff.getFileName())

            if overlay:
                camVolumeSlider.startVolumeSlider(
                    keepWindow=keepOriginalWindow,
                    preProcess=preProcess,
                    framesPerVol=slicesPerVolume,
                    framesToDelete=slicesDeletedPerVolume,
                    overlayEmbeded=True,
                    A_overlay=A[overlayStart:endFrame, :, :])

            else:
                camVolumeSlider.startVolumeSlider(
                    keepWindow=keepOriginalWindow,
                    preProcess=preProcess,
                    framesPerVol=slicesPerVolume,
                    framesToDelete=slicesDeletedPerVolume)

        return

    def closeEvent(self, event):
        BaseProcess_noPriorWindow.closeEvent(self, event)

    def gui(self):
        self.gui_reset()

        #combobox
        inputChoice = ComboBox()
        inputChoice.addItem('Current Window')
        inputChoice.addItem('Load file')
        inputChoice.addItem('Numpy Array')
        inputChoice.addItem('Batch Process')

        #checkbox
        self.keepOriginalWindow = CheckBox()
        self.keepOriginalWindow.setValue(False)

        self.preProcess = CheckBox()
        self.preProcess.setValue(g.settings['volumeSlider']['preProcess'])

        self.framesPerVolume = pg.SpinBox(int=True, step=1)
        self.framesPerVolume.setValue(
            g.settings['volumeSlider']['slicesPerVolume'])

        self.framesRemoved = pg.SpinBox(int=True, step=1)
        self.framesRemoved.setValue(
            g.settings['volumeSlider']['slicesDeletedPerVolume'])

        self.framesRemovedStart = pg.SpinBox(int=True, step=1)
        self.framesRemovedStart.setValue(
            g.settings['volumeSlider']['slicesDeletedPerMovie'])

        self.overlay = CheckBox()
        self.overlay.setValue(g.settings['volumeSlider']['overlay'])

        self.overlayStart = pg.SpinBox(int=True, step=1)
        self.overlayStart.setValue(g.settings['volumeSlider']['overlayStart'])

        #populate GUI
        self.items.append({
            'name': 'inputChoice',
            'string': 'Choose Input Data:',
            'object': inputChoice
        })
        self.items.append({
            'name': 'keepOriginalWindow',
            'string': 'Keep Original Window',
            'object': self.keepOriginalWindow
        })

        self.items.append({
            'name': 'spacer',
            'string': '------------ Preprocessing Options --------------',
            'object': None
        })
        self.items.append({
            'name': 'preProcess',
            'string': 'Preprocess Image Stack',
            'object': self.preProcess
        })
        self.items.append({
            'name': 'slicesPerVolume',
            'string': 'Slices per Volume',
            'object': self.framesPerVolume
        })
        self.items.append({
            'name': 'slicesDeletedPerVolume',
            'string': 'Frames to Remove per Volume',
            'object': self.framesRemoved
        })
        self.items.append({
            'name': 'slicesDeletedPerMovie',
            'string': 'Frames to Remove From Start of Stack',
            'object': self.framesRemovedStart
        })

        self.items.append({
            'name': 'spacer',
            'string': '------------    Overlay Options    --------------',
            'object': None
        })
        self.items.append({
            'name': 'overlay',
            'string': 'Overlay Image in Stack',
            'object': self.overlay
        })
        self.items.append({
            'name': 'overlayStart',
            'string': '1st Frame of Overlay',
            'object': self.overlayStart
        })

        super().gui()
Пример #22
0
class Synapse3D_batch(QtWidgets.QDialog):
    def __init__(self, parent = None):
        super(Synapse3D_batch, self).__init__(parent)
        #add window title
        self.setWindowTitle("Volume Slider GUI")
        
        self.pathName = ''

        self.eps  = clusterAnalysis.eps
        self.min_samples = clusterAnalysis.min_samples
        self.maxDistance = clusterAnalysis.maxDistance
        self.unitPerPixel = clusterAnalysis.unitPerPixel
        #self.multiThreadingFlag = clusterAnalysis.multiThreadingFlag
        self.displayFlag = clusterAnalysis.displayFlag
        
        self.clusterType = '3D'
        
        #window geometry
        self.left = 300
        self.top = 300
        self.width = 300
        self.height = 200

        #labels
        self.clusterTitle = QtWidgets.QLabel("----- Cluster Parameters -----") 
        self.label_eps = QtWidgets.QLabel("max distance between points:") 
        self.label_minSamples = QtWidgets.QLabel("minimum number of points:") 
        self.label_maxDistance = QtWidgets.QLabel("max distance between clusters:") 
        self.label_clustertype = QtWidgets.QLabel("clustering type:")        
        self.displayTitle = QtWidgets.QLabel("----- Display Parameters -----") 
        self.label_unitPerPixel = QtWidgets.QLabel("nanometers/pixel:") 
        #self.label_centroidSymbolSize = QtWidgets.QLabel("centroid symbol size:")  
        
        self.analysisTitle = QtWidgets.QLabel("----- Cluster Analysis -----") 
        self.label_analysis = QtWidgets.QLabel("Clusters to analyse: ")

        self.displayTitle = QtWidgets.QLabel("----- Display -----") 
        self.label_display = QtWidgets.QLabel("Plot results: ")         
        
        #self.multiThreadTitle = QtWidgets.QLabel("----- Multi-Threading -----") 
        #self.label_multiThread = QtWidgets.QLabel("Multi-Threading On: ")        
        
        #self.label_displayPlot = QtWidgets.QLabel("show plot")         

        #spinboxes
        self.epsBox = QtWidgets.QSpinBox()
        self.epsBox.setRange(0,10000)
        self.epsBox.setValue(self.eps)
        self.minSampleBox = QtWidgets.QSpinBox()    
        self.minSampleBox.setRange(0,10000)
        self.minSampleBox.setValue(self.min_samples)
        self.maxDistanceBox = QtWidgets.QSpinBox()    
        self.maxDistanceBox.setRange(0,10000)
        self.maxDistanceBox.setValue(self.maxDistance)    
        self.unitPerPixelBox = QtWidgets.QSpinBox()    
        self.unitPerPixelBox.setRange(0,1000)
        self.unitPerPixelBox.setValue(self.unitPerPixel)  
        #self.centroidSymbolSizeBox = QtWidgets.QSpinBox()    
        #self.centroidSymbolSizeBox.setRange(0,1000)
        #self.centroidSymbolSizeBox.setValue(self.centroidSymbolSize)          

        #combobox
        #self.analysis_Box = QtWidgets.QComboBox()
        #self.analysis_Box.addItems(["All Clusters", "Paired Clusters"])
        self.clustertype_Box = QtWidgets.QComboBox()
        self.clustertype_Box.addItems(["2D", "3D"])
        self.clustertype_Box.setCurrentText(self.clusterType)
        self.clustertype_Box.currentIndexChanged.connect(self.clusterTypeChange)
        
        #tickbox
        self.display_checkbox = CheckBox()
        self.display_checkbox.setChecked(self.displayFlag)
        self.display_checkbox.stateChanged.connect(self.displayClicked)
        #self.multiThread_checkbox = CheckBox()
        #self.multiThread_checkbox.setChecked(self.multiThreadingFlag)
        #self.multiThread_checkbox.stateChanged.connect(self.multiThreadClicked)

        #buttons
        self.button_getFolder = QtWidgets.QPushButton("Set Folder")
        self.button_start = QtWidgets.QPushButton("Start Batch Analysis")
        
        #grid layout
        layout = QtWidgets.QGridLayout()
        layout.setSpacing(5)
        layout.addWidget(self.clusterTitle, 0, 0, 1, 2)        
        layout.addWidget(self.label_eps, 1, 0)
        layout.addWidget(self.epsBox, 1, 1)       
        layout.addWidget(self.label_minSamples, 2, 0)        
        layout.addWidget(self.minSampleBox, 2, 1)     
        layout.addWidget(self.label_maxDistance, 3, 0)        
        layout.addWidget(self.maxDistanceBox, 3, 1)
        layout.addWidget(self.displayTitle, 4, 0, 1, 2)          
        layout.addWidget(self.label_unitPerPixel, 5, 0)  
        layout.addWidget(self.unitPerPixelBox, 5, 1)         
        layout.addWidget(self.label_clustertype, 6, 0) 
        layout.addWidget(self.clustertype_Box, 6, 1)
        layout.addWidget(self.displayTitle, 7, 0, 1, 2) 
        layout.addWidget(self.label_display, 8, 0)        
        layout.addWidget(self.display_checkbox, 8, 1)         
        layout.addWidget(self.button_getFolder, 9, 0)          
        layout.addWidget(self.button_start, 10, 0)         
        
        #layout.addWidget(self.label_centroidSymbolSize, 6, 0)  
        #layout.addWidget(self.centroidSymbolSizeBox, 6, 1) 
        
        #layout.addWidget(self.analysisTitle, 8, 0, 1, 2)  
        #layout.addWidget(self.label_analysis, 9, 0)  
        #layout.addWidget(self.analysis_Box, 9, 1)     
        
        #layout.addWidget(self.multiThreadTitle, 10, 0, 1, 2)  
        #layout.addWidget(self.label_multiThread, 11, 0)  
        #layout.addWidget(self.multiThread_checkbox, 11, 1)  
        

        
        self.setLayout(layout)
        self.setGeometry(self.left, self.top, self.width, self.height)

        #add window title
        self.setWindowTitle("Clustering Options")

        #connect spinboxes
        self.epsBox.valueChanged.connect(self.epsValueChange)
        self.minSampleBox.valueChanged.connect(self.minSampleChange) 
        self.maxDistanceBox.valueChanged.connect(self.maxDistanceChange)    
        self.unitPerPixelBox.valueChanged.connect(self.unitPerPixelChange) 
        #self.centroidSymbolSizeBox.valueChanged.connect(self.centroidSymbolSizeChange)  
        #connect combobox
        #self.analysis_Box.setCurrentIndex(0)
        #self.analysis_Box.currentIndexChanged.connect(self.analysisChange)         

        #connect buttons
        self.button_getFolder.clicked.connect(self.getSavePath)
        self.button_start.clicked.connect(self.run)

        
    def epsValueChange(self,value):
        self.epsBox = value
        clusterAnalysis.eps = self.epsBox
        return
    
    def minSampleChange(self,value):
        self.min_samples = value
        clusterAnalysis.min_samples = self.min_samples 
        return
        
    def maxDistanceChange(self,value):
        self.maxDistance = value
        clusterAnalysis.maxDistance = self.maxDistance
        return

    def unitPerPixelChange(self,value):
        self.unitPerPixel = value
        clusterAnalysis.unitPerPixel = self.unitPerPixel
        return
 
    def clusterTypeChange(self):
        self.clusterType = self.clustertype_Box.currentText
        clusterAnalysis.clusterType = self.clusterType
    
#    def centroidSymbolSizeChange(self,value):
#        self.centroidSymbolSize = value
#        self.viewer.centroidSymbolSize = self.centroidSymbolSize
#        return   
    
#    def analysisChange(self):
#        self.viewer.clusterAnaysisSelection = self.analysis_Box.currentText()
#        return
    
#    def multiThreadClicked(self):
#        self.viewer.multiThreadingFlag = self.multiThread_checkbox.isChecked()
#        return

    def getSavePath(self): 
        folder = QtWidgets.QFileDialog.getExistingDirectory(g.m, "Select batch folder.", os.path.expanduser("~"), QtWidgets.QFileDialog.ShowDirsOnly)
        self.pathName = folder
        return

    def run(self):
        if not os.path.exists(os.path.join(self.pathName,'results')):
            os.makedirs(os.path.join(self.pathName,'results'))
        clusterAnalysis.runBatch(self.pathName)
        return

    def displayClicked(self):
        clusterAnalysis.displayFlag = self.display_checkbox.isChecked()
        self.displayFlag = clusterAnalysis.displayFlag
        return

    def start(self):
        self.show()
        return
Пример #23
0
    def gui(self):      
        self.filename = ''          
        self.gui_reset()        
        s=g.settings['puffMapper']  
        
        #buttons      
        self.plotChart_button = QPushButton('Create Line plot')
        self.plotChart_button.pressed.connect(self.plotData)  
                
        self.generateHeatmap_button = QPushButton('Create Heatmap')        
        self.generateHeatmap_button.pressed.connect(self.createHeatmap)  

                         
        #checkbox
        self.sorted_checkbox = CheckBox()
        self.sorted_checkbox.setChecked(s['sortedByMax'])

        #comboboxes
        self.xFunc_Box = pg.ComboBox()
        xFuncs = {'mean':np.mean, 'max':np.max, 'median':np.median}
        self.xFunc_Box.setItems(xFuncs)

        
        #spinboxes
        #Frames
        self.startFrame_Box = pg.SpinBox(int=True, step=1)
        self.startFrame_Box.setMinimum(0)
        self.startFrame_Box.setMaximum(1000000)  
        self.startFrame_Box.setValue(s['startFrame'])            
                
        self.nFrames_Box = pg.SpinBox(int=True, step=1)
        self.nFrames_Box.setMinimum(0)
        self.nFrames_Box.setMaximum(1000000)  
        self.nFrames_Box.setValue(s['nFrames'])          

        self.xBin_Box = pg.SpinBox(int=True, step=2)
        self.xBin_Box.setMinimum(1)
        self.xBin_Box.setMaximum(10000)  
        self.xBin_Box.setValue(s['xBin'])   

        self.yExpand_Box = pg.SpinBox(int=True, step=1)
        self.yExpand_Box.setMinimum(1)
        self.yExpand_Box.setMaximum(1000)  
        self.yExpand_Box.setValue(s['yExpand'])   


        #export file selector
        self.getFile = FileSelector()
        
        #connections
        self.getFile.valueChanged.connect(self.loadData)
           
        #################################################################
        #self.exportFolder = FolderSelector('*.txt')
        #MEPPS
        self.items.append({'name': 'blank1 ', 'string': '-------------   Parameters    ---------------', 'object': None}) 
        self.items.append({'name': 'startFrame', 'string': 'Set start frame ', 'object': self.startFrame_Box})          
        self.items.append({'name': 'nFrames', 'string': 'Set number of frames ', 'object': self.nFrames_Box}) 
        self.items.append({'name': 'xBin', 'string': 'Set x-axis binning number ', 'object': self.xBin_Box})  
        self.items.append({'name': 'xBinType', 'string': 'Set x-axis bin function ', 'object': self.xFunc_Box})  
        self.items.append({'name': 'yExpand', 'string': 'Set y-axis expansion value ', 'object': self.yExpand_Box})          
        self.items.append({'name': 'sortedByMax', 'string': 'Sorted by maximum', 'object': self.sorted_checkbox})         
        self.items.append({'name': 'blank ', 'string': '-------------------------------------------', 'object': None})           
        
        self.items.append({'name': 'filepath ', 'string': '', 'object': self.getFile})              

        self.items.append({'name': 'heatmap', 'string': '', 'object': self.generateHeatmap_button })            
        self.items.append({'name': 'lineplot', 'string': '', 'object': self.plotChart_button }) 

        
        super().gui()
        ######################################################################
        return
Пример #24
0
class PuffMapper(BaseProcess_noPriorWindow):
    """
    puff heat map generator
    ------------------
    
    input:      csv file with one or more time traces (columns) 
    
    variables:  
    
    analysis:   
    
    output:     
    """
    def __init__(self):
        if g.settings['puffMapper'] is None or 'yExpand' not in g.settings['puffMapper']:
            s = dict()            
            s['nFrames'] = 1000           
            s['startFrame'] = 0 
            s['sortedByMax'] = False             
            s['xBin'] = 0 
            s['yExpand'] = 0                  
            
            g.settings['puffMapper'] = s
                   
        BaseProcess_noPriorWindow.__init__(self)
            
        

    def __call__(self, nFrames, startFrame, sortedByMax, xBin, yExpand, keepSourceWindow=False):
        '''
        '''

        #currently not saving parameter changes on call
        g.settings['puffMapper']['nFrames'] = nFrames         
        g.settings['puffMapper']['startFrame'] = startFrame   
        g.settings['puffMapper']['sortedByMax'] = sortedByMax  
        g.settings['puffMapper']['xBin'] = xBin  
        g.settings['puffMapper']['yExpand'] = yExpand         
        
        g.m.statusBar().showMessage("Starting puff mapper...")
        return



    def closeEvent(self, event):
        self.clearPlots()
        BaseProcess_noPriorWindow.closeEvent(self, event)
        return

    def gui(self):      
        self.filename = ''          
        self.gui_reset()        
        s=g.settings['puffMapper']  
        
        #buttons      
        self.plotChart_button = QPushButton('Create Line plot')
        self.plotChart_button.pressed.connect(self.plotData)  
                
        self.generateHeatmap_button = QPushButton('Create Heatmap')        
        self.generateHeatmap_button.pressed.connect(self.createHeatmap)  

                         
        #checkbox
        self.sorted_checkbox = CheckBox()
        self.sorted_checkbox.setChecked(s['sortedByMax'])

        #comboboxes
        self.xFunc_Box = pg.ComboBox()
        xFuncs = {'mean':np.mean, 'max':np.max, 'median':np.median}
        self.xFunc_Box.setItems(xFuncs)

        
        #spinboxes
        #Frames
        self.startFrame_Box = pg.SpinBox(int=True, step=1)
        self.startFrame_Box.setMinimum(0)
        self.startFrame_Box.setMaximum(1000000)  
        self.startFrame_Box.setValue(s['startFrame'])            
                
        self.nFrames_Box = pg.SpinBox(int=True, step=1)
        self.nFrames_Box.setMinimum(0)
        self.nFrames_Box.setMaximum(1000000)  
        self.nFrames_Box.setValue(s['nFrames'])          

        self.xBin_Box = pg.SpinBox(int=True, step=2)
        self.xBin_Box.setMinimum(1)
        self.xBin_Box.setMaximum(10000)  
        self.xBin_Box.setValue(s['xBin'])   

        self.yExpand_Box = pg.SpinBox(int=True, step=1)
        self.yExpand_Box.setMinimum(1)
        self.yExpand_Box.setMaximum(1000)  
        self.yExpand_Box.setValue(s['yExpand'])   


        #export file selector
        self.getFile = FileSelector()
        
        #connections
        self.getFile.valueChanged.connect(self.loadData)
           
        #################################################################
        #self.exportFolder = FolderSelector('*.txt')
        #MEPPS
        self.items.append({'name': 'blank1 ', 'string': '-------------   Parameters    ---------------', 'object': None}) 
        self.items.append({'name': 'startFrame', 'string': 'Set start frame ', 'object': self.startFrame_Box})          
        self.items.append({'name': 'nFrames', 'string': 'Set number of frames ', 'object': self.nFrames_Box}) 
        self.items.append({'name': 'xBin', 'string': 'Set x-axis binning number ', 'object': self.xBin_Box})  
        self.items.append({'name': 'xBinType', 'string': 'Set x-axis bin function ', 'object': self.xFunc_Box})  
        self.items.append({'name': 'yExpand', 'string': 'Set y-axis expansion value ', 'object': self.yExpand_Box})          
        self.items.append({'name': 'sortedByMax', 'string': 'Sorted by maximum', 'object': self.sorted_checkbox})         
        self.items.append({'name': 'blank ', 'string': '-------------------------------------------', 'object': None})           
        
        self.items.append({'name': 'filepath ', 'string': '', 'object': self.getFile})              

        self.items.append({'name': 'heatmap', 'string': '', 'object': self.generateHeatmap_button })            
        self.items.append({'name': 'lineplot', 'string': '', 'object': self.plotChart_button }) 

        
        super().gui()
        ######################################################################
        return



    def loadData(self):
        self.filename = self.getFile.value()
        self.data = pd.read_csv(self.filename, header=None, skiprows=1, index_col = 0)
        
        #drop extra x columns
        self.data = self.data[self.data.columns[::2]] 
        #drop columns with na values
        self.data = self.data.dropna(axis=1, how='all')        
        #set column names by number
        nCols = len(self.data.columns)
        colNames = list(range(0,nCols))
        self.data.columns = colNames
        #copy df and make one sorted by intensity
        self.dataSorted = self.data.copy()
        self.dataSorted = self.dataSorted.iloc[:, self.dataSorted.max().sort_values(ascending=False).index]

        #set nFrames max
        nRows = len(self.data)
        self.nFrames_Box.setMaximum(nRows)  
        self.nFrames_Box.setValue(nRows)  

        print('-------------------------------------')
        print('Data loaded (first 5 rows displayed):')
        print(self.data.head())
        print('-------------------------------------')



    def plotData(self):
        ### plot test result
        self.data.plot()
        plt.show()
        g.m.statusBar().showMessage('scatter plot created') 
        print('scatter plot created')    
        return

    def createHeatmap(self):
        ### create heatmap image
        if self.sorted_checkbox.isChecked():
            try:
                mapData = self.dataSorted.to_numpy()
            except:
                mapData = self.dataSorted.values
        else:
            try:
                mapData = self.data.to_numpy()
            except:
                mapData = self.data.values              
            

        nRows,nCols = mapData.shape
        print('original data has: {} columns, {} rows'.format(nRows, nCols))
        start = self.startFrame_Box.value()
        end = self.startFrame_Box.value() + self.nFrames_Box.value()
        
        if end > nRows:
            end = nRows

        #crop data
        img = mapData[start:end]
        
        #x binning
        img = groupedAvg(img,block_size=(self.xBin_Box.value(),1),func=self.xFunc_Box.value())

        #y expansion
        img = np.repeat(img,self.yExpand_Box.value(),axis=1)
        print('y-axis expanded by {}'.format(self.yExpand_Box.value()))
        
        #get new img shape
        nRows_img,nCols_img = img.shape
        print('displayed image has: {} columns, {} rows'.format(nRows_img, nCols_img))
      
        self.heatmapImg = Window(img,name='puff map')
        print('puff map created')
        return

    
    def clearPlots(self):
        try:
            plt.close('all')  
        except:
            pass
        return
Пример #25
0
    def gui(self):
        s = g.settings['mepp_simulator']
        self.gui_reset()
        self.meppWindow = PlotWindow('Single MEPP (No noise)')
        self.traceWindow = PlotWindow('Time Trace')
        self.meppWindow.hide()
        self.traceWindow.hide()

        self.traceLength = SliderLabel(0)
        self.traceLength.setRange(0, 1000000)
        self.traceLength.setValue(s['traceLength'])

        self.startTime = SliderLabel(0)
        self.startTime.setRange(0, s['traceLength'])
        self.startTime.setValue(s['startTime'])

        self.meppDuration_slider = pg.SpinBox(int=True, step=1)
        self.meppDuration_slider.setValue(s['meppDuration'])

        self.meppDuration_sigma_slider = pg.SpinBox(int=True, step=1)
        self.meppDuration_sigma_slider.setValue(1)

        self.baseline_slider = pg.SpinBox(int=False, step=.01)
        self.baseline_slider.setValue(s['baseline'])

        self.noiseSigma_slider = pg.SpinBox(int=False, step=.01)
        self.noiseSigma_slider.setValue(s['noiseSigma'])

        self.meppAmplitude_slider = pg.SpinBox(int=False, step=.01)
        self.meppAmplitude_slider.setValue(s['meppAmplitude'])

        self.meppAmplitude_sigma_slider = pg.SpinBox(int=False, step=.01)
        self.meppAmplitude_sigma_slider.setValue(1.0)

        self.meppRiseTime_slider = pg.SpinBox(int=False, step=.01)
        self.meppRiseTime_slider.setValue(s['riseTime'])

        #self.meppRiseTime_sigma_slider = pg.SpinBox(int=False, step=.01)
        #self.meppRiseTime_sigma_slider.setValue(0.01)

        self.meppDecayTime_slider = pg.SpinBox(int=False, step=.01)
        self.meppDecayTime_slider.setValue(s['decayTime'])

        #self.meppDecayTime_sigma_slider = pg.SpinBox(int=False, step=.01)
        #self.meppDecayTime_sigma_slider.setValue(0.1)

        self.randommeppsAdded = False

        self.meanExp_slider = pg.SpinBox(int=False, step=.01)
        self.meanExp_slider.setValue(1000.0)

        self.plotHistoTimes = CheckBox()
        self.plotHistoTimes.setValue(False)

        self.exportTimes_button = QPushButton('Export times')
        self.exportTimes_button.pressed.connect(self.exportTimes)

        self.randommeppButton = QPushButton('Generate Trace')
        self.randommeppButton.pressed.connect(self.addRandommepps)

        self.plotmeppButton = QPushButton('Plot single MEPP')
        self.plotmeppButton.pressed.connect(self.plotSingleMEPP)

        self.items.append({
            'name': 'traceLength',
            'string': 'Recording length',
            'object': self.traceLength
        })
        self.items.append({
            'name': 'startTime',
            'string': 'Start time',
            'object': self.startTime
        })
        self.items.append({
            'name': 'meppDuration',
            'string': 'MEPP duration (mean)',
            'object': self.meppDuration_slider
        })
        self.items.append({
            'name': 'meppDuration_sigma',
            'string': 'MEPP duration (standard deviation)',
            'object': self.meppDuration_sigma_slider
        })

        self.items.append({
            'name': 'riseTime',
            'string': 'MEPP rise time constant',
            'object': self.meppRiseTime_slider
        })
        #self.items.append({'name': 'riseTime_sigma','string':'MEPP rise time constant (standard deviation)','object':self.meppRiseTime_sigma_slider})

        self.items.append({
            'name': 'decayTime',
            'string': 'MEPP decay time constant',
            'object': self.meppDecayTime_slider
        })
        #self.items.append({'name': 'decayTime_sigma','string':'MEPP decay time constant (standard deviation)','object':self.meppDecayTime_sigma_slider})

        self.items.append({
            'name': 'meppAmplitude',
            'string': 'MEPP Amplitude (mean)',
            'object': self.meppAmplitude_slider
        })
        self.items.append({
            'name': 'meppAmplitude_sigma',
            'string': 'MEPP Amplitude (standard deviation)',
            'object': self.meppAmplitude_sigma_slider
        })
        self.items.append({
            'name': 'meanExp',
            'string': 'Mean of exponential distibution',
            'object': self.meanExp_slider
        })

        self.items.append({
            'name': 'baseline',
            'string': 'Baseline',
            'object': self.baseline_slider
        })
        self.items.append({
            'name': 'noiseSigma',
            'string': 'Noise Sigma',
            'object': self.noiseSigma_slider
        })

        self.items.append({
            'name': 'histoTimes',
            'string': 'Plot histogram of mepp start times:',
            'object': self.plotHistoTimes
        })
        self.items.append({
            'name': 'random_mepp_Button',
            'string': 'Click to add randomly distibuted mepps',
            'object': self.randommeppButton
        })
        self.items.append({
            'name': 'listTimes',
            'string': 'Export list of mepp start times',
            'object': self.exportTimes_button
        })
        self.items.append({
            'name': 'plotMEPP',
            'string': 'Plot single MEPP (without noise)',
            'object': self.plotmeppButton
        })
        super().gui()
Пример #26
0
class Simulate_Puff(BaseProcess_noPriorWindow):
    """
    Add a simulated puff to an image stack
    
    """
    def __init__(self):
        super().__init__()
        self.currentWin = None
        self.currentROI = None
        self.data = None

    def get_init_settings_dict(self):
        s = dict()
        s['nFrames'] = 100
        s['puffAmplitude'] = 5
        s['x'] = 128
        s['y'] = 128
        s['startFrame'] = 100
        s['sigma'] = 20
        s['useROI'] = False
        s['meanExp'] = 5.0
        s['nPuffs'] = 0
        s['nSites'] = 10
        s['meanDuration'] = 10

        return s

    def gui(self):
        self.gui_reset()
        self.nFrames = pg.SpinBox(int=False, step=.01)
        #self.nFrames.setRange(0,10000)
        self.startFrame = SliderLabel(0)
        self.startFrame.setRange(0, 10000)

        self.puffAmplitude = pg.SpinBox(int=False, step=.01)
        self.puffAmplitude.setValue(1.0)
        self.sigma = SliderLabel(0)
        self.sigma.setRange(1, 1000)
        self.x = SliderLabel(0)
        self.x.setRange(1, 10000)
        self.y = SliderLabel(0)
        self.y.setRange(1, 10000)
        self.useROI = CheckBox()
        self.useFrame = CheckBox()
        self.active_window = WindowSelector()
        self.previewButton = QPushButton('Preview Puff')
        self.previewButton.pressed.connect(self.previewPuff)
        self.puffButton = QPushButton('Add Puff')
        self.puffButton.pressed.connect(self.addPuff)

        self.randomPuffsAdded = False

        self.nSites = 10
        columnNames = ['time of puff', 'duration', 'site']
        self.timesAdded = pd.DataFrame(columns=columnNames)
        self.siteNumber = int(0)

        self.nPuffs_slider = SliderLabel(0)
        self.nPuffs_slider.setRange(1, 1000)

        self.meanExp_slider = pg.SpinBox(int=False, step=.01)
        self.meanExp_slider.setValue(5.0)

        self.randomDuration = CheckBox()
        self.randomDuration.setValue(False)

        self.durationMean = 10.0
        self.durationMean_box = pg.SpinBox(int=False, step=.01)
        self.durationMean_box.setRange(0, 10000)
        self.durationMean_box.setValue(self.durationMean)

        self.plotHistoTimes = CheckBox()
        self.plotHistoTimes.setValue(False)

        self.addPuffsSequentially = CheckBox()
        self.addPuffsSequentially.setValue(False)

        self.exportTimes_button = QPushButton('Export times')
        self.exportTimes_button.pressed.connect(self.exportTimes)

        self.randomPuffButton = QPushButton('Add Puffs to site')
        self.randomPuffButton.pressed.connect(self.addRandomPuffs)

        self.multipleRandomPuffButton = QPushButton('Add Puffs inside ROI')
        self.multipleRandomPuffButton.pressed.connect(
            self.addMultipleRandomPuffs)

        self.nSites_box = QSpinBox()
        self.nSites_box.setRange(0, 10000)
        self.nSites_box.setValue(self.nSites)

        self.items.append({
            'name': 'active_window',
            'string': 'Select Window',
            'object': self.active_window
        })
        self.items.append({
            'name': 'nFrames',
            'string': 'Duration (frames)',
            'object': self.nFrames
        })
        self.items.append({
            'name': 'randomDuration',
            'string': 'Use exponentially distributed random duration',
            'object': self.randomDuration
        })
        self.items.append({
            'name': 'meanDuration',
            'string': 'Mean duration',
            'object': self.durationMean_box
        })
        self.items.append({
            'name': 'startFrame',
            'string': 'Start Frame',
            'object': self.startFrame
        })
        #self.items.append({'name': 'useCurrentFrame', 'string': 'Use Current Frame For Start', 'object': self.useFrame})
        self.items.append({
            'name': 'puffAmplitude',
            'string': 'Amplitude',
            'object': self.puffAmplitude
        })
        self.items.append({'name': 'x', 'string': 'x', 'object': self.x})
        self.items.append({'name': 'y', 'string': 'y', 'object': self.y})
        #self.items.append({'name': 'useROI', 'string': 'Use ROI for position', 'object': self.useROI})
        self.items.append({
            'name': 'sigma',
            'string': 'sigma',
            'object': self.sigma
        })
        self.items.append({
            'name': 'preview_Button',
            'string': 'Click to preview Puff',
            'object': self.previewButton
        })
        self.items.append({
            'name': 'puff_Button',
            'string': 'Click to add Puff',
            'object': self.puffButton
        })
        self.items.append({
            'name': 'blank',
            'string': '---------- RANDOM PUFFS ---------------------------',
            'object': None
        })
        #self.items.append({'name': 'nPuffs', 'string': 'Number of puffs to add', 'object': self.nPuffs_slider})
        self.items.append({
            'name': 'meanExp',
            'string': 'Mean of exponential distibution of puff start times',
            'object': self.meanExp_slider
        })
        self.items.append({
            'name': 'puffsSequential',
            'string': 'Wait until puff ends before adding next puff:',
            'object': self.addPuffsSequentially
        })
        self.items.append({
            'name': 'histoTimes',
            'string': 'Plot histogram of puff start times:',
            'object': self.plotHistoTimes
        })
        self.items.append({
            'name': 'random_puff_Button',
            'string': 'Click to add randomly distibuted puffs at one site',
            'object': self.randomPuffButton
        })
        self.items.append({
            'name': 'multipleRandom_puff_Button',
            'string':
            'Click to add randomly distibuted puffs at multiple sites',
            'object': self.multipleRandomPuffButton
        })
        self.items.append({
            'name': 'nSites',
            'string': 'Number of Sites to add',
            'object': self.nSites_box
        })
        self.items.append({
            'name': 'blank',
            'string': '---------- Export Puffs ---------------------------',
            'object': None
        })
        self.items.append({
            'name': 'listTimes',
            'string': 'Export list of puff start times',
            'object': self.exportTimes_button
        })

        super().gui()

    def __call__(self):
        pass
        return

    def update(self):
        self.currentWin = self.getValue('active_window')
        #get image data
        self.data = np.array(deepcopy(self.currentWin.image))
        self.dt, self.dy, self.dx = self.data.shape
        self.x.setRange(1, self.dx - 1)
        self.y.setRange(1, self.dy - 1)

        self.x.setValue(int((self.dx - 1) / 2))
        self.y.setValue(int((self.dy - 1) / 2))

        self.nFrames.setRange(0, self.dt)
        self.startFrame.setRange(0, self.dt - 1)

        self.sigma.setRange(1, int(self.dx / 7))

    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

    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

    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

    def getRandomSites(self, xStart, xEnd, yStart, yEnd, qty, radius=0):
        import random

        rangeX = (xStart, xEnd)
        rangeY = (yStart, yEnd)

        deltas = set()
        for x in range(-radius, radius + 1):
            for y in range(-radius, radius + 1):
                if x * x + y * y <= radius * radius:
                    deltas.add((x, y))

        randPoints = []
        excluded = set()
        i = 0

        while i < qty:
            x = random.randrange(*rangeX)
            y = random.randrange(*rangeY)
            if (x, y) in excluded: continue
            randPoints.append((x, y))
            i += 1
            excluded.update((x + dx, y + dy) for (dx, dy) in deltas)

        return randPoints

    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))

        # #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)

    def previewPuff(self):
        '''preview blip to be added'''
        sigma = self.getValue('sigma')
        amp = self.getValue('puffAmplitude')

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

            #scale puff amplitude to account for durations <1 frame or spread across 2 frames
            spread = ceil(duration)
            if spread < 2:
                amp = amp * (duration / spread)

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

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

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

        Window(blip)

        return

    def generateBlip(sigma=1, amplitude=1, duration=1):
        sigma = int(sigma)
        width = sigma * 8 + 1
        xorigin = sigma * 4
        yorigin = sigma * 4
        x = np.arange(width)
        y = np.arange(width)
        x = x[:, None]
        y = y[None, :]
        gaussian = amplitude * (np.exp(-(x - xorigin)**2 / (2. * sigma**2)) *
                                np.exp(-(y - yorigin)**2 / (2. * sigma**2)))
        blip = np.repeat(gaussian[None, :, :], repeats=duration, axis=0)
        return blip
Пример #27
0
class Simulate_mepp(BaseProcess_noPriorWindow):
    """
    Simulate MEPP events in a noisy time trace
    
    Trace generated by linear summation of randomly occuring unitary events hF(t) (MEPPs)
    see Segal et al. Biophys J, 1985
    
    h = time independent amplitude factor
    F(t) = nondimensional function of time
    hF(t) = h(exp(-t/dT) - exp(-t/dR))

    dT = decay time constant
    rT = rise time constant

    time of MEPP addition drawn from exponential distribution (np.random.exponential())
    amplitude of MEPP drawn from normal distribution (np.random.normal())
    duration of MEPP drawn from normal distribution (np.random.normal()) 
        
    """
    def __init__(self):

        if g.settings[
                'mepp_simulator'] is None or 'decayTime' not in g.settings[
                    'mepp_simulator']:
            s = dict()
            s['traceLength'] = 10000
            s['meppAmplitude'] = 5
            s['meppDuration'] = 1
            s['startTime'] = 0
            s['meanExp'] = 1000.0
            s['baseline'] = 0.0
            s['noiseSigma'] = 0.1
            s['riseTime'] = 1.0
            #s['riseTime_sigma'] = 0.01
            s['decayTime'] = 10.0
            #s['decayTime_sigma'] = 0.1
            g.settings['mepp_simulator'] = s
        super().__init__()

        self.data = np.array([])

    def gui(self):
        s = g.settings['mepp_simulator']
        self.gui_reset()
        self.meppWindow = PlotWindow('Single MEPP (No noise)')
        self.traceWindow = PlotWindow('Time Trace')
        self.meppWindow.hide()
        self.traceWindow.hide()

        self.traceLength = SliderLabel(0)
        self.traceLength.setRange(0, 1000000)
        self.traceLength.setValue(s['traceLength'])

        self.startTime = SliderLabel(0)
        self.startTime.setRange(0, s['traceLength'])
        self.startTime.setValue(s['startTime'])

        self.meppDuration_slider = pg.SpinBox(int=True, step=1)
        self.meppDuration_slider.setValue(s['meppDuration'])

        self.meppDuration_sigma_slider = pg.SpinBox(int=True, step=1)
        self.meppDuration_sigma_slider.setValue(1)

        self.baseline_slider = pg.SpinBox(int=False, step=.01)
        self.baseline_slider.setValue(s['baseline'])

        self.noiseSigma_slider = pg.SpinBox(int=False, step=.01)
        self.noiseSigma_slider.setValue(s['noiseSigma'])

        self.meppAmplitude_slider = pg.SpinBox(int=False, step=.01)
        self.meppAmplitude_slider.setValue(s['meppAmplitude'])

        self.meppAmplitude_sigma_slider = pg.SpinBox(int=False, step=.01)
        self.meppAmplitude_sigma_slider.setValue(1.0)

        self.meppRiseTime_slider = pg.SpinBox(int=False, step=.01)
        self.meppRiseTime_slider.setValue(s['riseTime'])

        #self.meppRiseTime_sigma_slider = pg.SpinBox(int=False, step=.01)
        #self.meppRiseTime_sigma_slider.setValue(0.01)

        self.meppDecayTime_slider = pg.SpinBox(int=False, step=.01)
        self.meppDecayTime_slider.setValue(s['decayTime'])

        #self.meppDecayTime_sigma_slider = pg.SpinBox(int=False, step=.01)
        #self.meppDecayTime_sigma_slider.setValue(0.1)

        self.randommeppsAdded = False

        self.meanExp_slider = pg.SpinBox(int=False, step=.01)
        self.meanExp_slider.setValue(1000.0)

        self.plotHistoTimes = CheckBox()
        self.plotHistoTimes.setValue(False)

        self.exportTimes_button = QPushButton('Export times')
        self.exportTimes_button.pressed.connect(self.exportTimes)

        self.randommeppButton = QPushButton('Generate Trace')
        self.randommeppButton.pressed.connect(self.addRandommepps)

        self.plotmeppButton = QPushButton('Plot single MEPP')
        self.plotmeppButton.pressed.connect(self.plotSingleMEPP)

        self.items.append({
            'name': 'traceLength',
            'string': 'Recording length',
            'object': self.traceLength
        })
        self.items.append({
            'name': 'startTime',
            'string': 'Start time',
            'object': self.startTime
        })
        self.items.append({
            'name': 'meppDuration',
            'string': 'MEPP duration (mean)',
            'object': self.meppDuration_slider
        })
        self.items.append({
            'name': 'meppDuration_sigma',
            'string': 'MEPP duration (standard deviation)',
            'object': self.meppDuration_sigma_slider
        })

        self.items.append({
            'name': 'riseTime',
            'string': 'MEPP rise time constant',
            'object': self.meppRiseTime_slider
        })
        #self.items.append({'name': 'riseTime_sigma','string':'MEPP rise time constant (standard deviation)','object':self.meppRiseTime_sigma_slider})

        self.items.append({
            'name': 'decayTime',
            'string': 'MEPP decay time constant',
            'object': self.meppDecayTime_slider
        })
        #self.items.append({'name': 'decayTime_sigma','string':'MEPP decay time constant (standard deviation)','object':self.meppDecayTime_sigma_slider})

        self.items.append({
            'name': 'meppAmplitude',
            'string': 'MEPP Amplitude (mean)',
            'object': self.meppAmplitude_slider
        })
        self.items.append({
            'name': 'meppAmplitude_sigma',
            'string': 'MEPP Amplitude (standard deviation)',
            'object': self.meppAmplitude_sigma_slider
        })
        self.items.append({
            'name': 'meanExp',
            'string': 'Mean of exponential distibution',
            'object': self.meanExp_slider
        })

        self.items.append({
            'name': 'baseline',
            'string': 'Baseline',
            'object': self.baseline_slider
        })
        self.items.append({
            'name': 'noiseSigma',
            'string': 'Noise Sigma',
            'object': self.noiseSigma_slider
        })

        self.items.append({
            'name': 'histoTimes',
            'string': 'Plot histogram of mepp start times:',
            'object': self.plotHistoTimes
        })
        self.items.append({
            'name': 'random_mepp_Button',
            'string': 'Click to add randomly distibuted mepps',
            'object': self.randommeppButton
        })
        self.items.append({
            'name': 'listTimes',
            'string': 'Export list of mepp start times',
            'object': self.exportTimes_button
        })
        self.items.append({
            'name': 'plotMEPP',
            'string': 'Plot single MEPP (without noise)',
            'object': self.plotmeppButton
        })
        super().gui()

    def __call__(self, keepSourceWindow=False):
        g.settings['mepp_simulator']['traceLength'] = self.getValue(
            'traceLength')
        g.settings['mepp_simulator']['meppAmplitude'] = self.getValue(
            'meppAmplitude')
        g.settings['mepp_simulator']['meppDuration'] = self.getValue(
            'meppDuration')
        g.settings['mepp_simulator']['startTime'] = self.getValue('startTime')
        g.settings['mepp_simulator']['meanExp'] = self.getValue('meanExp')
        g.settings['mepp_simulator']['baseline'] = self.getValue('baseline')
        g.settings['mepp_simulator']['noiseSigma'] = self.getValue(
            'noiseSigma')
        g.settings['mepp_simulator']['riseTime'] = self.getValue('riseTime')
        g.settings['mepp_simulator']['decayTime'] = self.getValue('decayTime')

        return

    def addMEPP(self, time, amplitude, duration, dT=10, rT=1):
        #using Segal et al. Biophys J, 1985 MINIATURE ENDPLATE POTENTIAL FREQUENCY AND AMPLITUDE DETERMINED BY AN EXTENSION OF CAMPBELL'S THEOREM
        #dT = decay time
        #rT = rise time
        ampList = []
        for t in range(0, duration):
            ampList.append(amplitude * (math.exp(-t / dT) - math.exp(-t / rT)))

        #square event test
        #self.data[time:time+duration] = self.data[time:time+duration] + amplitude

        #add MEPP to trace
        self.data[time:time +
                  duration] = self.data[time:time +
                                        duration] + np.array(ampList)

    def plotSingleMEPP(self):
        amp = self.getValue('meppAmplitude')
        duration = self.getValue('meppDuration')
        dT = self.getValue('decayTime')
        rT = self.getValue('riseTime')
        self.plotMEPP(amp, duration, dT=dT, rT=rT)

    def plotMEPP(self, amplitude, duration, dT=10, rT=1):
        ampList = []
        for t in range(0, duration):
            ampList.append(amplitude * (math.exp(-t / dT) - math.exp(-t / rT)))
        #plot matplot
        #plt.figure(3)
        #plt.plot(range(0,duration),ampList)
        #plt.show()
        #plot pg
        self.meppWindow.update(ampList, [0, len(ampList)],
                               [0, self.getValue('meppAmplitude')])
        self.meppWindow.show()

    def addRandommepps(self):
        self.data = np.array([])

        #generate noisy time trace
        n = int(self.getValue('traceLength'))

        self.data = np.random.normal(self.getValue('baseline'),
                                     self.getValue('noiseSigma'), n)

        #add MEPPS to trace
        mean = self.getValue('meanExp')
        meppsAdded = 0
        meppsOutsideOfRange = 0
        self.timesAdded = []

        amp = self.getValue('meppAmplitude')
        duration = self.getValue('meppDuration')
        dT = self.getValue('decayTime')
        rT = self.getValue('riseTime')

        # add first mepp
        try:
            time = int((np.random.exponential(scale=mean, size=1) +
                        self.getValue('startTime')))
            #draw random amplitude
            randAmp = int(
                np.random.normal(amp, self.getValue('meppAmplitude_sigma'), 1))
            #draw random duration
            randDuration = int(
                np.random.normal(duration, self.getValue('meppDuration_sigma'),
                                 1))
            # add MEPP
            self.addMEPP(time, randAmp, randDuration, dT=dT, rT=rT)
            #record time
            self.timesAdded.append(time)
            meppsAdded += 1
        except BaseException as e:
            #print(e)
            #meppsOutsideOfRange += 1
            #print('{} MEPPs added, {} MEPPs out of time range'.format(meppsAdded,meppsOutsideOfRange))
            #print('1st MEPP outside of time range, aborting')
            pass

        # add mepp after each time selection untill end of stack
        # casting the exponential continous value as an int to select frame
        while time < self.getValue('traceLength') - self.getValue(
                'meppDuration'):
            try:
                time = int((time + np.random.exponential(scale=mean, size=1)))

                #draw random amplitude
                randAmp = int(
                    np.random.normal(amp, self.getValue('meppAmplitude_sigma'),
                                     1))
                #draw random duration
                randDuration = int(
                    np.random.normal(duration,
                                     self.getValue('meppDuration_sigma'), 1))
                # add MEPP
                self.addMEPP(time, randAmp, randDuration, dT=dT, rT=rT)
                #record time
                self.timesAdded.append(time)
                meppsAdded += 1
            except BaseException as e:
                #print(e)
                meppsOutsideOfRange += 1

        #print number of MEPPS added to console
        #print('{} MEPPs added, {} MEPPs out of time range'.format(meppsAdded,meppsOutsideOfRange))

        if self.plotHistoTimes.isChecked():
            plt.figure(1)
            plt.hist(self.timesAdded)
            plt.xlabel('Time MEPP added')
            plt.ylabel('Number of MEPPs added')
            plt.show()

        self.randommeppsAdded = True

        #print data to console
        #print(self.data)

        #plot data matplotlib
        #plt.figure(0)
        #plt.plot(self.data)
        #plt.show()

        #plot data pg
        self.traceWindow.update(self.data, [0, len(self.data)], [
            self.getValue('baseline') - (3 * self.getValue('noiseSigma')),
            self.getValue('meppAmplitude') +
            (3 * self.getValue('meppAmplitude_sigma'))
        ])
        self.traceWindow.show()
        return

    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)
Пример #28
0
    def __init__(self, parent = None):
        super(Synapse3D_batch, self).__init__(parent)
        #add window title
        self.setWindowTitle("Volume Slider GUI")
        
        self.pathName = ''

        self.eps  = clusterAnalysis.eps
        self.min_samples = clusterAnalysis.min_samples
        self.maxDistance = clusterAnalysis.maxDistance
        self.unitPerPixel = clusterAnalysis.unitPerPixel
        #self.multiThreadingFlag = clusterAnalysis.multiThreadingFlag
        self.displayFlag = clusterAnalysis.displayFlag
        
        self.clusterType = '3D'
        
        #window geometry
        self.left = 300
        self.top = 300
        self.width = 300
        self.height = 200

        #labels
        self.clusterTitle = QtWidgets.QLabel("----- Cluster Parameters -----") 
        self.label_eps = QtWidgets.QLabel("max distance between points:") 
        self.label_minSamples = QtWidgets.QLabel("minimum number of points:") 
        self.label_maxDistance = QtWidgets.QLabel("max distance between clusters:") 
        self.label_clustertype = QtWidgets.QLabel("clustering type:")        
        self.displayTitle = QtWidgets.QLabel("----- Display Parameters -----") 
        self.label_unitPerPixel = QtWidgets.QLabel("nanometers/pixel:") 
        #self.label_centroidSymbolSize = QtWidgets.QLabel("centroid symbol size:")  
        
        self.analysisTitle = QtWidgets.QLabel("----- Cluster Analysis -----") 
        self.label_analysis = QtWidgets.QLabel("Clusters to analyse: ")

        self.displayTitle = QtWidgets.QLabel("----- Display -----") 
        self.label_display = QtWidgets.QLabel("Plot results: ")         
        
        #self.multiThreadTitle = QtWidgets.QLabel("----- Multi-Threading -----") 
        #self.label_multiThread = QtWidgets.QLabel("Multi-Threading On: ")        
        
        #self.label_displayPlot = QtWidgets.QLabel("show plot")         

        #spinboxes
        self.epsBox = QtWidgets.QSpinBox()
        self.epsBox.setRange(0,10000)
        self.epsBox.setValue(self.eps)
        self.minSampleBox = QtWidgets.QSpinBox()    
        self.minSampleBox.setRange(0,10000)
        self.minSampleBox.setValue(self.min_samples)
        self.maxDistanceBox = QtWidgets.QSpinBox()    
        self.maxDistanceBox.setRange(0,10000)
        self.maxDistanceBox.setValue(self.maxDistance)    
        self.unitPerPixelBox = QtWidgets.QSpinBox()    
        self.unitPerPixelBox.setRange(0,1000)
        self.unitPerPixelBox.setValue(self.unitPerPixel)  
        #self.centroidSymbolSizeBox = QtWidgets.QSpinBox()    
        #self.centroidSymbolSizeBox.setRange(0,1000)
        #self.centroidSymbolSizeBox.setValue(self.centroidSymbolSize)          

        #combobox
        #self.analysis_Box = QtWidgets.QComboBox()
        #self.analysis_Box.addItems(["All Clusters", "Paired Clusters"])
        self.clustertype_Box = QtWidgets.QComboBox()
        self.clustertype_Box.addItems(["2D", "3D"])
        self.clustertype_Box.setCurrentText(self.clusterType)
        self.clustertype_Box.currentIndexChanged.connect(self.clusterTypeChange)
        
        #tickbox
        self.display_checkbox = CheckBox()
        self.display_checkbox.setChecked(self.displayFlag)
        self.display_checkbox.stateChanged.connect(self.displayClicked)
        #self.multiThread_checkbox = CheckBox()
        #self.multiThread_checkbox.setChecked(self.multiThreadingFlag)
        #self.multiThread_checkbox.stateChanged.connect(self.multiThreadClicked)

        #buttons
        self.button_getFolder = QtWidgets.QPushButton("Set Folder")
        self.button_start = QtWidgets.QPushButton("Start Batch Analysis")
        
        #grid layout
        layout = QtWidgets.QGridLayout()
        layout.setSpacing(5)
        layout.addWidget(self.clusterTitle, 0, 0, 1, 2)        
        layout.addWidget(self.label_eps, 1, 0)
        layout.addWidget(self.epsBox, 1, 1)       
        layout.addWidget(self.label_minSamples, 2, 0)        
        layout.addWidget(self.minSampleBox, 2, 1)     
        layout.addWidget(self.label_maxDistance, 3, 0)        
        layout.addWidget(self.maxDistanceBox, 3, 1)
        layout.addWidget(self.displayTitle, 4, 0, 1, 2)          
        layout.addWidget(self.label_unitPerPixel, 5, 0)  
        layout.addWidget(self.unitPerPixelBox, 5, 1)         
        layout.addWidget(self.label_clustertype, 6, 0) 
        layout.addWidget(self.clustertype_Box, 6, 1)
        layout.addWidget(self.displayTitle, 7, 0, 1, 2) 
        layout.addWidget(self.label_display, 8, 0)        
        layout.addWidget(self.display_checkbox, 8, 1)         
        layout.addWidget(self.button_getFolder, 9, 0)          
        layout.addWidget(self.button_start, 10, 0)         
        
        #layout.addWidget(self.label_centroidSymbolSize, 6, 0)  
        #layout.addWidget(self.centroidSymbolSizeBox, 6, 1) 
        
        #layout.addWidget(self.analysisTitle, 8, 0, 1, 2)  
        #layout.addWidget(self.label_analysis, 9, 0)  
        #layout.addWidget(self.analysis_Box, 9, 1)     
        
        #layout.addWidget(self.multiThreadTitle, 10, 0, 1, 2)  
        #layout.addWidget(self.label_multiThread, 11, 0)  
        #layout.addWidget(self.multiThread_checkbox, 11, 1)  
        

        
        self.setLayout(layout)
        self.setGeometry(self.left, self.top, self.width, self.height)

        #add window title
        self.setWindowTitle("Clustering Options")

        #connect spinboxes
        self.epsBox.valueChanged.connect(self.epsValueChange)
        self.minSampleBox.valueChanged.connect(self.minSampleChange) 
        self.maxDistanceBox.valueChanged.connect(self.maxDistanceChange)    
        self.unitPerPixelBox.valueChanged.connect(self.unitPerPixelChange) 
        #self.centroidSymbolSizeBox.valueChanged.connect(self.centroidSymbolSizeChange)  
        #connect combobox
        #self.analysis_Box.setCurrentIndex(0)
        #self.analysis_Box.currentIndexChanged.connect(self.analysisChange)         

        #connect buttons
        self.button_getFolder.clicked.connect(self.getSavePath)
        self.button_start.clicked.connect(self.run)
class Light_Sheet_Analyzer(BaseProcess):
    """ light_Sheet_Analyzer(nSteps, shift_factor, triangle_scan, interpolate, trim_last_frame, keepSourceWindow=False)
    Makes a 3D viewer for data acquired using a light sheet microscope.

    Parameters:
        | nSteps (int) -- How many stacks per volume
        | shift_factor (int) -- How many pixels (measured along the width of the light sheet) the sample moves per frame
        | triangle_scan (bool) -- If the scan moves back and forth this is true. If the scan moves like a typewriter, this is false.
        | interpolate (bool) -- This will upsample the data before the transformation to prevent information loss, but is slow
        | trim_last_frame (bool) -- This removes the last frame of each volume.
    Returns:
        Volume_Viewer
    """
    def __init__(self):
        if g.settings[
                'light_sheet_analyzer'] is None or 'trim_last_frame' not in g.settings[
                    'light_sheet_analyzer']:
            s = dict()
            s['nSteps'] = 1
            s['shift_factor'] = 1
            s['triangle_scan'] = False
            s['interpolate'] = False
            s['trim_last_frame'] = False
            g.settings['light_sheet_analyzer'] = s
        super().__init__()

    def __call__(self,
                 nSteps,
                 shift_factor,
                 triangle_scan,
                 interpolate,
                 trim_last_frame,
                 keepSourceWindow=False):
        g.settings['light_sheet_analyzer']['nSteps'] = nSteps
        g.settings['light_sheet_analyzer']['shift_factor'] = shift_factor
        g.settings['light_sheet_analyzer']['triangle_scan'] = triangle_scan
        g.settings['light_sheet_analyzer']['interpolate'] = interpolate
        g.settings['light_sheet_analyzer']['trim_last_frame'] = trim_last_frame
        g.m.statusBar().showMessage("Generating 4D movie ...")
        t = time()
        self.start(keepSourceWindow)
        A = np.copy(self.tif)
        # A = A[1:]  # Ian Parker said to hard code removal of the first frame.
        mt, mx, my = A.shape
        if triangle_scan:
            for i in np.arange(mt // (nSteps * 2)):
                t0 = i * nSteps * 2 + nSteps
                tf = (i + 1) * nSteps * 2
                A[t0:tf] = A[tf:t0:-1]
        mv = mt // nSteps  # number of volumes
        A = A[:mv * nSteps]
        B = np.reshape(A, (mv, nSteps, mx, my))
        if trim_last_frame:
            B = B[:, :-1, :, :]
        #D = perform_shear_transform_old(B, shift_factor, interpolate, A.dtype)
        D = perform_shear_transform(B, shift_factor, interpolate, A.dtype)
        g.m.statusBar().showMessage(
            "Successfully generated movie ({} s)".format(time() - t))
        w = Window(np.squeeze(D[:, 0, :, :]), name=self.oldname)
        w.volume = D

        Volume_Viewer(w)
        return

    def closeEvent(self, event):
        self.ui.close()
        event.accept()

    def gui(self):
        s = g.settings['light_sheet_analyzer']
        self.gui_reset()
        self.nSteps = pg.SpinBox(int=True, step=1)
        self.nSteps.setMinimum(1)
        self.nSteps.setValue(s['nSteps'])

        self.shift_factor = pg.SpinBox(int=False, step=.1)
        self.shift_factor.setValue(s['shift_factor'])

        self.triangle_scan = CheckBox()
        self.triangle_scan.setValue(s['triangle_scan'])

        self.interpolate = CheckBox()
        self.interpolate.setValue(s['interpolate'])

        self.trim_last_frame = CheckBox()
        self.trim_last_frame.setValue(s['trim_last_frame'])

        self.items.append({
            'name': 'nSteps',
            'string': 'Number of steps per volume',
            'object': self.nSteps
        })
        self.items.append({
            'name': 'shift_factor',
            'string': 'Shift Factor',
            'object': self.shift_factor
        })
        self.items.append({
            'name': 'triangle_scan',
            'string': 'Trangle Scan',
            'object': self.triangle_scan
        })
        self.items.append({
            'name': 'interpolate',
            'string': 'Interpolate',
            'object': self.interpolate
        })
        self.items.append({
            'name': 'trim_last_frame',
            'string': 'Trim Last Frame',
            'object': self.trim_last_frame
        })
        super().gui()
Пример #30
0
    def gui(self):
        s = g.settings['dipoleAnalysis']
        self.gui_reset()
        #paths
        self.resultsFolder1 = FolderSelector('*.txt')
        self.resultsFolder2 = FolderSelector('*.txt')
        self.resultsFolder3 = FolderSelector('*.txt')
        #windows
        self.dipoleWindow = WindowSelector()
        self.twoColorWindow = WindowSelector()
        self.twoColorWindow_crop = WindowSelector()
        #buttons
        self.step2_Button = QPushButton('Extract Clusters from 2-Color Image')
        self.step2_Button.pressed.connect(self.step2)
        self.step3_Button = QPushButton('Rotate Clusters - Get Positions')
        self.step3_Button.pressed.connect(self.step3)
        self.step1_Button = QPushButton('Filter Clusters by Dipole Image')
        self.step1_Button.pressed.connect(self.step1)
        #checkboxes
        self.step1Gaussian = CheckBox()
        self.step1Threshold = CheckBox()
        #Spinboxes
        self.step1GuassianValue = pg.SpinBox(int=True, step=1)
        self.step1GuassianValue.setValue(s['step1GuassianValue'])
        self.step1ThresholdValue = pg.SpinBox(int=False, step=.001)
        self.step1ThresholdValue.setValue(s['step1ThresholdValue'])

        self.step2GuassianValue = pg.SpinBox(int=True, step=1)
        self.step2GuassianValue.setValue(s['step2GuassianValue'])
        self.step2ThresholdValue = pg.SpinBox(int=False, step=.001)
        self.step2ThresholdValue.setValue(s['step2ThresholdValue'])

        self.step2minClusterArea = pg.SpinBox(int=True, step=1)
        self.step2minClusterArea.setValue(s['step2minClusterArea'])

        #populate GUI
        self.items.append({
            'name': 'resultsFolder1',
            'string': 'Results Folder 1 (for filtered two-color image)',
            'object': self.resultsFolder1
        })
        self.items.append({
            'name': 'resultsFolder2',
            'string': 'Results Folder 2 (for extracted clusters)',
            'object': self.resultsFolder2
        })
        self.items.append({
            'name': 'resultsFolder3',
            'string': 'Results Folder 3 (for final rotated clusters)',
            'object': self.resultsFolder3
        })
        self.items.append({
            'name': 'dipoleWindow',
            'string': 'Dipole Window (Step 1)',
            'object': self.dipoleWindow
        })
        self.items.append({
            'name': 'twoColorWindow',
            'string': 'Two-color Window (Step 1)',
            'object': self.twoColorWindow
        })
        self.items.append({
            'name': 'twoColorWindow_crop',
            'string': 'Two-color Window for cluster analysis (Step 2)',
            'object': self.twoColorWindow_crop
        })
        self.items.append({
            'name': 'step1Gaussian',
            'string': 'Display Step 1 Gaussian Image',
            'object': self.step1Gaussian
        })
        self.items.append({
            'name': 'step1Threshold',
            'string': 'Display Step 1 Thresholded Image',
            'object': self.step1Threshold
        })
        self.items.append({
            'name': 'step1GuassianValue',
            'string': 'Step 1 Gaussian Value',
            'object': self.step1GuassianValue
        })
        self.items.append({
            'name': 'step1ThresholdValue',
            'string': 'Step 1 Threshold Value',
            'object': self.step1ThresholdValue
        })
        self.items.append({
            'name': 'step2GuassianValue',
            'string': 'Step 2 Gaussian Value',
            'object': self.step2GuassianValue
        })
        self.items.append({
            'name': 'step2ThresholdValue',
            'string': 'Step 2 Threshold Value',
            'object': self.step2ThresholdValue
        })
        self.items.append({
            'name': 'step2minClusterArea',
            'string': 'Step 2 Minimum Cluster Area',
            'object': self.step2minClusterArea
        })

        self.items.append({
            'name': 'step1_Button',
            'string': 'Step 1',
            'object': self.step1_Button
        })
        self.items.append({
            'name': 'step2_Button',
            'string': 'Step 2',
            'object': self.step2_Button
        })
        self.items.append({
            'name': 'step3_Button',
            'string': 'Step 3',
            'object': self.step3_Button
        })
        super().gui()