Esempio n. 1
0
    def __init__(self):
        super(MyWindow, self).__init__()
        uic.loadUi('MobilityCalculator.ui', self)
        
        self.initVariables()
        
        # Connect up the buttons.
        self.pbLoad.clicked.connect(self.loadDataClickedSlot)
        self.pbSavePltDat.clicked.connect(self.savePltDat)   
        self.cbXAxis.currentIndexChanged.connect(self.updatePlot_RawData)
        self.cbYAxis.currentIndexChanged.connect(self.updatePlot_RawData)        
        self.cbLineStyle.currentIndexChanged.connect(self.lineOrMarkerStyleChangedSlot)      
        self.cbMarkerStyle.currentIndexChanged.connect(self.lineOrMarkerStyleChangedSlot)
        self.cbPlotColour.currentIndexChanged.connect(self.plotColourChangedSlot)       
        self.ckbAvgData.stateChanged.connect(self.updatePlot_RawData)
        self.ckbRmvFiller.stateChanged.connect(self.updatePlot_RawData)  
        self.tabWidget.currentChanged.connect(self.tabChangedSlot)        
        self.cbAXAxis.currentIndexChanged.connect(self.updatePlotFromAxisSettings)
        self.cbAYAxis.currentIndexChanged.connect(self.updatePlotFromAxisSettings)        
        self.cbAIndex.currentIndexChanged.connect(self.updatePlotFromAxisSettings)
        self.sbLegendEntries.valueChanged.connect(self.updatePlotFromAxisSettings)
        self.cbLineStyle_Analysis.currentIndexChanged.connect(self.lineOrMarkerStyleChangedSlot)      
        self.cbMarkerStyle_Analysis.currentIndexChanged.connect(self.lineOrMarkerStyleChangedSlot)
        self.cbPlotColour_Analysis.currentIndexChanged.connect(self.AplotColourmapChangedSlot)  
        self.lwMeasSelect.itemSelectionChanged.connect(self.updateDataSet)
        self.lwSweepDirSelect.itemSelectionChanged.connect(self.updateDataSet)        
        self.ckbShowVtFit.stateChanged.connect(self.updatePlotFromAxisSettings)
        self.ckbSmoothing.stateChanged.connect(self.updateDataSet)
        self.hsSmoothing.valueChanged.connect(self.updateDataSet)
        self.ckbDriftCorr.stateChanged.connect(self.updateDataSet)
        
        self.leFitVtFrom.setValidator(QtGui.QDoubleValidator())
        self.leFitVtTo.setValidator(QtGui.QDoubleValidator())
        self.leFitVtFrom.editingFinished.connect(self.updateDataSet)         
        self.leFitVtTo.editingFinished.connect(self.updateDataSet)
        self.leFitVtFrom.setText(str(self.defVtFitFrom))
        self.leFitVtTo.setText(str(self.defVtFitTo))
        
        #Add NavigationToolbar
        self.mplwidget.figure.set_dpi(120)
        self.mplwidget.mpl_toolbar = NavigationToolbar(self.mplwidget.figure.canvas, self.mplwidget)
        self.verticalLayout.setDirection(QtGui.QBoxLayout.BottomToTop)
        self.verticalLayout.addWidget(self.mplwidget.mpl_toolbar,1)

        self.mplwidget.myplot = self.mplwidget.figure.add_subplot(111)        
        self.mplwidget.myplot.set_title("Pulse Curve")
        self.mplwidget.myplot.set_xlabel("Pt Index")
        self.mplwidget.myplot.set_ylabel("Voltage (V)") 
        
        #Configure latex for plotting, from here: stackoverflow.com/questions/22348756/upright-mu-in-plot-label-retaining-original-tick-fonts  
        mpl.rcParams['mathtext.fontset'] = 'custom'
        mpl.rcParams['mathtext.rm'] = 'Bitstream Vera Sans'
        mpl.rcParams['mathtext.it'] = 'Bitstream Vera Sans:italic'
        mpl.rcParams['mathtext.bf'] = 'Bitstream Vera Sans:bold'
        
        self.pltCfg_RawData = {'marker':'.','linestyle':'-','linecolor':'b','title':'Title','xlabel':'xlabel','ylabel':'ylabel'}        
        self.pltCfg_Analysis = {'marker':'.','linestyle':'-','linecolor':'b','title':'Title','xlabel':'xlabel','ylabel':'ylabel'}                
        
        self.lineStyleDict = {0:'-',1:'--',2:'-.',3:':',4:''}
        self.markerDict = {0:'.',1:'o',2:'+',3:'.',4:'1',5:'2',6:'3',7:'4',8:''}
        self.lineColourDict = {0:'b',1:'g',2:'r',3:'c',4:'m',5:'y',6:'k',7:'w'}

        self.dict_NWLen = {'MF-08-ZA' : {'AD':3.474E-6, 'AB':0.929E-6, 'BC':0.929E-6,'CD':0.929E-6},
                           'MF-07-GA' : {'AD':3.400E-6, 'AB':0.924E-6, 'BC':0.924E-6,'CD':0.924E-6},
                           'MF-06-IA' : {'AD':2.667E-6, 'AB':0.745E-6, 'BC':0.745E-6,'CD':0.745E-6},
                           'MF-05-IA' : {'AD':3.400E-6, 'AB':0.924E-6, 'BC':0.924E-6,'CD':0.924E-6},
                           'MF-04-IA' : {'AD':3.400E-6, 'AB':0.924E-6, 'BC':0.924E-6,'CD':0.924E-6},                                                      
                           'MF-03-IA' : {'AD':2.971E-6, 'AB':None, 'BC':None,'CD':None}}
        self.dict_NWDiam = {'MF-08-ZA' : 71E-9,  #Zn3As2
                            'MF-07-GA' : 100E-9, #InAs/GaSb Core-shell
                            'MF-06-IA' : 130E-9, #InAsSb
                            'MF-05-IA' : 100E-9, #InAs 14-04-23B
                            'MF-04-IA' : 100E-9, #InAs 14-04-23B
                            'MF-03-IA' : 100E-9} #InAs 14-04-23B
                            
        self.dict_units = {'mobility':'$cm^2/V\cdot s$', #From most specific string first to most general strings at end
                           'conductance': 'mS',                           
                           'vg':'V',
                           'n_':'cm$^{-3}$',                           
                           'v':'mV',
                           'i':'$\mu$A',
                           't':'s'}                     
        #Must match the dict_units dictionary
        self.dict_unitsMult = {'mobility':1e4, #From most specific string first to most general strings at end
                           'conductance': 1e3, 
                           'vg':1,
                           'n_':1e-6,                           
                           'v':1e3,
                           'i':1e6,
                           't':1}                                             
        self.show()
        self.updatePlot_RawData() 
Esempio n. 2
0
    def initUI(self):

        self.shellnr = 1
        self.savedshellnr = 1
        self.isfitted = 0

        self.fig = plt.figure(3, figsize=(12, 6))
        self.ax_bft = plt.subplot2grid((1, 2), (0, 0))
        self.ax_bftft = plt.subplot2grid((1, 2), (0, 1))

        self.canv = FigureCanvas(self.fig)
        self.tbar = NavigationToolbar(self.canv, self)

        self.fig.tight_layout()

        #        self.lblNrShells = QtGui.QLabel("Number of shells")
        #        self.edtNrShells = QtGui.QLineEdit("1")

        self.lblkmin = QtGui.QLabel("K min")
        self.lblkmax = QtGui.QLabel("K max")
        self.lbldk = QtGui.QLabel("dK")
        self.edtkmin = QtGui.QLineEdit("0.5")
        self.edtkmax = QtGui.QLineEdit("15")
        self.edtdk = QtGui.QLineEdit("0.05")

        self.lblMaxiterations = QtGui.QLabel("Max number of iterations")
        self.edtMaxiterations = QtGui.QLineEdit("1000")

        self.tabShells = QtGui.QTabWidget()
        self.tabs = []
        self.tabs.append(QtGui.QFrame())
        self.tabShells.addTab(self.tabs[0], "Shell 1")

        self.ltShell = []
        self.shellN = []
        self.shellR = []
        self.shellSigma = []
        self.shellC3 = []
        self.shellC4 = []
        self.shellC5 = []
        self.shellC6 = []
        #        self.shellE0 = []
        self.shellAmp = []
        self.shellPha = []

        lblN = QtGui.QLabel("N")
        lblR = QtGui.QLabel("R")
        lblSigma = QtGui.QLabel("Sigma")
        lblC3 = QtGui.QLabel("C3")
        lblC4 = QtGui.QLabel("C4")
        lblC5 = QtGui.QLabel("C5")
        lblC6 = QtGui.QLabel("C6")
        #        lblE0 = QtGui.QLabel("E0")

        lblAmp = QtGui.QLabel("Amplitude")
        lblPha = QtGui.QLabel("Phase")

        self.ltShell.append(QtGui.QGridLayout())
        self.shellN.append([
            QtGui.QLineEdit("4"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("8"),
            QtGui.QCheckBox()
        ])
        self.shellR.append([
            QtGui.QLineEdit("2"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("4"),
            QtGui.QCheckBox()
        ])
        self.shellSigma.append([
            QtGui.QLineEdit("0.001"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("1"),
            QtGui.QCheckBox()
        ])
        self.shellC3.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.1"),
            QtGui.QCheckBox()
        ])
        self.shellC4.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.1"),
            QtGui.QCheckBox()
        ])
        self.shellC5.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.1"),
            QtGui.QCheckBox()
        ])
        self.shellC6.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.1"),
            QtGui.QCheckBox()
        ])
        #        self.shellE0.append([QtGui.QLineEdit("0"), QtGui.QLineEdit("0"), QtGui.QLineEdit("0"), QtGui.QLineEdit("0.0001"), QtGui.QCheckBox()])
        self.shellAmp.append(QtGui.QComboBox())
        self.shellPha.append(QtGui.QComboBox())

        self.shellAmp[-1].addItem("")
        self.shellPha[-1].addItem("")

        self.shellAmp[-1].currentIndexChanged.connect(self.AmpChanged)
        self.shellPha[-1].currentIndexChanged.connect(self.PhaChanged)

        self.shellN[len(self.shellN) - 1][3].setChecked(True)
        self.shellR[len(self.shellR) - 1][3].setChecked(True)
        self.shellSigma[len(self.shellSigma) - 1][3].setChecked(True)

        self.ltShell[0].addWidget(lblN, 0, 0)
        self.ltShell[0].addWidget(lblR, 1, 0)
        self.ltShell[0].addWidget(lblSigma, 2, 0)
        self.ltShell[0].addWidget(lblC3, 3, 0)
        self.ltShell[0].addWidget(lblC4, 4, 0)
        self.ltShell[0].addWidget(lblC5, 5, 0)
        self.ltShell[0].addWidget(lblC6, 6, 0)
        #        self.ltShell[0].addWidget(lblE0, 7, 0)
        self.ltShell[0].addWidget(lblAmp, 7, 0)
        self.ltShell[0].addWidget(lblPha, 8, 0)

        for i in range(4):
            self.ltShell[0].addWidget(self.shellN[0][i], 0, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellR[0][i], 1, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellSigma[0][i], 2, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellC3[0][i], 3, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellC4[0][i], 4, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellC5[0][i], 5, 2 * i + 1)
            self.ltShell[0].addWidget(self.shellC6[0][i], 6, 2 * i + 1)
#            self.ltShell[0].addWidget(self.shellE0[0][i], 7,  2*i+1)
        self.ltShell[0].addWidget(self.shellAmp[0], 7, 1, 1, 7)
        self.ltShell[0].addWidget(self.shellPha[0], 8, 1, 1, 7)

        self.shellAmp[0].addItem("E:/work/development/xaslib/fit/amp0001.dat")
        self.shellPha[0].addItem("E:/work/development/xaslib/fit/pha0001.dat")

        for j in range(6):
            self.ltShell[0].addWidget(QtGui.QLabel("Min. limit"), j, 2)
            self.ltShell[0].addWidget(QtGui.QLabel("Max. limit"), j, 4)
#            self.ltShell[0].addWidget(QtGui.QLabel("Accuracy"), j, 6)

        self.tabs[0].setLayout(self.ltShell[0])

        self.lblFuncEval = QtGui.QLabel("Number of function evaluations done")
        self.edtFuncEval = QtGui.QLineEdit()

        self.lblFitMessage = QtGui.QLabel("Termination reason")
        self.edtFitMessage = QtGui.QLineEdit()

        self.lblOptimality = QtGui.QLabel("Cost function")
        self.edtOptimality = QtGui.QLineEdit()

        lfit = QtGui.QGridLayout()
        lfit.addWidget(self.lblFitMessage, 0, 0)
        lfit.addWidget(self.edtFitMessage, 0, 1)
        lfit.addWidget(self.lblFuncEval, 1, 0)
        lfit.addWidget(self.edtFuncEval, 1, 1)
        lfit.addWidget(self.lblOptimality, 2, 0)
        lfit.addWidget(self.edtOptimality, 2, 1)

        self.btnFit = QtGui.QPushButton('Fit')
        self.btnFit.clicked.connect(self.Fit_leastsquares)

        self.btnApply = QtGui.QPushButton('Apply')
        self.btnApply.clicked.connect(self.apply)

        self.btnCancel = QtGui.QPushButton('Cancel')
        self.btnCancel.clicked.connect(self.cancel)

        self.btnAddShell = QtGui.QPushButton('Add shell')
        self.btnAddShell.clicked.connect(self.addshell)
        self.btnRemoveShell = QtGui.QPushButton('Remove shell')
        self.btnRemoveShell.clicked.connect(self.removeshell)
        self.btnOpenAmp = QtGui.QPushButton('Open amplitude file(s) ...')
        self.btnOpenAmp.clicked.connect(self.openamp)
        self.btnOpenPha = QtGui.QPushButton('Open phase file(s) ...')
        self.btnOpenPha.clicked.connect(self.openpha)
        self.btnOpenFeff = QtGui.QPushButton('Open feff file(s) ...')
        self.btnOpenFeff.clicked.connect(self.openfeff)

        self.btnSaveFitResults = QtGui.QPushButton('Save fit Results ...')
        self.btnSaveFitResults.clicked.connect(self.saveFitResults)

        lb = QtGui.QGridLayout()
        lb.addWidget(self.btnOpenAmp, 0, 0)
        lb.addWidget(self.btnOpenPha, 0, 1)
        lb.addWidget(self.btnOpenFeff, 1, 0)
        lb.addWidget(self.btnAddShell, 2, 0)
        lb.addWidget(self.btnRemoveShell, 2, 1)

        lfig = QtGui.QGridLayout()
        lfig.addWidget(self.tbar, 0, 0)
        lfig.addWidget(self.canv, 1, 0, 2, 1)

        lfig.addLayout(lfit, 3, 0)

        lfig.addWidget(self.btnFit, 4, 0)
        lfig.addWidget(self.btnApply, 5, 0)
        lfig.addWidget(self.btnCancel, 6, 0)

        lfig.addWidget(self.lblkmin, 0, 1)
        lfig.addWidget(self.edtkmin, 0, 2)
        lfig.addWidget(self.lblkmax, 0, 3)
        lfig.addWidget(self.edtkmax, 0, 4)
        lfig.addWidget(self.lbldk, 0, 5)
        lfig.addWidget(self.edtdk, 0, 6)

        lfig.addWidget(self.lblMaxiterations, 1, 1)
        lfig.addWidget(self.edtMaxiterations, 1, 2, 1, 4)

        lfig.addWidget(self.tabShells, 2, 1, 2, 6)
        lfig.addLayout(lb, 4, 1, 2, 6)

        self.setLayout(lfig)
