Beispiel #1
0
    def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)

        #        imageWidget = pg.GraphicsLayoutWidget()
        #        self.vb = imageWidget.addViewBox(row=1, col=1)

        # LiveView Button

        self.liveviewButton = QtGui.QPushButton('confocal LIVEVIEW')
        #        self.liveviewButton.setCheckable(True)
        self.liveviewButton.clicked.connect(self.liveview)

        # Scanning parameters

        self.initialPositionLabel = QtGui.QLabel(
            'ptsamano [Ni, Ncasi,Nfin,Nflip] (µm)')
        self.initialPositionEdit = QtGui.QLineEdit('0 10 10 20')
        self.scanRangeLabel = QtGui.QLabel('Scan range (µm)')
        self.scanRangeEdit = QtGui.QLineEdit('10')
        self.pixelTimeLabel = QtGui.QLabel('Pixel time (ms)')
        self.pixelTimeEdit = QtGui.QLineEdit('0.01')
        self.numberofPixelsLabel = QtGui.QLabel('Number of pixels')
        self.numberofPixelsEdit = QtGui.QLineEdit('500')
        self.pixelSizeLabel = QtGui.QLabel('Pixel size (nm)')
        self.pixelSizeValue = QtGui.QLabel('')

        self.numberofPixelsEdit.textChanged.connect(self.paramChanged)
        self.scanRangeEdit.textChanged.connect(self.paramChanged)
        self.pixelTimeEdit.textChanged.connect(self.paramChanged)
        self.initialPositionEdit.textChanged.connect(self.paramChanged)

        self.aLabel = QtGui.QLabel('puntos agregados a mano')
        self.aEdit = QtGui.QLineEdit('10')
        self.mLabel = QtGui.QLabel('Vback (µm/ms)')
        self.mEdit = QtGui.QLineEdit('10')
        self.mEdit.setStyleSheet(" background-color: red; ")

        self.aEdit.textChanged.connect(self.paramChanged)
        self.mEdit.textChanged.connect(self.paramChanged)

        self.startXLabel = QtGui.QLabel('startX')
        self.startXEdit = QtGui.QLineEdit('0')
        self.startXEdit.textChanged.connect(self.paramChanged)
        self.paramChanged()

        self.paramWidget = QtGui.QWidget()

        grid = QtGui.QGridLayout()
        self.setLayout(grid)
        #        grid.addWidget(imageWidget, 0, 0)
        grid.addWidget(self.paramWidget, 1, 1)

        subgrid = QtGui.QGridLayout()
        self.paramWidget.setLayout(subgrid)
        subgrid.addWidget(self.liveviewButton, 14, 1, 2, 2)
        subgrid.addWidget(self.initialPositionLabel, 0, 1)
        subgrid.addWidget(self.initialPositionEdit, 1, 1)
        #        subgrid.addWidget(self.aLabel, 0, 1)
        #        subgrid.addWidget(self.aEdit, 1, 1)
        subgrid.addWidget(self.mLabel, 2, 1)
        subgrid.addWidget(self.mEdit, 3, 1)
        subgrid.addWidget(self.scanRangeLabel, 4, 1)
        subgrid.addWidget(self.scanRangeEdit, 5, 1)
        subgrid.addWidget(self.pixelTimeLabel, 6, 1)
        subgrid.addWidget(self.pixelTimeEdit, 7, 1)
        subgrid.addWidget(self.numberofPixelsLabel, 8, 1)
        subgrid.addWidget(self.numberofPixelsEdit, 9, 1)
        subgrid.addWidget(self.pixelSizeLabel, 10, 1)
        subgrid.addWidget(self.pixelSizeValue, 11, 1)
        subgrid.addWidget(self.startXLabel, 12, 1)
        subgrid.addWidget(self.startXEdit, 13, 1)

        self.figure = matplotlib.figure.Figure()
        #        plt.close(self.figure)
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        #        grid.addWidget(self.canvas, 0, 5, 10, 1)
        grid.addWidget(
            self.toolbar,
            0,
            0,
        )
        grid.addWidget(self.canvas, 1, 0)
        self.paramWidget.setFixedHeight(300)

        self.liveview()
Beispiel #2
0
    def init_Ui(self):

        # Set software gain
        self.gain.setText(self.config.get('USRP', 'software_gain'))

        self.listWidget_spectra.currentItemChanged.connect(self.change_spectra)

        # Define progresstimer
        self.clear_progressbar()
        self.progresstimer = QtCore.QTimer()
        self.progresstimer.timeout.connect(self.update_progressbar)

        # Define and run UiTimer
        self.uitimer = QtCore.QTimer()
        self.uitimer.timeout.connect(self.update_Ui)
        self.uitimer.start(1000)  #ms

        # Create timer used to toggle (and update) tracking
        # Do not start this, started by user on Track button.
        self.trackingtimer = QtCore.QTimer()
        self.trackingtimer.timeout.connect(self.track)

        # Reset needs its own timer to be able
        # to check if reset position has been reached
        # and then, only then, enable GUI input again.
        self.resettimer = QtCore.QTimer()
        self.resettimer.timeout.connect(self.resettimer_action)

        # Initialise buttons and tracking status.
        self.tracking = False
        self.btn_track.clicked.connect(self.track_or_stop)
        self.btn_reset.clicked.connect(self.reset)

        # Make sure Ui is updated when changing target
        self.coordselector.currentIndexChanged.connect(self.update_Ui)
        # Make sure special targets like "The Sun" are handled correctly.
        self.coordselector.currentIndexChanged.connect(
            self.update_desired_target)

        # RECEIVER CONTROL
        self.btn_observe.clicked.connect(self.observe)
        self.btn_observe.clicked.connect(self.disable_receiver_controls)
        self.btn_abort.clicked.connect(self.abort_obs)
        self.btn_abort.setEnabled(False)

        # Plotting and saving
        self.btn_upload.clicked.connect(self.send_to_webarchive)

        # ADD MATPLOTLIB CANVAS, based on:
        # http://stackoverflow.com/questions/12459811/how-to-embed-matplotib-in-pyqt-for-dummies
        # a figure instance to plot on
        self.figure = plt.figure()
        self.figure.patch.set_facecolor('white')
        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self.groupBox_spectrum)
        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self.groupBox_spectrum)
        # set the layout
        # Position as left, top, width, height
        #self.canvas.setGeometry(QtCore.QRect(20, 20, 500, 380)
        plotwinlayout = QtGui.QVBoxLayout()
        plotwinlayout.addWidget(self.canvas)
        plotwinlayout.addWidget(self.toolbar)
        self.groupBox_spectrum.setLayout(plotwinlayout)
        self.radioButton_frequency.toggled.connect(self.change_spectra)
    def initUI(self):
        #first gui controls that apply to all modes
#        self.checkbox_trackSelection = QtGui.QCheckBox('Plot selected pixel(s)',self)
#        self.checkbox_trackSelection.setChecked(True)

