Exemple #1
0
class SimpleFitGUI(qt.QWidget):
    def __init__(self, parent=None, fit=None, graph=None, actions=True):
        qt.QWidget.__init__(self, parent)
        self.setWindowTitle("SimpleFitGUI")
        if fit is None:
            self.fitModule = SimpleFitModule.SimpleFit()
            self.fitModule.importFunctions(SimpleFitUserEstimatedFunctions)
        else:
            self.fitModule = fit
        if graph is None:
            self.__useTab = True
            self.graph = GraphWindow()
        else:
            self.__useTab = False
            self.graph = graph
        if hasattr(self.graph, "fitButton"):
            self.graph.fitButton.hide()
        if hasattr(self.graph, "scanWindowInfoWidget"):
            self.graph.scanWindowInfoWidget.hide()
        self._configurationDialog = None
        self.mainLayout = qt.QVBoxLayout(self)
        self.mainLayout.setMargin(2)
        self.mainLayout.setSpacing(2)
        self.topWidget = TopWidget(self)
        config = self.fitModule.getConfiguration()
        self.topWidget.setFunctions(config['fit']['functions'])
        config = None

        if self.__useTab:
            self.mainTab = qt.QTabWidget(self)
            self.mainLayout.addWidget(self.mainTab)
            self.parametersTable = Parameters.Parameters()
            self.mainTab.addTab(self.graph, 'GRAPH')
            self.mainTab.addTab(self.parametersTable, 'FIT')
        else:
            self.parametersTable = Parameters.Parameters(self)

        self.statusWidget = StatusWidget(self)

        self.mainLayout.addWidget(self.topWidget)
        if self.__useTab:
            self.mainLayout.addWidget(self.mainTab)
        else:
            self.mainLayout.addWidget(self.parametersTable)
        self.mainLayout.addWidget(self.statusWidget)

        if actions:
            #build the actions widget
            self.fitActions = qt.QWidget(self)
            self.fitActions.mainLayout = qt.QHBoxLayout(self.fitActions)
            self.fitActions.mainLayout.setMargin(2)
            self.fitActions.mainLayout.setSpacing(2)
            self.fitActions.estimateButton = qt.QPushButton(self.fitActions)
            self.fitActions.estimateButton.setText("Estimate")
            self.fitActions.startFitButton = qt.QPushButton(self.fitActions)
            self.fitActions.startFitButton.setText("Start Fit")
            self.fitActions.dismissButton = qt.QPushButton(self.fitActions)
            self.fitActions.dismissButton.setText("Dismiss")
            self.fitActions.mainLayout.addWidget(
                self.fitActions.estimateButton)
            self.fitActions.mainLayout.addWidget(
                self.fitActions.startFitButton)
            self.fitActions.mainLayout.addWidget(self.fitActions.dismissButton)
            self.mainLayout.addWidget(self.fitActions)

        #connect top widget
        self.connect(self.topWidget.addFunctionButton, qt.SIGNAL("clicked()"),
                     self.importFunctions)

        self.connect(self.topWidget.fitFunctionCombo,
                     qt.SIGNAL("currentIndexChanged(int)"),
                     self.fitFunctionComboSlot)

        self.connect(self.topWidget.backgroundCombo,
                     qt.SIGNAL("currentIndexChanged(int)"),
                     self.backgroundComboSlot)

        self.connect(self.topWidget.configureButton, qt.SIGNAL("clicked()"),
                     self.configureButtonSlot)

        if actions:
            #connect actions
            self.connect(self.fitActions.estimateButton,
                         qt.SIGNAL("clicked()"), self.estimate)
            self.connect(self.fitActions.startFitButton,
                         qt.SIGNAL("clicked()"), self.startFit)
            self.connect(self.fitActions.dismissButton, qt.SIGNAL("clicked()"),
                         self.dismiss)

    def importFunctions(self, functionsfile=None):
        if functionsfile is None:
            fn = qt.QFileDialog.getOpenFileName()
            if fn.isEmpty():
                functionsfile = ""
            else:
                functionsfile = qt.safe_str(fn)
            if not len(functionsfile):
                return
        if DEBUG:
            self.fitModule.importFunctions(functionsfile)
        else:
            try:
                self.fitModule.importFunctions(functionsfile)
            except:
                qt.QMessageBox.critical(self, "ERROR", "Function not imported")

        config = self.fitModule.getConfiguration()
        self.topWidget.setFunctions(config['fit']['functions'])

    def fitFunctionComboSlot(self, idx):
        if idx <= 0:
            fname = "None"
        else:
            fname = qt.safe_str(self.topWidget.fitFunctionCombo.itemText(idx))
        self.fitModule.setFitFunction(fname)

    def backgroundComboSlot(self, idx):
        if idx <= 0:
            fname = "None"
        else:
            fname = qt.safe_str(self.topWidget.backgroundCombo.itemText(idx))
        self.setBackgroundFunction(fname)

    def configureButtonSlot(self):
        if self._configurationDialog is None:
            self._configurationDialog =\
                SimpleFitConfigurationGUI.SimpleFitConfigurationGUI()
        self._configurationDialog.setSimpleFitInstance(self.fitModule)
        if not self._configurationDialog.exec_():
            if DEBUG:
                print("NOT UPDATING CONFIGURATION")
            oldConfig = self.fitModule.getConfiguration()
            self._configurationDialog.setConfiguration(oldConfig)
            return
        newConfig = self._configurationDialog.getConfiguration()
        self.topWidget.setFunctions(newConfig['fit']['functions'])
        self.fitModule.setConfiguration(newConfig)
        newConfig = self.fitModule.getConfiguration()
        #self.topWidget.setFunctions(newConfig['fit']['functions'])
        fname = self.fitModule.getFitFunction()
        if fname in [None, "None", "NONE"]:
            idx = 0
        else:
            idx = newConfig['fit']['functions'].index(fname) + 1
        self.topWidget.fitFunctionCombo.setCurrentIndex(idx)
        fname = self.fitModule.getBackgroundFunction()
        if fname in [None, "None", "NONE"]:
            idx = 0
        else:
            idx = newConfig['fit']['functions'].index(fname) + 1
        idx = self.topWidget.backgroundCombo.findText(fname)
        self.topWidget.backgroundCombo.setCurrentIndex(idx)
        if DEBUG:
            print("TABLE TO BE CLEANED")
        #self.estimate()

    def setFitFunction(self, fname):
        current = self.fitModule.getFitFunction()
        if current != fname:
            self.fitModule.setFitFunction(fname)
            idx = self.topWidget.fitFunctionCombo.findText(fname)
            self.topWidget.fitFunctionCombo.setCurrentIndex(idx)

    def setBackgroundFunction(self, fname):
        current = self.fitModule.getBackgroundFunction()
        if current != fname:
            self.fitModule.setBackgroundFunction(fname)
            idx = self.topWidget.backgroundCombo.findText(fname)
            self.topWidget.backgroundCombo.setCurrentIndex(idx)

    def setData(self, *var, **kw):
        returnValue = self.fitModule.setData(*var, **kw)
        if self.__useTab:
            if hasattr(self.graph, "addCurve"):
                self.graph.addCurve(self.fitModule._x,
                                    self.fitModule._y,
                                    legend='Data',
                                    replace=True)
            elif hasattr(self.graph, "newCurve"):
                self.graph.clearCurves()
                self.graph.newCurve('Data', self.fitModule._x,
                                    self.fitModule._y)
            self.graph.replot()
        return returnValue

    def estimate(self):
        self.setStatus("Estimate started")
        self.statusWidget.chi2Line.setText("")
        try:
            x = self.fitModule._x
            y = self.fitModule._y
            if hasattr(self.graph, "addCurve"):
                self.graph.addCurve(x, y, 'Data')
            elif hasattr(self.graph, "newCurve"):
                self.graph.newCurve('Data', x, y)
            self.graph.removeCurve("Fit")
            self.graph.removeCurve("Background", replot=True)
            self.fitModule.estimate()
            self.setStatus()
            self.parametersTable.fillTableFromFit(self.fitModule.paramlist)
        except:
            if DEBUG:
                raise
            text = "%s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText(text)
            msg.exec_()
            self.setStatus("Ready (after estimate error)")

    def setStatus(self, text=None):
        if text is None:
            text = "%s" % self.fitModule.getStatus()

        self.statusWidget.statusLine.setText(text)

    def startFit(self):
        #get parameters from table
        self.fitModule.paramlist = self.parametersTable.fillFitFromTable()
        try:
            values, chisq, sigma, niter, lastdeltachi = self.fitModule.startFit(
            )
            self.setStatus()
        except:
            if DEBUG:
                raise
            text = "%s:%s" % (sys.exc_info()[0], sys.exc_info()[1])
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText(text)
            msg.exec_()
            self.setStatus("Ready (after fit error)")
            return

        self.parametersTable.fillTableFromFit(self.fitModule.paramlist)
        self.statusWidget.chi2Line.setText("%f" % chisq)
        ddict = {}
        ddict['event'] = "FitFinished"
        ddict['x'] = self.fitModule._x
        ddict['y'] = self.fitModule._y
        ddict['yfit'] = self.evaluateDefinedFunction()
        self.emit(qt.SIGNAL('SimpleFitSignal'), ddict)
        self.updateGraph()

    def updateGraph(self):
        #this is to be overwritten and for test purposes
        if self.graph is None:
            return
        ddict = {}
        ddict['event'] = "FitFinished"
        ddict['x'] = self.fitModule._x
        ddict['y'] = self.fitModule._y
        ddict['yfit'] = self.evaluateDefinedFunction()
        ddict['background'] = self.fitModule._evaluateBackground()
        if hasattr(self.graph, "addCurve"):
            self.graph.addCurve(ddict['x'], ddict['y'], 'Data')
            self.graph.addCurve(ddict['x'], ddict['yfit'], 'Fit')
            self.graph.addCurve(ddict['x'], ddict['background'], 'Background')
        elif hasattr(self.graph, "newCurve"):
            self.graph.newCurve('Data', ddict['x'], ddict['y'])
            self.graph.newCurve('Fit', ddict['x'], ddict['yfit'])
            self.graph.newCurve('Background', ddict['x'], ddict['background'])
        self.graph.replot()
        self.graph.show()

    def dismiss(self):
        self.close()

    def evaluateDefinedFunction(self, x=None):
        return self.fitModule.evaluateDefinedFunction()