Esempio n. 3
0
    def __init__(self,
                 parent,
                 mainWindow,
                 dlgTitle,
                 plotType,
                 plotArgs,
                 plotKwargs,
                 settingsDict={}):
        super(PlotDialog, self).__init__(parent)

        self.parent = parent
        self.mainWindow = mainWindow

        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.setSizePolicy(QtGui.QSizePolicy.Minimum,
                           QtGui.QSizePolicy.Minimum)

        self.setWindowTitle("Plotter - %s" % dlgTitle)
        self.setWindowIcon(QtGui.QIcon(
            iconPath("oxygen/office-chart-bar.png")))

        # settings
        settings = self.mainWindow.preferences.matplotlibForm

        figWidth = settings.figWidth
        figHeight = settings.figHeight
        figDpi = settings.figDpi
        showGrid = settings.showGrid
        fontsize = settings.fontsize
        tickFontsize = settings.tickFontsize
        legendFontsize = settings.legendFontsize

        # set dimension of dialog
        self.dlgWidth = figWidth * figDpi + 20
        self.dlgHeight = figHeight * figDpi + 100
        self.resize(self.dlgWidth, self.dlgHeight)

        # make size fixed
        self.setMinimumSize(self.dlgWidth, self.dlgHeight)
        self.setMaximumSize(self.dlgWidth, self.dlgHeight)

        # plot widget
        self.mainWidget = QtGui.QWidget(self)

        # setup figure
        self.fig = Figure((figWidth, figHeight), dpi=figDpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mainWidget)

        # axes
        self.axes = self.fig.add_subplot(111)

        # toolbar
        self.mplToolbar = NavigationToolbar(self.canvas, self.mainWidget)

        # get plot method
        if hasattr(self.axes, plotType):
            plotMethod = getattr(self.axes, plotType)

            try:
                # plot
                plotMethod(*plotArgs, **plotKwargs)

                # store plot args for later use
                self.plotArgs = plotArgs

            except Exception as e:
                self.mainWindow.displayError(
                    "Matplotlib plot failed with following error:\n\n%s" %
                    "".join(traceback.format_exception(*sys.exc_info())))
                self.close()

        else:
            self.mainWindow.displayError(
                "Unrecognised matplotlib plot method:\n\n%s" % plotType)

        # show grid
        if showGrid:
            self.axes.grid(True)

        # text size
        for tick in self.axes.xaxis.get_major_ticks():
            tick.label1.set_fontsize(tickFontsize)

        for tick in self.axes.yaxis.get_major_ticks():
            tick.label1.set_fontsize(tickFontsize)

        # axis labels (if specified!)
        if "xlabel" in settingsDict:
            self.axes.set_xlabel(settingsDict["xlabel"], fontsize=fontsize)

        if "ylabel" in settingsDict:
            self.axes.set_ylabel(settingsDict["ylabel"], fontsize=fontsize)

        if "title" in settingsDict:
            self.axes.set_title(settingsDict["title"], fontsize=fontsize)

        # tight layout
        self.fig.tight_layout()

        # draw canvas
        self.canvas.draw()

        # write to file button
        writeDataButton = QtGui.QPushButton("Write csv")
        writeDataButton.setAutoDefault(False)
        writeDataButton.setDefault(False)
        writeDataButton.clicked.connect(self.writeData)
        writeDataButton.setToolTip("Write csv file containing plot data")

        # close button
        closeButton = QtGui.QPushButton("Close")
        closeButton.clicked.connect(self.accept)

        # button box
        buttonBox = QtGui.QDialogButtonBox()
        buttonBox.addButton(writeDataButton, QtGui.QDialogButtonBox.ActionRole)
        buttonBox.addButton(closeButton, QtGui.QDialogButtonBox.AcceptRole)

        # layout
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mplToolbar)
        vbox.addWidget(buttonBox)

        self.mainWidget.setLayout(vbox)
Esempio n. 4
0
    def __init__(self, filename=None, arg=None, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        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.loadSPE)
        self.connect(self.ui.sigTop, 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, QtCore.SIGNAL('triggered()'), self.closeEvent)
        self.connect(self.ui.multisig, QtCore.SIGNAL("toggled(bool)"),
                     self.on_draw)

        if filename != None:
            self.loadSPE(filename)
Esempio n. 5
0
    def drawLayout(self):
        """
        Draws the GUI layout.
        """
        self.widgetslist = [[
            'pair', 'show', 'Instrument', 'combo', self.instruments,
            self.setInstrument, 'InstrumentCombo'
        ],
                            [
                                'pair', 'show', 'Chopper', 'combo', '',
                                self.setChopper, 'ChopperCombo'
                            ],
                            [
                                'pair', 'show', 'Frequency', 'combo', '',
                                self.setFreq, 'FrequencyCombo'
                            ],
                            [
                                'pair', 'hide', 'Pulse remover chopper freq',
                                'combo', '', self.setFreq, 'PulseRemoverCombo'
                            ],
                            [
                                'pair', 'show', 'Ei', 'edit', '', self.setEi,
                                'EiEdit'
                            ],
                            [
                                'pair', 'hide', 'Chopper 2 phase delay time',
                                'edit', '5', self.setFreq, 'Chopper2Phase'
                            ], ['spacer'],
                            [
                                'single', 'show', 'Calculate and Plot',
                                'button', self.calc_callback, 'CalculateButton'
                            ],
                            [
                                'single', 'show', 'Hold current plot', 'check',
                                lambda: None, 'HoldCheck'
                            ],
                            [
                                'single', 'show', 'Show multi-reps', 'check',
                                lambda: None, 'MultiRepCheck'
                            ], ['spacer'],
                            [
                                'single', 'show', 'Show data ascii window',
                                'button', self.showText, 'ShowAsciiButton'
                            ],
                            [
                                'single', 'show', 'Save data as ascii',
                                'button', self.saveText, 'SaveAsciiButton'
                            ]]
        self.droplabels = []
        self.dropboxes = []
        self.singles = []
        self.widgets = {}

        self.leftPanel = QtGui.QVBoxLayout()
        self.rightPanel = QtGui.QVBoxLayout()
        self.tabs = QtGui.QTabWidget(self)
        self.fullWindow = QtGui.QGridLayout()
        for widget in self.widgetslist:
            if 'pair' in widget[0]:
                self.droplabels.append(QtGui.QLabel(widget[2]))
                if 'combo' in widget[3]:
                    self.dropboxes.append(QtGui.QComboBox(self))
                    self.dropboxes[-1].activated['QString'].connect(widget[5])
                    for item in widget[4]:
                        self.dropboxes[-1].addItem(item)
                    self.widgets[widget[-1]] = {
                        'Combo': self.dropboxes[-1],
                        'Label': self.droplabels[-1]
                    }
                elif 'edit' in widget[3]:
                    self.dropboxes.append(QtGui.QLineEdit(self))
                    self.dropboxes[-1].returnPressed.connect(widget[5])
                    self.widgets[widget[-1]] = {
                        'Edit': self.dropboxes[-1],
                        'Label': self.droplabels[-1]
                    }
                else:
                    raise RuntimeError(
                        'Bug in code - widget %s is not recognised.' %
                        (widget[3]))
                self.leftPanel.addWidget(self.droplabels[-1])
                self.leftPanel.addWidget(self.dropboxes[-1])
                if 'hide' in widget[1]:
                    self.droplabels[-1].hide()
                    self.dropboxes[-1].hide()
            elif 'single' in widget[0]:
                if 'check' in widget[3]:
                    self.singles.append(QtGui.QCheckBox(widget[2], self))
                    self.singles[-1].stateChanged.connect(widget[4])
                elif 'button' in widget[3]:
                    self.singles.append(QtGui.QPushButton(widget[2]))
                    self.singles[-1].clicked.connect(widget[4])
                else:
                    raise RuntimeError(
                        'Bug in code - widget %s is not recognised.' %
                        (widget[3]))
                self.leftPanel.addWidget(self.singles[-1])
                if 'hide' in widget[1]:
                    self.singles[-1].hide()
                self.widgets[widget[-1]] = self.singles[-1]
            elif 'spacer' in widget[0]:
                self.leftPanel.addItem(QtGui.QSpacerItem(0, 35))
            else:
                raise RuntimeError(
                    'Bug in code - widget class %s is not recognised.' %
                    (widget[0]))

        # Right panel, matplotlib figures
        self.resfig = Figure()
        self.resfig.patch.set_facecolor('white')
        self.rescanvas = FigureCanvas(self.resfig)
        self.resaxes = self.resfig.add_subplot(111)
        self.resaxes.axhline(color='k')
        self.resaxes.set_xlabel('Energy Transfer (meV)')
        self.resaxes.set_ylabel(r'$\Delta$E (meV FWHM)')
        self.resfig_controls = NavigationToolbar(self.rescanvas, self)
        self.restab = QtGui.QWidget(self.tabs)
        self.restabbox = QtGui.QVBoxLayout()
        self.restabbox.addWidget(self.rescanvas)
        self.restabbox.addWidget(self.resfig_controls)
        self.restab.setLayout(self.restabbox)

        self.flxfig = Figure()
        self.flxfig.patch.set_facecolor('white')
        self.flxcanvas = FigureCanvas(self.flxfig)
        self.flxaxes1 = self.flxfig.add_subplot(121)
        self.flxaxes1.set_xlabel('Incident Energy (meV)')
        self.flxaxes1.set_ylabel('Flux (n/cm$^2$/s)')
        self.flxaxes2 = self.flxfig.add_subplot(122)
        self.flxaxes2.set_xlabel('Incident Energy (meV)')
        self.flxaxes2.set_ylabel('Elastic Resolution FWHM (meV)')
        self.flxfig_controls = NavigationToolbar(self.flxcanvas, self)
        self.flxsldfg = Figure()
        self.flxsldfg.patch.set_facecolor('white')
        self.flxsldcv = FigureCanvas(self.flxsldfg)
        self.flxsldax = self.flxsldfg.add_subplot(111)
        self.flxslder = Slider(self.flxsldax, 'Ei (meV)', 0, 100, valinit=100)
        self.flxslder.valtext.set_visible(False)
        self.flxslder.on_changed(self.update_slider)
        self.flxedt = QtGui.QLineEdit()
        self.flxedt.setText('1000')
        self.flxedt.returnPressed.connect(self.update_slider)
        self.flxtab = QtGui.QWidget(self.tabs)
        self.flxsldbox = QtGui.QHBoxLayout()
        self.flxsldbox.addWidget(self.flxsldcv)
        self.flxsldbox.addWidget(self.flxedt)
        self.flxsldwdg = QtGui.QWidget()
        self.flxsldwdg.setLayout(self.flxsldbox)
        sz = self.flxsldwdg.maximumSize()
        sz.setHeight(50)
        self.flxsldwdg.setMaximumSize(sz)
        self.flxtabbox = QtGui.QVBoxLayout()
        self.flxtabbox.addWidget(self.flxcanvas)
        self.flxtabbox.addWidget(self.flxsldwdg)
        self.flxtabbox.addWidget(self.flxfig_controls)
        self.flxtab.setLayout(self.flxtabbox)

        self.frqfig = Figure()
        self.frqfig.patch.set_facecolor('white')
        self.frqcanvas = FigureCanvas(self.frqfig)
        self.frqaxes1 = self.frqfig.add_subplot(121)
        self.frqaxes1.set_xlabel('Chopper Frequency (Hz)')
        self.frqaxes1.set_ylabel('Flux (n/cm$^2$/s)')
        self.frqaxes2 = self.frqfig.add_subplot(122)
        self.frqaxes1.set_xlabel('Chopper Frequency (Hz)')
        self.frqaxes2.set_ylabel('Elastic Resolution FWHM (meV)')
        self.frqfig_controls = NavigationToolbar(self.frqcanvas, self)
        self.frqtab = QtGui.QWidget(self.tabs)
        self.frqtabbox = QtGui.QVBoxLayout()
        self.frqtabbox.addWidget(self.frqcanvas)
        self.frqtabbox.addWidget(self.frqfig_controls)
        self.frqtab.setLayout(self.frqtabbox)

        self.repfig = Figure()
        self.repfig.patch.set_facecolor('white')
        self.repcanvas = FigureCanvas(self.repfig)
        self.repaxes = self.repfig.add_subplot(111)
        self.repaxes.axhline(color='k')
        self.repaxes.set_xlabel(r'TOF ($\mu$sec)')
        self.repaxes.set_ylabel('Distance (m)')
        self.repfig_controls = NavigationToolbar(self.repcanvas, self)
        self.repfig_nframe_label = QtGui.QLabel('Number of frames to plot')
        self.repfig_nframe_edit = QtGui.QLineEdit('1')
        self.repfig_nframe_button = QtGui.QPushButton('Replot')
        self.repfig_nframe_button.clicked.connect(lambda: self.plot_frame())
        self.repfig_nframe_box = QtGui.QHBoxLayout()
        self.repfig_nframe_box.addWidget(self.repfig_nframe_label)
        self.repfig_nframe_box.addWidget(self.repfig_nframe_edit)
        self.repfig_nframe_box.addWidget(self.repfig_nframe_button)
        self.reptab = QtGui.QWidget(self.tabs)
        self.repfig_nframe = QtGui.QWidget(self.reptab)
        self.repfig_nframe.setLayout(self.repfig_nframe_box)
        self.repfig_nframe.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
                              QtGui.QSizePolicy.Fixed))
        self.reptabbox = QtGui.QVBoxLayout()
        self.reptabbox.addWidget(self.repcanvas)
        self.reptabbox.addWidget(self.repfig_nframe)
        self.reptabbox.addWidget(self.repfig_controls)
        self.reptab.setLayout(self.reptabbox)

        self.qefig = Figure()
        self.qefig.patch.set_facecolor('white')
        self.qecanvas = FigureCanvas(self.qefig)
        self.qeaxes = self.qefig.add_subplot(111)
        self.qeaxes.axhline(color='k')
        self.qeaxes.set_xlabel(r'$|Q| (\mathrm{\AA}^{-1})$')
        self.qeaxes.set_ylabel('Energy Transfer (meV)')
        self.qefig_controls = NavigationToolbar(self.qecanvas, self)
        self.qetabbox = QtGui.QVBoxLayout()
        self.qetabbox.addWidget(self.qecanvas)
        self.qetabbox.addWidget(self.qefig_controls)
        self.qetab = QtGui.QWidget(self.tabs)
        self.qetab.setLayout(self.qetabbox)

        self.scrtab = QtGui.QWidget(self.tabs)
        self.scredt = QtGui.QTextEdit()
        self.scrcls = QtGui.QPushButton("Clear")
        self.scrcls.clicked.connect(lambda: self.scredt.clear())
        self.scrbox = QtGui.QVBoxLayout()
        self.scrbox.addWidget(self.scredt)
        self.scrbox.addWidget(self.scrcls)
        self.scrtab.setLayout(self.scrbox)
        self.scrtab.hide()

        self.tabs.addTab(self.restab, 'Resolution')
        self.tabs.addTab(self.flxtab, 'Flux-Ei')
        self.tabs.addTab(self.frqtab, 'Flux-Freq')
        self.tabs.addTab(self.reptab, 'Time-Distance')
        self.tdtabID = 3
        self.tabs.setTabEnabled(self.tdtabID, False)
        self.tabs.addTab(self.qetab, 'Q-E')
        self.qetabID = 4
        self.tabs.setTabEnabled(self.qetabID, False)
        self.scrtabID = 5
        self.rightPanel.addWidget(self.tabs)

        self.menuLoad = QtGui.QMenu('Load')
        self.loadAct = QtGui.QAction('Load YAML', self.menuLoad)
        self.loadAct.triggered.connect(self.loadYaml)
        self.menuLoad.addAction(self.loadAct)
        self.menuOptions = QtGui.QMenu('Options')
        self.instSciAct = QtGui.QAction('Instrument Scientist Mode',
                                        self.menuOptions,
                                        checkable=True)
        self.instSciAct.triggered.connect(self.instSciCB)
        self.menuOptions.addAction(self.instSciAct)
        self.eiPlots = QtGui.QAction('Press Enter in Ei box updates plots',
                                     self.menuOptions,
                                     checkable=True)
        self.menuOptions.addAction(self.eiPlots)
        self.overwriteload = QtGui.QAction(
            'Always overwrite instruments in memory',
            self.menuOptions,
            checkable=True)
        self.menuOptions.addAction(self.overwriteload)
        self.menuBar().addMenu(self.menuLoad)
        self.menuBar().addMenu(self.menuOptions)

        self.leftPanelWidget = QtGui.QWidget()
        self.leftPanelWidget.setLayout(self.leftPanel)
        self.leftPanelWidget.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed,
                              QtGui.QSizePolicy.Preferred))
        self.fullWindow.addWidget(self.leftPanelWidget, 0, 0)
        self.fullWindow.addLayout(self.rightPanel, 0, 1)
        self.helpbtn = QtGui.QPushButton("?", self)
        self.helpbtn.setMaximumWidth(30)
        self.helpbtn.clicked.connect(self.onHelp)
        self.fullWindow.addWidget(self.helpbtn, 1, 0, 1, -1)

        self.mainWidget = QtGui.QWidget()
        self.mainWidget.setLayout(self.fullWindow)
        self.setCentralWidget(self.mainWidget)
        self.setWindowTitle('PyChopGUI')
        self.show()