#        self.checkbox_trackTimes = QtGui.QCheckBox('Use main window times',self)
#        self.checkbox_trackTimes.setChecked(True)
#        self.connect(self.checkbox_trackTimes,QtCore.SIGNAL('stateChanged(int)'),self.changeTrackTimes)

        self.checkbox_clearPlot = QtGui.QCheckBox('Clear axes before plotting',self)
        self.checkbox_clearPlot.setChecked(True)

        self.button_drawPlot = QtGui.QPushButton('Plot',self)
        self.connect(self.button_drawPlot,QtCore.SIGNAL('clicked()'), self.updatePlot)
        self.dpi = 100
        self.fig = Figure((10.0, 3.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        #self.canvasToolbar = NavigationToolbar(self.canvas, self)
        self.axes = self.fig.add_subplot(111)
        self.fig.subplots_adjust(left=0.07,right=.93,top=.93,bottom=0.15)
        self.axes.tick_params(axis='both', which='major', labelsize=8)

        cid = self.fig.canvas.mpl_connect('button_press_event', self.buttonPressCanvas)
        cid = self.fig.canvas.mpl_connect('button_release_event', self.buttonReleaseCanvas)
        cid = self.fig.canvas.mpl_connect('motion_notify_event', self.motionNotifyCanvas)
        self.selectFirstPoint = None
        self.selectSecondPoint = None
        self.selectedRange = None
        self.selecting = False
        self.lastPlotType = None

        #self.combobox_plotType = QtGui.QComboBox(self)
        self.plotTypeStrs = ['Light Curve']
        #self.combobox_plotType.addItems(self.plotTypeStrs)
        #self.connect(self.combobox_plotType,QtCore.SIGNAL('activated(QString)'), self.changePlotType)


        #light curve controls
#        self.textbox_intTime = QtGui.QLineEdit('1')
#        self.textbox_intTime.setFixedWidth(50)
#
#        lightCurveControlsBox = layoutBox('H',['Int Time',self.textbox_intTime,'s',1.])
#        self.lightCurveControlsGroup = QtGui.QGroupBox('Light Curve Controls',parent=self)
#        self.lightCurveControlsGroup.setLayout(lightCurveControlsBox)


        #time controls
#        self.textbox_startTime = QtGui.QLineEdit('0')
#        self.textbox_startTime.setFixedWidth(50)
#        self.textbox_endTime = QtGui.QLineEdit(str(len(self.parent.imageStack)))
#        self.textbox_endTime.setFixedWidth(50)
#        self.timesGroup = QtGui.QGroupBox('',parent=self)
#        timesBox = layoutBox('H',['Start Time',self.textbox_startTime,'s',1.,'End Time',self.textbox_endTime,'s',10.])
#        self.timesGroup.setLayout(timesBox)
#        self.timesGroup.setVisible(False)
#        timesChoiceBox = layoutBox('H',[self.checkbox_trackTimes,self.timesGroup])

        checkboxBox = layoutBox('H',[self.button_drawPlot])
        #controlsBox = layoutBox('H',[self.lightCurveControlsGroup])

        mainBox = layoutBox('V',[checkboxBox,self.checkbox_clearPlot,self.canvas])
        self.setLayout(mainBox)
Beispiel #4
0
    def __init__(self):
        ## Initialize the application
        self.app = QApplication(sys.argv)
        super().__init__(None)
        self.setWindowTitle("SV2TTS toolbox")

        ## Main layouts
        # Root
        root_layout = QGridLayout()
        self.setLayout(root_layout)

        # Browser
        browser_layout = QGridLayout()
        root_layout.addLayout(browser_layout, 0, 1)

        # Visualizations
        vis_layout = QVBoxLayout()
        root_layout.addLayout(vis_layout, 1, 1, 2, 3)

        # Generation
        gen_layout = QVBoxLayout()
        root_layout.addLayout(gen_layout, 0, 2)

        # Projections
        self.projections_layout = QVBoxLayout()
        root_layout.addLayout(self.projections_layout, 1, 0)

        ## Projections
        # UMap
        fig, self.umap_ax = plt.subplots(figsize=(4, 4), facecolor="#F0F0F0")
        fig.subplots_adjust(left=0.02, bottom=0.02, right=0.98, top=0.98)
        self.projections_layout.addWidget(FigureCanvas(fig))
        self.umap_hot = False
        self.clear_button = QPushButton("Clear")
        self.projections_layout.addWidget(self.clear_button)

        ## Browser
        # Dataset, speaker and utterance selection
        i = 0
        self.dataset_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Dataset</b>"), i, 0)
        browser_layout.addWidget(self.dataset_box, i + 1, 0)
        self.speaker_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Speaker</b>"), i, 1)
        browser_layout.addWidget(self.speaker_box, i + 1, 1)
        self.utterance_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Utterance</b>"), i, 2)
        browser_layout.addWidget(self.utterance_box, i + 1, 2)
        self.browser_browse_button = QPushButton("Browse")
        browser_layout.addWidget(self.browser_browse_button, i, 3)
        self.browser_load_button = QPushButton("Load")
        browser_layout.addWidget(self.browser_load_button, i + 1, 3)
        i += 2

        # Random buttons
        self.random_dataset_button = QPushButton("Random")
        browser_layout.addWidget(self.random_dataset_button, i, 0)
        self.random_speaker_button = QPushButton("Random")
        browser_layout.addWidget(self.random_speaker_button, i, 1)
        self.random_utterance_button = QPushButton("Random")
        browser_layout.addWidget(self.random_utterance_button, i, 2)
        self.auto_next_checkbox = QCheckBox("Auto select next")
        self.auto_next_checkbox.setChecked(True)
        browser_layout.addWidget(self.auto_next_checkbox, i, 3)
        i += 1

        # Utterance box
        browser_layout.addWidget(QLabel("<b>Use embedding from:</b>"), i, 0)
        i += 1

        # Random & next utterance buttons
        self.utterance_history = QComboBox()
        browser_layout.addWidget(self.utterance_history, i, 0, 1, 3)
        i += 1

        # Random & next utterance buttons
        self.take_generated_button = QPushButton("Take generated")
        browser_layout.addWidget(self.take_generated_button, i, 0)
        self.record_button = QPushButton("Record")
        browser_layout.addWidget(self.record_button, i, 1)
        self.play_button = QPushButton("Play")
        browser_layout.addWidget(self.play_button, i, 2)
        self.stop_button = QPushButton("Stop")
        browser_layout.addWidget(self.stop_button, i, 3)
        i += 2

        # Model selection
        self.encoder_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Encoder</b>"), i, 0)
        browser_layout.addWidget(self.encoder_box, i + 1, 0)
        self.synthesizer_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Synthesizer</b>"), i, 1)
        browser_layout.addWidget(self.synthesizer_box, i + 1, 1)
        self.vocoder_box = QComboBox()
        browser_layout.addWidget(QLabel("<b>Vocoder</b>"), i, 2)
        browser_layout.addWidget(self.vocoder_box, i + 1, 2)
        i += 2

        ## Embed & spectrograms
        vis_layout.addStretch()

        gridspec_kw = {"width_ratios": [1, 4]}
        fig, self.current_ax = plt.subplots(1,
                                            2,
                                            figsize=(10, 2.25),
                                            facecolor="#F0F0F0",
                                            gridspec_kw=gridspec_kw)
        fig.subplots_adjust(left=0, bottom=0.1, right=1, top=0.8)
        vis_layout.addWidget(FigureCanvas(fig))

        fig, self.gen_ax = plt.subplots(1,
                                        2,
                                        figsize=(10, 2.25),
                                        facecolor="#F0F0F0",
                                        gridspec_kw=gridspec_kw)
        fig.subplots_adjust(left=0, bottom=0.1, right=1, top=0.8)
        vis_layout.addWidget(FigureCanvas(fig))

        for ax in self.current_ax.tolist() + self.gen_ax.tolist():
            ax.set_facecolor("#F0F0F0")
            for side in ["top", "right", "bottom", "left"]:
                ax.spines[side].set_visible(False)

        ## Generation
        self.text_prompt = QTextEdit(default_text.replace("\n", "<br>"))
        gen_layout.addWidget(self.text_prompt, stretch=1)

        self.generate_button = QPushButton("Synthesize and vocode")
        gen_layout.addWidget(self.generate_button)

        layout = QHBoxLayout()
        self.synthesize_button = QPushButton("Synthesize only")
        layout.addWidget(self.synthesize_button)
        self.vocode_button = QPushButton("Vocode only")
        layout.addWidget(self.vocode_button)
        gen_layout.addLayout(layout)

        self.loading_bar = QProgressBar()
        gen_layout.addWidget(self.loading_bar)

        self.log_window = QLabel()
        self.log_window.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
        gen_layout.addWidget(self.log_window)
        self.logs = []
        gen_layout.addStretch()

        ## Set the size of the window and of the elements
        max_size = QDesktopWidget().availableGeometry(self).size() * 0.8
        self.resize(max_size)

        ## Finalize the display
        self.reset_interface()
        self.show()
Beispiel #5
0
    def __init__(self):
        super(MainWindow, self).__init__()

        self.expression_index = 0
        self.point_index = 0
        self.size = 0
        self.current_full_filename = ''
        self.current_filename = ''
        self.limits = 96

        self.x_ = []
        self.y_ = []
        self.z_ = []
        self.head_data = ()
        self.head_data_copy = ()

        self.setFixedSize(800, 600)
        self.setWindowTitle('HeadEditor')
        self.center()

        main_layout = QtGui.QHBoxLayout()
        layout_left = QtGui.QVBoxLayout()

        self.figure = matplotlib.figure.Figure()  # Plot
        self.canvas = FigureCanvas(self.figure)
        self.axes = Axes3D(self.figure)

        group_box = QGroupBox("Editing:")

        self.cb = QComboBox()
        self.cb.currentIndexChanged.connect(self.select_change)

        slider_lim = 128
        slider_interval = 32

        self.x_slider = QSlider(Qt.Horizontal)
        self.x_slider.valueChanged.connect(self.x_slider_change)
        self.x_slider.setMinimum(-slider_lim)
        self.x_slider.setMaximum(slider_lim)
        self.x_slider.setTickPosition(QSlider.TicksBelow)
        self.x_slider.setTickInterval(slider_interval)
        self.x_slider.setEnabled(False)

        self.y_slider = QSlider(Qt.Horizontal)
        self.y_slider.valueChanged.connect(self.y_slider_change)
        self.y_slider.setMinimum(-slider_lim)
        self.y_slider.setMaximum(slider_lim)
        self.y_slider.setTickPosition(QSlider.TicksBelow)
        self.y_slider.setTickInterval(slider_interval)
        self.y_slider.setEnabled(False)

        self.z_slider = QSlider(Qt.Horizontal)
        self.z_slider.valueChanged.connect(self.z_slider_change)
        self.z_slider.setMinimum(-slider_lim)
        self.z_slider.setMaximum(slider_lim)
        self.z_slider.setTickPosition(QSlider.TicksBelow)
        self.z_slider.setTickInterval(slider_interval)
        self.z_slider.setEnabled(False)

        self.expression_slider = QSlider(Qt.Horizontal)
        self.expression_slider.valueChanged.connect(
            self.expression_slider_change)
        self.expression_slider.setMinimum(0)
        self.expression_slider.setMaximum(4)
        self.expression_slider.setValue(0)
        self.expression_slider.setTickPosition(QSlider.TicksBelow)
        self.expression_slider.setTickInterval(1)
        self.expression_slider.setEnabled(False)

        self.load_button = QtGui.QPushButton('Load', self)
        self.load_button.clicked.connect(self.load_data)

        self.save_button = QtGui.QPushButton('Save', self)
        self.save_button.clicked.connect(self.save_data)

        self.x_slider_label = QLabel("x : 0")
        self.y_slider_label = QLabel("y : 0")
        self.z_slider_label = QLabel("z : 0")
        self.exp_slider_label = QLabel("Expression : 1")

        hbox = QVBoxLayout()
        hbox.addWidget(self.x_slider_label)
        hbox.addWidget(self.x_slider)
        hbox.addWidget(self.y_slider_label)
        hbox.addWidget(self.y_slider)
        hbox.addWidget(self.z_slider_label)
        hbox.addWidget(self.z_slider)
        hbox.addWidget(self.exp_slider_label)
        hbox.addWidget(self.expression_slider)
        hbox.addWidget(self.load_button)
        hbox.addWidget(self.save_button)
        hbox.addStretch(1)

        allitems = QVBoxLayout()
        allitems.addWidget(self.cb)
        allitems.addLayout(hbox)

        group_box.setLayout(allitems)

        layout_left.addWidget(self.canvas)

        main_layout.addLayout(layout_left)
        main_layout.addWidget(group_box)
        self.setLayout(main_layout)

        self.axes.view_init(20, 60)
        self.plot_3d()
Beispiel #6
0
    def __init__(self):
        super(MainForm,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        
        layout = QVBoxLayout()
        
        self.figure = Figure()
        self.ui.bottomImage.canvas = FigureCanvas(self.figure)

        layout.addWidget(self.ui.bottomImage.canvas)        
        self.ui.bottomImage.setLayout(layout)

        self.ax1 = self.figure.add_subplot(1,1,1 )#, projection='3d')
        
        self.ax1.get_yaxis().set_visible(False)
        self.ax1.get_xaxis().set_visible(True)
        
        self.figure.subplots_adjust(left=0.001, right=0.999, top=1.0, bottom=0.1)



        self.scaleFactor=1.0
        self.frameID=0        
        self.strt=0
        self.isRun=True
        self.resizegoing=False
        self.sliderbusy=False
        self.sliderbusy2=False
        self.linebusy=False
        self.template=np.zeros((1,1,1))
        self.ui.openButton.clicked.connect(self.openButtonPressed)
        self.ui.startButton.clicked.connect(self.startButtonPressed)   
        self.ui.fileButton.clicked.connect(self.fileButtonPressed)      
        self.ui.horizontalSlider.sliderPressed.connect(self.horizontalSliderPressed)
        self.ui.horizontalSlider.sliderReleased.connect(self.horizontalSliderReleased)
        self.ui.horizontalSlider.valueChanged.connect(self.slider_value_changed)
        self.fps = 20

        # processed frames


        self.ui.pauseButton.clicked.connect(self.pauseButtonPressed)
        #self.ui.MainWindow.
        
        self.resized.connect(self._on_resized)
        #self.keypressed.connect(self._key_pressed)
        self.startx=0
        self.starty=0
        self.isvideo=False
        self.isdata=False

        
        

        self.isbusy=0
        self.frameHeight=1
        self.frameWidth=1
        self.limg=np.zeros((1,1,1))
        self.tracker=None
        self.cap=None
        self.timer=None

       
        self.ui.statusbar.showMessage("Select a video for analysis")
        self.isthreadActive=False

        self.wthread = workerThread(self)        
        self.wthread.updatedM.connect(self.horizontalSliderSet)        
        self.wthread.start()  

        self.wthread2 = workerThread2(self)        
        #self.wthread2.updatedLine.connect(self.lineSliderSet)       
        self.wthread2.start() 

        klistener=pynput.keyboard.Listener(on_press=self.on_press) #,on_release=self.on_release)
        klistener.start()
Beispiel #7
0
    def __init__(self, parent):
        QMainWindow.__init__(self, parent)
        
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        #self.prm = prm
     
            
        self.pchs = ["o", "s", "v", "p", "h", "8", "*", "x", "+", "d", ",", "^", "<", ">", "1", "2", "3", "4", "H", "D", ".", "|", "_"]  


        mpl.rcParams['xtick.major.size'] = 6
        mpl.rcParams['xtick.minor.size'] = 4
        mpl.rcParams['xtick.major.width'] = 1
        mpl.rcParams['xtick.minor.width'] = 1
        mpl.rcParams['ytick.major.size'] = 9
        mpl.rcParams['ytick.minor.size'] = 5
        mpl.rcParams['ytick.major.width'] = 0.8
        mpl.rcParams['ytick.minor.width'] = 0.8
        mpl.rcParams['xtick.direction'] = 'out'
        mpl.rcParams['ytick.direction'] = 'out'
        mpl.rcParams['font.size'] = 14
        mpl.rcParams['figure.facecolor'] = 'white'
        mpl.rcParams['lines.color'] = 'black'
        mpl.rcParams['axes.color_cycle'] = ["#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"]#['k', 'b', 'g', 'r', 'c', 'm', 'y']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(figsize=(8,8))#facecolor=self.canvasColor, dpi=self.dpi)
        self.ax4 = self.fig.add_subplot(221) #stimulus
        self.ax1 = self.fig.add_subplot(222) #midpoint
        self.ax2 = self.fig.add_subplot(223) #slope
        self.ax3 = self.fig.add_subplot(224) #lapse

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
        self.ntb = NavigationToolbar(self.canvas, self.mw)
      

        self.logAxisMidpoint = QCheckBox(self.tr("Stim./Midpoint Log Axis"))
        self.logAxisMidpoint.stateChanged[int].connect(self.toggleMidpointLogAxis)

        self.logAxisSlope = QCheckBox(self.tr("Slope Log Axis"))
        self.logAxisSlope.stateChanged[int].connect(self.toggleSlopeLogAxis)

        self.logAxisLapse = QCheckBox(self.tr("Lapse Log Axis"))
        self.logAxisLapse.stateChanged[int].connect(self.toggleLapseLogAxis)

        self.updateButton = QPushButton(self.tr("Update"), self)
        self.updateButton.setIcon(QIcon.fromTheme("view-refresh", QIcon(":/view-refresh")))
        self.updateButton.clicked.connect(self.onClickUpdateButton)
        
        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.logAxisMidpoint)
        self.ntbBox.addWidget(self.logAxisSlope)
        self.ntbBox.addWidget(self.logAxisLapse)
        self.ntbBox.addWidget(self.updateButton)
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)

        self.getPSIPars()
        if self.stimScaling == "Linear":
            self.logAxisMidpoint.setChecked(False)
            self.plotDataMidpoint()
            self.plotDataStimulus()
        elif self.stimScaling == "Logarithmic":
            self.logAxisMidpoint.setChecked(True)
            self.plotDataMidpointLogAxis()
            self.plotDataStimulusLogAxis()

        if self.slopeSpacing == "Linear":
            self.logAxisSlope.setChecked(False)
            self.plotDataSlope()
        elif self.slopeSpacing == "Logarithmic":
            self.logAxisSlope.setChecked(True)
            self.plotDataSlopeLogAxis()

        if self.lapseSpacing == "Linear":
            self.logAxisLapse.setChecked(False)
            self.plotDataLapse()
        elif self.lapseSpacing == "Logarithmic":
            self.logAxisLapse.setChecked(True)
            self.plotDataLapseLogAxis()

        self.fig.suptitle(self.tr("PSI Parameter Space"))
        self.show()
        self.canvas.draw()
Beispiel #8
0
userLabels, conflicts = backgroundCollecting(userLabels, conflicts)
fracUserLabels = getUserLabelFraction(userLabels)
#counter = 0
#for val in userLabels:
#    if val != 0: counter += 1
print "Provided Labels: ", round(fracUserLabels, 3), " %"
propLabels = np.copy(userLabels)

# Calculate diffusion kernel
P, _ = diffusionKernel(X, eps=eps, knn=len(propLabels))

# Launch GUI app
app = QtGui.QApplication(sys.argv)
win = MainWindow()
fig = plt.figure()
canvas = FigureCanvas(fig)
canvas.setParent(win)
promptConflicts(conflicts)
if set(userLabels) != set([0] * len(userLabels)):
    fillProp()
    notLabeled()
ax = fig.add_subplot(111, projection='3d')
colors = [
    'red' if propLabels[idx] == 1 else 'green'
    if propLabels[idx] == 2 else 'blue' if propLabels[idx] == 3 else 'black'
    for idx, val in enumerate(X[:, 1])
]
ax.scatter(X[:, 0], X[:, 1], X[:, 2], color=colors, picker=5, alpha=0.1)
ax.set_xlabel('$\psi_1$')
ax.set_ylabel('$\psi_2$')
ax.set_zlabel('$\psi_3$')
    def initUI(self):
        # SET THE GEOMETRY

        mainWindow = QtGui.QVBoxLayout()
        mainWindow.setSpacing(15)

        fileBox = QtGui.QHBoxLayout()
        spaceBox1 = QtGui.QHBoxLayout()
        rawDataBox = QtGui.QHBoxLayout()

        mainWindow.addLayout(fileBox)
        mainWindow.addLayout(spaceBox1)
        mainWindow.addLayout(rawDataBox)

        Col1 = QtGui.QGridLayout()
        Col2 = QtGui.QHBoxLayout()
        Col3 = QtGui.QVBoxLayout()

        rawDataBox.addLayout(Col1)
        rawDataBox.addLayout(Col2)
        rawDataBox.addLayout(Col3)

        self.setLayout(mainWindow)

        # DEFINE ALL WIDGETS AND BUTTONS

        loadBtn = QtGui.QPushButton('Load DataSet')
        computeBtn = QtGui.QPushButton('Compute current image')
        computeBtn.setFixedWidth(200)
        self.computeAllBtn = QtGui.QPushButton(
            'Compute %s signal for all the images' % '???')
        self.computeAllBtn.setFixedWidth(200)
        saveBtn = QtGui.QPushButton('Save data (F12)')

        tpLbl = QtGui.QLabel('Relative Tp:')
        slLbl = QtGui.QLabel('Slice:')
        fNameLbl = QtGui.QLabel('File name:')
        gridLbl = QtGui.QLabel('Grid size:')

        self.tp = QtGui.QSpinBox(self)
        self.tp.setValue(-5)
        self.tp.setMaximum(100000)

        self.sl = QtGui.QSpinBox(self)
        self.sl.setValue(0)
        self.sl.setMaximum(100000)

        self.gridsize = QtGui.QSpinBox(self)
        self.gridsize.setValue(5)
        self.gridsize.setMaximum(20)

        self.fName = QtGui.QLabel('')

        self._488nmBtn = QtGui.QRadioButton('488nm')
        self._561nmBtn = QtGui.QRadioButton('561nm')
        self.CoolLEDBtn = QtGui.QRadioButton('CoolLED')

        self.sld1 = QtGui.QSlider(QtCore.Qt.Vertical, self)
        self.sld1.setMaximum(2**16 - 1)
        self.sld1.setValue(0)
        self.sld2 = QtGui.QSlider(QtCore.Qt.Vertical, self)
        self.sld2.setMaximum(2**16)
        self.sld2.setValue(2**16 - 1)

        self.fig1 = Figure((8.0, 8.0), dpi=100)
        self.fig1.subplots_adjust(left=0., right=1., top=1., bottom=0.)
        self.ax1 = self.fig1.add_subplot(111)
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.canvas1.setFocus()
        self.canvas1.setFixedSize(QtCore.QSize(600, 600))
        self.canvas1.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)

        self.fig2 = Figure((4.0, 4.0), dpi=100)
        self.fig2.subplots_adjust(left=0., right=1., top=1., bottom=0.)
        self.ax2 = self.fig2.add_subplot(111)
        self.canvas2 = FigureCanvas(self.fig2)
        self.canvas2.setFixedSize(QtCore.QSize(300, 300))
        self.canvas2.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)

        # PLACE ALL THE WIDGET ACCORDING TO THE GRIDS

        fileBox.addWidget(loadBtn)
        fileBox.addWidget(saveBtn)

        spaceBox1.addWidget(self.HLine())

        Col1.addWidget(tpLbl, 0, 0)  #, 1, 1, Qt.AlignTop)
        Col1.addWidget(self.tp, 0, 1)  #, 1, 1, Qt.AlignTop)
        Col1.addWidget(slLbl, 1, 0)  #, 1, 1, Qt.AlignTop)
        Col1.addWidget(self.sl, 1, 1)  #, 1, 1, Qt.AlignTop)
        Col1.addWidget(fNameLbl, 2, 0)
        Col1.addWidget(self.fName, 2, 1)
        Col1.addWidget(self._488nmBtn, 3, 0)
        Col1.addWidget(self._561nmBtn, 4, 0)
        Col1.addWidget(self.CoolLEDBtn, 5, 0)

        Col2.addWidget(self.sld1)
        Col2.addWidget(self.sld2)
        Col2.addWidget(self.canvas1)

        Col3.addWidget(self.canvas2)
        Col1.addWidget(gridLbl, 6, 0)
        Col1.addWidget(self.gridsize, 6, 1)
        Col1.addWidget(computeBtn, 7, 0)
        Col1.addWidget(self.computeAllBtn, 8, 0)

        self.setFocus()
        self.show()

        # BIND BUTTONS TO FUNCTIONS

        loadBtn.clicked.connect(self.selectWorm)
        saveBtn.clicked.connect(self.saveData)

        self.tp.valueChanged.connect(self.loadNewStack)
        self.sl.valueChanged.connect(self.updateAllCanvas)
        self.sld1.valueChanged.connect(self.updateBC)
        self.sld2.valueChanged.connect(self.updateBC)

        self._488nmBtn.toggled.connect(self.radio488Clicked)
        self._561nmBtn.toggled.connect(self.radio561Clicked)
        self.CoolLEDBtn.toggled.connect(self.radioCoolLEDClicked)

        computeBtn.clicked.connect(self.computeFluo)
        self.computeAllBtn.clicked.connect(self.computeAllFluo)

        self.fig1.canvas.mpl_connect('button_press_event',
                                     self.onMouseClickOnCanvas1)
        self.fig1.canvas.mpl_connect('scroll_event', self.wheelEvent)