Esempio n. 6
0
    def createMainFrame(self):
        self.mainFrame = QtGui.QWidget()
        self.dpi = 100
        self.fig = Figure((7.0, 7.0), dpi=self.dpi)
        #Creating Canvas which will figure
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mainFrame)
        self.axes = self.fig.add_subplot(111)
        self.navToolBar = NavigationToolbar(self.canvas, self.mainFrame)

        #LeftVbox hold navigation tool bar and canvas
        self.left_vbox = QtGui.QVBoxLayout()
        self.left_vbox.addWidget(self.navToolBar)
        self.left_vbox.addWidget(self.canvas)

        #right VBOX is main Layout which hold right grid(bottom part) and top grid(top part)
        self.right_vbox = QtGui.QVBoxLayout()
        self.right_grid = QtGui.QGridLayout()
        self.top_grid = QtGui.QGridLayout()

        #Get DataExtraction Details
        self.obj_dataext = DataExtraction()
        self.plotType = self.obj_dataext.openFile(self.fpath)

        self.obj_dataext.computeAxes()
        self.a = self.obj_dataext.numVals()

        self.chkbox = []

        ########### Generating list of colors :
        self.full_colors = [
            'r', 'b', 'g', 'y', 'c', 'm', 'k'
        ]  #,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)]
        self.color = []
        for i in range(0, self.a[0] - 1):
            if i % 7 == 0:
                self.color.append(self.full_colors[0])
            elif (i - 1) % 7 == 0:
                self.color.append(self.full_colors[1])
            elif (i - 2) % 7 == 0:
                self.color.append(self.full_colors[2])
            elif (i - 3) % 7 == 0:
                self.color.append(self.full_colors[3])
            elif (i - 4) % 7 == 0:
                self.color.append(self.full_colors[4])
            elif (i - 5) % 7 == 0:
                self.color.append(self.full_colors[5])
            elif (i - 6) % 7 == 0:
                self.color.append(self.full_colors[6])

        ###########Color generation ends here

        #Total number of voltage source
        self.volts_length = self.a[1]
        self.analysisType = QtGui.QLabel()
        self.top_grid.addWidget(self.analysisType, 0, 0)
        self.listNode = QtGui.QLabel()
        self.top_grid.addWidget(self.listNode, 1, 0)
        self.listBranch = QtGui.QLabel()
        self.top_grid.addWidget(self.listBranch, self.a[1] + 2, 0)
        for i in range(0, self.a[1]):  #a[0]-1
            self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i]))
            self.chkbox[i].setStyleSheet('color')
            self.chkbox[i].setToolTip('<b>Check To Plot</b>')
            self.top_grid.addWidget(self.chkbox[i], i + 2, 0)
            self.colorLab = QtGui.QLabel()
            self.colorLab.setText('____')
            self.colorLab.setStyleSheet(
                self.colorName(self.color[i]) + '; font-weight = bold;')
            self.top_grid.addWidget(self.colorLab, i + 2, 1)

        for i in range(self.a[1], self.a[0] - 1):  #a[0]-1
            self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i]))
            self.chkbox[i].setToolTip('<b>Check To Plot</b>')
            self.top_grid.addWidget(self.chkbox[i], i + 3, 0)
            self.colorLab = QtGui.QLabel()
            self.colorLab.setText('____')
            self.colorLab.setStyleSheet(
                self.colorName(self.color[i]) + '; font-weight = bold;')
            self.top_grid.addWidget(self.colorLab, i + 3, 1)

        self.clear = QtGui.QPushButton("Clear")
        self.warnning = QtGui.QLabel()
        self.funcName = QtGui.QLabel()
        self.funcExample = QtGui.QLabel()

        self.plotbtn = QtGui.QPushButton("Plot")
        self.plotbtn.setToolTip('<b>Press</b> to Plot')
        self.multimeterbtn = QtGui.QPushButton("Multimeter")
        self.multimeterbtn.setToolTip(
            '<b>RMS</b> value of the current and voltage is displayed')
        self.text = QtGui.QLineEdit()
        self.funcLabel = QtGui.QLabel()
        self.palette1 = QtGui.QPalette()
        self.palette2 = QtGui.QPalette()
        self.plotfuncbtn = QtGui.QPushButton("Plot Function")
        self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function')

        self.palette1.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue)
        self.palette2.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red)
        self.funcName.setPalette(self.palette1)
        self.funcExample.setPalette(self.palette2)

        self.right_vbox.addLayout(self.top_grid)
        self.right_vbox.addWidget(self.plotbtn)
        self.right_vbox.addWidget(self.multimeterbtn)

        self.right_grid.addWidget(self.funcLabel, 1, 0)
        self.right_grid.addWidget(self.text, 1, 1)
        self.right_grid.addWidget(self.plotfuncbtn, 2, 1)
        self.right_grid.addWidget(self.clear, 2, 0)
        self.right_grid.addWidget(self.warnning, 3, 0)
        self.right_grid.addWidget(self.funcName, 4, 0)
        self.right_grid.addWidget(self.funcExample, 4, 1)
        self.right_vbox.addLayout(self.right_grid)

        self.hbox = QtGui.QHBoxLayout()
        self.hbox.addLayout(self.left_vbox)
        self.hbox.addLayout(self.right_vbox)

        self.widget = QtGui.QWidget()
        self.widget.setLayout(self.hbox)  #finalvbox
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.widget)

        self.finalhbox = QtGui.QHBoxLayout()
        self.finalhbox.addWidget(self.scrollArea)

        self.mainFrame.setLayout(self.finalhbox)
        self.showMaximized()

        self.listNode.setText("<font color='indigo'>List of Nodes:</font>")
        self.listBranch.setText(
            "<font color='indigo'>List of Branches:</font>")
        self.funcLabel.setText("<font color='indigo'>Function:</font>")
        self.funcName.setText("<font color='indigo'>Standard functions</font>\
                <br><br>Addition:<br>Subtraction:<br>Multiplication:<br>Division:<br>Comparison:"
                              )
        self.funcExample.setText(
            "\n\nNode1 + Node2\nNode1 - Node2\nNode1 * Node2\nNode1 / Node2\nNode1 vs Node2"
        )

        #Connecting to plot and clear function
        self.connect(self.clear, QtCore.SIGNAL('clicked()'), self.pushedClear)
        self.connect(self.plotfuncbtn, QtCore.SIGNAL('clicked()'),
                     self.pushedPlotFunc)
        self.connect(self.multimeterbtn, QtCore.SIGNAL('clicked()'),
                     self.multiMeter)

        if self.plotType[0] == 0:
            self.analysisType.setText("<b>AC Analysis</b>")
            if self.plotType[1] == 1:
                self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                             self.onPush_decade)
            else:
                self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                             self.onPush_ac)

        elif self.plotType[0] == 1:
            self.analysisType.setText("<b>Transient Analysis</b>")
            self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                         self.onPush_trans)

        else:
            self.analysisType.setText("<b>DC Analysis</b>")
            self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                         self.onPush_dc)

        self.setCentralWidget(self.mainFrame)
Esempio n. 7
0
    def pregxs(self):
        if self.ui.tabWidget.count() == 4:
            self.ui.tabWidget.removeTab(3)
        SASTBXpathfile = os.path.join(base, "SASTBXpath.txt")
        with open(SASTBXpathfile, "r") as f1:
            self.SASTBXpath = f1.read().strip()
        env = str(os.path.join(self.SASTBXpath, 'build', 'bin')) + ':'
        self.targetfile_SAS = os.path.join(self.SASTBXpath, "modules",
                                           "cctbx_project", "sastbx",
                                           "targetpath_GUI.txt")
        with open(self.targetfile_SAS, "w") as f:
            print >> f, self.targetdir
        os.environ['PATH'] = env + os.environ['PATH']

        self.ui.textBrowser.clear()
        datfile = str(self.ui.dat_lineEdit.displayText()).strip()
        dmax = str(self.ui.dmax_lineEdit.displayText()).strip()
        scan = str(self.ui.scan_comboBox.currentText())
        # with open(str(sys.path[0])+"/tmp.txt","r") as f:
        # 	project=f.read().strip()
        project = self.targetdir
        self.outdir = os.path.join(self.targetdir, "Pr_Estimation")
        datname = datfile.split(".")[0].split("/")[-1]
        output = os.path.join(self.outdir, datname)

        if os.path.isdir(self.outdir) == False:
            os.makedirs(self.outdir)

        if datfile == '':
            msgBox = QtGui.QMessageBox()
            msgBox.setTextFormat(QtCore.Qt.RichText)
            msgBox.setIcon(QtGui.QMessageBox.Critical)

            msgBox.setText("Please input the dat file")
            msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
            ret = msgBox.exec_()
            if ret == QtGui.QMessageBox.Ok:
                return False

        elif dmax == '':
            msgBox = QtGui.QMessageBox()
            msgBox.setTextFormat(QtCore.Qt.RichText)
            msgBox.setIcon(QtGui.QMessageBox.Critical)

            msgBox.setText("Please input dmax")
            msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
            ret = msgBox.exec_()
            if ret == QtGui.QMessageBox.Ok:
                return False
        else:
            command = "sastbx.pregxs"
            command = command + " data=%s" % datfile
            command = command + " d_max=%s" % dmax
            command = command + " scan=%s" % scan
            command = command + " output=%s" % str(output)
            self.movie_screen = QtGui.QLabel()
            self.movie_screen.setText("The program is running, please wait")
            self.ui.tabWidget.setCurrentIndex(2)
            #self.pregxsfile = os.path.join(self.targetdir,"Pr_Estimation","temp.txt")
            self.pregxsfile = os.path.join(self.SASTBXpath, "modules",
                                           "cctbx_project", "sastbx",
                                           "pregxs.txt")

            ###########copy input file to out dir
            shutil.copy(datfile, self.outdir)

            progdialog = QtGui.QProgressDialog(self)
            progdialog.setWindowTitle("Renaming Archives")
            progdialog.setWindowModality(QtCore.Qt.WindowModal)
            progdialog.setLabel(self.movie_screen)
            progdialog.show()
            # child = subprocess.Popen(shlex.split(command),stdout=subprocess.PIPE,shell=False)
            # out = child.communicate()
            iner = open(self.pregxsfile, "w")
            iner.write("Start.")
            iner.close()
            import threading
            t = []
            t.append(threading.Thread(target=self.run(command)))
            t.append(threading.Thread(target=self.read()))
            for t1 in t:
                t1.setDaemon(True)
                t1.start()
                t1.join()
            progdialog.close()
            # explainStr = "The result files are saved in the following directory"
            # self.ui.textBrowser.append(explainStr)
            # self.ui.textBrowser.append(os.path.join(project,"pregxs"))

            # result = str(str(out[0]).split()[3])
            # self.ui.textBrowser.append(str(out))
            self.ui.tabWidget.setCurrentIndex(2)

            if scan == "False":
                ######add widget to tabwidget############
                ########pr page###########

                self.summary_tab = QtGui.QTabWidget()
                summarypage = QtGui.QWidget()
                summarylayout = QtGui.QVBoxLayout(summarypage)
                # file = output+"average.pr"
                # step_list,pr_list = self.getlist(file)

                file2 = output + "best.pr"
                step_list2, pr_list2 = self.getlist_pr(file2)

                sc1 = MyMplCanvas11(step_list2, pr_list2, "step",
                                    "pair distance", "best pair distance",
                                    "Pair_distance distribution")

                self.ntb1 = NavigationToolbar(sc1, self)
                summarylayout.addWidget(self.ntb1)
                summarylayout.addWidget(sc1)

                self.summary_tab.addTab(summarypage, "pair distance")
                ##########qii page###############

                summarypage2 = QtGui.QWidget()
                summarylayout2 = QtGui.QVBoxLayout(summarypage2)

                inputq, inputi = self.getlist(datfile)
                bestqi_file = output + "best.qii"
                bestq, besti = self.getlist(bestqi_file)

                sc2 = MyMplCanvas2(inputq, inputi, bestq, besti, "q",
                                   "intensity(log)", "input saxs file",
                                   "best intensity file",
                                   "Intensity Comparison")
                self.ntb2 = NavigationToolbar(sc2, self)
                summarylayout2.addWidget(self.ntb2)
                summarylayout2.addWidget(sc2)

                self.summary_tab.addTab(summarypage2, "Intensity")

                self.ui.tabWidget.addTab(self.summary_tab, "summary")

            else:

                self.summary_tab = QtGui.QTabWidget()
                summarypage = QtGui.QWidget()
                summarylayout = QtGui.QVBoxLayout(summarypage)
                # file = output+"average.pr"
                # step_list,pr_list = self.getlist(file)

                file2 = output + "best.pr"
                step_list2, pr_list2 = self.getlist_pr(file2)

                file3 = output + "average.pr"
                step_list3, pr_list3 = self.getlist_pr(file3)

                sc1 = MyMplCanvas2(step_list2, pr_list2, step_list3, pr_list3,
                                   "step", "pair distance",
                                   "best pair distance",
                                   "average pair distance",
                                   "Pair_distance distribution")

                self.ntb1 = NavigationToolbar(sc1, self)
                summarylayout.addWidget(self.ntb1)
                summarylayout.addWidget(sc1)

                self.summary_tab.addTab(summarypage, "pair distance")

                ##########qii page###############

                summarypage2 = QtGui.QWidget()
                summarylayout2 = QtGui.QVBoxLayout(summarypage2)

                inputq, inputi = self.getlist(datfile)
                bestqi_file = output + "best.qii"
                bestq, besti = self.getlist(bestqi_file)

                sc2 = MyMplCanvas2(inputq, inputi, bestq, besti, "q",
                                   "intensity(log)", "input saxs file",
                                   "best intensity file",
                                   "Intensity Comparison")
                self.ntb2 = NavigationToolbar(sc2, self)
                summarylayout2.addWidget(self.ntb2)
                summarylayout2.addWidget(sc2)

                self.summary_tab.addTab(summarypage2, "Intensity")

                self.ui.tabWidget.addTab(self.summary_tab, "summary")
                # self.summary_tab = QtGui.QTabWidget()
                # summarypage = QtGui.QWidget()
                # summarylayout = QtGui.QVBoxLayout(summarypage)
                # file2 =output+"average.pr"
                # step_list2,pr_list2 = self.getlist_pr(file2)
                # sc1 = MyMplCanvas11(step_list2,pr_list2,"step","pair distance","average pair distance","Pair_distance distribution" )
                # self.ntb1 = NavigationToolbar(sc1,self)
                # summarylayout.addWidget(self.ntb1)
                # summarylayout.addWidget(sc1)

                # self.summary_tab.addTab(summarypage,"pair distance")
                # self.ui.tabWidget.addTab(self.summary_tab,"summary")

            shutil.copy(self.pregxsfile, self.outdir)
            os.rename(os.path.join(self.outdir, "pregxs.txt"),
                      os.path.join(self.outdir, "log.txt"))

        with open(self.targetfile_SAS, "w") as f:
            f.truncate()
Esempio n. 8
0
 def __init__(self, parent):
     self.figure = figure.Figure(facecolor='white')
     self.canvas = FigureCanvas(self.figure)
     self.toolbar = NavigationToolbar(self.canvas, parent)