Beispiel #10
0
    def initUI(self): 
        self.setGeometry(1200,800, 1800, 800)
        self.center()
        self.setWindowTitle('This f*cking GUI')     
        
        #Grid Layout-------------
        grid = QtGui.QGridLayout()
        self.setLayout(grid)
                    
        #Canvas and Toolbar--------------------
        self.figure,self.ax = plt.subplots(6,3,figsize=(1,1),sharex=True,sharey=True)   
        plt.ioff() #Avoid figure poping as extra window 
        self.canvas = FigureCanvas(self.figure)     
        self.toolbar = NavigationToolbar(self.canvas, self)
        grid.addWidget(self.canvas, 3,0,1,6)
        grid.addWidget(self.toolbar, 2,0,1,2)
        
        #Import File Button----------------------------------
        btn1 = QtGui.QPushButton('Import ePhy File (HdF5)...', self)
        btn1.resize(btn1.sizeHint()) 
        btn1.clicked.connect(self.getFile)
        grid.addWidget(btn1, 0,0)
        
        #Plot Button------------------------------
        btn2 = QtGui.QPushButton('Plot (P)', self)
        btn2.resize(btn2.sizeHint())    
        btn2.clicked.connect(self.plot)
        btn2.setShortcut("p")
        grid.addWidget(btn2, 0,1)
        
        #Sweep text----------------
        sweep_text = QtGui.QLabel()
        sweep_text.setText("Sweep #")
        grid.addWidget(sweep_text,0,2)
        
        #Sweep combo box----------------
        combobox = QtGui.QComboBox(self)
        grid.addWidget(combobox,0,3)
        sweep_list = np.arange(0,100,1).astype(str).tolist()
        combobox.addItems(sweep_list)
        combobox.activated.connect(self.combo_box_update)
        current_sweep = int(combobox.currentText()) #Used in functions later very important !!
        
        #Channel text -----------------
        channel_text = QtGui.QLabel()
        channel_text.setText("Channel select")
        grid.addWidget(channel_text,0,4)
        
        #Channel combo box-----------------
        ch_combobox = QtGui.QComboBox(self)
        grid.addWidget(ch_combobox,0,5)
        ch_list = np.arange(0,2,1).astype(str).tolist()
        ch_combobox.addItems(ch_list)
        ch_combobox.activated.connect(self.ch_box_update)
        current_ch = int(ch_combobox.currentText()) #Used in functions later very important !!

        
        #Previous sweep btn---------------------------------
        Prev_btn = QtGui.QPushButton('Previous (left)', self)
        Prev_btn.resize(Prev_btn.sizeHint())    
        Prev_btn.clicked.connect(self.previous_sweep)
        Prev_btn.setShortcut("Left")
        grid.addWidget(Prev_btn, 1,0)
          
        #Next sweep btn----------------------------------
        Next_btn = QtGui.QPushButton('Next (right)', self)
        Next_btn.resize(Next_btn.sizeHint())    
        Next_btn.clicked.connect(self.next_sweep)
        grid.addWidget(Next_btn, 1,1)
        Next_btn.setShortcut("Right")
        
        #Tag button-----------------------------------
        Tag_button = QtGui.QPushButton('Tag (up)',self)
        Tag_button.resize(Tag_button.sizeHint())
        Tag_button.clicked.connect(self.tag_this)
        grid.addWidget(Tag_button,1,2)
        Tag_button.setShortcut("Up")
    
        #UnTag button----------------------------------------
        UnTag_button = QtGui.QPushButton('UnTag (down)',self)
        UnTag_button.resize(UnTag_button.sizeHint())
        UnTag_button.clicked.connect(self.untag_this)
        grid.addWidget(UnTag_button,1,3)
        UnTag_button.setShortcut("Down")
        
        #Tag All button----------------------------------
        TagAll_button = QtGui.QPushButton('Tag All',self)
        TagAll_button.resize(TagAll_button.sizeHint())
        TagAll_button.clicked.connect(self.tag_all)
        grid.addWidget(TagAll_button,1,4)
        
        #UnTag All button------------------------------------
        UnTagAll_button = QtGui.QPushButton('UnTag All',self)
        UnTagAll_button.resize(UnTagAll_button.sizeHint())
        UnTagAll_button.clicked.connect(self.untag_all)
        grid.addWidget(UnTagAll_button,1,5)

                     
        #Uniform time toggle---------------------------------
        Set_Time_Toggle = QtGui.QCheckBox('Unify Time', self)
        Set_Time_Toggle.stateChanged.connect(self.unify_time)
        grid.addWidget(Set_Time_Toggle,2,3)
        self.time = 0 #Defaut time is conserved
        #Set_Time_Toggle.toggle()  #Uncomment if u want time to be set by default              
               
        #Leak Remove toggle--------------------------------
        LeakcheckBox = QtGui.QCheckBox('Remove Leak', self)
        LeakcheckBox.stateChanged.connect(self.leak_remove)
        grid.addWidget(LeakcheckBox,2,2)
        self.leak = 0 #Defaut is leak conserved 
        #LeakcheckBox.toggle()  #Uncomment if u want leak to be removed by default

        #Tag state------------------------------------------------------

        self.tag_text = QtGui.QLabel()
        self.tag_text.setText("---")
        grid.addWidget(self.tag_text,2,4)        
        
        #Tag List btn--------------------------------------
        TagList_Btn = QtGui.QPushButton('Tag List...',self)
        TagList_Btn.resize(TagList_Btn.sizeHint())
        TagList_Btn.clicked.connect(self.get_tag_list)
        grid.addWidget(TagList_Btn,2,5)
        
        #Average button--------------------------------------------------------
        self.Av_Btn = QtGui.QPushButton('Average...')
        self.Av_Btn.resize(self.Av_Btn.sizeHint())
        self.Av_Btn.clicked.connect(self.Average)
        grid.addWidget(self.Av_Btn,4,0)
        
        #Spike detection button 
        self.Spike_detection_btn = QtGui.QPushButton('Spike Detection...')
        self.Spike_detection_btn.resize(self.Spike_detection_btn.sizeHint())
        self.Spike_detection_btn.clicked.connect(self.Spike_detect)
        grid.addWidget(self.Spike_detection_btn,4,1)
            
        
        self.file = np.ones((10,10,2)) #Default file before any load 
    
        self.show()
    def __init__(self):
        super(Traitement_img, self).__init__()

        #---- La figure ou se place les images -----------
        self.figure = plt.figure()
        self.cluster = 3

        self.canvas = FigureCanvas(self.figure)
        self.filename = None
        self.img = None

        #------ Les Boutons conecte avec sa fonction ------------
        self.label = QtGui.QLabel("Kmeans!")
        self.labell = QtGui.QPushButton("Choose number of cluster Kmeans!")
        self.labell.clicked.connect(self.openInputDialog)
        self.browse = QtGui.QPushButton('Parcourir')
        self.browse.clicked.connect(self.browse_on)
        self.hsi = QtGui.QPushButton('Chromaticite HSI')
        self.hsi.clicked.connect(self.calculate_HSI)
        self.hsd = QtGui.QPushButton('Chromaticite HSD')
        self.hsd.clicked.connect(self.calculate_HSD)
        #self.to_rotate = QtGui.QPushButton('Kmeans')
        #self.to_rotate.clicked.connect(self.openInputDialog)
        self.cluster = QtGui.QLineEdit('3')
        self.od = QtGui.QPushButton('Espace OD')
        self.od.clicked.connect(self.ODSpace)
        self.deconvolution = QtGui.QPushButton('Color deconvolution')
        self.deconvolution.clicked.connect(self.colorDeconvolution)
        self.reconstruction = QtGui.QPushButton('Image HSI')
        self.reconstruction.clicked.connect(self.reconstructionToRGB)
        self.reconstructionHSD = QtGui.QPushButton('Image HSD')
        self.reconstructionHSD.clicked.connect(self.reconstructionToRGBHSD)

        self.normeL = QtGui.QPushButton('Espace de representation normeL1')
        self.normeL.clicked.connect(self.normeL1)

        self.DigitalComplet = QtGui.QPushButton(
            'Espace de representation passageAuCubeDigitalComplet')
        self.DigitalComplet.clicked.connect(self.CubeDigitalComplet)

        self.norme = QtGui.QPushButton(
            'Espace de representation norme max-min')
        self.norme.clicked.connect(self.maxmin)
        #---rotation layout------
        rot = QtGui.QHBoxLayout()
        #rot.addWidget(self.label)
        #rot.addWidget(self.cluster)
        rot.addWidget(self.labell)

        #----Bouton Layout_____
        lbo = QtGui.QVBoxLayout()
        lbo.addWidget(self.browse)
        lbo.addWidget(self.hsi)
        lbo.addWidget(self.hsd)
        lbo.addLayout(rot)
        lbo.addWidget(self.reconstruction)
        lbo.addWidget(self.reconstructionHSD)
        lbo.addWidget(self.od)
        lbo.addWidget(self.deconvolution)
        lbo.addWidget(self.normeL)
        lbo.addWidget(self.DigitalComplet)
        lbo.addWidget(self.norme)

        #------- Le Layout Principal -----
        layout = QtGui.QGridLayout()
        layout.addWidget(self.canvas, 0, 0, 5, 5)

        layout.addLayout(lbo, 0, 5)

        #---------------------------
        self.setLayout(layout)

        self.setWindowTitle(u'Traitement d\'image')
        self.show()
Beispiel #12
0
    def __init__(self):
        print("to je tale ja")
        super().__init__()
        self.stats = []
        self.dataset = None
        self.categories = []
        self.file_names = []
        self.tmp_file_names = []

        gui.listBox(self.controlArea,
                    self,
                    'categories_settings',
                    labels='categories',
                    box='Choose category',
                    selectionMode=QListWidget.ExtendedSelection,
                    callback=self.category_changed)

        gui.listBox(self.controlArea,
                    self,
                    'file_names_settings',
                    labels='file_names',
                    box='File names',
                    selectionMode=QListWidget.ExtendedSelection,
                    callback=self.file_changed)

        parameters_box = gui.widgetBox(self.controlArea, 'Parameters')

        self.nfft_spin = gui.spin(parameters_box,
                                  self,
                                  "nfft",
                                  minv=1,
                                  maxv=10000,
                                  controlWidth=80,
                                  alignment=Qt.AlignRight,
                                  label="NFFT: ")
        self.noverlap_spin = gui.spin(parameters_box,
                                      self,
                                      "noverlap",
                                      minv=1,
                                      maxv=10000,
                                      controlWidth=80,
                                      alignment=Qt.AlignRight,
                                      label="Noverlap: ")
        self.scale_combo = gui.comboBox(parameters_box,
                                        self,
                                        "scale_id",
                                        orientation=Qt.Horizontal,
                                        label="Scale type: ",
                                        items=[m for m in scale])
        self.mode_combo = gui.comboBox(parameters_box,
                                       self,
                                       "mode_id",
                                       orientation=Qt.Horizontal,
                                       label="Mode type: ",
                                       items=[m for m in mode])

        self.export_png_button = gui.button(
            self.controlArea,
            self,
            "Export to png",
            callback=lambda: self.export_to_png())

        self.figure = plt.figure()
        self.figure.patch.set_facecolor('white')

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        policy = QtGui.QSizePolicy()
        policy.setHorizontalStretch(100)

        gui.vBox(self.mainArea, addSpace=True, sizePolicy=policy)

        self.mainArea.layout().addWidget(self.toolbar)
        self.mainArea.layout().addWidget(self.canvas)

        self.mainArea.setMinimumWidth(600)