Esempio n. 9
0
    def create_main_frame(self):
        """
        """

        self.main_frame = QWidget()

        # create the matplotlib figure
        self.dpi = 100
        # initial figure size in inch
        self.fig = Figure((9.0, 5.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # using subplot in order to get the navigation toolbar working
        self.axes = self.fig.add_subplot(111)
        # create the navigation toolbar
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        load_label = QLabel()
        load_label.setText("Load CWA database files:")

        self.load1_button = QPushButton("Load CWA-SQLite &1")
        self.connect(self.load1_button, SIGNAL('clicked()'), self.open1)
        self.load1_label = QLabel()

        self.load2_button = QPushButton("Load CWA-SQLite &2")
        self.connect(self.load2_button, SIGNAL('clicked()'), self.open2)
        self.load2_label = QLabel()

        self.find_matches_button = QPushButton("&Find matches")
        self.find_matches_button.setEnabled(False)
        self.connect(self.find_matches_button, SIGNAL('clicked()'),
                     self.getMatches)
        self.find_matches_label = QLabel()

        self.x_acc_cb = QCheckBox("&x-acceleration")
        self.x_acc_cb.setChecked(True)
        self.connect(self.x_acc_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.y_acc_cb = QCheckBox("&y-acceleration")
        self.connect(self.y_acc_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.z_acc_cb = QCheckBox("&z-acceleration")
        self.connect(self.z_acc_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.light_cb = QCheckBox("&light")
        self.connect(self.light_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.temperature_cb = QCheckBox("&temperature")
        self.connect(self.temperature_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.battery_cb = QCheckBox("&battery")
        self.connect(self.battery_cb, SIGNAL('stateChanged(int)'),
                     self.getMatchedGraph)

        self.x_acc_exp = QCheckBox("x-acceleration")
        self.y_acc_exp = QCheckBox("y-acceleration")
        self.z_acc_exp = QCheckBox("z-acceleration")
        self.light_exp = QCheckBox("light")
        self.temperature_exp = QCheckBox("temperature")
        self.battery_exp = QCheckBox("battery")

        self.export_button = QPushButton("&Export data")
        self.connect(self.export_button, SIGNAL('clicked()'), self.export_data)

        #
        # Layout with box sizers
        #
        hbox_load = QHBoxLayout()
        vbox_load1 = QVBoxLayout()
        vbox_load1.addWidget(self.load1_button)
        vbox_load1.addWidget(self.load1_label)
        hbox_load.addLayout(vbox_load1)
        vbox_load2 = QVBoxLayout()
        vbox_load2.addWidget(self.load2_button)
        vbox_load2.addWidget(self.load2_label)
        hbox_load.addLayout(vbox_load2)
        vbox_load3 = QVBoxLayout()
        vbox_load3.addWidget(self.find_matches_button)
        vbox_load3.addWidget(self.find_matches_label)
        hbox_load.addLayout(vbox_load3)

        self.start_label = QLabel("Start point:")
        self.lm1 = ListModel([], self)
        self.list_view1 = QListView()
        self.list_view1.setModel(self.lm1)
        self.connect(
            self.list_view1.selectionModel(),
            SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            self.slot_match1)

        self.end_label = QLabel("End point:")
        self.lm2 = ListModel([], self)
        self.list_view2 = QListView()
        self.list_view2.setModel(self.lm2)
        self.connect(
            self.list_view2.selectionModel(),
            SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),
            self.slot_match2)

        hbox_matches = QHBoxLayout()
        vbox_matches1 = QVBoxLayout()
        vbox_matches1.addWidget(self.start_label)
        vbox_matches1.addWidget(self.list_view1)
        hbox_matches.addLayout(vbox_matches1)
        vbox_matches2 = QVBoxLayout()
        vbox_matches2.addWidget(self.end_label)
        vbox_matches2.addWidget(self.list_view2)
        hbox_matches.addLayout(vbox_matches2)

        hbox_preview = QHBoxLayout()
        for w in [
                self.x_acc_cb, self.y_acc_cb, self.z_acc_cb, self.battery_cb,
                self.temperature_cb, self.light_cb
        ]:
            hbox_preview.addWidget(w)
            hbox_preview.setAlignment(w, Qt.AlignVCenter)

        # group box for preview data
        self.groupBox_preview = QGroupBox('Show data in preview')
        self.groupBox_preview.setLayout(hbox_preview)

        # export layout
        vbox_export = QVBoxLayout()
        hbox_export_axis = QHBoxLayout()
        for w in [
                self.x_acc_exp, self.y_acc_exp, self.z_acc_exp,
                self.battery_exp, self.temperature_exp, self.light_exp
        ]:
            hbox_export_axis.addWidget(w)
            hbox_export_axis.setAlignment(w, Qt.AlignVCenter)
        vbox_export.addLayout(hbox_export_axis)
        vbox_export.addWidget(self.export_button)

        # groupbox for the export things
        self.groupBox_export = QGroupBox('Export synchronized data')
        self.groupBox_export.setLayout(vbox_export)

        # the main vertical layout
        vbox_main = QVBoxLayout()
        vbox_main.addWidget(load_label)
        vbox_main.addLayout(hbox_load)
        vbox_main.addLayout(hbox_matches)
        vbox_main.addWidget(self.canvas)
        vbox_main.addWidget(self.mpl_toolbar)
        vbox_main.addWidget(self.groupBox_preview)
        vbox_main.addWidget(self.groupBox_export)

        self.main_frame.setLayout(vbox_main)
        self.setCentralWidget(self.main_frame)
Esempio n. 10
0
    def __init__(self, parent, prm):
        QMainWindow.__init__(self, parent)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        self.prm = prm
        self.currLocale = self.parent().prm['data']['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)

        #define some parameters before axes creation
        self.canvasColor = pltColorFromQColor(self.prm['pref']['canvasColor'])
        self.backgroundColor = pltColorFromQColor(self.prm['pref']['backgroundColor'])
        self.axesColor = pltColorFromQColor(self.prm['pref']['axes_color'])
        self.tickLabelColor = pltColorFromQColor(self.prm['pref']['tick_label_color'])
        self.gridColor = pltColorFromQColor(self.prm['pref']['grid_color'])
        self.axesLabelColor = pltColorFromQColor(self.prm['pref']['axes_label_color'])
        self.labelFontFamily = self.prm['pref']['label_font_family']
        self.labelFontWeight = self.prm['pref']['label_font_weight']
        self.labelFontStyle = self.prm['pref']['label_font_style']
        self.labelFontSize = self.prm['pref']['label_font_size']
        self.labelFont = font_manager.FontProperties(family=self.labelFontFamily,
                                                     weight=self.labelFontWeight,
                                                     style= self.labelFontStyle,
                                                     size=self.labelFontSize)
        
        self.majorTickLength = self.prm['pref']['major_tick_length']
        self.majorTickWidth = self.prm['pref']['major_tick_width']
        self.minorTickLength = self.prm['pref']['minor_tick_length']
        self.minorTickWidth = self.prm['pref']['minor_tick_width']
        self.tickLabelFontFamily = self.prm['pref']['tick_label_font_family']
        self.tickLabelFontWeight = self.prm['pref']['tick_label_font_weight']
        self.tickLabelFontStyle = self.prm['pref']['tick_label_font_style']
        self.tickLabelFontSize = self.prm['pref']['tick_label_font_size']
        self.tickLabelFont = font_manager.FontProperties(family=self.tickLabelFontFamily,
                                                         weight=self.tickLabelFontWeight,
                                                         style= self.tickLabelFontStyle,
                                                         size=self.tickLabelFontSize)
        self.xAxisLabel = ''
        self.yAxisLabel = ''
        self.dpi = self.prm['pref']['dpi']
        self.spinesLineWidth = self.prm['pref']['spines_line_width']
        self.gridLineWidth = self.prm['pref']['grid_line_width']

        self.mw = QWidget(self)
        self.vbl = QVBoxLayout(self.mw)
        self.fig = Figure(facecolor=self.canvasColor, dpi=self.dpi)
        self.axes = self.fig.add_subplot(111, facecolor=self.backgroundColor)
       
        self.createBaseMenus()
        self.createAdditionalMenus()
        self.defineMenusLayout()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mw)
       
        self.ntb = NavigationToolbar(self.canvas, self.mw)
        self.gridOn = QCheckBox(self.tr('Grid'))
        self.gridOn.setChecked(self.prm['pref']['grid'])
        self.gridOn.stateChanged[int].connect(self.toggleGrid)
        self.setBaseFigureProperties()
        self.gridBox = QGridLayout()
        self.createBaseControlWidgets()

        self.createAdditionalControlWidgets()
        self.defineGridBoxLayout()

        self.ntbBox = QHBoxLayout()
        self.ntbBox.addWidget(self.ntb)
        self.ntbBox.addWidget(self.gridOn)
        
        self.vbl.addWidget(self.canvas)
        self.vbl.addLayout(self.ntbBox)
        self.vbl.addLayout(self.gridBox)
        self.mw.setFocus()
        self.setCentralWidget(self.mw)
        self.show()
        self.canvas.draw()
Esempio n. 11
0
    def __init__(self, parent, filename, settings):
        super(ResultWidget, self).__init__(parent)
        self.filename = unicode(filename)
        self.settings = settings.copy()
        self.dirty = True
        self.settings.OUTPUT = "-"

        self.results = ResultSet.load_file(self.filename)
        self.extra_results = []
        self.settings.update(self.results.meta())
        self.settings.load_test(informational=True)
        self.settings.compute_missing_results(self.results)

        try:
            self.formatter = PlotFormatter(self.settings)
        except Exception as e:
            traceback.print_exc()
            if isinstance(e, RuntimeError):
                err = "%s" % e
            else:
                typ, val, tra = sys.exc_info()
                err = "".join(traceback.format_exception_only(typ, val))
            QMessageBox.warning(
                self, "Error loading plot",
                "Error while loading plot:\n\n%s\nFalling back to default plot. Full traceback output to console."
                % err)

            self.settings.PLOT = self.settings.DEFAULTS['PLOT']
            self.formatter = PlotFormatter(self.settings)

        self.canvas = FigureCanvas(self.formatter.figure)
        self.canvas.setParent(self.graphDisplay)
        self.toolbar = NavigationToolbar(self.canvas, self.graphDisplay)

        vbl = QVBoxLayout()
        vbl.addWidget(self.canvas)
        vbl.addWidget(self.toolbar)
        self.graphDisplay.setLayout(vbl)

        self.plotModel = PlotModel(self, self.settings)
        self.plotSelectionModel = QItemSelectionModel(self.plotModel)
        self.plotSelectionModel.setCurrentIndex(
            self.plotModel.index_of(self.settings.PLOT),
            QItemSelectionModel.SelectCurrent)
        self.plotSelectionModel.currentChanged.connect(self.change_plot)

        self.metadataModel = MetadataModel(self, self.results.meta())
        self.metadataSelectionModel = QItemSelectionModel(self.metadataModel)

        if self.settings.TITLE:
            self.title = "%s - %s" % (self.settings.NAME, self.settings.TITLE)
            self.long_title = "%s - %s" % (
                self.title, self.settings.TIME.strftime("%Y-%m-%d %H:%M:%S"))
        else:
            self.title = "%s - %s" % (
                self.settings.NAME,
                self.settings.TIME.strftime("%Y-%m-%d %H:%M:%S"))
            self.long_title = self.title

        if self.settings.GUI_NO_DEFER:
            self.redraw()
Esempio n. 12
0
    def initGUI(self):
        self.main_frame = QWidget(self)

        # XY plot and toolbar
        self.fig_xy = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas_xy = FigureCanvas(self.fig_xy)
        self.canvas_xy.setParent(self.main_frame)
        self.ax_xy = self.fig_xy.add_subplot(111)
        self.ax_xy.set_title('Click and drag a point to move it')
        box = self.ax_xy.get_position()
        self.ax_xy.set_position(
            [box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9])
        self.mpl_toolbar_xy = NavigationToolbar(self.canvas_xy,
                                                self.main_frame)

        def pan_callback():
            self.panned = True

        self.fig_xy.canvas.toolbar.actions()[4].triggered.connect(pan_callback)

        # XZ, YZ plot and toolbar
        self.fig_xz_yz = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas_xz_yz = FigureCanvas(self.fig_xz_yz)
        self.canvas_xz_yz.setParent(self.main_frame)
        gs = matplotlib.gridspec.GridSpec(2, 1)
        self.ax_xz = self.fig_xz_yz.add_subplot(gs[0])
        self.ax_xz.axes.set_frame_on(False)
        self.ax_yz = self.fig_xz_yz.add_subplot(gs[1])
        self.ax_yz.axes.set_frame_on(False)
        self.mpl_toolbar_xz_yz = NavigationToolbar(self.canvas_xz_yz,
                                                   self.main_frame)

        # optional color plot and toolbar
        if hasattr(self._seq.data[self.curFrame], 'colorFileName'):
            self.fig_color = Figure((5.0, 4.0), dpi=self.dpi)
            self.canvas_color = FigureCanvas(self.fig_color)
            self.canvas_color.setParent(self.main_frame)
            self.ax_color = self.fig_color.add_subplot(111)
            self.ax_color.axes.set_frame_on(False)
            self.mpl_toolbar_color = NavigationToolbar(self.canvas_color,
                                                       self.main_frame)
        else:
            self.ax_color = None

        # Layout with posebit controls
        hbox_pb_controls = QHBoxLayout()

        self.prevButton = QPushButton('Previous', self.main_frame)
        self.connect(self.prevButton, SIGNAL('clicked()'),
                     self.prevButton_callback)
        hbox_pb_controls.addWidget(self.prevButton)

        self.pointcloudButton = QPushButton('3D View', self.main_frame)
        self.connect(self.pointcloudButton, SIGNAL('clicked()'),
                     self.pointcloudButton_callback)
        hbox_pb_controls.addWidget(self.pointcloudButton)

        self.nextButton = QPushButton('Next', self.main_frame)
        self.connect(self.nextButton, SIGNAL('clicked()'),
                     self.nextButton_callback)
        hbox_pb_controls.addWidget(self.nextButton)

        hbox_plots = QHBoxLayout()

        vbox_xy = QVBoxLayout()
        vbox_xy.addWidget(self.canvas_xy)
        vbox_xy.addWidget(self.mpl_toolbar_xy)
        hbox_plots.addLayout(vbox_xy)

        vbox_xz_yz = QVBoxLayout()
        vbox_xz_yz.addWidget(self.canvas_xz_yz)
        vbox_xz_yz.addWidget(self.mpl_toolbar_xz_yz)
        hbox_plots.addLayout(vbox_xz_yz)

        if self.ax_color is not None:
            vbox_color = QVBoxLayout()
            vbox_color.addWidget(self.canvas_color)
            vbox_color.addWidget(self.mpl_toolbar_color)
            hbox_plots.addLayout(vbox_color)

        vbox_all = QVBoxLayout()
        vbox_all.addLayout(hbox_plots)
        sep = QFrame(self.main_frame)
        sep.setFrameShape(QFrame.HLine)
        sep.setFrameShadow(QFrame.Sunken)
        vbox_all.addWidget(sep)
        vbox_all.addLayout(hbox_pb_controls)

        self.main_frame.setLayout(vbox_all)
        self.setCentralWidget(self.main_frame)
Esempio n. 13
0
    def createMainFrame(self):
        self.main_frame = QWidget()

        self.fig = Figure((5.0, 4.0), dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()

        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        self.canvas.mpl_connect('key_press_event', self.onKey)
        self.canvas.mpl_connect('pick_event', self.onPick)
        self.canvas.mpl_connect('button_press_event', self.onMouseDown)
        self.canvas.mpl_connect('button_release_event', self.onMouseUp)
        self.canvas.mpl_connect('motion_notify_event', self.onMouseMotion)

        # Initial draw
        self.fig.clear()
        self.fig.hold(True)
        self.ax = self.fig.add_subplot(111)
        self.ax.plot(self.rawData[self.baseChannel])

        # Other GUI controls
        #
        self.numTrialBox = QSpinBox()
        self.numTrialBox.setMinimum(1)
        self.numTrialBox.setValue(2)
        self.numTrialBox.setMinimumWidth(200)
        self.connect(self.numTrialBox, SIGNAL('valueChanged(int)'),
                     self.onNumTrialBox)

        self.submitButton = QPushButton("&Submit")
        self.connect(self.submitButton, SIGNAL('clicked()'), self.onSubmit)

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

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

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

        for w in [
                self.numTrialBox, self.submitButton, 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)
    def create_main_frame(self):
        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        #self.dpi = 100
        self.fig = Figure((5.0, 4.0))
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

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

        # 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.setLayout(vbox)
Esempio n. 15
0
    def __init__(self, parent, dirName):
        super(smileiQtPlot, self).__init__()
        self.setParent(parent)
        uiFile = os.path.dirname(
            os.path.realpath(__file__)) + '/smileiQtPlot.ui'
        self.ui = uic.loadUi(uiFile, self)

        self.dirName = dirName
        self.parent = parent

        self.parent.timer.timeout.connect(self.next)
        self.parent.ui.next.released.connect(self.next)
        self.parent.ui.previous.released.connect(self.previous)
        self.parent.ui.first.released.connect(self.first)
        self.parent.ui.last.released.connect(self.last)

        self.pauseSignal.connect(self.parent.pause)

        self.setWindowFlags(Qt.Window)
        self.setWindowTitle(dirName)

        self.step = 0

        self.ui.savePoints.setIcon(self.ui.style().standardIcon(
            QStyle.SP_DialogSaveButton))
        self.ui.savePoints.released.connect(self.doSavePoints)

        self.ui.tabWidget.currentChanged.connect(self.changeTab)
        self.ui.autoScale.stateChanged.connect(self.doPlots)

        self.fig = Figure()

        self.ui.reload.setIcon(self.ui.style().standardIcon(
            QStyle.SP_BrowserReload))
        self.ui.reload.released.connect(self.reloadAll)

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        self.canvas.mpl_connect('motion_notify_event', self.on_movement)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('key_release_event', self.on_key_release)
        self.canvas.mpl_connect('button_press_event', self.on_button_press)

        self.toolbar = NavigationToolbar(self.canvas, self)
        self.toolbar.setFixedHeight(18)
        self.canvas.setCursor(Qt.CrossCursor)

        self.ui.plotLayout.addWidget(self.canvas)
        self.ui.plotLayout.addWidget(self.toolbar)

        fname = os.path.join(dirName, "scalars.txt")
        if os.path.isfile(fname):
            self.scalarData = np.loadtxt(fname)
            names = []
            for line in open(fname):
                li = line.strip()
                if li.startswith("#"):
                    list = line.split()
                    names.append(list[-1])

            scalars_names = names[1:-2]
            for i in range(len(scalars_names)):
                my_button = QCheckBox(scalars_names[i])
                my_button.stateChanged.connect(self.checkBoxChanged)

                self.ui.layoutScalars.addWidget(my_button)

            self.ui.layoutScalars.addStretch()
        else:
            print "Problem reading ", fname
#             self.deleteLater()

        self.fieldSteps = []
        fname = os.path.join(dirName, "Fields.h5")
        if os.path.isfile(fname):

            self.fieldFile = tb.openFile(fname)
            self.cell_length = self.fieldFile.root._v_attrs.cell_length[0]
            self.res_time = self.fieldFile.root._v_attrs.res_time
            self.sim_length = self.fieldFile.root._v_attrs.sim_length
            # JDT self.fieldEvery=self.fieldFile.root._v_attrs.every

            first = True
            for group in self.fieldFile.listNodes("/", classname='Group'):
                self.fieldSteps.append(group._v_name)
                if first:
                    first = False
                    for array in group:
                        my_button = QCheckBox(array._v_name)
                        my_button.stateChanged.connect(self.checkBoxChanged)
                        self.ui.layoutFields.addWidget(my_button)

            self.ui.layoutFields.addStretch()
            self.ui.slider.setRange(0, len(self.fieldSteps) - 1)
        else:
            print "Problem reading ", fname
#             self.deleteLater()

        self.ui.spinStep.setSuffix("/" + str(len(self.fieldSteps) - 1))
        self.ui.spinStep.setMaximum(len(self.fieldSteps) - 1)

        fname = os.path.join(dirName, "PhaseSpace.h5")
        if os.path.isfile(fname):
            self.phaseFile = tb.openFile(fname)
            for phaseData in self.phaseFile.walkNodes("/", classname='Array'):
                my_button = QCheckBox(phaseData._v_pathname)
                my_button.stateChanged.connect(self.checkBoxChanged)
                self.ui.layoutPhase.addWidget(my_button)
            self.ui.layoutPhase.addStretch()
        else:
            print "Problem reading ", fname


#             self.deleteLater()

        self.load_settings()

        if sys.platform == "darwin":
            self.raise_()
        self.show()
Esempio n. 16
0
    def __init__(self):
        super().__init__()
        self.current_model = model_building.protbind_model()
        self.current_data = pd.DataFrame()
        self.weight_options = {
            'No weighting': 0,
            '1/C weighting': 1,
            '1/(C^2) weighting': 2,
            '1/(C^3) weighting': 3
        }
        self.regression_options = {
            'One-binding site model': 0,
            'Two-binding site model': 1
        }

        self.current_model_selection = self.regression_options[
            'One-binding site model']
        self.current_weight_selection = self.weight_options['No weighting']
        self.color_options = {
            'Blue': 'b',
            'Green': 'g',
            'Red': 'r',
            'Orange': 'orange'
        }
        self.color_index = {'b': 0, 'g': 1, 'r': 2}

        self.central_plot = Figure(figsize=(15, 5))
        self.canvas = FigureCanvas(self.central_plot)
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.setWindowTitle('Protein Binding Fitter')
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        mainlayout = QVBoxLayout(self.central_widget)
        self.central_widget.setFixedWidth(1200)
        top_panel = QHBoxLayout()
        left_panel = QVBoxLayout()
        right_panel = QVBoxLayout()
        left_panel.addStretch(1)

        right_panel.addWidget(self.toolbar)
        right_panel.addWidget(self.canvas)

        data_label = QLabel('Data options')
        left_panel.addWidget(data_label)

        import_button = QPushButton('Import new protein binding dataset')
        left_panel.addWidget(import_button)
        import_button.clicked.connect(self.load_pb_file)

        fit_button = QPushButton('Fit/Plot protein binding data')
        left_panel.addWidget(fit_button)
        fit_button.clicked.connect(self.fit_pb_data)

        model_label = QLabel('Model fitting options')
        left_panel.addWidget(model_label)

        self.regression_type = QComboBox()
        self.regression_type.addItem("One-binding site model")
        self.regression_type.addItem("Two-binding site model")
        self.regression_type.activated[str].connect(
            self.change_regression_type)
        left_panel.addWidget(self.regression_type)

        self.weight_type = QComboBox()
        self.weight_type.addItem("No weighting")
        self.weight_type.addItem("1/C weighting")
        self.weight_type.addItem("1/(C^2) weighting")
        self.weight_type.addItem("1/(C^3) weighting")
        self.weight_type.activated[str].connect(self.change_weight_type)
        left_panel.addWidget(self.weight_type)

        self.color_palette = QComboBox()
        self.color_palette.addItem("Blue")
        self.color_palette.addItem("Green")
        self.color_palette.addItem("Red")
        self.color_palette.addItem("Orange")
        self.color_palette.activated[str].connect(self.change_color_palette)
        left_panel.addWidget(self.color_palette)

        save_label = QLabel('Model options')
        left_panel.addWidget(save_label)

        save_button = QPushButton('Save Model')
        left_panel.addWidget(save_button)
        save_button.clicked.connect(self.save_model)

        load_button = QPushButton('Load Saved Model')
        left_panel.addWidget(load_button)
        load_button.clicked.connect(self.load_saved_model)

        pk_calc_button = QPushButton('Run calculations for PK data')
        left_panel.addWidget(pk_calc_button)
        pk_calc_button.clicked.connect(self.run_pk_calcs)

        top_panel.addLayout(left_panel)
        top_panel.addLayout(right_panel)

        mainlayout.addLayout(top_panel)
        self.show()
Esempio n. 17
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
Esempio n. 18
0
    def setupUi(self, MainWindow):
        global Tree
        global threshold
        global etiquets
        self.counter = 1
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.setWindowTitle("Cluster and merge")
        MainWindow.resize(1215, 1000)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.processedValues = []
        self.threshold = threshold
        self.CurrentDir = os.getcwd()
        self.etiquets = etiquets

        ###########
        #Buttons Widget:
        #to contain all the buttons and inputs
        #to run clusterings
        ###########

        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.centralWidgetLayout = QtGui.QHBoxLayout(self.centralwidget)
        self.verticalLayoutWidget = QtGui.QWidget(self.centralwidget)
        self.verticalLayoutWidget.setMaximumSize(200, 191)
        self.verticalLayoutWidget.setObjectName(
            _fromUtf8("verticalLayoutWidget"))
        self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setMargin(0)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.PlotButton = QtGui.QPushButton(self.verticalLayoutWidget)
        self.PlotButton.setObjectName(_fromUtf8("PlotButton"))
        self.PlotButton.clicked.connect(self.createDendrogram)

        self.verticalLayout.addWidget(self.PlotButton)
        self.lineEdit = QtGui.QLineEdit(self.verticalLayoutWidget)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.verticalLayout.addWidget(self.lineEdit)
        self.checkBox = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.checkBox.setChecked(True)
        self.checkBox.setObjectName(_fromUtf8("checkBox"))
        self.verticalLayout.addWidget(self.checkBox)
        self.anomBox = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.anomBox.setChecked(True)
        self.checkBox.setObjectName(_fromUtf8("anomBox"))
        self.verticalLayout.addWidget(self.anomBox)
        self.processButton = QtGui.QPushButton(self.verticalLayoutWidget)
        self.processButton.setObjectName(_fromUtf8("processButton"))
        self.processButton.clicked.connect(self.processClusters)
        self.verticalLayout.addWidget(self.processButton)
        self.summaryButton = QtGui.QPushButton(self.verticalLayoutWidget)
        self.summaryButton.setObjectName(_fromUtf8("summaryButton"))
        self.summaryButton.clicked.connect(self.showSummary)
        self.verticalLayout.addWidget(self.summaryButton)

        self.centralWidgetLayout.addWidget(self.verticalLayoutWidget)

        ###########
        #Tab Widget:
        #to show Dendrogram and clustering results
        #Each Run of XSCALE will create a new tab for results
        ###########

        self.verticalLayoutWidget_2 = QtGui.QWidget(self.centralwidget)
        self.verticalLayoutWidget_2.setMinimumSize(1020, 410)
        #self.verticalLayoutWidget_2.setGeometry(QtCore.QRect(160, 0, 1021, 411))
        self.verticalLayoutWidget_2.setObjectName(
            _fromUtf8("verticalLayoutWidget_2"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.verticalLayoutWidget_2)
        self.verticalLayout_2.setMargin(0)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.tabWidget = QtGui.QTabWidget(self.verticalLayoutWidget_2)
        self.tabWidget.setTabPosition(QtGui.QTabWidget.North)
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))

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

        self.TreeCanvas = FigureCanvas(self.Dendrogram)
        cid = self.Dendrogram.canvas.mpl_connect('button_press_event',
                                                 self.getThreshold)
        self.TreeBar = NavigationToolbar(self.TreeCanvas, self)
        self.createDendrogram()

        self.plotTab = QtGui.QWidget()
        self.plotTabLayout = QtGui.QVBoxLayout(self.plotTab)
        self.plotTabLayout.addWidget(self.TreeBar)
        self.plotTabLayout.addWidget(self.TreeCanvas)
        self.plotTab.setObjectName(_fromUtf8("plotTab"))
        self.tabWidget.addTab(self.plotTab, _fromUtf8("Dendrogram"))
        self.verticalLayout_2.addWidget(self.tabWidget)
        self.centralWidgetLayout.addWidget(self.verticalLayoutWidget_2)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        #self.menubar.setGeometry(QtCore.QRect(0, 0, 1215, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        self.statusbar.showMessage('Ready!')
        MainWindow.setStatusBar(self.statusbar)
        ##########
        #Show previous results
        # to be removed from the setupUi class
        ###########

        self.alreadyDone = []
        if os.path.isfile(os.getcwd() + '/.cc_cluster.log'):
            with open(os.getcwd() + '/.cc_cluster.log') as log:
                for line in log:
                    L = line.split(',')
                    try:
                        self.tabWidget.addTab(
                            resultsTab(float(L[1]), L[2].strip(), L[3].strip(),
                                       L[4]), L[1] + L[2] + L[3].strip())
                        self.alreadyDone.append(
                            [L[1], L[2].strip(), L[3].strip()])

                    except:
                        self.tabWidget.addTab(
                            resultsTab(float(L[1]), L[2].strip(), L[3].strip(),
                                       'unk'), L[1] + L[2] + L[3].strip())
                        self.alreadyDone.append(
                            [L[1], L[2].strip(), L[3].strip()])


# L[1] = threshold, L[2]=number, L[3] = anomFlag

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Esempio n. 19
0
    def __init__(self):
        super(Averager, self).__init__()
        self.setupUi(self)

        # Set data acquisition variables
        self.idle = True  # state variable
        self.size = 8193  # number of samples to show on the plot # max size
        self.buffer = bytearray(
            4 * self.size)  # buffer and offset for the incoming samples
        self.offset = 0
        self.data = np.frombuffer(self.buffer, np.int32)

        self.isScaled = True
        self.isLogScale = False
        self.isFFT = False
        self.haveData = False
        self.showComp = 0  # Real, Imag, Abs, Phase from combo box

        # Create figure
        figure = Figure()
        figure.set_facecolor('none')
        self.axes = figure.add_subplot(111)
        self.canvas = FigureCanvas(figure)
        self.plotLayout.addWidget(self.canvas)

        # Create navigation toolbar
        self.toolbar = NavigationToolbar(self.canvas, self.plotWidget, False)

        # Remove subplots action
        actions = self.toolbar.actions()
        self.toolbar.removeAction(actions[7])
        self.plotLayout.addWidget(self.toolbar)

        # Create TCP socket
        self.socket = QTcpSocket(self)
        self.socket.connected.connect(self.connected)
        self.socket.readyRead.connect(self.read_data)
        self.socket.error.connect(self.display_error)

        # Populate Combo boxes
        self.cbShowComp.clear()
        self.cbShowComp.addItems(["Real", "Imaginary", "Absolute", "Phase"])
        self.cbShowComp.setCurrentIndex(0)

        self.cbNOS.clear()  # Number of Samples
        for i in range(11):  # maximal value set by the FPGA program
            self.cbNOS.addItems([str(1 << i)])
        self.cbNOS.setCurrentIndex(10)

        self.cbNOA.clear()  # Number of Averages
        for i in range(22):  # maximal value could be larger
            self.cbNOA.addItems([str(1 << i)])
        self.cbNOA.setCurrentIndex(0)

        self.cbTrigger.clear()  # Trigger rate
        for i in range(26):  # maximal value set by the FPGA program
            self.cbTrigger.addItems(["f0/" + str(int(1 << (26 + 1 - i)))])
        self.cbTrigger.setCurrentIndex(16)
        # +1 comes from the fact that counter's lowest bit has f0/2 frequency

        # Connect UI elements and functions
        self.btnStart.clicked.connect(self.start)
        self.chkFFT.stateChanged.connect(self.update_values)
        self.chkScale.stateChanged.connect(self.update_values)
        self.chkLogScale.stateChanged.connect(self.update_values)
        self.cbShowComp.currentIndexChanged.connect(self.update_values)
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.showMaximized()
        # a figure instance to plot on
        self.figure = Figure()

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

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)

        button_layout = QtGui.QHBoxLayout()
        button_layout.addStretch()
        self.select_button = QtGui.QPushButton('Back')
        self.select_button.setFixedWidth(135)
        self.select_button.clicked.connect(self.back3)
        button_layout.addWidget(self.select_button)
        layout.addLayout(button_layout)

        ifile = open('ec1.csv', "rb")
        reader = pd.read_csv(ifile, sep=',')
        df = pd.DataFrame(reader)

        ifile3 = open('eg1.csv', "rb")
        reader = pd.read_csv(ifile3, sep=',')
        df1 = pd.DataFrame(reader)

        l1 = list(df.iloc[54:71, 1])
        l2 = list(df1['Year'])
        x_pos = np.arange(len(l2))
        l3 = list(df1['Grand total'])
        l4 = l1 + l3
        myarray = np.array(l4).reshape(2, 17)
        l5 = ['Consumption', 'Generation']
        width = 0.40

        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        ax.bar(x_pos,
               myarray[0],
               width,
               alpha=0.5,
               color='r',
               edgecolor='black',
               linewidth=0.5,
               align='center')
        ax.bar([p + width for p in x_pos],
               myarray[1],
               width,
               alpha=0.5,
               color='b',
               edgecolor='black',
               linewidth=0.5,
               align='center')
        ax.set_xticks(x_pos + 0.24)
        ax.set_xticklabels(l2, rotation='vertical', fontsize=13)
        ax.set_ylabel('Total Generation (GWh)', fontsize=23)
        ax.set_xlabel('Years', fontsize=19)
        ax.legend(l5, loc="best", borderpad=2)
        ax.set_title('Electricity Growth pattern', fontsize=23)

        # refresh canvas"""
        self.canvas.draw()
Esempio n. 21
0
    def populate(self):
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.settingLabel = QtGui.QLabel("Setting")
        self.settingSelect = QtGui.QComboBox(self)
        self.settingSelect.addItem("0")
        self.settingSelect.addItem("1")
        self.settingSelect.setToolTip("K: 0; Rb: 1")
        self.settingSelect.currentIndexChanged.connect(self.settingChanged)

        self.frameLabel = QtGui.QLabel("Frame")
        self.frameSelect = QtGui.QComboBox(self)
        self.frameSelect.addItem("OD")
        self.frameSelect.addItem("Shadow")
        self.frameSelect.addItem("Light")
        self.frameSelect.addItem("Dark")
        self.frameSelect.currentIndexChanged.connect(self.displayData)

        self.shadowFrameLabel = QtGui.QLabel("Shadow")
        self.shadowFrameSelect = QtGui.QComboBox(self)
        self.shadowFrameSelect.setToolTip("K: (0,0); Rb: (0,1)")
        self.shadowFrameSelect.currentIndexChanged.connect(self.displayData)

        self.lightFrameLabel = QtGui.QLabel("Light")
        self.lightFrameSelect = QtGui.QComboBox(self)
        self.lightFrameSelect.setToolTip("K: (1,0); Rb: (1,1)")
        self.lightFrameSelect.currentIndexChanged.connect(self.displayData)

        self.darkFrameLabel = QtGui.QLabel("Dark")
        self.darkFrameSelect = QtGui.QComboBox(self)
        self.darkFrameSelect.setToolTip("K: (2,0); Rb: (2,1)")
        self.darkFrameSelect.currentIndexChanged.connect(self.displayData)

        self.frameSelectArray = [
            self.shadowFrameSelect, self.lightFrameSelect, self.darkFrameSelect
        ]

        self.colorLabel = QtGui.QLabel("Colormap", self)
        self.colorSelect = QtGui.QComboBox(self)
        self.colorSelect.addItem("White Jet")
        self.colorSelect.addItem("White Magma")
        self.colorSelect.addItem("White Plasma")
        self.colorSelect.addItem("Jet")
        self.colorSelect.currentIndexChanged.connect(self.displayData)

        self.minLabel = QtGui.QLabel("Min", self)
        self.minEdit = QtGui.QLineEdit(self)
        self.maxLabel = QtGui.QLabel("Max", self)
        self.maxEdit = QtGui.QLineEdit(self)

        self.maxEdit.returnPressed.connect(self.validateLimits)
        self.minEdit.returnPressed.connect(self.validateLimits)

        self.autoscaleButton = QtGui.QPushButton("Autoscale", self)
        self.autoscaleButton.clicked.connect(self.autoscale)

        self.spacer = QtGui.QSpacerItem(1, 1)

        self.layout = QtGui.QGridLayout()

        self.layout.addWidget(self.toolbar, 0, 0, 1, 6)
        self.layout.addWidget(self.canvas, 1, 0, 6, 6)

        row = 8
        self.layout.addWidget(self.settingLabel, row, 0)
        self.layout.addWidget(self.settingSelect, row, 1)
        row += 1

        self.layout.addWidget(self.frameLabel, row, 0)
        self.layout.addWidget(self.frameSelect, row, 1)
        row += 1

        self.layout.addWidget(self.shadowFrameLabel, row, 0)
        self.layout.addWidget(self.shadowFrameSelect, row, 1)
        row += 1

        self.layout.addWidget(self.lightFrameLabel, row, 0)
        self.layout.addWidget(self.lightFrameSelect, row, 1)
        row += 1

        self.layout.addWidget(self.darkFrameLabel, row, 0)
        self.layout.addWidget(self.darkFrameSelect, row, 1)
        row += 1

        row = 8
        self.layout.addWidget(self.colorLabel, row, 4)
        self.layout.addWidget(self.colorSelect, row, 5)
        row += 1

        self.layout.addWidget(self.minLabel, row, 4)
        self.layout.addWidget(self.minEdit, row, 5)
        row += 1

        self.layout.addWidget(self.maxLabel, row, 4)
        self.layout.addWidget(self.maxEdit, row, 5)
        row += 1

        self.layout.addWidget(self.autoscaleButton, row, 4, 1, 2)

        # Try to make the layout look nice
        for i in range(4):
            self.layout.setColumnStretch(i, 1)

        self.setLayout(self.layout)
Esempio n. 22
0
    def __init__(self, parent, context, windowName):
        #    def __init__(self, parent, context):
        QtGui.QWidget.__init__(self)
        self.parent = parent
        self.context = context
        self.windowName = windowName
        self.parameterWindows = {}
        self.publishWindows = {}  # new
        self.datasetCheckboxes = {}
        self.datasetCheckboxesItems = {}
        self.datasetAnalysisCheckboxes = {}
        self.datasetCheckboxCounter = 0
        self.datasetCheckboxPositionDict = {
        }  # [dataset, directory, index], integer
        self.itemDatasetCheckboxPositionDict = {}  # item: integer
        self.toggleDict = {}  # dataset, directory, index: 0 off, 1 on
        self.datasetAnalysisCheckboxCounter = 0
        self.manuallyLoaded = True
        self.setWindowTitle(self.windowName)

        # create a vertical box layout widget
        grapherLayout = QtGui.QVBoxLayout()
        # instantiate our Matplotlib canvas widget
        self.qmc = Qt4MplCanvas(self)
        # instantiate the navigation toolbar
        ntb = NavigationToolbar(self.qmc, self)

        # Layout that involves the canvas, toolbar, graph options...etc.
        grapherLayout.addWidget(ntb)
        grapherLayout.addWidget(self.qmc)

        # Main horizontal layout
        mainLayout = QtGui.QHBoxLayout()
        # Layout that controls datasets
        datasetLayout = QtGui.QVBoxLayout()

        mainLayout.addLayout(datasetLayout)
        mainLayout.addLayout(grapherLayout)

        # Layout for keeping track of datasets on a graph and analysis
        self.datasetCheckboxListWidget = DatasetCheckBoxListWidget(
            self)  #QtGui.QListWidget()
        self.datasetCheckboxListWidget.setMaximumWidth(180)
        self.datasetCheckboxListWidget.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAsNeeded)
        datasetLayout.addWidget(self.datasetCheckboxListWidget)

        #        self.analysisWidget = AnalysisWidget(self)
        #        datasetLayout.addWidget(self.analysisWidget)

        self.setLayout(mainLayout)

        # checkbox to change boundaries
        self.cb1 = QtGui.QCheckBox('AutoScroll', self)
        #self.cb1.move(290, 23)
        self.cb1.clicked.connect(self.autoscrollSignal)
        # checkbox to overlay new dataset
        self.cb2 = QtGui.QCheckBox('Overlay', self)
        #self.cb2.move(500, 35)
        # checkbox to toggle AutoFit
        self.cb3 = QtGui.QCheckBox('AutoFit', self)
        #self.cb3.move(290, 39)
        #        self.cb3.toggle()
        self.cb3.clicked.connect(self.autofitSignal)

        self.cb4 = QtGui.QCheckBox('Probability mode', self)

        # button to fit data on screen
        fitButton = QtGui.QPushButton("Fit", self)
        fitButton.setGeometry(QtCore.QRect(0, 0, 30, 30))
        fitButton.clicked.connect(self.fitDataSignal)

        windowNameButton = QtGui.QPushButton("Change Window Name", self)
        windowNameButton.setGeometry(QtCore.QRect(0, 0, 30, 30))
        windowNameButton.clicked.connect(self.changeWindowName)

        # Layout that controls graph options
        buttonBox = QtGui.QHBoxLayout()
        buttonBox.addWidget(self.cb1)
        buttonBox.addWidget(self.cb3)
        buttonBox.addWidget(self.cb2)
        buttonBox.addWidget(self.cb4)
        buttonBox.addWidget(fitButton)
        buttonBox.addWidget(windowNameButton)

        grapherLayout.addLayout(buttonBox)
Esempio n. 23
0
    def plot(self, volatilidad, Time_mature, k):
        print("aca")

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

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

        # set the layout
        layout = QtGui.QVBoxLayout(self.widget_graph)
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)

        # self.addButton = QtGui.QPushButton('button to add other widgets')

        # self.mainLayout = QtGui.QVBoxLayout(self.widget_graph)

        # self.mainLayout.addWidget(self.addButton)

        data = cumprod(
            1 + random.randn(1000, int(Time_mature * 252)) *
            (volatilidad / sqrt(int(Time_mature * 252))), 1) * k
        print(data)
        ax = self.figure.add_subplot(111)
        ax.clear()
        avg = [
            sum([subdata[j] for subdata in data]) / len(data)
            for j in xrange(len(data[0]))
        ]
        perc95 = percentile(95, data)
        perc5 = percentile(5, data)
        ax.plot(perc95, 'k- -')
        ax.plot(perc5, 'k- -')
        ax.plot(avg, 'r-')
        #for i in data:
        #    ax.plot(i, '*-')
        self.canvas.draw()

        # data = [random.random() for i in range(10)]

        # # create an axis
        # ax = self.figure.add_subplot(111)

        # # discards the old graph
        # ax.clear()

        # # plot data
        # ax.plot(data, '*-')

        # # refresh canvas
        # self.canvas.draw()

        print("alla")
        self.show()
Esempio n. 24
0
    def initGui(self):
        # a figure instance to plot on
        self.figure = Figure()

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

        # Setup a label widget to show temperature in Fahrenheit
#         self.label_temp = QLabel(self)
# 
#         self.label_temp.setFont(QFont("Microsoft YaHei",18,QFont.Bold))
#         self.label_temp.setAlignment(Qt.AlignCenter)
#         self.label_temp.setText('Temperature reading: 0.0*F 0.0*C')

        # to include canvas related widgets
        h1 = QVBoxLayout()
        h1.addWidget(self.toolbar)
#         h1.addWidget(self.label_temp)
        h1.addWidget(self.canvas)
        
        h2 = QHBoxLayout()
        h3 = QVBoxLayout()
        self.content_label = QLabel()
        self.content_label.setText('Add a Name to Plot')
        h3.addWidget(self.content_label)
        
        # line text to input key words to be filtered
        self.cnt_text = QLineEdit()
        h3.addWidget(self.cnt_text)
        
        # List widget to show key words being filtered
        self.list = QListWidget()
        self.list.setEnabled(False)
        h3.addWidget(self.list) 
        
        h2.addLayout(h3)
        
        h4 = QVBoxLayout()
        self.modeBtn = QPushButton()
        self.modeBtn.setText('Ewards mode')
        self.modeBtn.clicked.connect(self.on_click_modeChange) 
        h4.addWidget(self.modeBtn)      
        
        self.addBtn = QPushButton()
        self.addBtn.setText('Add')
        self.addBtn.clicked.connect(self.on_click_add) 
        h4.addWidget(self.addBtn)
        
        self.clearBtn = QPushButton()
        self.clearBtn.setText('Clear buffer')
        self.clearBtn.clicked.connect(self.on_click_clear) 
        h4.addWidget(self.clearBtn)
        
        self.plotBtn = QPushButton()
        self.plotBtn.setText('Begin Plotting')
        self.plotBtn.clicked.connect(self.on_click_plot)
        
        h4.addWidget(self.plotBtn)

        self.stopBtn = QPushButton()
        self.stopBtn.setText('Stop Plotting')
        self.stopBtn.clicked.connect(self.on_click_stop)
        self.stopBtn.setEnabled(False)
        
        h4.addWidget(self.stopBtn)
                
        h2.addLayout(h4)   
             
        h1.addLayout(h2) 
        
        self.setLayout(h1)
        
        # Canvas settings
        self.ax = self.figure.add_subplot(111)
        self.ax.grid(True)
        
        self.ax.set_ylabel('Counts')
        self.ax.set_xlabel('LTC sensitivity/uA')
        
        self.keyWordsDict = dict()
        
        self.itemsTextList = list()
        
        self.x_data = list()
        
        self.flag = False
        self.EW_mode = True
        
        # Define timer to loop events
        self.timer = QBasicTimer()
#         self.timer.start(300, self)

        # initialize visibility of buttons and list, labels.
        if self.modeBtn.text() == 'Ewards mode':
            self.modeBtn.setText('Kidde mode')
            self.EW_mode = True
            self.addBtn.setVisible(False)
#             self.clearBtn.setVisible(False)
            #self.plotBtn.setVisible(False)
            #self.stopBtn.setVisible(False)
            self.list.setVisible(False)
            self.cnt_text.setVisible(False)
            self.content_label.setVisible(False)
            # in Ewards mode, create a name list for specified key words
            self.keyWordsDict['IRFR']=[]
            self.keyWordsDict['IRBR']=[]
            self.keyWordsDict['BLFR']=[]
            self.keyWordsDict['IRFX0']=[]
            self.keyWordsDict['IRBX0']=[]
            self.keyWordsDict['BLFX0']=[]
Esempio n. 25
0
    def __init__(self):
        self.__inputfile__ = ""
        self.__fileio__ = False
        self.__entropiadone__ = False
        self.__plot_done__ = False

        QtGui.QMainWindow.__init__(self)
        self.resize(640, 480)
        self.setWindowTitle('Forecasted dynamic Theil\'s entropy')
        self.statusBar().showMessage('Markov started')

        ofile = QtGui.QAction(QtGui.QIcon("icons/open.png"), "Open", self)
        ofile.setShortcut("Ctrl+O")
        ofile.setStatusTip("Open file")
        ofile.connect(ofile, QtCore.SIGNAL('triggered()'), self.openfile)

        self.__savefile__ = QtGui.QAction(QtGui.QIcon("icons/save.png"),
                                          "Save", self)
        self.__savefile__.setStatusTip("Save file")
        self.__savefile__.connect(self.__savefile__ , QtCore.SIGNAL('triggered()'), \
                self.savefile)
        self.__savefile__.setEnabled(False)

        sep = QtGui.QAction(self)
        sep.setSeparator(True)

        quit = QtGui.QAction(QtGui.QIcon("icons/cancel.png"), "Quit", self)
        quit.setShortcut("Ctrl+Q")
        quit.setStatusTip("Quit application")
        self.connect(quit, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))

        run = QtGui.QAction(QtGui.QIcon("icons/run.png"), "Run", self)
        run.setShortcut("Ctrl+R")
        run.setStatusTip("Run")
        self.connect(run, QtCore.SIGNAL('triggered()'), self.mainrun)

        self.__plots__ = QtGui.QAction(QtGui.QIcon("icons/save.png"),
                                       "Plot CS distributions", self)
        self.__plots__.setShortcut("Ctrl+S")
        self.__plots__.setStatusTip("Credit spread distributions")
        self.__plots__.connect(self.__plots__ , QtCore.SIGNAL('triggered()'), \
                self.plot_hist)
        self.__plots__.setEnabled(False)

        self.__mats__ = QtGui.QAction(QtGui.QIcon("icons/save.png"),
                                      "View transition matrix", self)
        self.__mats__.setShortcut("Ctrl+M")
        self.__mats__.setStatusTip("View transition matrices")
        self.__mats__.connect(self.__mats__ , QtCore.SIGNAL('triggered()'), \
                self.view_mats)
        self.__mats__.setEnabled(False)

        self.statusBar().show()

        menubar = self.menuBar()

        file = menubar.addMenu('&File')
        file.addAction(ofile)
        file.addAction(self.__savefile__)
        file.addAction(sep)
        file.addAction(quit)

        edit = menubar.addMenu('&Edit')
        edit.addAction(run)
        edit.addAction(self.__plots__)
        edit.addAction(self.__mats__)

        help = menubar.addMenu('&Help')

        self.__figure__ = plt.figure()
        self.__canvas__ = FigureCanvas(self.__figure__)
        self.__toolbar__ = NavigationToolbar(self.__canvas__, self)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.__toolbar__)
        layout.addWidget(self.__canvas__)

        maindialog = QtGui.QWidget()
        maindialog.setLayout(layout)

        self.setCentralWidget(maindialog)

        self.__options_dialog__ = options.optiondialog(self)

        self.__options_name_dialog__ = options.optionnamedialog(self)
Esempio n. 26
0
    def initUI(self):

        self.fit_result = []
        self.fit_basis = []

        lblBasis = QtGui.QLabel("Select basis:")
        lblFit = QtGui.QLabel(
            "Select spectra to fit (multiple selection possible):")
        lblResult = QtGui.QLabel("Fit coeficients:")

        self.lstBasis = QtGui.QListWidget()
        self.lstFit = QtGui.QListWidget()
        self.lstBasis.setSelectionMode(
            QtGui.QAbstractItemView.ExtendedSelection)
        self.lstFit.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.lstFit.itemClicked.connect(self.lstFitItemClicked)

        self.lstFitResult = QtGui.QListWidget()

        anfn = []
        fit_res = []
        for i in range(0, self.mainform.lstSpectra.count()):
            anfn.append(str(self.mainform.lstSpectra.item(i).text()))
            fit_res.append("")
            self.fit_result.append([])
            self.fit_basis.append([])

        self.lstBasis.addItems(anfn)
        self.lstFit.addItems(anfn)
        self.lstFitResult.addItems(fit_res)

        lout = QtGui.QGridLayout()
        lout.addWidget(lblBasis, 0, 0)
        lout.addWidget(lblFit, 0, 1)
        lout.addWidget(lblResult, 0, 2)
        lout.addWidget(self.lstBasis, 1, 0)
        lout.addWidget(self.lstFit, 1, 1)
        lout.addWidget(self.lstFitResult, 1, 2)

        #Figures
        self.fig = plt.figure(6, figsize=(12, 6))
        self.ax_exafs = plt.subplot2grid((1, 2), (0, 1))
        self.ax_fit = plt.subplot2grid((1, 2), (0, 0))

        self.canv = FigureCanvas(self.fig)
        self.tbar = NavigationToolbar(self.canv, self)

        self.exafs_line, = self.ax_exafs.plot([], [])
        #        self.bftexafs_line, = self.ax_exafs.plot([], [])
        self.difference_line, = self.ax_exafs.plot([], [], "o")
        self.exafsdgcomp_line, = self.ax_exafs.plot([], [])

        #        self.fit_line, = self.ax_fit.plot([], [], "o")
        #        self.fit_line.set_markersize(2)

        self.exafsdgcomp_line.set_color('r')

        self.glitch_lines = []
        self.minmaxlines = []

        self.fig.tight_layout()

        self.btnFit = QtGui.QPushButton('Fit')
        self.btnFit.clicked.connect(self.fit)

        self.btnApply = QtGui.QPushButton('Save fit results...')
        self.btnApply.clicked.connect(self.save_fit)

        self.btnCancel = QtGui.QPushButton('Exit')
        self.btnCancel.clicked.connect(self.cancel)

        lfig = QtGui.QVBoxLayout()
        lfig.addWidget(self.tbar)
        lfig.addWidget(self.canv)

        lfig.addLayout(lout)
        lfig.addWidget(self.btnFit)
        lfig.addWidget(self.btnApply)
        lfig.addWidget(self.btnCancel)

        self.setLayout(lfig)
Esempio n. 27
0
    def __init__(self, net=None, parent=None, fname=None):
        QMainWindow.__init__(self)

        self.ui = Ui_SimulationWindow()
        self.ui.setupUi(self)

        if fname:
            self.set_title(fname)

        # context menu
        self.ui.nodeInspector.addAction(self.ui.actionCopyInspectorData)
        self.ui.nodeInspector.addAction(self.ui.actionShowLocalizedSubclusters)
        # callbacks
        self.ui.actionCopyInspectorData.activated\
            .connect(self.on_actionCopyInspectorData_triggered)
        self.ui.actionShowLocalizedSubclusters.activated\
            .connect(self.on_actionShowLocalizedSubclusters_triggered)

        self.dpi = 72
        # take size of networDisplayWidget
        self.fig = Figure((700 / self.dpi, 731 / self.dpi),
                          self.dpi,
                          facecolor='0.9')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.ui.networkDisplayWidget)
        self.nav = NavigationToolbar(self.canvas,
                                     self.ui.networkDisplayWidget,
                                     coordinates=True)
        self.nav.setGeometry(QRect(0, 0, 651, 36))
        self.nav.setIconSize(QSize(24, 24))

        self.axes = self.fig.add_subplot(111)
        # matplotlib.org/api/figure_api.html#matplotlib.figure.SubplotParams
        self.fig.subplots_adjust(left=0.03, right=0.99, top=0.92)

        if net:
            self.init_sim(net)

        self.connect(self.ui.showNodes, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showEdges, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showMessages, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.showLabels, SIGNAL('stateChanged(int)'),
                     self.refresh_visibility)
        self.connect(self.ui.redrawNetworkButton, SIGNAL('clicked(bool)'),
                     self.redraw)
        self.connect(self.ui.treeGroupBox, SIGNAL('toggled(bool)'),
                     self.refresh_visibility)
        self.connect(self.ui.treeKey, SIGNAL('textEdited(QString)'),
                     self.redraw)
        self.connect(self.ui.propagationError, SIGNAL('toggled(bool)'),
                     self.refresh_visibility)
        self.connect(self.ui.locKey, SIGNAL('textEdited(QString)'),
                     self.redraw)
        # callbacks
        self.ui.actionOpenNetwork.activated\
            .connect(self.on_actionOpenNetwork_triggered)
        self.ui.actionSaveNetwork.activated\
            .connect(self.on_actionSaveNetwork_triggered)
        self.ui.actionRun.activated.connect(self.on_actionRun_triggered)
        self.ui.actionStep.activated.connect(self.on_actionStep_triggered)
        self.ui.actionReset.activated.connect(self.on_actionReset_triggered)

        self.canvas.mpl_connect('pick_event', self.on_pick)
Esempio n. 28
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 = plt.figure()
        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 = Axes3D(self.fig)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.onclick)
        self.canvas.setFocusPolicy(Qt.ClickFocus)
        self.canvas.setFocus()
        self.canvas.mpl_connect('key_press_event', self.onkey)
        self.canvas.mpl_connect('key_release_event', self.onrelease)
        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        self.grid_cb = QCheckBox("Show &Grid")
        self.grid_cb.setChecked(True)
        self.connect(self.grid_cb, SIGNAL('stateChanged(int)'), lambda: self.draw(fix=True))

        # x range selector
        self.groupxrange = QGroupBox("x")
        hboxX = QHBoxLayout()
        self.buttonXminus = QPushButton("<")
        self.buttonXminus.clicked.connect(lambda: self.rangeChanger("x", False))
        hboxX.addWidget(self.buttonXminus)

        self.buttonXplus = QPushButton(">")
        self.buttonXplus.clicked.connect(lambda: self.rangeChanger("x", True))
        hboxX.addWidget(self.buttonXplus)
        self.groupxrange.setLayout(hboxX)

        # y range selector
        self.groupyrange = QGroupBox("y")
        hboxY = QHBoxLayout()
        self.buttonYminus = QPushButton("<")
        self.buttonYminus.clicked.connect(lambda: self.rangeChanger("y", False))
        hboxY.addWidget(self.buttonYminus)

        self.buttonYplus = QPushButton(">")
        self.buttonYplus.clicked.connect(lambda: self.rangeChanger("y", True))
        hboxY.addWidget(self.buttonYplus)
        self.groupyrange.setLayout(hboxY)

        # z range changer
        self.groupzrange = QGroupBox("z")
        hboxZ = QHBoxLayout()
        self.buttonZminus = QPushButton("<")
        self.buttonZminus.clicked.connect(lambda: self.rangeChanger("z", False))
        hboxZ.addWidget(self.buttonZminus)

        self.buttonZplus = QPushButton(">")
        self.buttonZplus.clicked.connect(lambda: self.rangeChanger("z", True))
        hboxZ.addWidget(self.buttonZplus)
        self.groupzrange.setLayout(hboxZ)

        self.groupxrange.setEnabled(False)
        self.groupyrange.setEnabled(False)
        self.groupzrange.setEnabled(False)
        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [self.grid_cb, self.groupxrange, self.groupyrange, self.groupzrange]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignVCenter)

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

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)
Esempio n. 29
0
    def __init__(self,
                 parent=None,
                 pos=None,
                 quat=None,
                 js_table=None,
                 params=None,
                 forbiden_frames=None,
                 robot_config_change_list=None):
        '''
        pos, quat stands for the position and orientation of tongs in a certain demonstration
        js_table stands for the joint states solved by RIK
        '''
        super(Window, self).__init__(parent)
        # a figure instance to plot on
        self.figure = plt.figure()
        # get init of data tables
        self._pos = pos
        self._orientation = quat
        self._js_table = js_table
        self._params = params
        # use for checking performance
        self._forbiden_frames = forbiden_frames
        self._robot_config_change = robot_config_change_list

        layout = QVBoxLayout()

        # Add label to show some texts
        self.l1 = QLabel("Hello!")
        self.l1.setAlignment(Qt.AlignCenter)
        self.l1.setFont(QFont("Arial", 30))
        layout.addWidget(self.l1)

        # Add other labels to show other parameter values
        # 'Orien Weight', 'EE Vel', 'JS Vel', 'Obj Val'
        self.l2 = QLabel("Orientation Weights: 0.0")
        self.l2.setAlignment(Qt.AlignLeft)
        self.l2.setFont(QFont("Arial", 15))

        self.l3 = QLabel("EE Vel: 0.0")
        self.l3.setAlignment(Qt.AlignLeft)
        self.l3.setFont(QFont("Arial", 15))

        self.l4 = QLabel("JS Vel: 0.0")
        self.l4.setAlignment(Qt.AlignLeft)
        self.l4.setFont(QFont("Arial", 15))

        self.l5 = QLabel("Obj Val: 0.0")
        self.l5.setAlignment(Qt.AlignLeft)
        self.l5.setFont(QFont("Arial", 15))

        self.l6 = QLabel("Robot Config Change: 0.0")
        self.l6.setAlignment(Qt.AlignLeft)
        self.l6.setFont(QFont("Arial", 15))

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

        self.sl = QSlider(Qt.Horizontal)
        self.sl.setMinimum(0)
        self.sl.setMaximum(len(self._pos) - 1)
        self.sl.setValue(500)
        self.sl.setTickPosition(QSlider.TicksBelow)
        self.sl.setTickInterval(1)

        # add QPushButton to implement single step
        '''
        self.btn_fwd = QPushButton('>>')
        layout.addWidget(self.btn_fwd)
        self.btn_fwd.resize(self.btn_fwd.sizeHint())
        self.btn_bwd = QPushButton('<<')
        layout.addWidget(self.btn_bwd)
        self.btn_bwd.resize(self.btn_bwd.sizeHint())
	'''

        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.sl)
        layout.addWidget(self.l2)
        layout.addWidget(self.l3)
        layout.addWidget(self.l4)
        layout.addWidget(self.l5)
        layout.addWidget(self.l6)
        self.sl.valueChanged.connect(self.valuechange)
        self.setLayout(layout)
        self.setWindowTitle("Playback Simulator with UI by HWang")