Beispiel #13
0
    def __init__(self, parent=None):
        qg.QFrame.__init__(self, parent)

        # bgrgb = self.palette().color(qg.QPalette.Window).getRgb()[:3]
        fgcolor = plot.tango_colors['aluminium5']
        dpi = 0.5 * (self.logicalDpiX() + self.logicalDpiY())

        font = qg.QFont()
        font.setBold(True)
        fontsize = font.pointSize()

        import matplotlib
        matplotlib.rcdefaults()
        matplotlib.rc('xtick', direction='out', labelsize=fontsize)
        matplotlib.rc('ytick', direction='out', labelsize=fontsize)
        matplotlib.rc('xtick.major', size=8)
        matplotlib.rc('xtick.minor', size=4)
        matplotlib.rc('ytick.major', size=8)
        matplotlib.rc('ytick.minor', size=4)
        # matplotlib.rc(
        #     'figure', facecolor=tohex(bgrgb), edgecolor=tohex(fgcolor))
        matplotlib.rc('figure', facecolor='white', edgecolor=tohex(fgcolor))
        matplotlib.rc('font',
                      family='sans-serif',
                      weight='bold',
                      size=fontsize,
                      **{'sans-serif': [font.family()]})
        matplotlib.rc('text', color=tohex(fgcolor))
        matplotlib.rc('xtick', color=tohex(fgcolor))
        matplotlib.rc('ytick', color=tohex(fgcolor))
        matplotlib.rc('figure.subplot', bottom=0.15)

        matplotlib.rc('axes', linewidth=0.5, unicode_minus=False)
        matplotlib.rc('axes',
                      facecolor='white',
                      edgecolor=tohex(fgcolor),
                      labelcolor=tohex(fgcolor))

        try:
            matplotlib.rc('axes',
                          color_cycle=[to01(x) for x in plot.graph_colors])

        except KeyError:
            pass

        try:
            matplotlib.rc('axes', labelsize=fontsize)
        except KeyError:
            pass

        try:
            matplotlib.rc('axes', labelweight='bold')
        except KeyError:
            pass

        from matplotlib.figure import Figure
        try:
            from matplotlib.backends.backend_qt4agg import \
                NavigationToolbar2QTAgg as NavigationToolbar
        except:
            from matplotlib.backends.backend_qt4agg import \
                NavigationToolbar2QT as NavigationToolbar

        from matplotlib.backends.backend_qt4agg \
            import FigureCanvasQTAgg as FigureCanvas

        layout = qg.QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self.setLayout(layout)
        self.figure = Figure(dpi=dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        layout.addWidget(self.toolbar, 0, 0)
        layout.addWidget(self.canvas, 1, 0)
        self.closed = False
Beispiel #14
0
    def __init__(self):
        self.filters = list()
        super(CalibrationViewer, self).__init__()
        self.setWindowTitle('Olfa Calibration')
        self.statusBar()
        self.trial_selected_list = []
        self.trialsChanged.connect(self._trial_selection_changed)

        mainwidget = QtGui.QWidget(self)
        self.setCentralWidget(mainwidget)
        layout = QtGui.QGridLayout(mainwidget)
        mainwidget.setLayout(layout)

        menu = self.menuBar()
        filemenu = menu.addMenu("&File")
        toolsmenu = menu.addMenu("&Tools")

        openAction = QtGui.QAction("&Open recording...", self)
        openAction.triggered.connect(self._openAction_triggered)
        openAction.setStatusTip("Open a HDF5 data file with calibration recording.")
        openAction.setShortcut("Ctrl+O")
        filemenu.addAction(openAction)
        saveFigsAction = QtGui.QAction('&Save figures...', self)
        saveFigsAction.triggered.connect(self._saveFiguresAction_triggered)
        saveFigsAction.setShortcut('Ctrl+S')
        openAction.setStatusTip("Saves current figures.")
        filemenu.addAction(saveFigsAction)
        exitAction = QtGui.QAction("&Quit", self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.setStatusTip("Quit program.")
        exitAction.triggered.connect(QtGui.qApp.quit)
        filemenu.addAction(exitAction)
        removeTrialAction = QtGui.QAction("&Remove trials", self)
        removeTrialAction.setStatusTip('Permanently removes selected trials (bad trials) from trial list.')
        removeTrialAction.triggered.connect(self._remove_trials)
        removeTrialAction.setShortcut('Ctrl+R')
        toolsmenu.addAction(removeTrialAction)

        trial_group_list_box = QtGui.QGroupBox()
        trial_group_list_box.setTitle('Trial Groups')
        self.trial_group_list = TrialGroupListWidget()
        trial_group_layout = QtGui.QVBoxLayout()
        trial_group_list_box.setLayout(trial_group_layout)
        trial_group_layout.addWidget(self.trial_group_list)
        layout.addWidget(trial_group_list_box, 0, 0)
        self.trial_group_list.itemSelectionChanged.connect(self._trial_group_selection_changed)

        trial_select_list_box = QtGui.QGroupBox()
        trial_select_list_box.setMouseTracking(True)
        trial_select_list_layout = QtGui.QVBoxLayout()
        trial_select_list_box.setLayout(trial_select_list_layout)
        trial_select_list_box.setTitle('Trials')
        self.trial_select_list = TrialListWidget()
        self.trial_select_list.setMouseTracking(True)
        trial_select_list_layout.addWidget(self.trial_select_list)
        self.trial_select_list.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.trial_select_list.itemSelectionChanged.connect(self._trial_selection_changed)
        layout.addWidget(trial_select_list_box, 0, 1)
        self.trial_select_list.createGroupSig.connect(self.trial_group_list.create_group)

        filters_box = QtGui.QGroupBox("Trial filters.")
        filters_box_layout = QtGui.QVBoxLayout(filters_box)
        filters_scroll_area = QtGui.QScrollArea()
        filters_buttons = QtGui.QHBoxLayout()
        filters_all = QtGui.QPushButton('Select all', self)
        filters_all.clicked.connect(self._select_all_filters)
        filters_none = QtGui.QPushButton('Select none', self)
        filters_none.clicked.connect(self._select_none_filters)
        filters_buttons.addWidget(filters_all)
        filters_buttons.addWidget(filters_none)
        filters_box_layout.addLayout(filters_buttons)
        filters_box_layout.addWidget(filters_scroll_area)
        filters_wid = QtGui.QWidget()
        filters_scroll_area.setWidget(filters_wid)
        filters_scroll_area.setWidgetResizable(True)
        filters_scroll_area.setFixedWidth(300)
        self.filters_layout = QtGui.QVBoxLayout()
        filters_wid.setLayout(self.filters_layout)
        layout.addWidget(filters_box, 0, 2)

        plots_box = QtGui.QGroupBox()
        plots_box.setTitle('Plots')
        plots_layout = QtGui.QHBoxLayout()

        self.figure = Figure((9, 5))
        self.figure.patch.set_facecolor('None')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(plots_box)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        plots_layout.addWidget(self.canvas)
        plots_box.setLayout(plots_layout)
        layout.addWidget(plots_box, 0, 3)
        self.ax_pid = self.figure.add_subplot(2, 1, 1)
        self.ax_pid.set_title('PID traces')
        self.ax_pid.set_ylabel('')
        self.ax_pid.set_xlabel('t (ms)')
        # self.ax_pid.set_yscale('log')
        self.ax_mean_plots = self.figure.add_subplot(2, 1, 2)
        self.ax_mean_plots.set_title('Mean value')
        self.ax_mean_plots.set_ylabel('value')
        self.ax_mean_plots.set_xlabel('Concentration')
        self.ax_mean_plots.autoscale(enable=True, axis=u'both', tight=False)
        self.figure.tight_layout()
Beispiel #15
0
    def initGui( self ):
        dsHandle = self.dsHandle

        varTup = yield dsHandle( 'variables' )
        xVars, yVars = [ [ var[0] for var in indOrDep ] for indOrDep in varTup ]
        self.xData = numpy.array( [] ).reshape( 0, len( xVars ) )
        self.yData = numpy.array( [] ).reshape( 0, len( yVars ) )

        config = self.configDialog = ConfigDialog( self, xVars, yVars, dsHandle )
        config.axesChanged.connect( self.newPlotData )
        config.setModal( True )

        params = yield dsHandle( 'get parameters' )
        params = dict( params ) if params is not None else {}
        xConfig, yConfigs = params.get( XPLOT ), params.get( YPLOT )

        def parseAxis( config, sympyVars ):
            if type( config ) is int and config < len( sympyVars ):
                return config
            if type( config ) is tuple:
                foo = getSympyFunc( config[1], sympyVars )
                if foo:
                    return foo
            return None

        listView = config.xList.listView
        tmpSelectionMode = listView.selectionMode()
        listView.setSelectionMode( listView.MultiSelection )
        tmp = parseAxis( xConfig, config.xList.sympyVars )
        if tmp is None: tmp = 0
        if type( tmp ) is int:
            listView.setCurrentIndex( listView.model().index( tmp, 0, QtCore.QModelIndex() ) )
        if callable( tmp ):
            count = listView.model().rowCount()
            listView.model().addAxis( Map( xConfig[0], tmp, xConfig[1] ) )
            listView.setCurrentIndex( listView.model().index( count, 0, QtCore.QModelIndex() ) )
        listView.setSelectionMode( tmpSelectionMode )

        listView = config.yList.listView
        tmpSelectionMode = listView.selectionMode()
        listView.setSelectionMode( listView.MultiSelection )
        if yConfigs is not None:
            for yConfig in yConfigs:
                tmp = parseAxis( yConfig, config.yList.sympyVars )
                if tmp is not None:
                    if type( tmp ) is int:
                        listView.setCurrentIndex( listView.model().index( int, 0, QtCore.QModelIndex() ) )
                    if callable( tmp ):
                        count = listView.model().rowCount()
                        listView.model().addAxis( Map( yConfig[0], tmp, yConfig[1] ) )
                        listView.setCurrentIndex( listView.model().index( count, 0, QtCore.QModelIndex() ) )
        if not listView.selectedIndexes():
            listView.setCurrentIndex( listView.model().index( 0, 0, QtCore.QModelIndex() ) )
        listView.setSelectionMode( tmpSelectionMode )

        self.xPlot = []
        self.yPlotModel = YPlotModel( self )
        self.fitDialog = FitDialog( self.yPlotModel, self )

        self.fig = Figure( ( 5.0, 4.0 ), dpi = 100 )
        self.canvas = FigureCanvas( self.fig )
        self.canvas.setParent( self )
        self.axes = self.fig.add_subplot( 111 )
        mpl_toolbar = NavigationToolbar( self.canvas, self )
        mpl_toolbar.addAction( QtGui.QIcon( 'icons/fit.svg' ), 'Fit Data', self.fitData ).setToolTip( 'Fit curve to data' )
        mpl_toolbar.addAction( QtGui.QIcon( 'icons/removefit.svg' ), 'Remove Fit', self.removeFit ).setToolTip( 'Remove current fit' )
        self.layout().addWidget( self.canvas, 1 )
        self.layout().addWidget( mpl_toolbar )

        editRow = QtGui.QWidget( self )
        editRow.setLayout( QtGui.QHBoxLayout() )

        rangeMin = self.rangeMin = self.RangeAdjuster( self )
        rangeMax = self.rangeMax = self.RangeAdjuster( self )
        sliderMin, checkMin = rangeMin.slider, rangeMin.checkBox
        sliderMax, checkMax = rangeMax.slider, rangeMax.checkBox
        checkMin.setText( 'Anchor min' )
        checkMax.setText( 'Anchor max' )
        sliderMin.valueChanged.connect( sliderMax.setMinimum )
        sliderMax.valueChanged.connect( sliderMin.setMaximum )
        sliderMin.valueChanged.connect( lambda min: self.updateRange( 'min', min ) )
        sliderMax.valueChanged.connect( lambda max: self.updateRange( 'max', max ) )
        self.lengthChanged.connect( lambda length: sliderMax.setMaximum( length ) if not checkMax.isChecked() else None )
        self.lengthChanged.connect( lambda length: sliderMax.setValue( length ) if self.following else None )
        self.lengthChanged.connect( lambda length: sliderMin.setValue( length - self._tail ) if self.following else None )
        checkMin.toggled.connect( lambda checked: sliderMin.setMinimum( sliderMin.value() ) if checked else sliderMin.setMinimum( 0 ) )
        checkMax.toggled.connect( lambda checked: sliderMax.setMaximum( sliderMax.value() ) if checked else sliderMax.setMaximum( self.length ) )

        editRow.layout().addWidget( rangeMin )
        editRow.layout().addWidget( rangeMax )

        following = QtGui.QCheckBox( 'Following', self )
        following.setChecked( False )
        following.toggled.connect( self.followingStateChange )
        tail = self.tail = QtGui.QSpinBox( self )
        tail.setMinimum( 0 )
        tail.setMaximum( 0 )
        tail.valueChanged.connect( self.tailChanged )
        self.lengthChanged.connect( tail.setMaximum )
        editRow.layout().addWidget( following )
        editRow.layout().addWidget( tail )

        editRow.layout().addStretch()

        xVarBox = self.xVarBox = QtGui.QComboBox( self )
        yVarBox = self.yVarBox = QtGui.QComboBox( self )

        editRow.layout().addWidget( xVarBox )
        editRow.layout().addWidget( yVarBox )

        configure = QtGui.QPushButton( "Configure", self )
        configure.clicked.connect( self.configurePlot )
        editRow.layout().addWidget( configure )
        self.layout().addWidget( editRow )

        self.xVarBox.setModel( self.configDialog.xList.listView.model() )
        self.yVarBox.setModel( self.configDialog.yList.listView.model() )

        self.xVarBox.activated.connect( lambda row: self.configDialog.xList.listView.setCurrentIndex( self.configDialog.xList.listView.model().index( row, 0, QtCore.QModelIndex() ) ) )
        self.xVarBox.activated.connect( lambda index: self.newPlotData() )
        self.yVarBox.activated.connect( lambda row: self.configDialog.yList.listView.setCurrentIndex( self.configDialog.yList.listView.model().index( row, 0, QtCore.QModelIndex() ) ) )
        self.yVarBox.activated.connect( lambda index: self.newPlotData() )

        self.newPlotData()
        yield self.newData()
        sliderMax.setValue( self.length )
        newData = getID()
        yield dsHandle( 'signal: data available', newData )
        dsHandle.addListener( lambda msgCon, null: self.newData(), newData )
Beispiel #16
0
	def refresh(self):

		Thresh = 0
		
		tSeek1 = self.tSeek1
		mini = 0
		maxi = 200
	
		self.fig = plt.figure(figsize=(10,6))
		
		self.canvas = FigureCanvas(self.fig)
		self.canvas.setParent(self.main_frame)
		
		ax = self.fig.add_subplot(1, 1, 1)

		cell_index = self.cell_flag.index(1)
		feat_index = self.feat_flag.index(1)
		
		if cell_index == 0:
			cell_key = 'E1'
			plot_title = 'Effector Cell 1 Feature Time Series'
			Thresh = self.EDInt
			try:
				feat_data = self.E[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell E1 or No given features"

		if cell_index == 1:
			cell_key = 'E2'
			plot_title = 'Effector Cell 2 Feature Time Series'
			Thresh = self.EDInt
			try:
				feat_data = self.E[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell E2 or No given features"
				

		if cell_index == 2:
			cell_key = 'E3'
			plot_title = 'Effector Cell 3 Feature Time Series'
			Thresh = self.EDInt
			try:
				feat_data = self.E[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)			
			except:
				print "No cell E3 or No given features"

		if cell_index == 3:
			cell_key = 'E4'
			plot_title = 'Effector Cell 4 Feature Time Series'
			Thresh = self.EDInt
			try:
				feat_data = self.E[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell E4 or No given features"
		

		if cell_index == 4:
			cell_key = 'T1'
			plot_title = 'Target Cell 1 Feature Time Series'
			Thresh = self.DInt
			try:
				feat_data = self.T[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell T1 or No given features"

		if cell_index == 5:
			cell_key = 'T2'
			plot_title = 'Target Cell 2 Feature Time Series'
			Thresh = self.DInt
			try:
				feat_data = self.T[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell T2 or No given features"
				

		if cell_index == 6:
			cell_key = 'T3'
			plot_title = 'Target Cell 3 Feature Time Series'
			Thresh = self.DInt
			try:
				feat_data = self.T[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell T3 or No given features"

		if cell_index == 7:
			cell_key = 'T4'
			plot_title = 'Target Cell 4 Feature Time Series'
			Thresh = self.DInt
			try:
				feat_data = self.T[cell_key][feat_index]
				mini = min(feat_data)
				maxi = max(feat_data)
			except:
				print "No cell T4 or No given features"
				
		if feat_index == 0:
			y_label = 'Position X'

		if feat_index == 1:
			y_label = 'Position Y'

		if feat_index == 2:
			y_label = 'Aspect Ratio'

		if feat_index == 3:
			y_label = 'Speed'

		if feat_index == 4:
			y_label = 'Death Marker'

		if feat_index == 5:
			y_label = 'Contact Ratio'
			

		try:
			plt.plot(feat_data)
			plt.plot(feat_data,'ro')
			
			# plot contact line
			if tSeek1>0 and tSeek1<self.t_span:
				plt.plot((tSeek1,tSeek1),(int(mini*0.95),int(maxi*1.05)),'r-')
			
			# plot deathmarker threshold
			if feat_index == 4:
				plt.plot((0,80),(Thresh,Thresh),'r-')
			
			plt.xlabel('Time')
			plt.ylabel(y_label)
			plt.title(plot_title)
		except:
			print "Can't Plot Time Series Left!"
Beispiel #17
0
 def initCanvas(self):
     self.figure = plt.figure()
     self.canvas = FigureCanvas(self.figure)
     self.verticalLayout.addWidget(self.canvas)
Beispiel #18
0
 def __init__(self, parent):
     self.figure = plt.figure(facecolor='white')
     self.canvas = FigureCanvas(self.figure)
     self.toolbar = NavigationToolbar(self.canvas, parent)
Beispiel #19
0
 def __init__(self):
     if mpl is None:
         load_matplotlib()
     self.fig = Figure(tight_layout=True, frameon=False)
     self.canvas = FigureCanvas(self.fig)
Beispiel #20
0
    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        self.textbox = QLineEdit()
        self.textbox.setMinimumWidth(200)
        self.connect(self.textbox, SIGNAL('editingFinished ()'), self.on_draw)

        self.draw_button = QPushButton("&Draw")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.on_draw)

        self.grid_cb = QCheckBox("Show &Grid")
        self.grid_cb.setChecked(False)
        self.connect(self.grid_cb, SIGNAL('stateChanged(int)'), self.on_draw)

        slider_label = QLabel('Bar width (%):')
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(1, 100)
        self.slider.setValue(20)
        self.slider.setTracking(True)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.connect(self.slider, SIGNAL('valueChanged(int)'), self.on_draw)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [
                self.textbox, self.draw_button, self.grid_cb, slider_label,
                self.slider
        ]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignVCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)
Beispiel #21
0
    def __init__(self,
                 parent=None,
                 toolbar=False,
                 tight_layout=True,
                 autofocus=False,
                 background_hack=True,
                 **kwargs):
        """
        A widget to contain a matplotlib figure.

        :param autofocus: [optional]
            If set to `True`, the figure will be in focus when the mouse hovers
            over it so that keyboard shortcuts/matplotlib events can be used.

        Methods for zooming:
        axis_right_mouse_press: call for MPLWidget.mpl_connect("button_press_event")
        update_zoom_box: connect to MPLWidget.mpl_connect("motion_notify_event")
                         MPLWidget.mpl_disconnect as needed
        axis_right_mouse_release: call for MPLWidget.mpl_connect("button_release_event")
        unzoom_on_z_press: MPLWidget.mpl_connect("key_press_event")
        reset_zoom_limits(ax): call whenever you reset limits on an axis and want it to be zoomable
        """
        super(MPLWidget, self).__init__(Figure())

        self.figure = Figure(tight_layout=tight_layout)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Focus the canvas initially.
        self.canvas.setFocusPolicy(QtCore.Qt.WheelFocus)
        self.canvas.setFocus()

        self.toolbar = None  #if not toolbar else NavigationToolbar(self, parent)

        # Get background of parent widget.

        # Because all these figures will be in a tab, we need to get the color
        # right. It seems impossible to get the *actual* color of the parent
        # background when the widget is in a tab, but it seems it is just 10
        # points darker.
        #if background_hack is not None:
        #    bg_color = [(_ - 10)/255. for _ in \
        #        parent.palette().color(QtGui.QPalette.Window).getRgb()[:3]]
        #    background_hack.figure.patch.set_facecolor(bg_color)

        if background_hack:
            self.figure.patch.set_facecolor([(_ - 10)/255. for _ in \
                self.palette().color(QtGui.QPalette.Window).getRgb()[:3]])

        if autofocus:
            self._autofocus_cid = self.canvas.mpl_connect(
                "figure_enter_event", self._focus)

        # State for zoom box
        self._right_click_zoom_box = {}

        # State for shift. (Antimasks)
        self.shift_key_pressed = False

        # State for space. (Pan)
        self.space_key_pressed = False
Beispiel #22
0
    def initialize(self):
        self.fusion=Fusion()
        self.frame=0
        self.obs=[]
        self.hmm=HMM_Classification()
        modelFileName = 'HMM/hmm_train.npy'
        self.hmm_models = np.load(modelFileName).item()
        self.names = ['Cumuliform0','Cumuliform1','Cumuliform2','Cumuliform3','Cumuliform4']
        self.alphas={}

        self.obs_group=QWidget(self)
        self.obs_group_layout=QVBoxLayout()
        self.obs_group.setLayout(self.obs_group_layout)
        obs_label=QLabel("Human Observations")
        obs_label.setAlignment(Qt.AlignCenter)
        self.obs_group_layout.addWidget(obs_label)

        self.layoutStratiform = QHBoxLayout()
        self.widgetStratiform = QWidget(self)
        self.widgetStratiform.setLayout(self.layoutStratiform)
        self.obs_group_layout.addWidget(self.widgetStratiform)
        self.layoutStratiform.addWidget(QWidget())
        self.lStratiform = QLabel('Genus 0:')
        self.layoutStratiform.addWidget(self.lStratiform)
        self.stratiformGroup = QButtonGroup(self.widgetStratiform)
        self.rStratiformYes = QRadioButton('Yes')
        self.stratiformGroup.addButton(self.rStratiformYes)
        self.rStratiformNo = QRadioButton('No')
        self.stratiformGroup.addButton(self.rStratiformNo)
        self.layoutStratiform.addWidget(self.rStratiformYes)
        self.layoutStratiform.addWidget(self.rStratiformNo)
        self.layoutStratiform.addWidget(QWidget())

        self.layoutCirriform = QHBoxLayout()
        self.widgetCirriform = QWidget(self)
        self.widgetCirriform.setLayout(self.layoutCirriform)
        self.obs_group_layout.addWidget(self.widgetCirriform)
        self.layoutCirriform.addWidget(QWidget())
        self.lCirriform = QLabel('Genus 1:')
        self.layoutCirriform.addWidget(self.lCirriform)
        self.CirriformGroup = QButtonGroup(self.widgetCirriform)
        self.rCirriformYes = QRadioButton('Yes')
        self.CirriformGroup.addButton(self.rCirriformYes)
        self.rCirriformNo = QRadioButton('No')
        self.CirriformGroup.addButton(self.rCirriformNo)
        self.layoutCirriform.addWidget(self.rCirriformYes)
        self.layoutCirriform.addWidget(self.rCirriformNo)
        self.layoutCirriform.addWidget(QWidget())

        self.layoutStratoCumuliform = QHBoxLayout()
        self.widgetStratoCumuliform = QWidget(self)
        self.widgetStratoCumuliform.setLayout(self.layoutStratoCumuliform)
        self.obs_group_layout.addWidget(self.widgetStratoCumuliform)
        self.layoutStratoCumuliform.addWidget(QWidget())
        self.lStratoCumuliform = QLabel('Genus 2:')
        self.layoutStratoCumuliform.addWidget(self.lStratoCumuliform)
        self.StratoCumuliformGroup = QButtonGroup(self.widgetStratoCumuliform)
        self.rStratoCumuliformYes = QRadioButton('Yes')
        self.StratoCumuliformGroup.addButton(self.rStratoCumuliformYes)
        self.rStratoCumuliformNo = QRadioButton('No')
        self.StratoCumuliformGroup.addButton(self.rStratoCumuliformNo)
        self.layoutStratoCumuliform.addWidget(self.rStratoCumuliformYes)
        self.layoutStratoCumuliform.addWidget(self.rStratoCumuliformNo)
        self.layoutStratoCumuliform.addWidget(QWidget())

        self.layoutCumuliform = QHBoxLayout()
        self.widgetCumuliform = QWidget(self)
        self.widgetCumuliform.setLayout(self.layoutCumuliform)
        self.obs_group_layout.addWidget(self.widgetCumuliform)
        self.layoutCumuliform.addWidget(QWidget())
        self.lCumuliform = QLabel('Genus 3:')
        self.layoutCumuliform.addWidget(self.lCumuliform)
        self.CumuliformGroup = QButtonGroup(self.widgetCumuliform)
        self.rCumuliformYes = QRadioButton('Yes')
        self.CumuliformGroup.addButton(self.rCumuliformYes)
        self.rCumuliformNo = QRadioButton('No')
        self.CumuliformGroup.addButton(self.rCumuliformNo)
        self.layoutCumuliform.addWidget(self.rCumuliformYes)
        self.layoutCumuliform.addWidget(self.rCumuliformNo)
        self.layoutCumuliform.addWidget(QWidget())

        self.layoutCumulonibiform = QHBoxLayout()
        self.widgetCumulonibiform = QWidget(self)
        self.widgetCumulonibiform.setLayout(self.layoutCumulonibiform)
        self.obs_group_layout.addWidget(self.widgetCumulonibiform)
        self.layoutCumulonibiform.addWidget(QWidget())
        self.lCumulonibiform = QLabel('Genus 4:')
        self.layoutCumulonibiform.addWidget(self.lCumulonibiform)
        self.CumulonibiformGroup = QButtonGroup(self.widgetCumulonibiform)
        self.rCumulonibiformYes = QRadioButton('Yes')
        self.CumulonibiformGroup.addButton(self.rCumulonibiformYes)
        self.rCumulonibiformNo = QRadioButton('No')
        self.CumulonibiformGroup.addButton(self.rCumulonibiformNo)
        self.layoutCumulonibiform.addWidget(self.rCumulonibiformYes)
        self.layoutCumulonibiform.addWidget(self.rCumulonibiformNo)
        self.layoutCumulonibiform.addWidget(QWidget())


        self.layoutspacing = QHBoxLayout()
        self.updateContainer=QWidget()
        self.updateContainer.setLayout(self.layoutspacing)
        self.layoutspacing.addWidget(QWidget())

        self.updatebutton=QPushButton("Update",self)
        #  self.updatebutton.setFixedWidth(100)
        self.layoutspacing.addWidget(self.updatebutton)
        self.layoutspacing.addWidget(QWidget())
        self.obs_group_layout.addWidget(self.updateContainer)
        self.obs_group_layout.addWidget(QWidget())
        self.obs_group_layout.addWidget(QWidget())
        self.obs_group_layout.addWidget(QWidget())
        self.layout.addWidget(self.obs_group,1,1)


        # Probability graph
        self.figure_prob=Figure()
        self.probability=FigureCanvas(self.figure_prob)
        self.prob_ax=self.probability.figure.subplots()
        names = ['Cumuliform0','Cumuliform1','Cumuliform2','Cumuliform3','Cumuliform4']
        self.graph_names=['0','Genus0','Genus1','Genus2','Genus3','Genus4',]
        self.fusion.probs={}
        for i in names:
            self.alphas[i]=[-1,-1]
            self.fusion.probs[i]=.2
            #  self.probs[i]=np.random.uniform()
        for i in names:
            self.fusion.probs[i]/=sum(self.fusion.probs.values())
        self.prob_ax.bar(range(5),self.fusion.probs.values())
        self.prob_ax.set_ylim(0,1)
        self.prob_ax.set_ylabel('Probability')
        self.prob_ax.set_xticklabels(self.graph_names)
        self.prob_ax.figure.canvas.draw()
        self.layout.addWidget(self.probability,1,0)
        
        # Intensity and Data on same tab
        self.tabs_top=QTabWidget(self)

        # Intensity graph
        self.figure_int=Figure()
        self.intensity=FigureCanvas(self.figure_int)
        self.int_ax=self.intensity.figure.subplots()
        self.intensity_data=self.get_intensity()
        self.int_ax.plot([0],self.intensity_data[0])
        self.int_ax.set_ylim(0,np.max(self.intensity_data)+1)
        self.int_ax.set_xlabel('Time Steps')
        self.figure_int.tight_layout()
        self.int_ax.figure.canvas.draw()
        self.tabs_top.addTab(self.intensity,'Intensity')

        self.reference=QLabel(self)
        self.reference.setPixmap(QPixmap('data_clean.png'))
        self.tabs_top.addTab(self.reference,'Reference')
        self.layout.addWidget(self.tabs_top,0,1)

        # Satellite image
        self.figure_sat=Figure()
        self.satellite=FigureCanvas(self.figure_sat)
        self.sat_ax=self.satellite.figure.subplots()
        self.satellite_data=self.make_some_data()
        self.maxsig=np.amax(self.satellite_data)
        self.sat_ax.imshow(self.satellite_data[0],vmax=self.maxsig,cmap='Greys_r')
        self.sat_ax.axis('off')
        self.sat_ax.figure.canvas.draw()
        self.layout.addWidget(self.satellite,0,0)


        self.table=self.fusion.DirPrior(5)
        self.give_advice=np.random.choice([1,0],p=[0.30,0.70])
        self.help=False

        self.updatebutton.clicked.connect(self.getObs)
        if self.type=='tied':
            self.updatebutton.clicked.connect(lambda: self.fusion.moment_matching(self.obs))
        elif self.tpye=='full':
            self.updatebutton.clicked.connect(lambda: self.fusion.moment_matching_full(self.obs))
        elif self.type=='ind':
            pass
        self.updatebutton.clicked.connect(self.reset)
 def addmpl2(self, fig):
     self.canvas2 = FigureCanvas(fig)
     self.mplvl2.addWidget(self.canvas2)
     self.canvas2.draw()
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(1150, 655)
        MainWindow.setMinimumSize(QtCore.QSize(1500, 250))
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.pushButton_2 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_2.setMinimumSize(QtCore.QSize(0, 30))
        self.pushButton_2.setMaximumSize(QtCore.QSize(70, 16777215))
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_2.setFont(font)
        self.pushButton_2.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.pushButton_2.setObjectName(_fromUtf8("pushButton_2"))
        self.pushButton_2.clicked.connect(self.zoom)  ########### zoom 함수 연결
        self.gridLayout.addWidget(self.pushButton_2, 2, 1, 1, 1)
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setMinimumSize(QtCore.QSize(0, 30))
        self.pushButton.setMaximumSize(QtCore.QSize(70, 16777215))
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.pushButton.setFont(font)
        self.pushButton.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.pushButton.clicked.connect(self.pan)  ###########pan 함수 연결
        self.gridLayout.addWidget(self.pushButton, 2, 2, 1, 1)
        self.pushButton_3 = QtGui.QPushButton(self.centralwidget)
        self.pushButton_3.setMinimumSize(QtCore.QSize(0, 30))
        self.pushButton_3.setMaximumSize(QtCore.QSize(70, 16777215))
        font = QtGui.QFont()
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_3.setFont(font)
        self.pushButton_3.setLayoutDirection(QtCore.Qt.RightToLeft)
        self.pushButton_3.setObjectName(_fromUtf8("pushButton_3"))
        self.pushButton_3.clicked.connect(self.home)  ##########home 함수 연결
        self.gridLayout.addWidget(self.pushButton_3, 2, 3, 1, 1)
        self.frame_4 = QtGui.QFrame(self.centralwidget)
        self.frame_4.setMinimumSize(QtCore.QSize(150, 0))
        self.frame_4.setMaximumSize(QtCore.QSize(16777215, 40))
        self.frame_4.setFrameShape(QtGui.QFrame.StyledPanel)
        self.frame_4.setFrameShadow(QtGui.QFrame.Plain)
        self.frame_4.setLineWidth(1)
        self.frame_4.setObjectName(_fromUtf8("frame_4"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.frame_4)
        self.horizontalLayout.setContentsMargins(-1, 0, -1, -1)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.label = QtGui.QLabel(self.frame_4)
        self.label.setMinimumSize(QtCore.QSize(0, 35))
        self.label.setMaximumSize(QtCore.QSize(40, 30))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout.addWidget(self.label)
        self.dateEdit = QtGui.QDateEdit(self.frame_4)
        self.dateEdit.setMinimumSize(QtCore.QSize(0, 30))
        self.dateEdit.setMaximumSize(QtCore.QSize(121, 20))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.dateEdit.setFont(font)
        self.dateEdit.setAlignment(QtCore.Qt.AlignCenter)
        self.dateEdit.setObjectName(_fromUtf8("dateEdit"))
        self.dateEdit.setDateTime(
            QtCore.QDateTime.currentDateTime())  ########## 현재 날짜로 업데이트
        self.dateEdit.setCalendarPopup(True)  ########## 캘린더 팝업
        self.dateEdit.dateChanged.connect(
            self.ShowDate)  ########## 선택한 날짜로 데이터 업데이트
        self.horizontalLayout.addWidget(self.dateEdit)
        self.label_2 = QtGui.QLabel(self.frame_4)
        self.label_2.setMinimumSize(QtCore.QSize(0, 35))
        self.label_2.setMaximumSize(QtCore.QSize(81, 30))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.horizontalLayout.addWidget(self.label_2)
        self.textEdit = QtGui.QTextEdit(self.frame_4)
        self.textEdit.setMinimumSize(QtCore.QSize(600, 30))
        self.textEdit.setMaximumSize(QtCore.QSize(16777215, 20))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.textEdit.setFont(font)
        self.textEdit.setFrameShape(QtGui.QFrame.StyledPanel)
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.horizontalLayout.addWidget(self.textEdit)
        self.comboBox = QtGui.QComboBox(self.frame_4)
        self.comboBox.setMinimumSize(QtCore.QSize(0, 30))
        self.comboBox.setMaximumSize(QtCore.QSize(16777215, 20))
        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.comboBox.setFont(font)
        self.comboBox.setObjectName(_fromUtf8("comboBox"))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.addItem(_fromUtf8(""))
        self.comboBox.activated.connect(self.convert_utc)
        self.horizontalLayout.addWidget(self.comboBox)
        self.gridLayout.addWidget(self.frame_4, 0, 0, 1, 4)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.fig = plt.figure()  ########## figure 만들기
        self.canvas = FigureCanvas(self.fig)  ########## canvas 만들기
        self.verticalLayout.addWidget(self.canvas)  ########## figure 삽입
        self.toolbar = NavigationToolbar(self.canvas,
                                         MainWindow)  ##########툴바 생성
        self.toolbar.hide()  ##########툴바 숨김
        self.gridLayout.addLayout(self.verticalLayout, 1, 0, 1, 4)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1150, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        self.menuOpen = QtGui.QMenu(self.menubar)
        self.menuOpen.setObjectName(_fromUtf8("menuOpen"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.actionFile = QtGui.QAction(MainWindow)
        self.actionFile.setObjectName(_fromUtf8("actionFile"))
        self.actionFile.triggered.connect(
            self.OpenFile)  ########## OpenFile 연결
        self.actionDirectory = QtGui.QAction(MainWindow)
        self.actionDirectory.setObjectName(_fromUtf8("actionDirectory"))
        self.actionDirectory.triggered.connect(
            self.OpenDirectory)  ########## OpenDirectory 연결
        self.menuOpen.addAction(self.actionFile)
        self.menuOpen.addAction(self.actionDirectory)
        self.menubar.addAction(self.menuOpen.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
 def addmpl(self, fig):
     self.canvas = FigureCanvas(fig)
     self.mplvl.addWidget(self.canvas)
     self.canvas.draw()
Beispiel #26
0
    def __init__(self, filename=None, arg=None, parent=None, debug=False):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.debug = debug

        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.ui.widget)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(411)
        self.raw = self.fig.add_subplot(412)
        self.plt = self.fig.add_subplot(413)
        self.ref = self.fig.add_subplot(414)
        #		self.vari = self.fig.add_subplot(515)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.ui.widget)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        self.ui.widget.setLayout(vbox)

        # Signals/Slots
        self.connect(self.ui.actionOpen, QtCore.SIGNAL('triggered()'),
                     self.loadSpec)
        self.connect(self.ui.sigTop, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.Smin, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.Smax, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.sigBottom, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.ref1Top, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.ref1Bottom, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.rawsigStdDev, QtCore.SIGNAL('stateChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.sigStdDev, QtCore.SIGNAL('stateChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.refStdDev, QtCore.SIGNAL('stateChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.NumSignals, QtCore.SIGNAL('valueChanged(int)'),
                     self.on_draw)
        self.connect(self.ui.SigSpacing, QtCore.SIGNAL('valueChanged(double)'),
                     self.on_draw)
        self.connect(self.ui.actionClose, QtCore.SIGNAL('triggered()'),
                     self.closeEvent)
        self.connect(self.ui.AlignTop, QtCore.SIGNAL('clicked()'),
                     self.AlignRefTop)
        self.connect(self.ui.AlignBottom, QtCore.SIGNAL('clicked()'),
                     self.AlignRefBottom)
        self.connect(self.ui.BTFindAntenna, QtCore.SIGNAL('clicked()'),
                     self.FindAntennas)
        self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.multisig, QtCore.SIGNAL("toggled(bool)"),
                     self.on_draw)
        self.connect(self.ui.MultiRef, QtCore.SIGNAL("toggled(bool)"),
                     self.on_draw)

        if filename != None:
            self.loadSpec(filename)
Beispiel #27
0
    def initialize(self):

        self.frame = 0
        self.obs = []

        self.obs_group = QWidget(self)
        self.obs_group_layout = QVBoxLayout()
        self.obs_group.setLayout(self.obs_group_layout)
        obs_label = QLabel("Human Observations")
        obs_label.setAlignment(Qt.AlignCenter)
        self.obs_group_layout.addWidget(obs_label)

        self.layoutStratiform = QHBoxLayout()
        self.widgetStratiform = QWidget(self)
        self.widgetStratiform.setLayout(self.layoutStratiform)
        self.obs_group_layout.addWidget(self.widgetStratiform)
        #self.lStratiform = QLabel('Stratiform            ')
        self.layoutStratiform.addWidget(QWidget())
        self.lStratiform = QLabel('Genus 0:')
        self.layoutStratiform.addWidget(self.lStratiform)
        self.stratiformGroup = QButtonGroup(self.widgetStratiform)
        self.rStratiformYes = QRadioButton('Yes')
        self.stratiformGroup.addButton(self.rStratiformYes)
        self.rStratiformNull = QRadioButton('IDK')
        self.stratiformGroup.addButton(self.rStratiformNull)
        self.rStratiformNo = QRadioButton('No')
        self.stratiformGroup.addButton(self.rStratiformNo)
        self.layoutStratiform.addWidget(self.rStratiformYes)
        self.layoutStratiform.addWidget(self.rStratiformNo)
        #  self.layoutStratiform.addWidget(self.rStratiformNull)
        self.layoutStratiform.addWidget(QWidget())

        self.layoutCirriform = QHBoxLayout()
        self.widgetCirriform = QWidget(self)
        self.widgetCirriform.setLayout(self.layoutCirriform)
        self.obs_group_layout.addWidget(self.widgetCirriform)
        #self.lCirriform = QLabel('Cirriform               ')
        self.layoutCirriform.addWidget(QWidget())
        self.lCirriform = QLabel('Genus 1:')
        self.layoutCirriform.addWidget(self.lCirriform)
        self.CirriformGroup = QButtonGroup(self.widgetCirriform)
        self.rCirriformYes = QRadioButton('Yes')
        self.CirriformGroup.addButton(self.rCirriformYes)
        self.rCirriformNull = QRadioButton('IDK')
        self.CirriformGroup.addButton(self.rCirriformNull)
        self.rCirriformNo = QRadioButton('No')
        self.CirriformGroup.addButton(self.rCirriformNo)
        self.layoutCirriform.addWidget(self.rCirriformYes)
        self.layoutCirriform.addWidget(self.rCirriformNo)
        #  self.layoutCirriform.addWidget(self.rCirriformNull)
        self.layoutCirriform.addWidget(QWidget())

        self.layoutStratoCumuliform = QHBoxLayout()
        self.widgetStratoCumuliform = QWidget(self)
        self.widgetStratoCumuliform.setLayout(self.layoutStratoCumuliform)
        self.obs_group_layout.addWidget(self.widgetStratoCumuliform)
        #self.lStratoCumuliform = QLabel('StratoCumuliform ')
        self.layoutStratoCumuliform.addWidget(QWidget())
        self.lStratoCumuliform = QLabel('Genus 2:')
        self.layoutStratoCumuliform.addWidget(self.lStratoCumuliform)
        self.StratoCumuliformGroup = QButtonGroup(self.widgetStratoCumuliform)
        self.rStratoCumuliformYes = QRadioButton('Yes')
        self.StratoCumuliformGroup.addButton(self.rStratoCumuliformYes)
        self.rStratoCumuliformNull = QRadioButton('IDK')
        self.StratoCumuliformGroup.addButton(self.rStratoCumuliformNull)
        self.rStratoCumuliformNo = QRadioButton('No')
        self.StratoCumuliformGroup.addButton(self.rStratoCumuliformNo)
        self.layoutStratoCumuliform.addWidget(self.rStratoCumuliformYes)
        self.layoutStratoCumuliform.addWidget(self.rStratoCumuliformNo)
        #  self.layoutStratoCumuliform.addWidget(self.rStratoCumuliformNull)
        self.layoutStratoCumuliform.addWidget(QWidget())

        self.layoutCumuliform = QHBoxLayout()
        self.widgetCumuliform = QWidget(self)
        self.widgetCumuliform.setLayout(self.layoutCumuliform)
        self.obs_group_layout.addWidget(self.widgetCumuliform)
        #self.lCumuliform = QLabel('Cumuliform          ')
        self.layoutCumuliform.addWidget(QWidget())
        self.lCumuliform = QLabel('Genus 3:')
        self.layoutCumuliform.addWidget(self.lCumuliform)
        self.CumuliformGroup = QButtonGroup(self.widgetCumuliform)
        self.rCumuliformYes = QRadioButton('Yes')
        self.CumuliformGroup.addButton(self.rCumuliformYes)
        self.rCumuliformNull = QRadioButton('IDK')
        self.CumuliformGroup.addButton(self.rCumuliformNull)
        self.rCumuliformNo = QRadioButton('No')
        self.CumuliformGroup.addButton(self.rCumuliformNo)
        self.layoutCumuliform.addWidget(self.rCumuliformYes)
        self.layoutCumuliform.addWidget(self.rCumuliformNo)
        #  self.layoutCumuliform.addWidget(self.rCumuliformNull)
        self.layoutCumuliform.addWidget(QWidget())

        self.layoutCumulonibiform = QHBoxLayout()
        self.widgetCumulonibiform = QWidget(self)
        self.widgetCumulonibiform.setLayout(self.layoutCumulonibiform)
        self.obs_group_layout.addWidget(self.widgetCumulonibiform)
        self.layoutCumulonibiform.addWidget(QWidget())
        # self.lCumulonibiform = QLabel('Cumulonibiform   ')
        self.lCumulonibiform = QLabel('Genus 4:')
        self.layoutCumulonibiform.addWidget(self.lCumulonibiform)
        self.CumulonibiformGroup = QButtonGroup(self.widgetCumulonibiform)
        self.rCumulonibiformYes = QRadioButton('Yes')
        self.CumulonibiformGroup.addButton(self.rCumulonibiformYes)
        self.rCumulonibiformNull = QRadioButton('IDK')
        self.CumulonibiformGroup.addButton(self.rCumulonibiformNull)
        self.rCumulonibiformNo = QRadioButton('No')
        self.CumulonibiformGroup.addButton(self.rCumulonibiformNo)
        self.layoutCumulonibiform.addWidget(self.rCumulonibiformYes)
        self.layoutCumulonibiform.addWidget(self.rCumulonibiformNo)
        #  self.layoutCumulonibiform.addWidget(self.rCumulonibiformNull)
        self.layoutCumulonibiform.addWidget(QWidget())

        self.layoutspacing = QHBoxLayout()
        self.updateContainer = QWidget()
        self.updateContainer.setLayout(self.layoutspacing)
        self.layoutspacing.addWidget(QWidget())

        self.updatebutton = QPushButton("Update", self)
        #  self.updatebutton.setFixedWidth(100)
        self.layoutspacing.addWidget(self.updatebutton)
        self.layoutspacing.addWidget(QWidget())
        self.obs_group_layout.addWidget(self.updateContainer)
        self.obs_group_layout.addWidget(QWidget())
        self.obs_group_layout.addWidget(QWidget())
        self.obs_group_layout.addWidget(QWidget())
        self.layout.addWidget(self.obs_group, 0, 1)

        # Probability graph
        self.figure_prob = Figure()
        self.probability = FigureCanvas(self.figure_prob)
        self.prob_ax = self.probability.figure.subplots()
        names = [
            'Cumuliform0', 'Cumuliform1', 'Cumuliform2', 'Cumuliform3',
            'Cumuliform4'
        ]
        graph_names = [
            '0',
            'Genus0',
            'Genus1',
            'Genus2',
            'Genus3',
            'Genus4',
        ]
        self.alphas = {}
        self.probs = {}
        for i in names:
            self.alphas[i] = [-1, -1]
            self.probs[i] = .2
            #  self.probs[i]=np.random.uniform()
        for i in names:
            self.probs[i] /= sum(self.probs.values())
        self.prob_ax.bar(range(5), self.probs.values())
        #DEBUG
        #  self.prob_ax.bar(range(2),self.probs.values())
        self.prob_ax.set_ylim(0, 1)
        self.prob_ax.set_ylabel('Probability')
        self.prob_ax.set_xticklabels(graph_names)
        self.prob_ax.figure.canvas.draw()
        self.layout.addWidget(self.probability, 0, 0)

        # Intensity and Data on same tab
        self.tabs_top = QTabWidget(self)

        # Intensity graph
        self.figure_int = Figure()
        self.intensity = FigureCanvas(self.figure_int)
        self.int_ax = self.intensity.figure.subplots()
        self.intensity_data = self.get_intensity()
        self.int_ax.plot([0], self.intensity_data[0])
        self.int_ax.set_ylim(0, np.max(self.intensity_data) + 1)
        self.int_ax.set_xlabel('Time Steps')
        self.int_ax.figure.canvas.draw()
        self.tabs_top.addTab(self.intensity, 'Intensity')

        # Satellite image
        self.figure_sat = Figure()
        self.satellite = FigureCanvas(self.figure_sat)
        self.sat_ax = self.satellite.figure.subplots()
        self.satellite_data = self.make_some_data()
        self.maxsig = np.amax(self.satellite_data)
        self.sat_ax.imshow(self.satellite_data[0],
                           vmax=self.maxsig,
                           cmap='Greys_r')
        self.sat_ax.axis('off')
        self.sat_ax.figure.canvas.draw()
        self.tabs_top.addTab(self.satellite, 'Satellite Image')

        self.layout.addWidget(self.tabs_top, 1, 0)

        # Genus dirichlet distributions
        self.tabs_bot = QTabWidget(self)

        self.table = self.DirPrior()
        self.theta1 = np.zeros((5, 10))
        for X in range(5):
            self.theta1[X, :] = scipy.stats.dirichlet.mean(
                alpha=np.mean(self.table, axis=1)[X, :])

        self.figure_gen0 = Figure()
        self.genus0 = FigureCanvas(self.figure_gen0)
        self.gen0_ax = self.genus0.figure.add_subplot(111, projection='3d')
        self.gen0_ax.set_xlabel('Previous Obs')
        self.gen0_ax.set_ylabel('Next Obs')
        self.updateDir(0)
        self.tabs_bot.addTab(self.genus0, 'Genus 0')

        self.figure_gen1 = Figure()
        self.genus1 = FigureCanvas(self.figure_gen1)
        self.gen1_ax = self.genus1.figure.add_subplot(111, projection='3d')
        self.gen1_ax.set_xlabel('Previous Obs')
        self.gen1_ax.set_ylabel('Next Obs')
        self.updateDir(1)
        self.tabs_bot.addTab(self.genus1, 'Genus 1')

        self.figure_gen2 = Figure()
        self.genus2 = FigureCanvas(self.figure_gen2)
        self.gen2_ax = self.genus2.figure.add_subplot(111, projection='3d')
        self.gen2_ax.set_xlabel('Previous Obs')
        self.gen2_ax.set_ylabel('Next Obs')
        self.updateDir(2)
        self.tabs_bot.addTab(self.genus2, 'Genus 2')

        self.figure_gen3 = Figure()
        self.genus3 = FigureCanvas(self.figure_gen3)
        self.gen3_ax = self.genus3.figure.add_subplot(111, projection='3d')
        self.gen3_ax.set_xlabel('Previous Obs')
        self.gen3_ax.set_ylabel('Next Obs')
        self.updateDir(3)
        self.tabs_bot.addTab(self.genus3, 'Genus 3')

        self.figure_gen4 = Figure()
        self.genus4 = FigureCanvas(self.figure_gen4)
        self.gen4_ax = self.genus4.figure.add_subplot(111, projection='3d')
        self.gen4_ax.set_xlabel('Previous Obs')
        self.gen4_ax.set_ylabel('Next Obs')
        self.updateDir(4)
        self.tabs_bot.addTab(self.genus4, 'Genus 4')

        self.layout.addWidget(self.tabs_bot, 1, 1)

        self.updatebutton.clicked.connect(
            lambda: self.updateProbs(updateType='human'))
        self.updatebutton.clicked.connect(lambda: self.updateDir(0))
        self.updatebutton.clicked.connect(lambda: self.updateDir(1))
        self.updatebutton.clicked.connect(lambda: self.updateDir(2))
        self.updatebutton.clicked.connect(lambda: self.updateDir(3))
        self.updatebutton.clicked.connect(lambda: self.updateDir(4))
Beispiel #28
0
    def setupGui(self):
        if self.dataSpaceNameSelected:
            self.tabWidget.setEnabled(True)

            #Set the calendar as per the starting year.
            self.calSpaceDateTimeIllum.setMinimumDateTime(
                QtCore.QDateTime(self.dataYear, 1, 1, 0, 0))
            self.calSpaceDateTimeIllum.setDateTime(
                QtCore.QDateTime(self.dataYear, 1, 1, 0, 0))
            self.calSpaceDateTimeIllum.setMaximumDateTime(
                QtCore.QDateTime(self.dataYear, 12, 31, 23, 59))

            self.grpContoursIlluminance.setEnabled(True)

            self.btnSpaceSettingsContour.setEnabled(True)
            #TODO: Change the visiblity settings to True later ;)
            self.btnSpaceSettingsContour.setVisible(True)

            #Setup matplotlib inside Qt.
            self.spFigure = Figure()
            self.spCanvas = FigureCanvas(self.spFigure)

            #Validator for setting values
            floatValidator = QtGui.QDoubleValidator(0.0, 20000.0, 3)

            #Settings for showing and hiding color and contours.
            self.grpColoursIlluminance.setVisible(False)
            self.grpContoursIlluminance.setVisible(False)

            #Initiate a dictioanry for ill files.
            self.spAllFilesDict = {}

            #Code for manipulating navigation settings for illuminance.
            #Code for manipulating navigation settings for illuminance.

            self.spTimeStepIlluminance = 1  #This attribute determines the time step for stepping between different illuminance plots.

            #Changing/clicking any of the below controls should trigger the illuminance plots.

            self.spIlluminanceActivated = False
            self.spCurrentIlluminanceHour = 9

            units = self.dataProject.unitsIlluminance
            unitsMultiplier = {'lux': 1, 'fc': 0.1}[str(units)]

            self.spIlluminanceMaxVal = 5000 * unitsMultiplier
            self.spIlluminanceMinVal = 0

            self.spIlluminanceMaxValDefault = 5000 * unitsMultiplier
            self.spIlluminanceMinValDefault = 0
            self.spIlluminanceUpperMaskValue = None
            self.spIlluminanceLowerMaskValue = None
            self.spIlluminanceUpperMaskColor = None
            self.spIlluminanceLowerMaskColor = None

            self.spElectricMaxVal = 400 * unitsMultiplier
            self.spElectricMinVal = 0

            self.spElectricMaxValDefault = 400 * unitsMultiplier
            self.spElectricMinValDefault = 0
            self.spElectricUpperMaskValue = None
            self.spElectricLowerMaskValue = None
            self.spElectricUpperMaskColor = None
            self.spElectricLowerMaskColor = None

            self.spMetricsMaxVal = 1.0
            self.spMetricsMinVal = 0.0
            self.spMetricsMaxValDefault = 1.0
            self.spMetricsMinValDefault = 0
            self.spMetricsUpperMaskValue = None
            self.spMetricsLowerMaskValue = None
            self.spMetricsUpperMaskColor = None
            self.spMetricsLowerMaskColor = None

            self.spCurrentPlotIsIlluminance = True
            self.spCurrentPlotIsElectric = False

            self.txtSpaceColorsMax.setText(str(
                self.spIlluminanceMaxValDefault))
            self.txtSpaceColorsMin.setText(str(
                self.spIlluminanceMinValDefault))
            self.txtSpaceColorsMax.setValidator(floatValidator)
            self.txtSpaceColorsMin.setValidator(floatValidator)

            self.spPlotIlluminanceColors = True

            #Put all contourboxes inside a list for easy iteration.
            self.spContourBoxes = [
                self.txtSpaceCountourValue1, self.txtSpaceCountourValue2,
                self.txtSpaceCountourValue3, self.txtSpaceCountourValue4,
                self.txtSpaceCountourValue5, self.txtSpaceCountourValue6,
                self.txtSpaceCountourValue7, self.txtSpaceCountourValue8
            ]

            for contourBox in self.spContourBoxes:
                contourBox.setValidator(floatValidator)

            self.spContourValuesIlluminance = (50, 100, 500, 1000, 2000, 3000,
                                               5000, 10000)
            self.spContourValuesIlluminance = map(
                lambda x: x * unitsMultiplier, self.spContourValuesIlluminance)

            self.spContourValuesElectric = (50, 100, 150, 200, 250, 300, 350,
                                            400)
            self.spContourValuesElectric = map(lambda x: x * unitsMultiplier,
                                               self.spContourValuesElectric)

            self.spContourValuesIlluminanceDefault = (50, 100, 500, 1000, 2000,
                                                      3000, 5000, 10000)
            self.spContourValuesIlluminanceDefault = map(
                lambda x: x * unitsMultiplier,
                self.spContourValuesIlluminanceDefault)

            self.spContourValuesElectricDefault = (50, 100, 150, 200, 250, 300,
                                                   350, 400)
            self.spContourValuesElectricDefault = map(
                lambda x: x * unitsMultiplier,
                self.spContourValuesElectricDefault)

            for idx, contourBox in enumerate(self.spContourBoxes):
                contourBox.setText(str(self.spContourValuesIlluminance[idx]))

            self.spContourValuesMetrics = (0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9,
                                           1.0)
            self.spContourValuesMetricsDefault = (0.1, 0.2, 0.3, 0.4, 0.5, 0.7,
                                                  0.9, 1.0)

            #Contstuctor Stuff
            self.spColorMapTuple = (
                ('Uniform01', 'viridis'), ('Uniform02', 'inferno'),
                ('Uniform03', 'plasma'), ('Uniform04', 'magma'), ('Blues',
                                                                  'Blues'),
                ('BlueGreen', 'BuGn'), ('BluePurple', 'BuPu'), ('GreenBlue',
                                                                'GnBu'),
                ('Greens', 'Greens'), ('Greys', 'Greys'), ('Oranges',
                                                           'Oranges'),
                ('OrangeRed', 'OrRd'), ('PurpleBlue',
                                        'PuBu'), ('PurpleBlueGreen', 'PuBuGn'),
                ('PurpleRed', 'PuRd'), ('Purples', 'Purples'), ('RedPurple',
                                                                'RdPu'),
                ('Reds', 'Reds'), ('YellowGreen', 'YlGn'), ('YellowGreenBlue',
                                                            'YlGnBu'),
                ('YellowOrangeBrown',
                 'YlOrBr'), ('YellowOrangeRed', 'YlOrRd'), ('Hot01', 'afmhot'),
                ('Hot02', 'hot'), ('Hot03', 'gist_heat'), ('Autumn', 'autumn'),
                ('Bone', 'bone'), ('Cool', 'cool'), ('Copper', 'copper'),
                ('Spring', 'spring'), ('Summer', 'summer'), ('Winter',
                                                             'winter'))

            colorNames = [name for name, plotName in self.spColorMapTuple]
            self.spColorDict = dict(self.spColorMapTuple)
            self.cmbSpaceColorScheme.addItems(colorNames)
            self.cmbSpaceColorScheme.setCurrentIndex(21)

            self.spCurrentColorScheme = 'YlOrRd'
            self.spCurrentSpaceChartOpacityValue = 1

            self.spCurrentColorSchemeMetrics = 'YlOrRd'
            self.spCurrentSpaceChartOpacityValueMetrics = 1

            self.spCurrentColorSchemeElectric = 'YlOrRd'
            self.spCurrentSpaceChartOpacityValueElectric = 1

            self.spInterpolateColorScheme = None

            self.txtSpaceStatusDisplay.setEnabled(False)

            illFileKeys, illFileNames = zip(*self.dataDayIllFilesList)

            self.ptsFile = self.dataPtsFile

            self.illData = Dayill(illFileNames[0], self.ptsFile)

            hourFormat = self.illData.timedata[0:24]
            hourFormat = [
                hourVal['tstamp'].strftime("%I:%M %p")
                for hourVal in hourFormat
            ]

            #Set valid time stamps for all the drop boxes that show time.
            self.cmbSpaceTimeIllum.clear()
            self.cmbSpaceTimeIllum.addItems(map(str, hourFormat))
            self.cmbSpaceTimeIllum.setCurrentIndex(9)

            self.cmbSpaceTimeIntervalMax.clear()
            self.cmbSpaceTimeIntervalMax.addItems(map(str, hourFormat))
            self.cmbSpaceTimeIntervalMax.setCurrentIndex(23)

            self.cmbSpaceTimeIntervalMin.clear()
            self.cmbSpaceTimeIntervalMin.addItems(map(str, hourFormat))
            self.cmbSpaceTimeIntervalMin.setCurrentIndex(0)

            # Set valid time stamps for all the drop boxes that show time.
            self.cmbCombinedTimeIllum.clear()
            self.cmbCombinedTimeIllum.addItems(map(str, hourFormat))
            self.cmbCombinedTimeIllum.setCurrentIndex(9)

            self.cmbCombinedTimeIntervalMax.clear()
            self.cmbCombinedTimeIntervalMax.addItems(map(str, hourFormat))
            self.cmbCombinedTimeIntervalMax.setCurrentIndex(23)

            self.cmbCombinedTimeIntervalMin.clear()
            self.cmbCombinedTimeIntervalMin.addItems(map(str, hourFormat))
            self.cmbCombinedTimeIntervalMin.setCurrentIndex(0)

            self.spAllFilesDict = self.dataAllFiles

            # Addedd this test as sometimes metrics are not calculated. In those cases it's just the illuminance readStadicData.
            try:
                resultsFiles, resultsFilesNames = zip(
                    *self.dataMetricsFilesList)
                if self.dataElectricIllFilesList:
                    electricFiles, electricFilesNames = zip(
                        *self.dataElectricIllFilesList)
                else:
                    electricFiles = []
                    electricFilesNames = []
                mainComboBoxContents = [illFileKeys[0]]+ \
                                       sorted(list(resultsFiles))+ \
                                       sorted(list(electricFiles))

            except ValueError:
                mainComboBoxContents = [illFileKeys[0]]

            self.cmbSpacePlotType.clear()
            self.cmbSpacePlotType.addItems(mainComboBoxContents)

            self.cmbSpaceSelectIlluminanceFile.clear()
            self.cmbSpaceSelectIlluminanceFile.addItems(illFileKeys)
            self.cmbCombinedSelectIlluminanceFile.clear()
            self.cmbCombinedSelectIlluminanceFile.addItems(illFileKeys)

            self.spacePlotTypeDict = self.dataAllFilesAvailable

            self.spShadeSchedule = self.dataProject.spaces[
                self.dataSpaceIndex].scheduleShades
            self.spWindowGroupNames = [
                windowGroup.name for windowGroup in self.dataProject.spaces[
                    self.dataSpaceIndex].windowGroups
            ]
            self.spShowWindowGroupInfo = True  #Toggle this to False in case window Group info isn't to be shown.

            if self.spShadeSchedule and self.spShowWindowGroupInfo:
                shadeData = TimeArray(self.spShadeSchedule)
                shadeData = [
                    map(int, timedata['readStadicData'])
                    for timedata in shadeData.timedata
                ]
                self.spShadeSchedule = shadeData

            self.btnSpaceSettingsContour.clicked.connect(
                self.spToggleContourSettings)
            self.btnSpaceSettingsColours.clicked.connect(
                self.spToggleColorSettings)
            self.calSpaceDateTimeIllum.dateChanged.connect(
                self.spSetCurrentIlluminanceHourCalendar)
            self.cmbSpaceTimeIllum.currentIndexChanged.connect(
                self.spSetCurrentIlluminanceHourCalendar)

            self.btnSpacePrevHour.clicked.connect(
                lambda: self.spSetCurrentIlluminanceHourTimeStep(False))
            self.btnSpaceNextHour.clicked.connect(
                lambda: self.spSetCurrentIlluminanceHourTimeStep(True))

            #If the timestep settings are changed, change the time step but don't trigger the illuminance plot.
            self.cmbSpaceIlluminanceStepType.currentIndexChanged.connect(
                self.spUpdateIlluminanceTimeStep)
            self.cmbSpaceIluminanceStepValue.currentIndexChanged.connect(
                self.spUpdateIlluminanceTimeStep)

            #Settings for displaying the opacity value on a box.
            self.sliderSpaceOpacity.valueChanged.connect(
                self.spOpacitySliderChanged)

            #Settings for color values of the illuminance plot.
            self.btnSelectColorLowerMask.clicked.connect(
                lambda: self.spMaskSettingsActivated(False))
            self.btnSelectColorUpperMask.clicked.connect(
                lambda: self.spMaskSettingsActivated(True))

            self.btnSpaceResetColors.clicked.connect(self.spResetColorSettings)
            self.btnSpaceSetColors.clicked.connect(self.spSetColorSettings)

            #settings for contour values for the illuminance plot.
            self.cmbSpaceContourQuantity.currentIndexChanged.connect(
                self.spSetContourQuantity)

            self.chkSpaceColors.clicked.connect(self.spRefreshPlots)
            self.chkSpaceContours.clicked.connect(self.spRefreshPlots)

            self.btnSpaceResetContours.clicked.connect(
                self.spResetContourSettings)
            self.btnSpaceSetContours.clicked.connect(self.spSetContourSettings)

            self.btnSpaceSetColorScheme.clicked.connect(
                self.spAssignSpaceColorScheme)

            self.cmbSpacePlotType.currentIndexChanged.connect(
                self.spPlotTypeSelect)

            self.cmbSpaceSelectIlluminanceFile.currentIndexChanged.connect(
                self.spLoadDifferentIlluminanceFile)

            self.cmbSpaceTimeIllum.setCurrentIndex(10)

            # self.spCanvas.mpl_connect('motion_notify_event',self.spMouseClicked)

            # self.spCurrentDataSet = None

            self.txtSpaceMsgBox.setText(self.dataLog)

            # TODO: Delete the line below to enable the timeseries stuff.
            self.tabWidget.removeTab(2)
Beispiel #29
0
    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 200
        self.show_movie = 0  # by default don't show moving filter kernel

        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        ## new from https://github.com/matplotlib/matplotlib/issues/707/
        self.canvas.setFocusPolicy(Qt.ClickFocus)
        self.canvas.setFocus()

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        if self.display_option == 0:  # filter and convolution
            self.axes = self.fig.add_subplot(211)
            self.axes.grid(True, 'major')
            self.axes.tick_params(axis='both', which='major', labelsize=6)

            self.axes2 = self.fig.add_subplot(212)
            # self.axes2.grid(True, 'major')
            self.axes2.tick_params(axis='both', which='major', labelsize=6)

            # self.axes3 = self.fig.add_subplot(224)
            # self.axes3.grid(True, 'major')
            # self.axes3.tick_params(axis='both', which='major', labelsize=6)
            # self.axes3.set_title("Kernel Spectrum", {'fontsize': 6})
        elif self.display_option == 1:  # Coherence
            self.trials_n = 5  # number of simulated signal trials
            self.trial_axes = []
            for nn in range(0, self.trials_n):
                # axes for signals and polar representations
                self.trial_axes.append(
                    self.fig.add_subplot(self.trials_n, 3, 3 * nn + 1))
                self.trial_axes.append(
                    self.fig.add_subplot(self.trials_n, 3, 3 * nn + 2))

            self.axes2 = self.fig.add_subplot(233)
            self.axes2.grid(True, 'major')
            self.axes2.tick_params(axis='both', which='major', labelsize=6)

        elif self.display_option == 2:  # Time-Frequency

            self.axes = self.fig.add_subplot(211)
            self.axes.tick_params(axis='both', which='major', labelsize=6)

            self.axes2 = self.fig.add_subplot(212)
            self.axes2.tick_params(axis='both', which='major', labelsize=6)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        ## new
        self.canvas.mpl_connect('button_press_event', self.curs_pos)

        # Other GUI controls
        #

        ## Text for x-axis limits (min, max, step)
        if not (hasattr(self, 'textbox_lim')):
            self.textbox_lim = QLineEdit()
            self.textbox_lim.setText(
                '-1000 1000 5')  # x-axis scale of signal time course in ms
            self.textbox_lim.setMinimumWidth(200)
            self.connect(self.textbox_lim, SIGNAL('editingFinished ()'),
                         self.on_draw)

        self.movie_button = QPushButton("&Movie")
        self.connect(self.movie_button, SIGNAL('clicked()'), self.on_movie)

        self.add_func_button = QPushButton(
            "&+Func")  # add textbox for function plotting
        self.connect(self.add_func_button, SIGNAL('clicked()'),
                     self.on_add_func)

        self.add_slider_button = QPushButton(
            "&+Slider")  # add slider for function plotting
        self.connect(self.add_slider_button, SIGNAL('clicked()'),
                     self.on_add_slider)

        # Menu box for display options (Filters, etc.)
        if not (hasattr(self, 'comboBox')):
            self.comboBox = QComboBox(self)
            self.comboBox.addItem("Filters")
            self.comboBox.addItem("Connectivity")
            self.comboBox.addItem("TimeFrequency")

            self.comboBox.activated[str].connect(self.display_method)

        ## Slider
        if not (hasattr(self, 'slider_scale')):
            self.slider_label = QLabel('Scaling:')
            self.slider_scale = QSlider(Qt.Horizontal)
            self.slider_scale.setRange(1, 1000)
            self.slider_scale.setValue(200)
            self.slider_scale.setTracking(True)
            # self.slider_scale.setTickPosition(QSlider.TicksBothSides)
            self.slider_scale.setTickPosition(QSlider.TicksBelow)
            self.slider_scale.setTickInterval(50)
            self.connect(self.slider_scale, SIGNAL('valueChanged(int)'),
                         self.on_draw)

        # Create layout within canvas

        hbox1 = QHBoxLayout()  # buttons, sliders, etc.
        hbox2 = QHBoxLayout()  # text boxes for regression
        hbox3 = QHBoxLayout()  # sliders for noise in regression
        hbox4 = QHBoxLayout()  # text boxes for correlation

        attr_list = [
            self.textbox_lim, self.movie_button, self.add_func_button,
            self.add_slider_button, self.slider_label, self.slider_scale,
            self.comboBox
        ]

        # HBOX1 for Draw/Add buttons etc.
        for w in attr_list:
            hbox1.addWidget(w)
            hbox1.setAlignment(w, Qt.AlignVCenter)

        if not (hasattr(self, 'funcsliders')):
            # sliders
            self.fslidelabels = []
            self.fslidelabels.append(QLabel('S0'))  # will be specified below

            # add one additional slider
            self.fslidelabels.append(QLabel('S1:'))

            self.funcsliders = []
            # Slider
            self.funcsliders.append(QSlider(Qt.Horizontal))
            self.funcsliders[0].setRange(0, 100)
            self.funcsliders[0].setMinimumWidth(200)
            self.funcsliders[0].setValue(10)
            self.funcsliders[0].setTracking(True)
            self.funcsliders[0].setTickPosition(QSlider.TicksBelow)
            self.funcsliders[0].setTickInterval(50)
            self.connect(self.funcsliders[0], SIGNAL('valueChanged(int)'),
                         self.on_draw)

            # Slider
            self.funcsliders.append(QSlider(Qt.Horizontal))
            self.funcsliders[1].setRange(0, 100)
            self.funcsliders[1].setMinimumWidth(200)
            self.funcsliders[1].setValue(20)
            self.funcsliders[1].setTracking(True)
            self.funcsliders[1].setTickPosition(QSlider.TicksBelow)
            self.funcsliders[1].setTickInterval(50)
            self.connect(self.funcsliders[1], SIGNAL('valueChanged(int)'),
                         self.on_draw)

        ## initialise or add TEXT BOXES

        options = [0, 1, 2]  # number of display option

        if not (hasattr(self, 'functext')):  # at the very beginning
            self.functext = []
            self.funclabels = []
            [self.functext.append([]) for ii in options
             ]  # text boxes for functions of different options
            [self.funclabels.append([])
             for ii in options]  # correponding display labels

        # If text specified, keep it
        # apparently widgets get deleted by their parents
        if self.functext[0] == []:
            txt0 = "box(0,W)"
            txt1 = "morlet(F, x)"
        else:
            txt0 = self.functext[0][0].text()
            txt1 = self.functext[0][1].text()

        self.functext[0] = []
        self.functext[0].append(QLineEdit(txt0))
        self.functext[0].append(QLineEdit(txt1))

        self.functext[0][0].setMinimumWidth(200)
        self.connect(self.functext[0][0], SIGNAL('editingFinished ()'),
                     self.on_edit)
        self.functext[0][1].setMinimumWidth(200)
        self.connect(self.functext[0][1], SIGNAL('editingFinished ()'),
                     self.on_edit)

        self.funclabels[0] = []
        self.funclabels[0].append(QLabel('Signal:'))
        self.funclabels[0].append(QLabel('Kernel:'))

        if self.functext[1] == []:
            txt0 = "sin(2*pi*(F/1000.)*x)"
            txt1 = "50"
        else:
            txt0 = self.functext[1][0].text()
            txt1 = self.functext[1][1].text()

        self.functext[1] = []
        self.functext[1].append(QLineEdit(txt0))
        self.functext[1].append(QLineEdit(txt1))

        self.functext[1][0].setMinimumWidth(200)
        self.connect(self.functext[1][1], SIGNAL('editingFinished ()'),
                     self.on_edit)
        self.functext[1][1].setMinimumWidth(200)
        self.connect(self.functext[1][1], SIGNAL('editingFinished ()'),
                     self.on_edit)

        self.funclabels[1] = []
        self.funclabels[1].append(QLabel('Signal:'))
        self.funclabels[1].append(QLabel('Delay (ms):'))

        if self.functext[2] == []:
            txt0 = "sin(2*pi*(F/1000.)*x)"
            txt1 = "arange(5,100,2)"
        else:
            txt0 = self.functext[2][0].text()
            txt1 = self.functext[2][1].text()

        self.functext[2] = []
        self.functext[2].append(QLineEdit(txt0))
        self.functext[2].append(QLineEdit(txt1))

        self.functext[2][0].setMinimumWidth(200)
        self.connect(self.functext[2][0], SIGNAL('editingFinished ()'),
                     self.on_edit)
        self.functext[2][1].setMinimumWidth(200)
        self.connect(self.functext[2][1], SIGNAL('editingFinished ()'),
                     self.on_edit)

        self.funclabels[2] = []
        self.funclabels[2].append(QLabel('Signal:'))
        self.funclabels[2].append(QLabel('Freqs:'))

        if self.display_option == 0:  # Filter
            self.fslidelabels[0].setText('Width (W):')
            self.fslidelabels[1].setText('Freq (F):')
        elif self.display_option == 1:  # Connectivity
            self.fslidelabels[0].setText('Freq (F):')
            self.fslidelabels[1].setText('Noise (N):')
            self.funcsliders[0].setValue(20)
            self.funcsliders[1].setValue(0)

        elif self.display_option == 2:
            self.fslidelabels[0].setText('Freq (F):')
            self.fslidelabels[1].setText('S[1]:')

        # add function text boxes to box
        opt = self.display_option  # current display option

        functext = self.functext[opt]  # text box and label for current option
        funclabels = self.funclabels[opt]

        for [fi, ff] in enumerate(functext):  # labels and text boxes
            w = self.funclabels[opt][fi]
            hbox2.addWidget(w)  # add label text

            hbox2.addWidget(ff)  # add corresponding text box
            hbox2.setAlignment(ff, Qt.AlignVCenter)

        # add function sliders to box
        for aa in range(len(self.fslidelabels)):
            w = self.fslidelabels[aa]
            hbox3.addWidget(w)

            w = self.funcsliders[aa]
            hbox3.addWidget(w)
            hbox3.setAlignment(w, Qt.AlignVCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        # if self.display_option==1: # only for regression
        #     vbox.addWidget(self.canvas2)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)
Beispiel #30
0
class CalibrationViewer(QtGui.QMainWindow):
    trialsChanged = QtCore.pyqtSignal()

    def __init__(self):
        self.filters = list()
        super(CalibrationViewer, self).__init__()
        self.setWindowTitle('Olfa Calibration')
        self.statusBar()
        self.trial_selected_list = []
        self.trialsChanged.connect(self._trial_selection_changed)

        mainwidget = QtGui.QWidget(self)
        self.setCentralWidget(mainwidget)
        layout = QtGui.QGridLayout(mainwidget)
        mainwidget.setLayout(layout)

        menu = self.menuBar()
        filemenu = menu.addMenu("&File")
        toolsmenu = menu.addMenu("&Tools")

        openAction = QtGui.QAction("&Open recording...", self)
        openAction.triggered.connect(self._openAction_triggered)
        openAction.setStatusTip("Open a HDF5 data file with calibration recording.")
        openAction.setShortcut("Ctrl+O")
        filemenu.addAction(openAction)
        saveFigsAction = QtGui.QAction('&Save figures...', self)
        saveFigsAction.triggered.connect(self._saveFiguresAction_triggered)
        saveFigsAction.setShortcut('Ctrl+S')
        openAction.setStatusTip("Saves current figures.")
        filemenu.addAction(saveFigsAction)
        exitAction = QtGui.QAction("&Quit", self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.setStatusTip("Quit program.")
        exitAction.triggered.connect(QtGui.qApp.quit)
        filemenu.addAction(exitAction)
        removeTrialAction = QtGui.QAction("&Remove trials", self)
        removeTrialAction.setStatusTip('Permanently removes selected trials (bad trials) from trial list.')
        removeTrialAction.triggered.connect(self._remove_trials)
        removeTrialAction.setShortcut('Ctrl+R')
        toolsmenu.addAction(removeTrialAction)

        trial_group_list_box = QtGui.QGroupBox()
        trial_group_list_box.setTitle('Trial Groups')
        self.trial_group_list = TrialGroupListWidget()
        trial_group_layout = QtGui.QVBoxLayout()
        trial_group_list_box.setLayout(trial_group_layout)
        trial_group_layout.addWidget(self.trial_group_list)
        layout.addWidget(trial_group_list_box, 0, 0)
        self.trial_group_list.itemSelectionChanged.connect(self._trial_group_selection_changed)

        trial_select_list_box = QtGui.QGroupBox()
        trial_select_list_box.setMouseTracking(True)
        trial_select_list_layout = QtGui.QVBoxLayout()
        trial_select_list_box.setLayout(trial_select_list_layout)
        trial_select_list_box.setTitle('Trials')
        self.trial_select_list = TrialListWidget()
        self.trial_select_list.setMouseTracking(True)
        trial_select_list_layout.addWidget(self.trial_select_list)
        self.trial_select_list.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.trial_select_list.itemSelectionChanged.connect(self._trial_selection_changed)
        layout.addWidget(trial_select_list_box, 0, 1)
        self.trial_select_list.createGroupSig.connect(self.trial_group_list.create_group)

        filters_box = QtGui.QGroupBox("Trial filters.")
        filters_box_layout = QtGui.QVBoxLayout(filters_box)
        filters_scroll_area = QtGui.QScrollArea()
        filters_buttons = QtGui.QHBoxLayout()
        filters_all = QtGui.QPushButton('Select all', self)
        filters_all.clicked.connect(self._select_all_filters)
        filters_none = QtGui.QPushButton('Select none', self)
        filters_none.clicked.connect(self._select_none_filters)
        filters_buttons.addWidget(filters_all)
        filters_buttons.addWidget(filters_none)
        filters_box_layout.addLayout(filters_buttons)
        filters_box_layout.addWidget(filters_scroll_area)
        filters_wid = QtGui.QWidget()
        filters_scroll_area.setWidget(filters_wid)
        filters_scroll_area.setWidgetResizable(True)
        filters_scroll_area.setFixedWidth(300)
        self.filters_layout = QtGui.QVBoxLayout()
        filters_wid.setLayout(self.filters_layout)
        layout.addWidget(filters_box, 0, 2)

        plots_box = QtGui.QGroupBox()
        plots_box.setTitle('Plots')
        plots_layout = QtGui.QHBoxLayout()

        self.figure = Figure((9, 5))
        self.figure.patch.set_facecolor('None')
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(plots_box)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        plots_layout.addWidget(self.canvas)
        plots_box.setLayout(plots_layout)
        layout.addWidget(plots_box, 0, 3)
        self.ax_pid = self.figure.add_subplot(2, 1, 1)
        self.ax_pid.set_title('PID traces')
        self.ax_pid.set_ylabel('')
        self.ax_pid.set_xlabel('t (ms)')
        # self.ax_pid.set_yscale('log')
        self.ax_mean_plots = self.figure.add_subplot(2, 1, 2)
        self.ax_mean_plots.set_title('Mean value')
        self.ax_mean_plots.set_ylabel('value')
        self.ax_mean_plots.set_xlabel('Concentration')
        self.ax_mean_plots.autoscale(enable=True, axis=u'both', tight=False)
        self.figure.tight_layout()

    @QtCore.pyqtSlot()
    def _list_context_menu_trig(self):
        pass

    @QtCore.pyqtSlot()
    def _filters_changed(self):
        mask = np.ones_like(self.trial_mask)
        for v in self.filters:
            mask *= v.trial_mask
        self.trial_mask = mask
        self.trial_select_list.itemSelectionChanged.disconnect(self._trial_selection_changed)
        for i in xrange(len(self.trial_mask)):
            hide = not self.trial_mask[i]
            it = self.trial_select_list.item(i)
            it.setHidden(hide)
            select = it.isSelected() * self.trial_mask[i]
            it.setSelected(select)
        self.trial_select_list.itemSelectionChanged.connect(self._trial_selection_changed)
        self.trial_select_list.itemSelectionChanged.emit()  # emit that something changed so that we redraw.

    @QtCore.pyqtSlot()
    def _openAction_triggered(self):
        filedialog = QtGui.QFileDialog(self)
        if os.path.exists('D:\\experiment\\raw_data'):
            startpath = 'D:\\experiment\\raw_data\\mouse_o_cal_cw\\sess_001'
        else:
            startpath = ''
        fn = filedialog.getOpenFileName(self, "Select a data file.", startpath, "HDF5 (*.h5)")
        if fn:
            data = CalibrationFile(str(fn))
            self.data = data
            self.trial_actions = []
            trial_num_list = []
            self.trial_select_list.clear()
            trials = self.data.trials
            for i, t in enumerate(trials):
                tstr = "Trial {0}".format(i)
                it = QtGui.QListWidgetItem(tstr, self.trial_select_list)
                # trial = trials[i]
                # odor = trial['odor']
                # vialconc = trial['vialconc']
                # odorconc = trial['odorconc']
                # dilution = 1000 - trial['dilution'][0]
                # trst = 'Odor: {0}, vialconc: {1}, odorconc: {2}, dilution: {3}'.format(odor, vialconc, odorconc,
                #                                                                        dilution)
                # it.setStatusTip(trst)
                trial_num_list.append(i)
            self.trial_select_list.trial_num_list = np.array(trial_num_list)
            self.trial_mask = np.ones(len(self.trial_select_list.trial_num_list), dtype=bool)
            self.build_filters(trials)
        else:
            print('No file selected.')
        return

    def build_filters(self, trials):
        while self.filters_layout.itemAt(0):
            self.filters_layout.takeAt(0)
        if self.filters:
            for f in self.filters:
                f.deleteLater()
        self.filters = list()
        colnames = trials.dtype.names
        if 'odorconc' not in colnames:
            self.error = QtGui.QErrorMessage()
            self.error.showMessage('Data file must have "odorconc" field to allow plotting.')
        start_strings = ('odorconc', 'olfas', 'dilutors')
        filter_fields = []
        for ss in start_strings:
            for fieldname in colnames:
                if fieldname.startswith(ss):
                    filter_fields.append(fieldname)

        for field in filter_fields:
            filter = FiltersListWidget(field)
            filter.populate_list(self.data.trials)
            filter.setVisible(False)
            self.filters.append(filter)
            box = QtGui.QWidget()
            box.setSizePolicy(0, 0)
            # box.setTitle(filter.fieldname)
            show_button = QtGui.QPushButton(filter.fieldname)
            show_button.setStyleSheet('text-align:left; border:0px')
            show_button.clicked.connect(filter.toggle_visible)
            _filt_layout = QtGui.QVBoxLayout(box)
            _filt_layout.addWidget(show_button)
            _filt_layout.addWidget(filter)
            _filt_layout.setSpacing(0)
            self.filters_layout.addWidget(box)
            filter.filterChanged.connect(self._filters_changed)
        for v in self.filters:
            assert isinstance(v, FiltersListWidget)

        # self.filters_layout.addWidget(QtGui.QSpacerItem())
        self.filters_layout.addStretch()
        self.filters_layout.setSpacing(0)

        return

    @QtCore.pyqtSlot()
    def _saveFiguresAction_triggered(self):
        # TODO: add figure saving functionality with filedialog.getSaveFileName.
        self.saveDialog = QtGui.QFileDialog()
        saveloc = self.saveDialog.getSaveFileName(self, 'Save figure', '', 'PDF (*.pdf);;JPEG (*.jpg);;TIFF (*.tif)')
        saveloc = str(saveloc)
        self.figure.savefig(saveloc)

    @QtCore.pyqtSlot()
    def _remove_trials(self):
        selected_idxes = self.trial_select_list.selectedIndexes()
        remove_idxes = []
        for id in selected_idxes:
            idx = id.row()
            remove_idxes.append(idx)
        while self.trial_select_list.selectedIndexes():
            selected_idxes = self.trial_select_list.selectedIndexes()
            idx = selected_idxes[0].row()
            self.trial_select_list.takeItem(idx)
        new_trials_array = np.zeros(len(self.trial_select_list.trial_num_list)-len(remove_idxes), dtype=np.int)
        ii = 0
        remove_trialnums = []
        new_trials_mask = np.zeros_like(new_trials_array, dtype=bool)
        for i in xrange(len(self.trial_select_list.trial_num_list)):
            if i not in remove_idxes:
                new_trials_mask[ii] = self.trial_mask[i]
                new_trials_array[ii] = self.trial_select_list.trial_num_list[i]
                ii += 1
            else:
                remove_trialnums.append(self.trial_select_list.trial_num_list[i])
        self.trial_mask = new_trials_mask
        self.trial_select_list.trial_num_list = new_trials_array

        for f in self.filters:
            f.remove_trials(remove_idxes)
        self.trial_group_list._remove_trials(remove_trialnums)

    @QtCore.pyqtSlot()
    def _trial_selection_changed(self):
        selected_idxes = self.trial_select_list.selectedIndexes()
        selected_trial_nums = []
        for id in selected_idxes:
            idx = id.row()
            trialnum = self.trial_select_list.trial_num_list[idx]
            selected_trial_nums.append(trialnum)
        self.update_plots(selected_trial_nums)
        self.trial_group_list.blockSignals(True)
        for i, g in zip(xrange(self.trial_group_list.count()), self.trial_group_list.trial_groups):
            it = self.trial_group_list.item(i)
            all_in = True
            group_trials = g['trial_nums']
            for t in group_trials:
                if t not in selected_trial_nums:
                    all_in = False
            if not all_in:
                it.setSelected(False)
            elif all_in:
                it.setSelected(True)
        self.trial_group_list.blockSignals(False)
        return

    @QtCore.pyqtSlot()
    def _trial_group_selection_changed(self):
        selected_idxes = self.trial_group_list.selectedIndexes()
        self._select_all_filters()
        selected_trial_nums = []
        for id in selected_idxes:
            idx = id.row()
            trialnums = self.trial_group_list.trial_groups[idx]['trial_nums']
            selected_trial_nums.extend(trialnums)
        self.trial_select_list.blockSignals(True)
        for i in range(self.trial_select_list.count()):
            item = self.trial_select_list.item(i)
            self.trial_select_list.setItemSelected(item, False)
        for i in selected_trial_nums:
            idx = np.where(self.trial_select_list.trial_num_list == i)[0][0]
            it = self.trial_select_list.item(idx)
            if not it.isSelected():
                it.setSelected(True)
        self.trial_select_list.blockSignals(False)
        self._trial_selection_changed()

    def update_plots(self, trials):
        padding = (2000, 2000)  #TODO: make this changable - this is the number of ms before/afterr trial to extract for stream.
        trial_streams = []
        trial_colors = []
        while self.ax_pid.lines:
            self.ax_pid.lines.pop(0)
        while self.ax_mean_plots.lines:
            self.ax_mean_plots.lines.pop(0)
        groups_by_trial = []
        all_groups = set()
        ntrials = len(trials)
        vals = np.empty(ntrials)
        concs = np.empty_like(vals)
        if trials:
            a = max([1./len(trials), .25])
            for i, tn in enumerate(trials):
                color = self.trial_group_list.get_trial_color(tn)
                groups = self.trial_group_list.get_trial_groups(tn)
                trial_colors.append(color)
                groups_by_trial.append(groups)
                all_groups.update(groups)
                trial = self.data.return_trial(tn, padding=padding)
                stream = remove_stream_trend(trial.streams['sniff'], (0, padding[0]))
                stream -= stream[0:padding[0]].min()
                # TODO: remove baseline (N2) trial average from this.
                trial_streams.append(stream)
                self.ax_pid.plot(stream, color=color, alpha=a)
                conc = trial.trials['odorconc']
                baseline = np.mean(stream[:2000])
                val = np.mean(stream[3000:4000]) - baseline
                vals[i] = val
                concs[i] = conc
                self.ax_mean_plots.plot(conc, val, '.', color=color)
        minlen = 500000000
        for i in trial_streams:
            minlen = min(len(i), minlen)
        streams_array = np.empty((ntrials, minlen))
        for i in xrange(ntrials):
            streams_array[i, :] = trial_streams[i][:minlen]
        for g in all_groups:
            mask = np.empty(ntrials, dtype=bool)
            for i in xrange(ntrials):
                groups = groups_by_trial[i]
                mask[i] = g in groups
            c = concs[mask]
            groupstreams = streams_array[mask]
            if len(np.unique(c)) < 2:
                self.ax_pid.plot(groupstreams.mean(axis=0), color='k', linewidth=2)
            else:
                v = vals[mask]
                a, b, _, _, _ = stats.linregress(c, v)
                color = self.trial_group_list.get_group_color(g)
                minn, maxx = self.ax_mean_plots.get_xlim()
                x = np.array([minn, maxx])
                self.ax_mean_plots.plot(x, a*x + b, color=color)
        self.ax_pid.relim()
        self.ax_mean_plots.set_yscale('log')
        self.ax_mean_plots.set_xscale('log')
        self.ax_mean_plots.relim()

        self.canvas.draw()

    @QtCore.pyqtSlot()
    def _select_none_filters(self):
        for filter in self.filters:
            filter.filterChanged.disconnect(self._filters_changed)
            filter.clearSelection()
            filter.filterChanged.connect(self._filters_changed)
        self._filters_changed()

    @QtCore.pyqtSlot()
    def _select_all_filters(self):
        for filter in self.filters:
            filter.filterChanged.disconnect(self._filters_changed)
            filter.selectAll()
            filter.filterChanged.connect(self._filters_changed)
        self._filters_changed()
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.loader = Loader([
            "PGVCAN.txt", "MultiReperage.txt", "ReperageEasyTrack.txt",
            "ReperagePsiNav.txt", "NavigationLaser.txt",
            "ReperageEasyTrackRepMeasure.txt"
        ])

        # a figure instance to plot on
        self.figure1 = plt.figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure1)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.button = QtGui.QPushButton('PGV x y angle')
        self.button.clicked.connect(self.plotxyangle)

        self.button1 = QtGui.QPushButton('X Y Reperages')
        self.button1.clicked.connect(self.plotxy)

        self.button2 = QtGui.QPushButton('Recalages EasyTrack')
        self.button2.clicked.connect(self.plotRecalages)

        self.button5 = QtGui.QPushButton('X Y Theta Reperages')
        self.button5.clicked.connect(self.plotxyt)

        self.button6 = QtGui.QPushButton('EasyTrackDistanceOdo')
        self.button6.clicked.connect(self.plotEasyTrackDistanceOdo)

        self.button7 = QtGui.QPushButton('dYPgv')
        self.button7.clicked.connect(self.plotEasyTrackdYPgv)

        self.button8 = QtGui.QPushButton('NPXYT')
        self.button8.clicked.connect(self.plotEasyTrackNPXYT)

        self.button9 = QtGui.QPushButton('PgvXY')
        self.button9.clicked.connect(self.plotEasyTrackPgvXYT)

        self.button10 = QtGui.QPushButton('EasyTrackErreur')
        self.button10.clicked.connect(self.plotEasyTrackErreurMeasure)

        self.button11 = QtGui.QPushButton('NavPlotT')
        self.button11.clicked.connect(self.NavPlotT)

        self.button12 = QtGui.QPushButton('Load Data')
        self.button12.clicked.connect(self.loadData)
        self.button12.setEnabled(True)

        self.button13 = QtGui.QPushButton('DeltaNP')
        self.button13.clicked.connect(self.plotDeltaNP)
        self.button13.setEnabled(True)

        self.button14 = QtGui.QPushButton('Flags')
        self.button14.clicked.connect(self.plotFlags)
        self.button14.setEnabled(True)

        self.buttonPGVSetEnabled(False)
        self.buttonReperageSetEnabled(False)
        self.buttonReperageErrorSetEnabled(False)
        self.buttonNavigationSetEnabled(False)

        self.connect(self.loader, SIGNAL("loaded"), self.signalloaded)
        self.connect(self.loader, SIGNAL("start"), self.signalstart)
        self.connect(self.loader, SIGNAL("fail"), self.signalfail)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.addWidget(self.button)
        buttonLayout.addWidget(self.button1)
        buttonLayout.addWidget(self.button2)
        buttonLayout.addWidget(self.button5)
        buttonLayout.addWidget(self.button6)
        buttonLayout.addWidget(self.button7)
        buttonLayout.addWidget(self.button8)
        buttonLayout.addWidget(self.button9)
        buttonLayout.addWidget(self.button10)
        buttonLayout.addWidget(self.button11)
        buttonLayout.addWidget(self.button12)
        buttonLayout.addWidget(self.button13)
        buttonLayout.addWidget(self.button14)
        layout.addLayout(buttonLayout)
        self.textedit = QtGui.QTextEdit()
        self.textedit.setFixedHeight(150)
        layout.addWidget(self.textedit)
        self.setLayout(layout)

        #optimisation de l'utilisation de la place dans la fenetre pour avoir des courbes les plus grandes possibles
        plt.subplots_adjust(left=0.05,
                            bottom=0.04,
                            right=0.96,
                            top=0.95,
                            wspace=0.20,
                            hspace=0.22)

        #afficher le nom du repertoire dans le titre de la fenetre
        currentPath = os.getcwd()
        self.setWindowTitle(currentPath)

        #lancer directement le chargement des fichiers
        self.loadData()
            self.selected = None
        self.fig.canvas.draw_idle()

if __name__ == '__main__':
    ncf = netcdf_file('KTLX_20100510_22Z.nc')
    data = ncf.variables['Reflectivity']
    lats = ncf.variables['lat']
    lons = ncf.variables['lon']
    stormcells = storm_loader('polygons.shp')

    # Must come before any Qt widgets are made
    app = QtGui.QApplication(sys.argv)
    win = QtGui.QMainWindow()

    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(1, 1, 1)
    raddisp = RadarDisplay(ax, lats, lons)
    raddisp.update_display(data[0])
    fig.colorbar(raddisp.im)
    polycolls = Stormcells(ax, stormcells)
    linecoll = Tracks(ax)

    # Turn on the first frame's polygons
    polycolls.toggle_polygons(0, True)
    ax.autoscale(True)

    ctrl_sys = ControlSys(fig, raddisp, data, polycolls, linecoll, stormcells)

    win.resize(int(fig.bbox.width), int(fig.bbox.height))
    win.setWindowTitle("Embedding with Qt")
    def __init__(self, model=None, parent=None):

        super(SyncPulseExtractor, self).__init__(parent)

        self.model = model or SyncPulseExtractionModel()
        self.setMinimumWidth(1000)

        subject_with_spacer = QHBoxLayout()

        self.subject_edit = LabeledEditLayout("Subject: ")
        self.subject_edit.edit.setMaximumWidth(100)
        self.subject_edit.addStretch(1)

        subject_with_spacer.addSpacing(8)
        subject_with_spacer.addLayout(self.subject_edit)

        self.data_root_button = QPushButton("Data Root")
        self.data_root_contents = QLabel("")

        self.data_root_contents.setMinimumWidth(200)
        self.data_root_contents.setFont(QFont('', 8))

        data_root_layout = QHBoxLayout()
        data_root_layout.addWidget(self.data_root_button)
        data_root_layout.addWidget(self.data_root_contents)
        data_root_layout.addStretch(1)

        subject_and_mount_layout = QVBoxLayout()
        subject_and_mount_layout.addLayout(subject_with_spacer)
        subject_and_mount_layout.addLayout(data_root_layout)
        subject_and_mount_layout.setSpacing(5)
        subject_and_mount_layout.setAlignment(QtCore.Qt.AlignLeft)

        info_layout = QHBoxLayout()
        info_layout.addLayout(subject_and_mount_layout)

        layout = QVBoxLayout(self)

        self.elec1_edit = LabeledEditLayout("Elec 1:")
        self.elec2_edit = LabeledEditLayout("Elec 2:")
        self.elec1_edit.edit.setMaximumWidth(60)
        self.elec2_edit.edit.setMaximumWidth(60)

        elec_layout = QVBoxLayout()
        elec_layout.setAlignment(QtCore.Qt.AlignRight)
        elec_layout.addLayout(self.elec1_edit)
        elec_layout.addLayout(self.elec2_edit)
        elec_layout.setSpacing(10)

        self.load_drop_down = QComboBox()
        self.load_drop_down.setMinimumWidth(200)

        self.save_button = QPushButton("Save Pulses")
        self.save_button.setMaximumWidth(400)
        self.save_button.setEnabled(False)

        button_layout = QVBoxLayout()
        button_layout.addWidget(self.load_drop_down)
        button_layout.addWidget(self.save_button)

        self.eeg_text = QLabel("No EEG Loaded")
        self.status_text = QLabel("")
        self.eeg_text.setAlignment(QtCore.Qt.AlignCenter)
        self.eeg_text.setMaximumWidth(400)
        self.eeg_text.setFont(QFont('', 8))

        status_layout = QVBoxLayout()
        status_layout.addWidget(self.eeg_text,
                                alignment=QtCore.Qt.AlignHCenter)
        status_layout.addWidget(self.status_text,
                                alignment=QtCore.Qt.AlignHCenter)

        self.elec1_edit.label.setMaximumWidth(45)
        self.elec1_edit.edit.setMaximumWidth(45)
        self.elec2_edit.label.setMaximumWidth(45)
        self.elec2_edit.edit.setMaximumWidth(45)

        top_layout = QHBoxLayout()
        top_layout.addLayout(info_layout)
        top_layout.addStretch(1)
        top_layout.addLayout(status_layout)
        top_layout.addStretch(1)
        top_layout.addLayout(elec_layout)
        top_layout.addLayout(button_layout)

        layout.addLayout(top_layout)

        self.figure = plt.figure()

        self.canvas = FigureCanvas(self.figure)

        self.toolbar = NavigationToolbar(self.canvas, self)

        self.clear_selection_button = QPushButton("Clear selection")

        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.clear_selection_button)

        self.gs = gridspec.GridSpec(2, 1, height_ratios=[1, 5])

        self.full_ax = plt.subplot(self.gs[1])
        self.zoom_ax = plt.subplot(self.gs[0])
        self.zoom_ax.get_xaxis().set_ticks([])
        self.zoom_ax.get_yaxis().set_ticks([])

        self.rectangle_selector = RectangleSelector(self.full_ax,
                                                    self.selection_callback,
                                                    drawtype='box',
                                                    useblit=True,
                                                    button=[1, 3],
                                                    minspanx=5,
                                                    minspany=5,
                                                    spancoords='pixels',
                                                    interactive=False,
                                                    rectprops={'fill': False})
        self.figure.set_tight_layout(True)
        self.assign_callbacks()
        self.apply_edits()