Esempio n. 30
0
        def __init__(self, parent=None):

            QtGui.QMainWindow.__init__(self)
            self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
            self.setWindowTitle("%s Ver %s" % (progname, progversion))
            self.setWindowIcon(QtGui.QIcon('test_icon.png'))

            self.file_menu = QtGui.QMenu('&File', self)
            self.file_menu.addAction('&Quit', self.fileQuit,
                                     QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
            self.menuBar().addMenu(self.file_menu)

            self.help_menu = QtGui.QMenu('&Help', self)
            self.menuBar().addSeparator()
            self.menuBar().addMenu(self.help_menu)

            self.help_menu.addAction('&About', self.about)

            self.main_widget = QtGui.QWidget(self)
            l = QtGui.QGridLayout(self.main_widget)

            sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=80)
            sc.figure.set_tight_layout(True)
            self.sc_navi_toolbar = NavigationToolbar(sc, self.main_widget)

            self.dc = MyDynamicMplCanvas(self.main_widget,
                                         width=5,
                                         height=4,
                                         dpi=80)
            self.dc.figure.set_tight_layout(True)
            self.dc_navi_toolbar = NavigationToolbar(self.dc, self.main_widget)

            l.addWidget(self.sc_navi_toolbar)
            l.addWidget(sc)
            l.addWidget(self.dc)
            l.addWidget(self.dc_navi_toolbar)

            self.main_widget.setFocus()
            self.setCentralWidget(self.main_widget)

            # --------------------------------------------------------------------------
            dock = QtGui.QDockWidget("Values")
            # not use close 'x'
            dock.setFeatures(QtGui.QDockWidget.DockWidgetMovable
                             | QtGui.QDockWidget.DockWidgetFloatable)
            self.addDockWidget(Qt.RightDockWidgetArea, dock)
            sliders = QtGui.QWidget()
            sliders_grid = QtGui.QGridLayout(sliders)

            vLayout = QtGui.QVBoxLayout()
            roiGroupBox = QtGui.QGroupBox('ROI')

            chkRepeaterRun = QtGui.QCheckBox("&Repeater...")
            chkRepeaterRun.setFocusPolicy(Qt.NoFocus)

            self.dispLowROI = QtGui.QLabel()
            self.dispLowROI.setAlignment(QtCore.Qt.AlignRight)

            labelLowRoi = QtGui.QLabel('Low ROI bins:')
            self.dispLowROI.setText('LOW ROI')

            self.dispHighROI = QtGui.QLabel()
            labelHighRoi = QtGui.QLabel('High ROI bins:')
            self.dispHighROI.setAlignment(QtCore.Qt.AlignRight)
            # self.dispHighROI.setFocusPolicy(Qt.NoFocus)
            # self.dispHighROI.setValidator(QtGui.QIntValidator(1, self.xlim - 1))
            self.dispHighROI.setText('HIGH ROI')

            # sliders_grid.addWidget(labelLowRoi, 1, 0)
            vLayout.addWidget(labelLowRoi, 0)
            vLayout.addWidget(self.dispLowROI, 0)
            vLayout.addWidget(labelHighRoi, 0)
            vLayout.addWidget(self.dispHighROI, 0)

            # Insert Height spaces
            vLayout.addStretch(20)

            roiGroupBox.setLayout(vLayout)

            leftLayOut = QtGui.QVBoxLayout()
            leftLayOut.addWidget(roiGroupBox)

            sliders_grid.addWidget(chkRepeaterRun, 0, 0)
            sliders_grid.addLayout(leftLayOut, 1, 0)

            # update current rois value if move axvline in the mca waveform
            self.dc.lowROIChanged.connect(self.dispLowROI.setText)
            self.dc.highROIChanged.connect(self.dispHighROI.setText)

            dock.setWidget(sliders)

            self.statusBar().showMessage("BL7D dxpXMAP monitoring")

            # CONNECTIONS.
            # connect average value to chart in sc instance
            self.dc.procStart.connect(sc.computer_sum)
            # Checkbox connect for EraseStart again
            chkRepeaterRun.stateChanged.connect(sc.RepeatEraseStart)