Beispiel #1
0
class LakeshoreBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.addProperty("mnemonic", "string", "")
        self.addProperty("unit", "combo", ("C", "K"), "C")
        self.addProperty("baseTime", "combo", ("current time", "0"), "0")

        self.lstChannelValueDisplay = []
        self.lstChannelWidgets = []
        self.data = {}
        self.lakeshore = None

        graphBox = QVBox(self)
        graphButtonsBox = QHBox(graphBox)
        graphButtonsBox.setSpacing(5)
        self.graph = QtBlissGraph(graphBox)
        self.graph.setx1timescale(True)
        self.graph.xlabel("time")
        self.graph.ylabel("temperature (%s)" % self["unit"])
        self.graph.setPaletteBackgroundColor(Qt.white)
        self.graph.canvas().setMouseTracking(True)
        self.cmdResetZoom = QPushButton("Reset zoom", graphButtonsBox)
        self.lblXY = QLabel("X = ? ; Y = ?", graphButtonsBox)
        HorizontalSpacer(graphButtonsBox)
        self.cmdSaveData = QToolButton(graphButtonsBox)
        self.cmdSaveData.setUsesTextLabel(True)
        self.cmdSaveData.setTextLabel("Save data to file")
        self.cmdSaveData.setIconSet(QIconSet(Icons.load("save")))
        self.cmdSaveData.setTextPosition(QToolButton.BesideIcon)

        self.topFrame = QVGroupBox("Lakeshore - ", self)
        updateFreqBox = QHBox(self.topFrame)
        updateFreqBox.setSpacing(5)
        QLabel("Update frequency : every", updateFreqBox)
        self.spnUpdateFrequency = QSpinBox(64, 30000, 500, updateFreqBox)
        QLabel("millisecond", updateFreqBox)
        self.lblUpdateFrequency = QLabel("<nobr><b>current = ?</b></nobr>",
                                         updateFreqBox)
        self.cmdUpdateFrequency = QPushButton("Change", updateFreqBox)
        HorizontalSpacer(updateFreqBox)
        self.lblStatus = QLabel("<h1>status</h1>", self.topFrame)
        self.lblStatus.setAlignment(Qt.AlignCenter)
        innerBox = QVBox(self.topFrame)
        self.channelsBox = QGrid(8, innerBox)
        self.channelsBox.setSpacing(5)
        self.channelsBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        commandsBox = QVBox(innerBox)
        VerticalSpacer(self.topFrame)
        resetBox = QHBox(self.topFrame)
        HorizontalSpacer(resetBox)
        #self.cmdReset = QToolButton(resetBox)
        #self.cmdReset.setUsesTextLabel(True)
        #self.cmdReset.setTextLabel("Reset instrument")
        #self.cmdReset.setIconSet(QIconSet(Icons.load("reload")))
        #self.cmdReset.setTextPosition(QToolButton.BesideIcon)

        #QObject.connect(self.cmdReset, SIGNAL("clicked()"), self.lsReset)
        QObject.connect(self.cmdResetZoom, SIGNAL('clicked()'),
                        self.graph.ResetZoom)
        QObject.connect(self.cmdSaveData, SIGNAL('clicked()'), self.saveGraph)
        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'),
                        self.graphSignal)
        QObject.connect(self.cmdUpdateFrequency, SIGNAL("clicked()"),
                        self.lsUpdateFrequency)

        QVBoxLayout(self, 5, 5)
        self.layout().addWidget(graphBox)
        self.layout().addWidget(self.topFrame)

    def graphSignal(self, dict):
        if dict['event'] == 'MouseAt':
            self.lblXY.setText("X = %.3f ; Y = %.3f" % (dict['x'], dict['y']))

    def setStatus(self, status):
        self.lblStatus.setText("<nobr><h1>status: %s</h1></nobr>" % status)

    def updateFrequency(self, freq):
        self.lblUpdateFrequency.setText("<nobr><b>current = %d</b></nobr>" %
                                        freq)
        self.spnUpdateFrequency.setValue(freq)

    def propertyChanged(self, property, oldValue, newValue):
        if property == 'mnemonic':
            self.lakeshore = self.getHardwareObject(newValue)

            if self.lakeshore is not None:
                self.lakeshore.setUnit(self["unit"])
                self.topFrame.setTitle("Lakeshore - %s" %
                                       self.lakeshore.getIdent())
                self.updateFrequency(self.lakeshore.interval)

                for w in self.lstChannelWidgets:
                    w.close(True)

                self.lstChannelValueDisplay = []
                self.lstChannelWidgets = []
                self.channelCheckboxCb = weakref.WeakKeyDictionary()

                for i in range(self.lakeshore.getChannelsNumber()):
                    newCheckbox = QCheckBox("Channel %d" % (i + 1),
                                            self.channelsBox)
                    self.lstChannelWidgets.append(newCheckbox)

                    self.data[i] = None

                    def checkbox_cb(state, channel=i):
                        if state == QButton.On:
                            self.data[channel] = {"x": [], "y": [], "t0": None}
                        else:
                            self.data[channel] = None

                    self.channelCheckboxCb[newCheckbox] = checkbox_cb

                    QObject.connect(newCheckbox, SIGNAL("stateChanged(int)"),
                                    checkbox_cb)

                    newValueDisplayBrick = ValueDisplayBrick.ValueDisplayBrick(
                        self.channelsBox, "channel%d" % i)
                    self.lstChannelValueDisplay.append(newValueDisplayBrick)
                    self.lstChannelWidgets.append(
                        self.lstChannelValueDisplay[-1])
                    newValueDisplayBrick["unit"] = self["unit"]
                    newValueDisplayBrick["valueLabel"] = ""
                    newValueDisplayBrick["showSynoptic"] = False
                    newValueDisplayBrick["showTitle"] = False
                    newValueDisplayBrick["formatString"] = "+####.##"
                    newValueDisplayBrick.show()

                self.connect(self.lakeshore, "statusChanged", self.setStatus)
                self.connect(self.lakeshore, "channelsUpdate",
                             self.lsChannelsUpdated)
                self.connect(self.lakeshore, "intervalChanged",
                             self.updateFrequency)
        elif property == "unit":
            if self.lakeshore is not None:
                self.lakeshore.setUnit(newValue)
        elif property == "baseTime":
            for channel, curve_data in self.data.items():
                if curve_data is None:
                    continue

                self.graph.delcurve("channel %d" % (channel + 1))

                curve_data["x"] = []
                curve_data["y"] = []
                curve_data["t0"] = None

    def saveGraph(self):
        filename = str(
            QFileDialog.getSaveFileName(os.environ["HOME"],
                                        "Data file (*.dat *.txt)", self,
                                        "Save file",
                                        "Choose a filename to save under"))

        if len(filename) == 0:
            return

        try:
            f = open(filename, "w")
        except:
            logging.getLogger().exception(
                "An error occured while trying to open file %s", filename)
            QMessageBox.warning(
                self, "Error",
                "Could not open file %s for writing !" % filename,
                QMessageBox.Ok)
        else:
            contents = [
                "#F Lakeshore temperatures",
                "#D %s" % time.ctime(time.time())
            ]

            for channel, curve_data in self.data.items():
                if curve_data is None:
                    continue

                contents.append("\n#S %d %s" % (channel + 1, "channel %d" %
                                                (channel + 1)))
                contents.append("#N 2")
                contents.append("#L  %s  %s" % ("time (s)", "temperature"))

                for x, y in zip(curve_data["x"], curve_data["y"]):
                    contents.append("%s %s" % (str(x), str(y)))

                contents.append("\n")

            try:
                try:
                    f.write("\n".join(contents))
                except:
                    QMessageBox.warning(
                        self, "Error", "Could not save file to\n%s" % filename,
                        QMessageBox.Ok)
                else:
                    QMessageBox.information(
                        self, "Success",
                        "Data have been saved successfully to\n%s" % filename,
                        QMessageBox.Ok)
            finally:
                f.close()

    def lsChannelsUpdated(self, values):
        i = 0
        t = None

        if self["baseTime"] == "0":
            t = time.time()

            try:
                t0 = min([
                    _f for _f in [
                        d["t0"]
                        for d in [_f for _f in iter(self.data.values()) if _f]
                    ] if _f
                ])
            except ValueError:
                t0 = t

        for v in values:
            curve_name = "channel %d" % (i + 1)

            self.lstChannelValueDisplay[i].setValue(v)
            self.lstChannelValueDisplay[i]["unit"] = self["unit"]

            if self.data[i] is not None:
                if self.data[i]["t0"] is None:
                    self.data[i]["t0"] = t

                if self["baseTime"] == "0":
                    self.data[i]["x"].append(t - t0)
                else:
                    # convert computer local time to seconds
                    t = time.localtime()
                    self.data[i]["x"].append(
                        sum([t[n + 3] * (60**(2 - n)) for n in range(3)]))

                self.data[i]["y"].append(v)

                self.graph.newcurve(curve_name, self.data[i]["x"],
                                    self.data[i]["y"])
            else:
                self.graph.delcurve(curve_name)

            i += 1

        self.graph.replot()

    def lsReset(self):
        if self.lakeshore is not None:
            self.lakeshore.reset()

    def lsUpdateFrequency(self):
        new_freq = self.spnUpdateFrequency.value()

        if self.lakeshore is not None:
            self.lakeshore.setInterval(new_freq)
Beispiel #2
0
class ScanPlotWidget(qt.QWidget):
    def __init__(self, parent=None, name="scan_plot_widget"):
        qt.QWidget.__init__(self, parent, name)

        self.xdata = []
        self.ylabel = ""

        self.isRealTimePlot = None
        self.isConnected = None
        self.isScanning = None

        self.lblTitle = qt.QLabel(self)
        self.graphPanel = qt.QFrame(self)
        buttonBox = qt.QHBox(self)
        self.lblPosition = qt.QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        qt.QObject.connect(
            self.graph, qt.PYSIGNAL("QtBlissGraphSignal"), self.handleBlissGraphSignal
        )
        qt.QObject.disconnect(
            self.graph,
            qt.SIGNAL("plotMousePressed(const QMouseEvent&)"),
            self.graph.onMousePressed,
        )
        qt.QObject.disconnect(
            self.graph,
            qt.SIGNAL("plotMouseReleased(const QMouseEvent&)"),
            self.graph.onMouseReleased,
        )

        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        # self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(qt.Qt.AlignRight)
        self.lblTitle.setAlignment(qt.Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        buttonBox.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)

        qt.QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        qt.QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)
        self.setPaletteBackgroundColor(qt.Qt.white)

    def setRealTimePlot(self, isRealTime):
        self.isRealTimePlot = isRealTime

    def newScanStarted(self, scanParameters):
        self.graph.clearcurves()
        self.isScanning = True
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" % scanParameters["title"])
        self.xdata = []
        self.graph.xlabel(scanParameters["xlabel"])
        self.ylabel = scanParameters["ylabel"]
        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels, ydata in zip(ylabels, self.ydatas):
            self.graph.newcurve(labels, self.xdata, ydata)
        self.graph.ylabel(self.ylabel)
        self.graph.setx1timescale(False)
        self.graph.replot()
        self.graph.setTitle("Energy scan started. Waiting values...")

    def newScanPoint(self, x, y):
        self.xdata.append(x)
        for label, ydata, yvalue in zip(
            self.ylabel.split(), self.ydatas, str(y).split()
        ):
            ydata.append(float(yvalue))
            self.graph.newcurve(label, self.xdata, ydata)
            self.graph.setTitle("Energy scan in progress. Please wait...")
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt" and self.isScanning:
            self.lblPosition.setText(
                "(X: %0.2f, Y: %0.2f)" % (signalDict["x"], signalDict["y"])
            )

    def plotResults(
        self,
        pk,
        fppPeak,
        fpPeak,
        ip,
        fppInfl,
        fpInfl,
        rm,
        chooch_graph_x,
        chooch_graph_y1,
        chooch_graph_y2,
        title,
    ):
        self.graph.clearcurves()
        self.graph.setTitle(title)
        self.graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.graph.replot()
        self.isScanning = False

    def plotScanCurve(self, scan_data):
        self.graph.clearcurves()
        self.graph.setTitle("Energy scan finished")
        self.lblTitle.setText("")
        xdata = [scan_data[el][0] for el in range(len(scan_data))]
        ydata = [scan_data[el][1] for el in range(len(scan_data))]
        self.graph.newcurve("energy", xdata, ydata)
        self.graph.replot()

    def clear(self):
        self.graph.clearcurves()
        # self.graph.setTitle("")
        self.lblTitle.setText("")
        self.lblPosition.setText("")

    def scanFinished(self):
        self.graph.setTitle("Energy scan finished")
Beispiel #3
0
class EnergyScanBrick(BlissWidget):
    STATES = {
        'error': QWidget.red,\
        'ok': QWidget.green,\
        'progress': QWidget.yellow
    }

    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.energyScan = None
        self.scanObject = None
        self.element = None

        self.sessionId = None
        self.blSampleId = None
        self.scanParameters = {}
        self.archive_directory = None

        self.addProperty('mnemonic', 'string', '')
        self.addProperty('icons', 'string', '')
        self.addProperty('formatString', 'formatString', '##.####')
        self.addProperty('decimalPlaces', 'string', '4')

        self.defineSlot('setDirectory', ())
        self.defineSlot('setPrefix', ())
        self.defineSlot('setElement', ())
        self.defineSlot('setSample', ())
        self.defineSlot('setSession', ())

        self.defineSignal('energyScanning', ())
        self.defineSignal('energyScanConnected', ())
        self.defineSignal('energyScanCanMove', ())
        self.defineSignal('edgeScanEnergies', ())

        self.parametersBox = QHGroupBox("Parameters", self)
        self.parametersBox.hide()
        self.parametersBox.setInsideMargin(4)
        self.parametersBox.setInsideSpacing(2)
        self.parametersBox.setCheckable(True)
        self.parametersBox.setChecked(False)

        QLabel("Prefix:", self.parametersBox)
        self.prefixInput = QLineEdit(self.parametersBox)
        self.prefixInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        QObject.connect(self.prefixInput,
                        SIGNAL('textChanged(const QString &)'),
                        self.prefixChanged)
        QLabel("Directory:", self.parametersBox)
        self.directoryInput = QLineEdit(self.parametersBox)
        self.directoryInput.setSizePolicy(QSizePolicy.Expanding,
                                          QSizePolicy.Fixed)
        QObject.connect(self.directoryInput,
                        SIGNAL('textChanged(const QString &)'),
                        self.directoryChanged)

        self.browseButton = QToolButton(self.parametersBox)
        self.browseButton.setTextLabel("Browse")
        self.browseButton.setUsesTextLabel(True)
        self.browseButton.setTextPosition(QToolButton.BesideIcon)
        QObject.connect(self.browseButton, SIGNAL("clicked()"),
                        self.browseButtonClicked)

        self.scanBox = QHGroupBox("Energy scan", self)
        self.scanBox.setInsideMargin(4)
        self.scanBox.setInsideSpacing(2)
        self.scanBox.hide()
        self.startScanButton = MenuButton(self.scanBox, "Start scan")
        self.startScanButton.hide()
        self.connect(self.startScanButton, PYSIGNAL('executeCommand'),
                     self.startEnergyScan)
        self.connect(self.startScanButton, PYSIGNAL('cancelCommand'),
                     self.cancelEnergyScan)

        self.statusBox = QHGroupBox("(no element)", self.scanBox)
        self.statusBox.hide()
        #self.statusBox.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.MinimumExpanding)
        self.statusBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.statusBox.setAlignment(QGroupBox.AlignCenter)
        self.scanStatus = QLabel(self.statusBox)
        self.scanStatus.setSizePolicy(QSizePolicy.Expanding,
                                      QSizePolicy.MinimumExpanding)
        self.scanStatus.setAlignment(QLabel.AlignCenter)

        box4 = QVBox(self.scanBox)
        peakLabel = QLabel("Peak:", box4)
        peakLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev1Label = QLabel("(keV)", box4)
        kev1Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        #kev2Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.peakInput = shortLineEdit(self.scanBox)
        self.peakInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.peakInput.setValidator(QDoubleValidator(self))

        box5 = QVBox(self.scanBox)
        inflectionLabel = QLabel("Inflection:", box5)
        inflectionLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev2Label = QLabel("(keV)", box5)
        kev2Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        #kev1Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.inflectionInput = shortLineEdit(self.scanBox)
        self.inflectionInput.setSizePolicy(QSizePolicy.Minimum,
                                           QSizePolicy.Fixed)
        self.inflectionInput.setValidator(QDoubleValidator(self))

        box6 = QVBox(self.scanBox)
        remoteLabel = QLabel("Remote:", box6)
        remoteLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev3Label = QLabel("(keV)", box6)
        kev3Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        #kev3Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.remoteInput = shortLineEdit(self.scanBox)
        self.remoteInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.remoteInput.setValidator(QDoubleValidator(self))

        box7 = QVBox(self.scanBox)
        remoteLabel = QLabel("2nd Remote:", box7)
        remoteLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev4Label = QLabel("(keV)", box7)
        kev4Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        #kev4Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.remote2Input = shortLineEdit(self.scanBox)
        self.remote2Input.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.remote2Input.setValidator(QDoubleValidator(self))

        self.acceptBox = QVBox(self.scanBox)
        self.acceptBox.setSpacing(2)
        self.acceptButton = MenuButton2(self.acceptBox, "Accept")
        self.resetButton = MenuButton2(self.acceptBox, "Reset")
        self.acceptBox.hide()
        QObject.connect(self.resetButton, SIGNAL('clicked()'),
                        self.resetEnergies)
        QObject.connect(self.acceptButton, SIGNAL('clicked()'),
                        self.acceptEnergies)

        self.parametersBox.setSizePolicy(QSizePolicy.MinimumExpanding,
                                         QSizePolicy.Fixed)
        self.scanBox.setSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.Fixed)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        self.instanceSynchronize("parametersBox", "prefixInput",
                                 "directoryInput", "peakInput",
                                 "inflectionInput", "remoteInput",
                                 "remote2Input")

        self.choochGraphs = QtBlissGraph(self)
        self.choochGraphs.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Fixed)

        QVBoxLayout(self)
        self.layout().addWidget(self.parametersBox)
        self.layout().addWidget(self.scanBox)
        self.layout().addWidget(self.choochGraphs)

        self.setEnabled(False)

    def setIcons(self, icons):
        icons_list = icons.split()
        try:
            self.startScanButton.setIcons(icons_list[0], icons_list[1])
        except IndexError:
            pass
        try:
            self.acceptButton.setPixmap(Icons.load(icons_list[2]))
        except IndexError:
            pass
        try:
            self.resetButton.setPixmap(Icons.load(icons_list[3]))
        except IndexError:
            pass
        try:
            self.browseButton.setPixmap(Icons.load(icons_list[4]))
        except IndexError:
            pass

    def prefixChanged(self, txt):
        txt = str(txt).replace(" ", "_")
        self.prefixInput.setText(txt)

    def directoryChanged(self, txt):
        txt = str(txt).replace(" ", "_")
        self.directoryInput.setText(txt)

    def browseButtonClicked(self):
        get_dir = QFileDialog(self)
        s = self.font().pointSize()
        f = get_dir.font()
        f.setPointSize(s)
        get_dir.setFont(f)
        get_dir.updateGeometry()
        d=get_dir.getExistingDirectory(self.directoryInput.text(),self,"",\
            "Select a directory",True,False)
        if d is not None and len(d) > 0:
            self.setDirectory(d)

    def setSample(self, samples_list):
        #print "EnergyScanBrick.setSample",samples_list
        if len(samples_list) == 0:
            self.blSampleId = None
        else:
            if len(samples_list) > 1:
                logging.getLogger().warning(
                    "EnergyScanBrick: multiple samples selected (attaching scan only to first sample)!"
                )
            for sample in samples_list:
                try:
                    blsample_id = int(sample[0])
                except:
                    pass
                else:
                    self.blSampleId = blsample_id
                    break

    def setSession(self,
                   session_id,
                   prop_code=None,
                   prop_number=None,
                   prop_id=None,
                   expiration_time=0):
        #print "EnergyScanBrick.setSession",session_id
        self.sessionId = session_id
        if prop_code is None or prop_number is None:
            pass
        else:
            self.archive_directory = str(prop_code) + str(prop_number)

    def setDirectory(self, scan_dir):
        self.directoryInput.setText(scan_dir)

    def setPrefix(self, scan_prefix):
        self.prefixInput.setText(scan_prefix)

    def setElement(self, symbol, edge):
        #print "ENERGYSCANBRICK.setElement",symbol,edge
        if symbol is None:
            self.clearEnergies()
            self.setEnabled(False)
            self.element = None
        else:
            if self.energyScan is not None and self.energyScan.canScanEnergy():
                self.setEnabled(True)
            self.element = (symbol, edge)

    def resetEnergies(self):
        confirm_dialog=QMessageBox("Confirm reset",\
            "This will also clear your energies in the Collect tab. Press OK to reset the energies.",\
            QMessageBox.Warning,QMessageBox.Ok,QMessageBox.Cancel,\
            QMessageBox.NoButton,self)

        s = self.font().pointSize()
        f = confirm_dialog.font()
        f.setPointSize(s)
        confirm_dialog.setFont(f)
        confirm_dialog.updateGeometry()

        if confirm_dialog.exec_loop() == QMessageBox.Ok:
            self.inflectionInput.setText("")
            self.peakInput.setText("")
            self.remoteInput.setText("")
            self.remote2Input.setText("")
            self.emit(PYSIGNAL('edgeScanEnergies'), ({}, ))

    def acceptEnergies(self):
        if self.peakInput.hasAcceptableInput():
            pk = float(self.peakInput.text())
        else:
            pk = None
        if self.inflectionInput.hasAcceptableInput():
            ip = float(self.inflectionInput.text())
        else:
            ip = None
        if self.remoteInput.hasAcceptableInput():
            rm = float(self.remoteInput.text())
        else:
            rm = None
        if self.remote2Input.hasAcceptableInput():
            rm2 = float(self.remote2Input.text())
        else:
            rm2 = None
        energies = {"pk": pk, "ip": ip, "rm": rm, "rm2": rm2}
        self.emit(PYSIGNAL('edgeScanEnergies'), (energies, ))

    def propertyChanged(self, propertyName, oldValue, newValue):
        if propertyName == 'mnemonic':
            if self.energyScan is not None:
                self.disconnect(self.energyScan, 'energyScanStarted',
                                self.scanStarted)
                self.disconnect(self.energyScan, 'energyScanFinished',
                                self.scanFinished)
                self.disconnect(self.energyScan, 'energyScanFailed',
                                self.scanFailed)
                self.disconnect(self.energyScan, 'scanStatusChanged',
                                self.scanStatusChanged)
                self.disconnect(self.energyScan, 'energyScanReady',
                                self.scanReady)
                self.disconnect(self.energyScan, 'connected', self.connected)
                self.disconnect(self.energyScan, 'disconnected',
                                self.disconnected)

            self.clearEnergies()
            self.energyScan = self.getHardwareObject(newValue)
            if self.energyScan is not None:
                self.scanObject = None
                try:
                    specversion = self.energyScan.getCommandObject(
                        "doEnergyScan").specVersion
                except:
                    logging.getLogger().exception(
                        "%s: could not get spec version from Energy Scan Hardware Object",
                        self.name())
                else:
                    self.scanObject = QSpecScan(specversion)

                self.connect(self.energyScan, 'energyScanStarted',
                             self.scanStarted)
                self.connect(self.energyScan, 'energyScanFinished',
                             self.scanFinished)
                self.connect(self.energyScan, 'energyScanFailed',
                             self.scanFailed)
                self.connect(self.energyScan, 'scanStatusChanged',
                             self.scanStatusChanged)
                self.connect(self.energyScan, 'energyScanReady',
                             self.scanReady)
                self.connect(self.energyScan, 'connected', self.connected)
                self.connect(self.energyScan, 'disconnected',
                             self.disconnected)
                self.connect(self.energyScan, 'chooch_finished',
                             self.chooch_finished)

                if self.energyScan.isConnected():
                    self.connected()
                else:
                    self.disconnected()
            else:
                self.disconnected()

        elif propertyName == 'icons':
            self.setIcons(newValue)
        else:
            BlissWidget.propertyChanged(self, propertyName, oldValue, newValue)

    def run(self):
        logging.getLogger().info(
            "Anonmalous Scattering Factors determination based on Chooch 5.0.6 by Gwyndaf Evans\nCopyright (C) 1994--2007\[email protected]\nG. Evans & R. F. Pettifer (2001)\nJ. Appl. Cryst. 34, 82-86."
        )

        if self.energyScan is not None:
            if self.energyScan.isConnected():
                self.connected()
            else:
                self.disconnected()
        else:
            self.disconnected()

    def connected(self):
        can_scan = self.energyScan.canScanEnergy()
        if self.element is not None:
            self.setEnabled(can_scan)
        else:
            self.setEnabled(False)
        self.emit(PYSIGNAL('energyScanConnected'), (True, can_scan))
        self.emit(PYSIGNAL('energyScanCanMove'), (can_scan, ))

    def disconnected(self):
        self.setEnabled(False)
        self.emit(PYSIGNAL('energyScanConnected'), (False, ))
        self.emit(PYSIGNAL('energyScanCanMove'), (False, ))

    def scanReady(self, state):
        self.startScanButton.setEnabled(state)
        self.statusBox.setEnabled(state)

    def scanStatusChanged(self, msg=None):
        if msg is None:
            msg = ""
            color = self.scanBox.paletteBackgroundColor()
        else:
            color = EnergyScanBrick.STATES['progress']
        self.scanStatus.setText(str(msg))
        self.scanStatus.setPaletteBackgroundColor(QColor(color))

    def startEnergyScan(self):
        self.scanParameters = {}
        go_on = True
        if self.sessionId is None or self.sessionId == "":
            res = QMessageBox.question(
                self, 'Energy scan',
                "You are not properly logged, therefore your scan won't be stored in ISPyB.\nProceed with the energy scan?",
                "Proceed", "Cancel")
            if res != 0:
                go_on = False
        if not go_on:
            self.startScanButton.commandFailed()
            return

        if self.sessionId is not None and self.sessionId != "":
            self.scanParameters["sessionId"] = self.sessionId
            self.scanParameters["element"] = self.element[0]
            self.scanParameters["edgeEnergy"] = self.element[1]
            self.scanParameters["startTime"] = time.strftime(
                "%Y-%m-%d %H:%M:%S")

        self.statusBox.setTitle("%s - %s" % (self.element[0], self.element[1]))
        self.inflectionInput.setText("")
        self.peakInput.setText("")
        self.remoteInput.setText("")
        self.remote2Input.setText("")

        scan_result=self.energyScan.startEnergyScan(self.element[0],self.element[1],\
            str(self.directoryInput.text()),\
            str(self.prefixInput.text()),\
            self.sessionId,self.blSampleId)
        if not scan_result:
            self.scanFailed()

    def cancelEnergyScan(self):
        self.energyScan.cancelEnergyScan()

    def scanStarted(self):
        self.choochGraphs.newcurve("spline", [], [])
        self.choochGraphs.newcurve("fp", [], [])
        self.choochGraphs.replot()

        self.startScanButton.commandStarted()
        self.emit(PYSIGNAL("energyScanning"), (True, ))
        self.parametersBox.setEnabled(False)
        self.acceptBox.setEnabled(False)
        self.inflectionInput.setEnabled(False)
        self.peakInput.setEnabled(False)
        self.remoteInput.setEnabled(False)
        self.remote2Input.setEnabled(False)

    def scanFailed(self):
        color = EnergyScanBrick.STATES['error']
        self.scanStatus.setPaletteBackgroundColor(QColor(color))
        self.startScanButton.commandFailed()
        self.emit(PYSIGNAL("energyScanning"), (False, ))
        self.parametersBox.setEnabled(True)
        self.acceptBox.setEnabled(True)
        self.inflectionInput.setEnabled(True)
        self.peakInput.setEnabled(True)
        self.remoteInput.setEnabled(True)
        self.remote2Input.setEnabled(True)

    def chooch_finished(self, pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm,
                        chooch_graph_x, chooch_graph_y1, chooch_graph_y2,
                        title):
        # display Chooch graphs
        self.choochGraphs.setTitle(title)
        self.choochGraphs.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.choochGraphs.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.choochGraphs.replot()

    def scanFinished(self, *args):
        pass

    #    color=EnergyScanBrick.STATES['ok']


#         try:
#           smis_name=os.environ["SMIS_BEAMLINE_NAME"].lower()
#           x,y=smis_name.split("-")
#           bldir=x+"eh"+y
#         except:
#           bldir=os.environ["SMIS_BEAMLINE_NAME"].lower()

#         import pdb
#         pdb.set_trace()
#         self.element = (self.energyScan._element, self.energyScan._edge)

#         scanArchiveFilePrefix="/data/pyarch/%s/%s/%s_escan_%s" % (bldir, self.archive_directory, self.prefixInput.text(), "_".join(self.element))
#         i=1
#         while os.path.isfile(os.path.extsep.join((scanArchiveFilePrefix+str(i), "raw"))):
#             i=i+1

#         scanArchiveFilePrefix = scanArchiveFilePrefix+str(i)
#         scanFilePrefix = os.path.join(str(self.directoryInput.text()), os.path.basename(scanArchiveFilePrefix))

#         pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title = self.energyScan.doChooch(self.scanObject, self.element[0], self.element[1], scanArchiveFilePrefix, scanFilePrefix)

#         # display Chooch graphs
#         self.choochGraphs.setTitle(title)
#         self.choochGraphs.newcurve("spline", chooch_graph_x, chooch_graph_y1)
#         self.choochGraphs.newcurve("fp", chooch_graph_x, chooch_graph_y2)
#         self.choochGraphs.replot()

#         # display Chooch results
#         energy_str=self['formatString'] % pk
#         self.peakInput.setText(energy_str)
#         energy_str=self['formatString'] % ip
#         self.inflectionInput.setText(energy_str)
#         energy_str=self['formatString'] % rm
#         self.remoteInput.setText(energy_str)

#         self.scanStatus.setPaletteBackgroundColor(QColor(color))

#         self.startScanButton.commandDone()
#         self.emit(PYSIGNAL("energyScanning"),(False,))
#         self.parametersBox.setEnabled(True)
#         self.acceptBox.setEnabled(True)
#         self.inflectionInput.setEnabled(True)
#         self.peakInput.setEnabled(True)
#         self.remoteInput.setEnabled(True)
#         self.remote2Input.setEnabled(True)

    def clearEnergies(self):
        self.inflectionInput.setText("")
        self.peakInput.setText("")
        self.remoteInput.setText("")
        self.remote2Input.setText("")
        self.statusBox.setTitle("(no element)")
class LakeshoreBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.addProperty("mnemonic", "string", "")
        self.addProperty("unit", "combo", ("C", "K"), "C")
        self.addProperty("baseTime", "combo", ("current time", "0"), "0")

        self.lstChannelValueDisplay = []
        self.lstChannelWidgets = []
        self.data = {}
        self.lakeshore = None

        graphBox = QVBox(self)
        graphButtonsBox = QHBox(graphBox)
        graphButtonsBox.setSpacing(5)
        self.graph = QtBlissGraph(graphBox)
        self.graph.setx1timescale(True)
        self.graph.xlabel("time")
        self.graph.ylabel("temperature (%s)" % self["unit"])
        self.graph.setPaletteBackgroundColor(Qt.white)
        self.graph.canvas().setMouseTracking(True)
        self.cmdResetZoom = QPushButton("Reset zoom", graphButtonsBox)
        self.lblXY = QLabel("X = ? ; Y = ?", graphButtonsBox)
        HorizontalSpacer(graphButtonsBox)
        self.cmdSaveData = QToolButton(graphButtonsBox)
        self.cmdSaveData.setUsesTextLabel(True)
        self.cmdSaveData.setTextLabel("Save data to file")
        self.cmdSaveData.setIconSet(QIconSet(Icons.load("save")))
        self.cmdSaveData.setTextPosition(QToolButton.BesideIcon)

        self.topFrame = QVGroupBox("Lakeshore - ", self)
        updateFreqBox = QHBox(self.topFrame)
        updateFreqBox.setSpacing(5)
        QLabel("Update frequency : every", updateFreqBox)
        self.spnUpdateFrequency = QSpinBox(64, 30000, 500, updateFreqBox)
        QLabel("millisecond", updateFreqBox)
        self.lblUpdateFrequency = QLabel("<nobr><b>current = ?</b></nobr>", updateFreqBox) 
        self.cmdUpdateFrequency = QPushButton("Change", updateFreqBox)
        HorizontalSpacer(updateFreqBox)
        self.lblStatus = QLabel("<h1>status</h1>", self.topFrame)
        self.lblStatus.setAlignment(Qt.AlignCenter)
        innerBox = QVBox(self.topFrame)
        self.channelsBox = QGrid(8, innerBox)
        self.channelsBox.setSpacing(5)
        self.channelsBox.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        commandsBox = QVBox(innerBox)
        VerticalSpacer(self.topFrame)
        resetBox = QHBox(self.topFrame)
        HorizontalSpacer(resetBox)
        #self.cmdReset = QToolButton(resetBox)
        #self.cmdReset.setUsesTextLabel(True)
        #self.cmdReset.setTextLabel("Reset instrument")
        #self.cmdReset.setIconSet(QIconSet(Icons.load("reload")))
        #self.cmdReset.setTextPosition(QToolButton.BesideIcon)

        #QObject.connect(self.cmdReset, SIGNAL("clicked()"), self.lsReset)
        QObject.connect(self.cmdResetZoom, SIGNAL('clicked()'), self.graph.ResetZoom)
        QObject.connect(self.cmdSaveData, SIGNAL('clicked()'), self.saveGraph)
        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'), self.graphSignal)
        QObject.connect(self.cmdUpdateFrequency, SIGNAL("clicked()"), self.lsUpdateFrequency) 
 
        QVBoxLayout(self, 5, 5)
        self.layout().addWidget(graphBox)
        self.layout().addWidget(self.topFrame)
        

    def graphSignal(self, dict):
        if dict['event'] == 'MouseAt':            
            self.lblXY.setText("X = %.3f ; Y = %.3f" % (dict['x'], dict['y']))


    def setStatus(self, status):
        self.lblStatus.setText("<nobr><h1>status: %s</h1></nobr>" % status)


    def updateFrequency(self, freq):
        self.lblUpdateFrequency.setText("<nobr><b>current = %d</b></nobr>" % freq)
        self.spnUpdateFrequency.setValue(freq)


    def propertyChanged(self, property, oldValue, newValue):
        if property == 'mnemonic':
            self.lakeshore = self.getHardwareObject(newValue)

            if self.lakeshore is not None:
                self.lakeshore.setUnit(self["unit"])
                self.topFrame.setTitle("Lakeshore - %s" % self.lakeshore.getIdent())
                self.updateFrequency(self.lakeshore.interval)
 
                for w in self.lstChannelWidgets:
                    w.close(True)

                self.lstChannelValueDisplay = []
                self.lstChannelWidgets = []
                self.channelCheckboxCb = weakref.WeakKeyDictionary()
                
                for i in range(self.lakeshore.getChannelsNumber()):
                    newCheckbox = QCheckBox("Channel %d" % (i+1), self.channelsBox)
                    self.lstChannelWidgets.append(newCheckbox)

                    self.data[i]=None

                    def checkbox_cb(state, channel=i):
                        if state == QButton.On:
                            self.data[channel]={ "x":[], "y":[], "t0": None }
                        else:
                            self.data[channel]=None

                    self.channelCheckboxCb[newCheckbox] = checkbox_cb

                    QObject.connect(newCheckbox, SIGNAL("stateChanged(int)"), checkbox_cb)
                    
                    newValueDisplayBrick = ValueDisplayBrick.ValueDisplayBrick(self.channelsBox, "channel%d" % i)
                    self.lstChannelValueDisplay.append(newValueDisplayBrick)
                    self.lstChannelWidgets.append(self.lstChannelValueDisplay[-1])
                    newValueDisplayBrick["unit"] = self["unit"]
                    newValueDisplayBrick["valueLabel"]=""
                    newValueDisplayBrick["showSynoptic"] = False
                    newValueDisplayBrick["showTitle"] = False
                    newValueDisplayBrick["formatString"]="+####.##"
                    newValueDisplayBrick.show()
                    
                self.connect(self.lakeshore, "statusChanged", self.setStatus)
                self.connect(self.lakeshore, "channelsUpdate", self.lsChannelsUpdated)
                self.connect(self.lakeshore, "intervalChanged", self.updateFrequency)
        elif property == "unit":
            if self.lakeshore is not None:
                self.lakeshore.setUnit(newValue)
        elif property == "baseTime":
            for channel, curve_data in self.data.items():
                if curve_data is None:
                   continue
 
                self.graph.delcurve("channel %d" % (channel+1))
                
                curve_data["x"]=[]
                curve_data["y"]=[]
                curve_data["t0"]=None


    def saveGraph(self):
        filename = str(QFileDialog.getSaveFileName(os.environ["HOME"],
                                               "Data file (*.dat *.txt)",
                                               self,
                                               "Save file",
                                               "Choose a filename to save under"))

        if len(filename) == 0:
            return
        
        try:
            f = open(filename, "w")
        except:
            logging.getLogger().exception("An error occured while trying to open file %s", filename)
            QMessageBox.warning(self, "Error", "Could not open file %s for writing !" % filename, QMessageBox.Ok)
        else:
            contents = ["#F Lakeshore temperatures", "#D %s" % time.ctime(time.time())]

            for channel, curve_data in self.data.items():
                if curve_data is None:
                    continue

                contents.append("\n#S %d %s" % (channel+1, "channel %d" % (channel+1)))
                contents.append("#N 2")
                contents.append("#L  %s  %s" % ("time (s)", "temperature"))

                for x, y in zip(curve_data["x"], curve_data["y"]):
                    contents.append("%s %s" % (str(x), str(y)))

                contents.append("\n")

            try:
                try:
                    f.write("\n".join(contents))
                except:
                    QMessageBox.warning(self, "Error", "Could not save file to\n%s" % filename, QMessageBox.Ok)
                else:
                    QMessageBox.information(self, "Success", "Data have been saved successfully to\n%s" % filename, QMessageBox.Ok)
            finally:
                f.close()

        

    def lsChannelsUpdated(self, values):
        i = 0
        t = None
        
        if self["baseTime"] == "0":
            t = time.time()
            
            try:
                t0 = min([_f for _f in [d["t0"] for d in [_f for _f in iter(self.data.values()) if _f]] if _f])
            except ValueError:
                t0 = t
 
        for v in values:
            curve_name = "channel %d" % (i+1)
            
            self.lstChannelValueDisplay[i].setValue(v)
            self.lstChannelValueDisplay[i]["unit"] = self["unit"]

            if self.data[i] is not None:
                if self.data[i]["t0"] is None:
                    self.data[i]["t0"] = t

                if self["baseTime"] == "0":
                    self.data[i]["x"].append(t-t0)
                else:
                    # convert computer local time to seconds
                    t = time.localtime()
                    self.data[i]["x"].append(sum([t[n+3]*(60**(2-n)) for n in range(3)]))
                
                self.data[i]["y"].append(v)

                self.graph.newcurve(curve_name, self.data[i]["x"], self.data[i]["y"])
            else:
                self.graph.delcurve(curve_name) 
                    
            i += 1 

        self.graph.replot()


    def lsReset(self):
        if self.lakeshore is not None:
            self.lakeshore.reset()


    def lsUpdateFrequency(self):
        new_freq = self.spnUpdateFrequency.value()
  
        if self.lakeshore is not None:
            self.lakeshore.setInterval(new_freq)
Beispiel #5
0
class BlissScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSignal("newScan", ())

        self.scanObject = None
        self.xdata = []
        self.ylable = ""
        self.mylog = 0
        self.canAddPoint = True
        self.dm = DataManager()
        event.connect(self.dm, "scan_new", self.newScan)
        event.connect(self.dm, "scan_data", self.newScanPoint)

        self.addProperty("backgroundColor", "combo", ("white", "default"),
                         "white")
        self.addProperty("graphColor", "combo", ("white", "default"), "white")
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        QObject.connect(self.graph, PYSIGNAL("QtBlissGraphSignal"),
                        self.handleBlissGraphSignal)
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMousePressed(const QMouseEvent&)"),
            self.graph.onMousePressed,
        )
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMouseReleased(const QMouseEvent&)"),
            self.graph.onMouseReleased,
        )

        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)

    def propertyChanged(self, property, oldValue, newValue):
        if property == "backgroundColor":
            if newValue == "white":
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        elif property == "graphColor":
            if newValue == "white":
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.graph.canvas().setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))
        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    # def newScan(self, dm, scan_id, filename, motors, npoints, counters,
    # save_flag=True):
    def newScan(self,
                scan_id,
                filename,
                motors,
                npoints,
                counters,
                save_flag=True):
        self.emit(PYSIGNAL("newScan"), ())
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" % filename)
        self.xdata = []

        self.graph.clearcurves()
        # self.graph.xlabel(scanParameters['xlabel'])
        self.graph.xlabel("Energy")
        self.ylabel = "Counts"

        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels, ydata in zip(ylabels, self.ydatas):
            self.graph.newcurve(labels, self.xdata, ydata)

        self.graph.ylabel(self.ylabel)
        if motors == "Time":
            self.graph.setx1timescale(True)
        else:
            self.graph.setx1timescale(False)

        self.graph.replot()

    def newScanPoint(self, scan_id, values):
        x = values[0]
        self.xdata.append(x)
        for label, ydata, yvalue in zip(self.ylabel.split(), self.ydatas,
                                        values[1:]):
            ydata.append(float(yvalue))
            self.graph.newcurve(label, self.xdata, ydata)
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt":
            self.lblPosition.setText("(X: %f, Y: %f)" %
                                     (signalDict["x"], signalDict["y"]))
class SoleilScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSlot('newScan', ())

        self.defineSlot('newScanPoint', ())

        self.scanObject = None
        self.xdata = []
        self.ydata = []

        self.isConnected = None
        self.canAddPoint = True

        self.addProperty('specVersion', 'string', '')
        self.addProperty('backgroundColor', 'combo', ('white', 'default'),
                         'white')
        self.addProperty('graphColor', 'combo', ('white', 'default'), 'white')
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'),
                        self.handleBlissGraphSignal)
        QObject.disconnect(self.graph,
                           SIGNAL('plotMousePressed(const QMouseEvent&)'),
                           self.graph.onMousePressed)
        QObject.disconnect(self.graph,
                           SIGNAL('plotMouseReleased(const QMouseEvent&)'),
                           self.graph.onMouseReleased)
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)

    def propertyChanged(self, property, oldValue, newValue):
        if property == 'specVersion':
            if self.scanObject is not None:
                self.safeDisconnect()

            self.scanObject = None
            if self.scanObject is not None:
                self.safeConnect()

        elif property == 'backgroundColor':
            if newValue == 'white':
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        elif property == 'graphColor':
            if newValue == 'white':
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.graph.canvas().setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    def newScan(self, scanParameters):
        logging.info('newScan scanParameters %s' % str(scanParameters))
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' %
                              scanParameters['title'])
        self.graph.xlabel(scanParameters['xlabel'])
        self.graph.ylabel(scanParameters['ylabel'])
        self.graph.setx1timescale(False)
        self.xdata = []
        self.ydata = []
        self.graph.newcurve('scan', self.xdata, self.ydata)
        self.graph.replot()

    def newScanPoint(self, x, y):
        logging.info('newScanPoint x %s, y %s' % (x, y))
        self.xdata.append(x)
        self.ydata.append(y)
        self.graph.newcurve('scan', self.xdata, self.ydata, curveinfo='bo-')
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt':
            self.lblPosition.setText("(X: %f, Y: %f)" %
                                     (signalDict['x'], signalDict['y']))

    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL('newScanPoint'),
                         self.newScan)
            self.connect(self.scanObject, PYSIGNAL('newPoint'),
                         self.newScanPoint)
            self.isConnected = True

    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL('newScan'), self.newScan)
            self.disconnect(self.scanObject, PYSIGNAL('newScanPoint'),
                            self.newScanPoint)
            self.isConnected = False
Beispiel #7
0
class PymcaPlotWidget(qt_import.QWidget):
    def __init__(self, parent, realtime_plot=False):

        qt_import.QWidget.__init__(self, parent)

        self.axis_x_array = []
        self.axis_y_array = []

        self.realtime_plot = realtime_plot

        self.pymca_graph = Plot(self)
        self.pymca_graph.showGrid()
        self.info_label = qt_import.QLabel("", self)
        self.info_label.setAlignment(qt_import.Qt.AlignRight)

        _main_vlayout = qt_import.QVBoxLayout(self)
        _main_vlayout.addWidget(self.pymca_graph)
        _main_vlayout.addWidget(self.info_label)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        self.setSizePolicy(qt_import.QSizePolicy.Expanding,
                           qt_import.QSizePolicy.Expanding)

        if PYMCA_EXISTS:
            qt_import.QObject.connect(
                self.pymca_graph,
                qt_import.SIGNAL("QtBlissGraphSignal"),
                self.handle_graph_signal,
            )

        colors.set_widget_color(self, colors.WHITE)

    def clear(self):
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle("")
        self.info_label.setText("")

    def plot_energy_scan_curve(self, scan_result, scan_title):
        """Results are converted to two list describing
           x and y axes
        """
        x_data = [item[0] for item in scan_result]
        y_data = [item[1] for item in scan_result]
        self.pymca_graph.newcurve("Energy", x_data, y_data)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_title)
        self.pymca_graph.setx1axislimits(min(x_data), max(x_data))

    def start_new_scan(self, scan_info):
        self.axis_x_array = []
        self.axis_y_array = []
        self.pymca_graph.clearcurves()
        self.pymca_graph.xlabel(scan_info["xlabel"])
        self.ylabel = scan_info["ylabel"]
        self.pymca_graph.ylabel(self.ylabel)
        self.pymca_graph.setx1timescale(False)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_info["title"])

    def plot_energy_scan_results(
        self,
        pk,
        fppPeak,
        fpPeak,
        ip,
        fppInfl,
        fpInfl,
        rm,
        chooch_graph_x,
        chooch_graph_y1,
        chooch_graph_y2,
        title,
    ):
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle(title)
        self.pymca_graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.pymca_graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.pymca_graph.replot()
        self.pymca_graph.setx1axislimits(min(chooch_graph_x),
                                         max(chooch_graph_x))

    def plot_finished(self):
        if self.axis_x_array:
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            self.pymca_graph.replot()

    def add_new_plot_value(self, x, y):
        if self.realtime_plot:
            self.axis_x_array.append(x / 1000.0)
            self.axis_y_array.append(y / 1000.0)
            self.pymca_graph.newcurve("Energy", self.axis_x_array,
                                      self.axis_y_array)
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            # self.pymca_graph.replot()

    def handle_graph_signal(self, signal_info):
        if signal_info["event"] == "MouseAt":
            self.info_label.setText("(X: %0.2f, Y: %0.2f)" %
                                    (signal_info["x"], signal_info["y"]))
Beispiel #8
0
class SpecScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSignal("newScan", ())

        self.scanObject = None
        self.xdata = []
        self.ylable = ""
        self.mylog = 0

        self.isConnected = None
        # self.canAddPoint = None
        self.canAddPoint = True

        self.addProperty("specVersion", "string", "")
        self.addProperty("backgroundColor", "combo", ("white", "default"),
                         "white")
        self.addProperty("graphColor", "combo", ("white", "default"), "white")
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        # self.cmdZoomIn = QToolButton(buttonBox)
        # self.cmdZoomOut = QToolButton(buttonBox)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        QObject.connect(self.graph, PYSIGNAL("QtBlissGraphSignal"),
                        self.handleBlissGraphSignal)
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMousePressed(const QMouseEvent&)"),
            self.graph.onMousePressed,
        )
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMouseReleased(const QMouseEvent&)"),
            self.graph.onMouseReleased,
        )
        # QObject.connect(self.cmdZoomIn, SIGNAL('clicked()'), self.cmdZoomInClicked)
        # QObject.connect(self.cmdZoomOut, SIGNAL('clicked()'), self.cmdZoomOutClicked)

        # self.cmdZoomIn.setIconSet(QIconSet(Icons.load("zoomin")))
        # self.cmdZoomOut.setIconSet(QIconSet(Icons.load("zoomout")))
        # self.cmdZoomIn.setToggleButton(True)
        # self.cmdZoomOut.setToggleButton(True)
        # self.cmdZoomIn.setUsesTextLabel(False)
        # self.cmdZoomOut.setUsesTextLabel(False)
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)

    def propertyChanged(self, property, oldValue, newValue):
        if property == "specVersion":
            if self.scanObject is not None:
                self.safeDisconnect()

            self.scanObject = QSpecScan(newValue)

            if self.scanObject is not None:
                self.safeConnect()

        elif property == "backgroundColor":
            if newValue == "white":
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        elif property == "graphColor":
            if newValue == "white":
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.graph.canvas().setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    def newScan(self, scanParameters):
        # self.canAddPoint = True
        self.emit(PYSIGNAL("newScan"), ())
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" %
                              scanParameters["title"])
        self.xdata = []

        self.graph.clearcurves()
        self.graph.xlabel(scanParameters["xlabel"])
        self.ylabel = scanParameters["ylabel"]

        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels, ydata in zip(ylabels, self.ydatas):
            self.graph.newcurve(labels, self.xdata, ydata)

        self.graph.ylabel(self.ylabel)
        if self.scanObject.getScanType() == SpecScan.TIMESCAN:
            self.graph.setx1timescale(True)
        else:
            self.graph.setx1timescale(False)

        try:
            scanParameters["scaletype"] == "log"
            if self.mylog == 0:
                self.graph.toggleLogY()
                self.mylog = 1
        except BaseException:
            if self.mylog == 1:
                self.graph.toggleLogY()
                self.mylog = 0

        self.graph.replot()

    def newScanPoint(self, x, y):
        self.xdata.append(x)
        for label, ydata, yvalue in zip(self.ylabel.split(), self.ydatas,
                                        str(y).split()):
            ydata.append(float(yvalue))
            self.graph.newcurve(label, self.xdata, ydata)
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt":
            self.lblPosition.setText("(X: %f, Y: %f)" %
                                     (signalDict["x"], signalDict["y"]))

    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL("newScan"), self.newScan)
            self.connect(self.scanObject, PYSIGNAL("newPoint"),
                         self.newScanPoint)
            self.isConnected = True

    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL("newScan"), self.newScan)
            self.disconnect(self.scanObject, PYSIGNAL("newScanPoint"),
                            self.newScanPoint)
            # self.canAddPoint = False
            self.isConnected = False

    # def instanceMirrorChanged(self,mirror):
    #    if BlissWidget.isInstanceMirrorAllow():
    #        self.safeConnect()
    #    else:
    #        self.safeDisconnect()
    """
Beispiel #9
0
class ScanPlotWidget(QtImport.QWidget):

    def __init__(self, parent=None, name="scan_plot_widget"):

        QtImport.QWidget.__init__(self, parent)

        if name is not None:
            self.setObjectName(name)

        self.xdata = []
        self.ylabel = ""

        self.isRealTimePlot = None
        self.is_connected = None
        self.isScanning = None

        self.lblTitle = QtImport.QLabel(self)
        self.lblPosition = QtImport.QLabel(self)
        self.graph = QtBlissGraph(self)

        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        _main_vlayout = QtImport.QVBoxLayout(self)
        _main_vlayout.addWidget(self.lblTitle)
        _main_vlayout.addWidget(self.lblPosition)
        _main_vlayout.addWidget(self.graph)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

    def setRealTimePlot(self, isRealTime):
        self.isRealTimePlot = isRealTime

    def start_new_scan(self, scanParameters):
        self.graph.clearcurves()
        self.isScanning = True
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" % scanParameters["title"])
        self.xdata = []
        self.graph.xlabel(scanParameters["xlabel"])
        self.ylabel = scanParameters["ylabel"]
        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels, ydata in zip(ylabels, self.ydatas):
            self.graph.newcurve(labels, self.xdata, ydata)
        self.graph.ylabel(self.ylabel)
        self.graph.setx1timescale(False)
        self.graph.replot()
        self.graph.setTitle("Energy scan started. Waiting values...")

    def add_new_plot_value(self, x, y):
        self.xdata.append(x)
        for label, ydata, yvalue in zip(
            self.ylabel.split(), self.ydatas, str(y).split()
        ):
            ydata.append(float(yvalue))
            self.graph.newcurve(label, self.xdata, ydata)
            self.graph.setTitle("Energy scan in progress. Please wait...")
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt" and self.isScanning:
            self.lblPosition.setText(
                "(X: %0.2f, Y: %0.2f)" % (signalDict["x"], signalDict["y"])
            )

    def plot_results(
        self,
        pk,
        fppPeak,
        fpPeak,
        ip,
        fppInfl,
        fpInfl,
        rm,
        chooch_graph_x,
        chooch_graph_y1,
        chooch_graph_y2,
        title,
    ):
        self.graph.clearcurves()
        self.graph.setTitle(title)
        self.graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.graph.replot()
        self.isScanning = False

    def plot_scan_curve(self, scan_data):
        self.graph.clearcurves()
        self.graph.setTitle("Energy scan finished")
        self.lblTitle.setText("")
        xdata = [scan_data[el][0] for el in range(len(scan_data))]
        ydata = [scan_data[el][1] for el in range(len(scan_data))]
        self.graph.newcurve("energy", xdata, ydata)
        self.graph.replot()

    def clear(self):
        self.graph.clearcurves()
        # self.graph.setTitle("")
        self.lblTitle.setText("")
        self.lblPosition.setText("")

    def scan_finished(self):
        self.graph.setTitle("Energy scan finished")
class ScanPlotWidget(QtGui.QWidget):

    def __init__(self, parent = None, name = "scan_plot_widget"):
        QtGui.QWidget.__init__(self, parent)

        if name is not None:
            self.setObjectName(name)

        self.xdata = []
        self.ylabel = ""

        self.isRealTimePlot = None
        self.isConnected = None
        self.isScanning = None

        self.lblTitle = QtGui.QLabel(self)
        #self.graphPanel = qt.QFrame(self)
        #buttonBox = qt.QHBox(self)
        self.lblPosition = QtGui.QLabel(self)
        self.graph = QtBlissGraph(self)

        QtCore.QObject.connect(self.graph, QtCore.SIGNAL('QtBlissGraphSignal'), self.handleBlissGraphSignal)
        QtCore.QObject.disconnect(self.graph, QtCore.SIGNAL('plotMousePressed(const QMouseEvent&)'), self.graph.onMousePressed)
        QtCore.QObject.disconnect(self.graph, QtCore.SIGNAL('plotMouseReleased(const QMouseEvent&)'), self.graph.onMouseReleased)

        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        #self.graph.setAutoLegend(False)
        """self.lblPosition.setAlignment(qt.Qt.AlignRight)
        self.lblTitle.setAlignment(qt.Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        buttonBox.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        
        qt.QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        qt.QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)
        self.setPaletteBackgroundColor(qt.Qt.white)"""
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self.lblTitle)
        _main_vlayout.addWidget(self.lblPosition)
        _main_vlayout.addWidget(self.graph)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

    def setRealTimePlot(self, isRealTime):
        self.isRealTimePlot = isRealTime 

    def start_new_scan(self, scanParameters):
        self.graph.clearcurves()
        self.isScanning = True
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' % scanParameters['title'])
        self.xdata = []
        self.graph.xlabel(scanParameters['xlabel'])
        self.ylabel = scanParameters['ylabel']
        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels,ydata in zip(ylabels,self.ydatas):
            self.graph.newcurve(labels,self.xdata,ydata)
        self.graph.ylabel(self.ylabel)
        self.graph.setx1timescale(False)
        self.graph.replot()
        self.graph.setTitle("Energy scan started. Waiting values...")
        
    def add_new_plot_value(self, x, y):
        self.xdata.append(x)
        for label,ydata,yvalue in zip(self.ylabel.split(),self.ydatas,str(y).split()) :
            ydata.append(float(yvalue))
            self.graph.newcurve(label,self.xdata,ydata)
            self.graph.setTitle("Energy scan in progress. Please wait...")
        self.graph.replot()
        
    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt' and self.isScanning:
            self.lblPosition.setText("(X: %0.2f, Y: %0.2f)" % (signalDict['x'], signalDict['y']))

    def plot_results(self, pk, fppPeak, fpPeak, ip, fppInfl, fpInfl,
                        rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title):
	self.graph.clearcurves()	
        self.graph.setTitle(title)
        self.graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.graph.replot()
	self.isScanning = False

    def plot_scan_curve(self, scan_data):
        self.graph.clearcurves()
        self.graph.setTitle("Energy scan finished")
        self.lblTitle.setText("")
        xdata = [scan_data[el][0] for el in range(len(scan_data))]
        ydata = [scan_data[el][1] for el in range(len(scan_data))]
        self.graph.newcurve("energy", xdata, ydata)
        self.graph.replot()

    def clear(self):
        self.graph.clearcurves()
        #self.graph.setTitle("")
        self.lblTitle.setText("")
        self.lblPosition.setText("")

    def scan_finished(self):
        self.graph.setTitle("Energy scan finished") 
Beispiel #11
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()
class PymcaPlotWidget(QWidget):
    """
    Descript. :
    """

    def __init__(self, parent, realtime_plot = False):
        """
        Descript. :
        """
        QWidget.__init__(self, parent)

        self.axis_x_array = []
        self.axis_y_array = []

        self.realtime_plot = realtime_plot
   
        self.pymca_graph = Graph(self)
        self.pymca_graph.showGrid()
        self.info_label = QLabel("", self)  
        self.info_label.setAlignment(Qt.AlignRight)

        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self.pymca_graph)  
        _main_vlayout.addWidget(self.info_label)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)

        if qt_variant == 'PyQt5':
             pass
        else:
             QObject.connect(self.pymca_graph,
                             SIGNAL("QtBlissGraphSignal"),
                             self.handle_graph_signal)

        Qt4_widget_colors.set_widget_color(self, Qt4_widget_colors.WHITE)         

    def clear(self):
        """
        Descript. :
        """
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle("")
        self.info_label.setText("")

    def plot_energy_scan_curve(self, scan_result, scan_title):
        """Results are converted to two list describing
           x and y axes
        """
        x_data = [item[0] for item in scan_result]
        y_data = [item[1] for item in scan_result] 
        self.pymca_graph.newcurve("Energy", x_data, y_data)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_title)
        self.pymca_graph.setx1axislimits(min(x_data), max(x_data))

    def start_new_scan(self, scan_info):
        """
        Descript. :
        """
        self.axis_x_array = []
        self.axis_y_array = []
        self.pymca_graph.clearcurves()
        self.pymca_graph.xlabel(scan_info['xlabel'])
        self.ylabel = scan_info['ylabel']
        self.pymca_graph.ylabel(self.ylabel)
        self.pymca_graph.setx1timescale(False)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_info['title'])

    def plot_energy_scan_results(self, pk, fppPeak, fpPeak, ip, fppInfl, 
            fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title):
        """
        """
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle(title)
        self.pymca_graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.pymca_graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.pymca_graph.replot()
        self.pymca_graph.setx1axislimits(min(chooch_graph_x),
                                         max(chooch_graph_x))
 
    def plot_finished(self):
        """
        Descript. :
        """
        if self.axis_x_array:
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            self.pymca_graph.replot()

    def add_new_plot_value(self, x, y):
        """
        Descript. :
        """
        if self.realtime_plot:
            self.axis_x_array.append(x / 1000.0)
            self.axis_y_array.append(y / 1000.0)
            self.pymca_graph.newcurve("Energy", self.axis_x_array, self.axis_y_array)
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            #self.pymca_graph.replot()
            

    def handle_graph_signal(self, signal_info):
        """
        """
        if signal_info['event'] == 'MouseAt':
            self.info_label.setText("(X: %0.4f, Y: %0.4f)" % \
                 (signal_info['x'], signal_info['y']))
class PymcaPlotWidget(QWidget):
    """
    Descript. :
    """

    def __init__(self, parent, realtime_plot = False):
        """
        Descript. :
        """
        QWidget.__init__(self, parent)

        self.axis_x_array = []
        self.axis_y_array = []

        self.realtime_plot = realtime_plot
   
        self.pymca_graph = Graph(self)
        self.pymca_graph.showGrid()
        self.info_label = QLabel("", self)  
        self.info_label.setAlignment(Qt.AlignRight)

        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self.pymca_graph)  
        _main_vlayout.addWidget(self.info_label)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)

        if qt_variant == 'PyQt5':
             pass
        else:
             QObject.connect(self.pymca_graph,
                             SIGNAL("QtBlissGraphSignal"),
                             self.handle_graph_signal)

        Qt4_widget_colors.set_widget_color(self, Qt4_widget_colors.WHITE)         

    def clear(self):
        """
        Descript. :
        """
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle("")
        self.info_label.setText("")

    def plot_energy_scan_curve(self, scan_result, scan_title):
        """Results are converted to two list describing
           x and y axes
        """
        x_data = [item[0] for item in scan_result]
        y_data = [item[1] for item in scan_result] 
        self.pymca_graph.newcurve("Energy", x_data, y_data)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_title)
        self.pymca_graph.setx1axislimits(min(x_data), max(x_data))

    def start_new_scan(self, scan_info):
        """
        Descript. :
        """
        self.axis_x_array = []
        self.axis_y_array = []
        self.pymca_graph.clearcurves()
        self.pymca_graph.xlabel(scan_info['xlabel'])
        self.ylabel = scan_info['ylabel']
        self.pymca_graph.ylabel(self.ylabel)
        self.pymca_graph.setx1timescale(False)
        self.pymca_graph.replot()
        self.pymca_graph.setTitle(scan_info['title'])

    def plot_energy_scan_results(self, pk, fppPeak, fpPeak, ip, fppInfl, 
            fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title):
        """
        """
        self.pymca_graph.clearcurves()
        self.pymca_graph.setTitle(title)
        self.pymca_graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.pymca_graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.pymca_graph.replot()
        self.pymca_graph.setx1axislimits(min(chooch_graph_x),
                                         max(chooch_graph_x))
 
    def plot_finished(self):
        """
        Descript. :
        """
        if self.axis_x_array:
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            self.pymca_graph.replot()

    def add_new_plot_value(self, x, y):
        """
        Descript. :
        """
        if self.realtime_plot:
            self.axis_x_array.append(x / 1000.0)
            self.axis_y_array.append(y / 1000.0)
            self.pymca_graph.newcurve("Energy", self.axis_x_array, self.axis_y_array)
            self.pymca_graph.setx1axislimits(min(self.axis_x_array),
                                             max(self.axis_x_array))
            #self.pymca_graph.replot()
            

    def handle_graph_signal(self, signal_info):
        """
        """
        if signal_info['event'] == 'MouseAt':
            self.info_label.setText("(X: %0.2f, Y: %0.2f)" % \
                 (signal_info['x'], signal_info['y']))
Beispiel #14
0
class ScanPlotWidget(QtGui.QWidget):
    def __init__(self, parent=None, name="scan_plot_widget"):
        QtGui.QWidget.__init__(self, parent)

        if name is not None:
            self.setObjectName(name)

        self.xdata = []
        self.ylabel = ""

        self.isRealTimePlot = None
        self.isConnected = None
        self.isScanning = None

        self.lblTitle = QtGui.QLabel(self)
        #self.graphPanel = qt.QFrame(self)
        #buttonBox = qt.QHBox(self)
        self.lblPosition = QtGui.QLabel(self)
        self.graph = QtBlissGraph(self)

        QtCore.QObject.connect(self.graph, QtCore.SIGNAL('QtBlissGraphSignal'),
                               self.handleBlissGraphSignal)
        QtCore.QObject.disconnect(
            self.graph, QtCore.SIGNAL('plotMousePressed(const QMouseEvent&)'),
            self.graph.onMousePressed)
        QtCore.QObject.disconnect(
            self.graph, QtCore.SIGNAL('plotMouseReleased(const QMouseEvent&)'),
            self.graph.onMouseReleased)

        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        #self.graph.setAutoLegend(False)
        """self.lblPosition.setAlignment(qt.Qt.AlignRight)
        self.lblTitle.setAlignment(qt.Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        buttonBox.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Fixed)
        
        qt.QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        qt.QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)
        self.setPaletteBackgroundColor(qt.Qt.white)"""
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self.lblTitle)
        _main_vlayout.addWidget(self.lblPosition)
        _main_vlayout.addWidget(self.graph)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

    def setRealTimePlot(self, isRealTime):
        self.isRealTimePlot = isRealTime

    def start_new_scan(self, scanParameters):
        self.graph.clearcurves()
        self.isScanning = True
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' %
                              scanParameters['title'])
        self.xdata = []
        self.graph.xlabel(scanParameters['xlabel'])
        self.ylabel = scanParameters['ylabel']
        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels, ydata in zip(ylabels, self.ydatas):
            self.graph.newcurve(labels, self.xdata, ydata)
        self.graph.ylabel(self.ylabel)
        self.graph.setx1timescale(False)
        self.graph.replot()
        self.graph.setTitle("Energy scan started. Waiting values...")

    def add_new_plot_value(self, x, y):
        self.xdata.append(x)
        for label, ydata, yvalue in zip(self.ylabel.split(), self.ydatas,
                                        str(y).split()):
            ydata.append(float(yvalue))
            self.graph.newcurve(label, self.xdata, ydata)
            self.graph.setTitle("Energy scan in progress. Please wait...")
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt' and self.isScanning:
            self.lblPosition.setText("(X: %0.2f, Y: %0.2f)" %
                                     (signalDict['x'], signalDict['y']))

    def plot_results(self, pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm,
                     chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title):
        self.graph.clearcurves()
        self.graph.setTitle(title)
        self.graph.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.graph.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.graph.replot()
        self.isScanning = False

    def plot_scan_curve(self, scan_data):
        self.graph.clearcurves()
        self.graph.setTitle("Energy scan finished")
        self.lblTitle.setText("")
        xdata = [scan_data[el][0] for el in range(len(scan_data))]
        ydata = [scan_data[el][1] for el in range(len(scan_data))]
        self.graph.newcurve("energy", xdata, ydata)
        self.graph.replot()

    def clear(self):
        self.graph.clearcurves()
        #self.graph.setTitle("")
        self.lblTitle.setText("")
        self.lblPosition.setText("")

    def scan_finished(self):
        self.graph.setTitle("Energy scan finished")
Beispiel #15
0
class ColormapDialog(qt.QDialog):
    def __init__(self, parent=None, name="Colormap Dialog", slider=False):
        if QTVERSION < '4.0.0':
            qt.QDialog.__init__(self, parent, name)
            self.setCaption(name)
        else:
            qt.QDialog.__init__(self, parent)
            self.setWindowTitle(name)
        self.title = name

        self.colormapList = [
            "Greyscale", "Reverse Grey", "Temperature", "Red", "Green", "Blue",
            "Many"
        ]

        # default values
        self.dataMin = -10
        self.dataMax = 10
        self.minValue = 0
        self.maxValue = 1

        self.colormapIndex = 2
        self.colormapType = 0

        self.autoscale = False
        self.autoscale90 = False
        # main layout
        if QTVERSION < '4.0.0':
            vlayout = qt.QVBoxLayout(self, 0, -1, "Main ColormapDialog Layout")
        else:
            vlayout = qt.QVBoxLayout(self)
        vlayout.setMargin(10)
        vlayout.setSpacing(0)

        # layout 1 : -combo to choose colormap
        #            -autoscale button
        #            -autoscale 90% button
        hbox1 = qt.QWidget(self)
        hlayout1 = qt.QHBoxLayout(hbox1)
        vlayout.addWidget(hbox1)
        hlayout1.setMargin(0)
        hlayout1.setSpacing(10)

        # combo
        self.combo = qt.QComboBox(hbox1)
        for colormap in self.colormapList:
            if QTVERSION < '4.0.0':
                self.combo.insertItem(colormap)
            else:
                self.combo.addItem(colormap)
        self.connect(self.combo, qt.SIGNAL("activated(int)"),
                     self.colormapChange)
        hlayout1.addWidget(self.combo)

        # autoscale
        self.autoScaleButton = qt.QPushButton("Autoscale", hbox1)
        if QTVERSION < '4.0.0':
            self.autoScaleButton.setToggleButton(True)
        else:
            self.autoScaleButton.setCheckable(True)
        self.autoScaleButton.setAutoDefault(False)
        self.connect(self.autoScaleButton, qt.SIGNAL("toggled(bool)"),
                     self.autoscaleChange)
        hlayout1.addWidget(self.autoScaleButton)

        # autoscale 90%
        self.autoScale90Button = qt.QPushButton("Autoscale 90%", hbox1)
        if QTVERSION < '4.0.0':
            self.autoScale90Button.setToggleButton(True)
        else:
            self.autoScale90Button.setCheckable(True)
        self.autoScale90Button.setAutoDefault(False)

        self.connect(self.autoScale90Button, qt.SIGNAL("toggled(bool)"),
                     self.autoscale90Change)
        hlayout1.addWidget(self.autoScale90Button)

        # hlayout
        if QTVERSION > '4.0.0':
            hbox0 = qt.QWidget(self)
            self.__hbox0 = hbox0
            hlayout0 = qt.QHBoxLayout(hbox0)
            hlayout0.setMargin(0)
            hlayout0.setSpacing(0)
            vlayout.addWidget(hbox0)
            #hlayout0.addStretch(10)

            self.buttonGroup = qt.QButtonGroup()
            g1 = qt.QCheckBox(hbox0)
            g1.setText("Linear")
            g2 = qt.QCheckBox(hbox0)
            g2.setText("Logarithmic")
            g3 = qt.QCheckBox(hbox0)
            g3.setText("Gamma")
            self.buttonGroup.addButton(g1, 0)
            self.buttonGroup.addButton(g2, 1)
            self.buttonGroup.addButton(g3, 2)
            self.buttonGroup.setExclusive(True)
            if self.colormapType == 1:
                self.buttonGroup.button(1).setChecked(True)
            elif self.colormapType == 2:
                self.buttonGroup.button(2).setChecked(True)
            else:
                self.buttonGroup.button(0).setChecked(True)
            hlayout0.addWidget(g1)
            hlayout0.addWidget(g2)
            hlayout0.addWidget(g3)
            vlayout.addWidget(hbox0)
            self.connect(self.buttonGroup, qt.SIGNAL("buttonClicked(int)"),
                         self.buttonGroupChange)

        vlayout.addSpacing(20)

        hboxlimits = qt.QWidget(self)
        hboxlimitslayout = qt.QHBoxLayout(hboxlimits)
        hboxlimitslayout.setMargin(0)
        hboxlimitslayout.setSpacing(0)

        if slider:
            self.slider = DoubleSlider.DoubleSlider(hboxlimits, scale=False)
            hboxlimitslayout.addWidget(self.slider)
        else:
            self.slider = None

        vlayout.addWidget(hboxlimits)

        vboxlimits = qt.QWidget(hboxlimits)
        vboxlimitslayout = qt.QVBoxLayout(vboxlimits)
        vboxlimitslayout.setMargin(0)
        vboxlimitslayout.setSpacing(0)
        hboxlimitslayout.addWidget(vboxlimits)

        # hlayout 2 : - min label
        #             - min texte
        hbox2 = qt.QWidget(vboxlimits)
        self.__hbox2 = hbox2
        hlayout2 = qt.QHBoxLayout(hbox2)
        hlayout2.setMargin(0)
        hlayout2.setSpacing(0)
        #vlayout.addWidget(hbox2)
        vboxlimitslayout.addWidget(hbox2)
        hlayout2.addStretch(10)

        self.minLabel = qt.QLabel(hbox2)
        self.minLabel.setText("Minimum")
        hlayout2.addWidget(self.minLabel)

        hlayout2.addSpacing(5)
        hlayout2.addStretch(1)
        self.minText = MyQLineEdit(hbox2)
        self.minText.setFixedWidth(150)
        self.minText.setAlignment(qt.Qt.AlignRight)
        self.connect(self.minText, qt.SIGNAL("returnPressed()"),
                     self.minTextChanged)
        hlayout2.addWidget(self.minText)

        # hlayout 3 : - min label
        #             - min text
        hbox3 = qt.QWidget(vboxlimits)
        self.__hbox3 = hbox3
        hlayout3 = qt.QHBoxLayout(hbox3)
        hlayout3.setMargin(0)
        hlayout3.setSpacing(0)
        #vlayout.addWidget(hbox3)
        vboxlimitslayout.addWidget(hbox3)

        hlayout3.addStretch(10)
        self.maxLabel = qt.QLabel(hbox3)
        self.maxLabel.setText("Maximum")
        hlayout3.addWidget(self.maxLabel)

        hlayout3.addSpacing(5)
        hlayout3.addStretch(1)

        self.maxText = MyQLineEdit(hbox3)
        self.maxText.setFixedWidth(150)
        self.maxText.setAlignment(qt.Qt.AlignRight)

        self.connect(self.maxText, qt.SIGNAL("returnPressed()"),
                     self.maxTextChanged)
        hlayout3.addWidget(self.maxText)

        # Graph widget for color curve...
        self.c = QtBlissGraph(self)
        self.c.xlabel("Data Values")
        self.c.enableZoom(False)
        self.c.setCanvasBackground(qt.Qt.white)
        self.c.canvas().setMouseTracking(1)

        self.c.enableAxis(Qwt5.QwtPlot.xBottom)

        self.marge = (abs(self.dataMax) + abs(self.dataMin)) / 6.0
        self.minmd = self.dataMin - self.marge
        self.maxpd = self.dataMax + self.marge

        self.c.setx1axislimits(self.minmd, self.maxpd)
        self.c.sety1axislimits(-11.5, 11.5)
        self.c.picker.setSelectionFlags(Qwt5.QwtPicker.NoSelection)

        x = [self.minmd, self.dataMin, self.dataMax, self.maxpd]
        y = [-10, -10, 10, 10]
        self.c.newCurve("ConstrainedCurve", x, y)
        self.markers = []
        self.__x = x
        self.__y = y
        for i in range(4):
            index = self.c.insertx1marker(x[i], y[i], noline=True)
            marker = self.c.markersdict[index]['marker']
            if i in [1, 2]:
                self.c.setmarkerfollowmouse(index, 1)
            marker.setLinePen(qt.QPen(qt.Qt.green, 2, qt.Qt.DashDotLine))
            marker.setSymbol(
                Qwt5.QwtSymbol(Qwt5.QwtSymbol.Diamond, qt.QBrush(qt.Qt.blue),
                               qt.QPen(qt.Qt.red), qt.QSize(15, 15)))
            self.markers.append(index)

        #self.c.enablemarkermode()
        self.c.setMinimumSize(qt.QSize(250, 200))
        vlayout.addWidget(self.c)

        if QTVERSION < '4.0.0':
            self.connect(self.c, qt.PYSIGNAL("QtBlissGraphSignal"), self.chval)
            self.connect(self.c, qt.PYSIGNAL("QtBlissGraphSignal"), self.chmap)
            if slider:
                self.connect(self.slider,
                             qt.PYSIGNAL("doubleSliderValueChanged"),
                             self._sliderChanged)
        else:
            self.connect(self.c, qt.SIGNAL("QtBlissGraphSignal"), self.chval)
            self.connect(self.c, qt.SIGNAL("QtBlissGraphSignal"), self.chmap)

            if slider:
                self.connect(self.slider,
                             qt.SIGNAL("doubleSliderValueChanged"),
                             self._sliderChanged)

        # colormap window can not be resized
        self.setFixedSize(vlayout.minimumSize())

    def _sliderChanged(self, ddict):
        if not self.__sliderConnected: return
        delta = (self.dataMax - self.dataMin) * 0.01
        xmin = self.dataMin + delta * ddict['min']
        xmax = self.dataMin + delta * ddict['max']
        self.setDisplayedMinValue(xmin)
        self.setDisplayedMaxValue(xmax)
        self.__x[1] = xmin
        self.__x[2] = xmax
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)
        for i in range(4):
            self.c.setMarkerXPos(self.c.markersdict[self.markers[i]]['marker'],
                                 self.__x[i])
            self.c.setMarkerYPos(self.c.markersdict[self.markers[i]]['marker'],
                                 self.__y[i])

        self.c.replot()
        if DEBUG:
            print("Slider asking to update colormap")
        #self._update()
        self.sendColormap()

    def _update(self):
        if DEBUG:
            print("colormap _update called")
        self.marge = (abs(self.dataMax) + abs(self.dataMin)) / 6.0
        self.minmd = self.dataMin - self.marge
        self.maxpd = self.dataMax + self.marge
        self.c.setx1axislimits(self.minmd, self.maxpd)
        self.c.sety1axislimits(-11.5, 11.5)

        self.__x = [self.minmd, self.dataMin, self.dataMax, self.maxpd]
        self.__y = [-10, -10, 10, 10]
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)
        for i in range(4):
            self.c.setMarkerXPos(self.c.markersdict[self.markers[i]]['marker'],
                                 self.__x[i])
            self.c.setMarkerYPos(self.c.markersdict[self.markers[i]]['marker'],
                                 self.__y[i])
        self.c.replot()
        self.sendColormap()

    def buttonGroupChange(self, val):
        if DEBUG:
            print("buttonGroup asking to update colormap")
        self.setColormapType(val, update=True)
        self._update()

    def setColormapType(self, val, update=False):
        self.colormapType = val
        if QTVERSION > '4.0.0':
            if self.colormapType == 1:
                self.buttonGroup.button(1).setChecked(True)
            elif self.colormapType == 2:
                self.buttonGroup.button(2).setChecked(True)
            else:
                self.colormapType = 0
                self.buttonGroup.button(0).setChecked(True)
        if update:
            self._update()

    def chval(self, ddict):
        if ddict['event'] == 'markerMoving':
            if ddict['marker'] in self.markers:
                markerIndex = self.markers.index(ddict['marker'])
            else:
                print("Unknown marker")
                return
        else:
            return
        diam = markerIndex + 1
        x = ddict['x']
        if diam == 2:
            self.setDisplayedMinValue(x)
        if diam == 3:
            self.setDisplayedMaxValue(x)

    def chmap(self, ddict):
        if ddict['event'] == 'markerMoved':
            if ddict['marker'] in self.markers:
                markerIndex = self.markers.index(ddict['marker'])
            else:
                print("Unknown marker")
                return
        else:
            return
        diam = markerIndex + 1

        x = ddict['x']
        if diam == 2:
            self.setMinValue(x)
        if diam == 3:
            self.setMaxValue(x)

    """
    Colormap
    """

    def setColormap(self, colormap):
        self.colormapIndex = colormap
        if QTVERSION < '4.0.0':
            self.combo.setCurrentItem(colormap)
        else:
            self.combo.setCurrentIndex(colormap)

    def colormapChange(self, colormap):
        self.colormapIndex = colormap
        self.sendColormap()

    # AUTOSCALE
    """
    Autoscale
    """

    def autoscaleChange(self, val):
        self.autoscale = val
        self.setAutoscale(val)
        self.sendColormap()

    def setAutoscale(self, val):
        if DEBUG:
            print("setAutoscale called", val)
        if val:
            if QTVERSION < '4.0.0':
                self.autoScaleButton.setOn(True)
                self.autoScale90Button.setOn(False)
            else:
                self.autoScaleButton.setChecked(True)
                self.autoScale90Button.setChecked(False)
                #self.autoScale90Button.setDown(False)
            self.setMinValue(self.dataMin)
            self.setMaxValue(self.dataMax)
            if self.slider is not None:
                self.__sliderConnected = False
                self.slider.setMinMax(0, 100)
                self.slider.setEnabled(False)
                self.__sliderConnected = True

            self.maxText.setEnabled(0)
            self.minText.setEnabled(0)
            self.c.setEnabled(0)
            self.c.disablemarkermode()
        else:
            if QTVERSION < '4.0.0':
                self.autoScaleButton.setOn(False)
                self.autoScale90Button.setOn(False)
            else:
                self.autoScaleButton.setChecked(False)
                self.autoScale90Button.setChecked(False)
            self.minText.setEnabled(1)
            self.maxText.setEnabled(1)
            if self.slider: self.slider.setEnabled(True)
            self.c.setEnabled(1)
            self.c.enablemarkermode()

    """
    set rangeValues to dataMin ; dataMax-10%
    """

    def autoscale90Change(self, val):
        self.autoscale90 = val
        self.setAutoscale90(val)
        self.sendColormap()

    def setAutoscale90(self, val):
        if val:
            if QTVERSION < '4.0.0':
                self.autoScaleButton.setOn(False)
            else:
                self.autoScaleButton.setChecked(False)
            self.setMinValue(self.dataMin)
            self.setMaxValue(self.dataMax - abs(self.dataMax / 10))
            if self.slider is not None:
                self.__sliderConnected = False
                self.slider.setMinMax(0, 90)
                self.slider.setEnabled(0)
                self.__sliderConnected = True

            self.minText.setEnabled(0)
            self.maxText.setEnabled(0)
            self.c.setEnabled(0)
            self.c.disablemarkermode()
        else:
            if QTVERSION < '4.0.0':
                self.autoScale90Button.setOn(False)
            else:
                self.autoScale90Button.setChecked(False)
            self.minText.setEnabled(1)
            self.maxText.setEnabled(1)
            if self.slider: self.slider.setEnabled(True)
            self.c.setEnabled(1)
            self.c.enablemarkermode()
            self.c.setFocus()

    # MINIMUM
    """
    change min value and update colormap
    """

    def setMinValue(self, val):
        v = float(str(val))
        self.minValue = v
        self.minText.setText("%g" % v)
        self.__x[1] = v
        self.c.setMarkerXPos(self.c.markersdict[self.markers[1]]['marker'], v)
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)
        self.sendColormap()

    """
    min value changed by text
    """

    def minTextChanged(self):
        text = str(self.minText.text())
        if not len(text): return
        val = float(text)
        self.setMinValue(val)
        if self.minText.hasFocus():
            self.c.setFocus()

    """
    change only the displayed min value
    """

    def setDisplayedMinValue(self, val):
        val = float(val)
        self.minValue = val
        self.minText.setText("%g" % val)
        self.__x[1] = val
        self.c.setMarkerXPos(self.c.markersdict[self.markers[1]]['marker'],
                             val)
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)

    # MAXIMUM
    """
    change max value and update colormap
    """

    def setMaxValue(self, val):
        v = float(str(val))
        self.maxValue = v
        self.maxText.setText("%g" % v)
        self.__x[2] = v
        self.c.setMarkerXPos(self.c.markersdict[self.markers[2]]['marker'], v)
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)
        self.sendColormap()

    """
    max value changed by text
    """

    def maxTextChanged(self):
        text = str(self.maxText.text())
        if not len(text): return
        val = float(text)
        self.setMaxValue(val)
        if self.maxText.hasFocus():
            self.c.setFocus()

    """
    change only the displayed max value
    """

    def setDisplayedMaxValue(self, val):
        val = float(val)
        self.maxValue = val
        self.maxText.setText("%g" % val)
        self.__x[2] = val
        self.c.newCurve("ConstrainedCurve", self.__x, self.__y)

    # DATA values
    """
    set min/max value of data source
    """

    def setDataMinMax(self, minVal, maxVal, update=True):
        if minVal is not None:
            vmin = float(str(minVal))
            self.dataMin = vmin
        if maxVal is not None:
            vmax = float(str(maxVal))
            self.dataMax = vmax

        if update:
            # are current values in the good range ?
            self._update()

    """
    send 'ColormapChanged' signal
    """

    def sendColormap(self):
        if DEBUG:
            print("sending colormap")
        #prevent unexpected behaviour because of bad limits
        if self.minValue > self.maxValue:
            vmax = self.minValue
            vmin = self.maxValue
        else:
            vmax = self.maxValue
            vmin = self.minValue
        try:
            if QTVERSION < '4.0.0':
                self.emit(qt.PYSIGNAL("ColormapChanged"),
                          (self.colormapIndex, self.autoscale, vmin, vmax,
                           self.dataMin, self.dataMax, self.colormapType))
            else:
                self.emit(qt.SIGNAL("ColormapChanged"), self.colormapIndex,
                          self.autoscale, vmin, vmax, self.dataMin,
                          self.dataMax, self.colormapType)

        except:
            sys.excepthook(sys.exc_info()[0],
                           sys.exc_info()[1],
                           sys.exc_info()[2])
class BlissScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSignal('newScan', ())

        self.scanObject = None
        self.xdata = []
        self.ylable = ""
        self.mylog = 0
        self.canAddPoint = True
        self.dm = DataManager()
        event.connect(self.dm, "scan_new", self.newScan)
        event.connect(self.dm, "scan_data", self.newScanPoint)

        self.addProperty('backgroundColor', 'combo', ('white', 'default'), 'white')
        self.addProperty('graphColor', 'combo', ('white', 'default'), 'white')
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)
                         
        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'), self.handleBlissGraphSignal)
        QObject.disconnect(self.graph, SIGNAL('plotMousePressed(const QMouseEvent&)'), self.graph.onMousePressed)
        QObject.disconnect(self.graph, SIGNAL('plotMouseReleased(const QMouseEvent&)'), self.graph.onMouseReleased)
 
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)


    def propertyChanged(self, property, oldValue, newValue):
        if property == 'backgroundColor':
            if newValue == 'white':
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))
        
        elif property == 'graphColor':
            if newValue == 'white':
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.graph.canvas().setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))
        else:
            BlissWidget.propertyChanged(self,property,oldValue,newValue)
               
    #def newScan(self, dm, scan_id, filename, motors, npoints, counters, save_flag=True):
    def newScan(self, scan_id, filename, motors, npoints, counters, save_flag=True):
        self.emit(PYSIGNAL('newScan'), ())
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' % filename)
        self.xdata = []

        self.graph.clearcurves()
        #self.graph.xlabel(scanParameters['xlabel'])
        self.graph.xlabel("Energy")
        self.ylabel = "Counts"

        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels,ydata in zip(ylabels,self.ydatas):
            self.graph.newcurve(labels,self.xdata,ydata)
            
        self.graph.ylabel(self.ylabel)
        if motors == 'Time':
            self.graph.setx1timescale(True)
        else:
            self.graph.setx1timescale(False)

        self.graph.replot()
        
    def newScanPoint(self, scan_id, values):
        x = values[0]
        self.xdata.append(x)
        for label,ydata,yvalue in zip(self.ylabel.split(),self.ydatas,values[1:]):
            ydata.append(float(yvalue))
            self.graph.newcurve(label,self.xdata,ydata)
        self.graph.replot()
        
    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt':
            self.lblPosition.setText("(X: %f, Y: %f)" % (signalDict['x'], signalDict['y']))
class EnergyScanBrickPX2(BlissWidget):
    STATES = {
        'error': QWidget.red,
        'ok': QWidget.green,
        'progress': QWidget.yellow
    }

    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.energyScan = None
        self.scanObject = None
        self.element = None

        self.sessionId = None
        self.blSampleId = None
        self.scanParameters = {}
        self.archive_directory = None

        self.addProperty('mnemonic', 'string', '')
        self.addProperty('icons', 'string', '')
        self.addProperty('formatString', 'formatString', '##.####')
        self.addProperty('decimalPlaces', 'string', '4')

        self.defineSlot('setDirectory', ())
        self.defineSlot('setPrefix', ())
        self.defineSlot('setElement', ())
        self.defineSlot('setSample', ())
        self.defineSlot('setSession', ())

        self.defineSignal('energyScanning', ())
        self.defineSignal('energyScanConnected', ())
        self.defineSignal('energyScanCanMove', ())
        self.defineSignal('edgeScanEnergies', ())
        self.defineSignal('addNewPoint', ())
        self.defineSignal('newScan', ())
        self.defineSignal('setDirectory', ())
        self.defineSignal('setValues', ())

        self.parametersBox = QHGroupBox("Parameters", self)
        # self.parametersBox.hide()
        self.parametersBox.setInsideMargin(4)
        self.parametersBox.setInsideSpacing(2)
        self.parametersBox.setCheckable(True)
#        self.parametersBox.setChecked(False)
        self.parametersBox.setChecked(True)

        QLabel("Prefix:", self.parametersBox)
        self.prefixInput = QLineEdit(self.parametersBox)
        self.prefixInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        QObject.connect(
            self.prefixInput,
            SIGNAL('textChanged(const QString &)'),
            self.prefixChanged)
        QLabel("Directory:", self.parametersBox)
        self.directoryInput = QLineEdit(self.parametersBox)
        self.directoryInput.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        QObject.connect(
            self.directoryInput,
            SIGNAL('textChanged(const QString &)'),
            self.directoryChanged)

        self.browseButton = QToolButton(self.parametersBox)
        self.browseButton.setTextLabel("Browse")
        self.browseButton.setUsesTextLabel(True)
        self.browseButton.setTextPosition(QToolButton.BesideIcon)
        QObject.connect(
            self.browseButton,
            SIGNAL("clicked()"),
            self.browseButtonClicked)

        self.scanBox = QHGroupBox("Energy scan", self)
        self.scanBox.setInsideMargin(4)
        self.scanBox.setInsideSpacing(2)
        # self.scanBox.hide()
        self.startScanButton = MenuButton(self.scanBox, "Start scan")
        # self.startScanButton.hide()
        self.connect(
            self.startScanButton,
            PYSIGNAL('executeCommand'),
            self.startEnergyScan)
        self.connect(
            self.startScanButton,
            PYSIGNAL('cancelCommand'),
            self.cancelEnergyScan)

        self.statusBox = QHGroupBox("(no element)", self.scanBox)
        # self.statusBox.hide()
        # self.statusBox.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.MinimumExpanding)
        self.statusBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.statusBox.setAlignment(QGroupBox.AlignCenter)
        self.scanStatus = QLabel(self.statusBox)
        self.scanStatus.setSizePolicy(
            QSizePolicy.Expanding,
            QSizePolicy.MinimumExpanding)
        self.scanStatus.setAlignment(QLabel.AlignCenter)

        box4 = QVBox(self.scanBox)
        peakLabel = QLabel("Peak:", box4)
        peakLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev1Label = QLabel("(keV)", box4)
        kev1Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        # kev2Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.peakInput = shortLineEdit(self.scanBox)
        self.peakInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.peakInput.setValidator(QDoubleValidator(self))

        box5 = QVBox(self.scanBox)
        inflectionLabel = QLabel("Inflection:", box5)
        inflectionLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev2Label = QLabel("(keV)", box5)
        kev2Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        # kev1Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.inflectionInput = shortLineEdit(self.scanBox)
        self.inflectionInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.inflectionInput.setValidator(QDoubleValidator(self))

        box6 = QVBox(self.scanBox)
        remoteLabel = QLabel("Remote:", box6)
        remoteLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev3Label = QLabel("(keV)", box6)
        kev3Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        # kev3Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.remoteInput = shortLineEdit(self.scanBox)
        self.remoteInput.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.remoteInput.setValidator(QDoubleValidator(self))

        box7 = QVBox(self.scanBox)
        remoteLabel = QLabel("2nd Remote:", box7)
        remoteLabel.setAlignment(QLabel.AlignHCenter | QLabel.AlignBottom)
        kev4Label = QLabel("(keV)", box7)
        kev4Label.setAlignment(QLabel.AlignHCenter | QLabel.AlignTop)
        # kev4Label.setSizePolicy(QSizePolicy.Minimum,QSizePolicy.Fixed)
        self.remote2Input = shortLineEdit(self.scanBox)
        self.remote2Input.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.remote2Input.setValidator(QDoubleValidator(self))

        self.acceptBox = QVBox(self.scanBox)
        self.acceptBox.setSpacing(2)
        self.acceptButton = MenuButton2(self.acceptBox, "Accept")
        self.resetButton = MenuButton2(self.acceptBox, "Reset")
        # self.acceptBox.hide()
        QObject.connect(self.resetButton, SIGNAL('clicked()'), self.resetEnergies)
        QObject.connect(self.acceptButton, SIGNAL('clicked()'), self.acceptEnergies)

        self.parametersBox.setSizePolicy(
            QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        self.scanBox.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)

        self.instanceSynchronize(
            "parametersBox",
            "prefixInput",
            "directoryInput",
            "peakInput",
            "inflectionInput",
            "remoteInput",
            "remote2Input")

        self.choochGraphs = QtBlissGraph(self)
        self.choochGraphs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self)
        self.layout().addWidget(self.parametersBox)
        self.layout().addWidget(self.scanBox)
        self.layout().addWidget(self.choochGraphs)

        self.setEnabled(True)

    def setIcons(self, icons):
        icons_list = icons.split()
        try:
            self.startScanButton.setIcons(icons_list[0], icons_list[1])
        except IndexError:
            pass
        try:
            self.acceptButton.setPixmap(Icons.load(icons_list[2]))
        except IndexError:
            pass
        try:
            self.resetButton.setPixmap(Icons.load(icons_list[3]))
        except IndexError:
            pass
        try:
            self.browseButton.setPixmap(Icons.load(icons_list[4]))
        except IndexError:
            pass

    def prefixChanged(self, txt):
        txt = str(txt).replace(" ", "_")
        self.prefixInput.setText(txt)

    def directoryChanged(self, txt):
        txt = str(txt).replace(" ", "_")
        self.directoryInput.setText(txt)

    def browseButtonClicked(self):
        get_dir = QFileDialog(self)
        s = self.font().pointSize()
        f = get_dir.font()
        f.setPointSize(s)
        get_dir.setFont(f)
        get_dir.updateGeometry()
        d = get_dir.getExistingDirectory(self.directoryInput.text(), self, "",
                                         "Select a directory", True, False)
        if d is not None and len(d) > 0:
            self.setDirectory(d)

    def setSample(self, samples_list):
        #print "EnergyScanBrick.setSample",samples_list
        if len(samples_list) == 0:
            self.blSampleId = None
        else:
            if len(samples_list) > 1:
                logging.getLogger().warning(
                    "EnergyScanBrick: multiple samples selected (attaching scan only to first sample)!")
            for sample in samples_list:
                try:
                    blsample_id = int(sample[0])
                except BaseException:
                    pass
                else:
                    self.blSampleId = blsample_id
                    break

    def setSession(self, session_id, prop_code=None,
                   prop_number=None, prop_id=None, expiration_time=0):
        #print "EnergyScanBrick.setSession",session_id
        self.sessionId = session_id
        if prop_code is None or prop_number is None:
            pass
        else:
            self.archive_directory = str(prop_code) + str(prop_number)

    def setDirectory(self, scan_dir):
        self.directoryInput.setText(scan_dir)

    def setPrefix(self, scan_prefix):
        self.prefixInput.setText(scan_prefix)

    def setElement(self, symbol, edge):
        logging.getLogger().info("ENERGYSCANBRICK.setElement %s, %s" % (symbol, edge))
        if symbol is None:
            self.clearEnergies()
            self.setEnabled(False)
            self.element = None
        else:
            if self.energyScan is not None and self.energyScan.canScanEnergy():
                self.setEnabled(True)
            self.element = (symbol, edge)
            self.statusBox.setTitle("%s - %s" % (self.element[0], self.element[1]))

    def resetEnergies(self):
        confirm_dialog = QMessageBox("Confirm reset",
                                     "This will also clear your energies in the Collect tab. Press OK to reset the energies.",
                                     QMessageBox.Warning, QMessageBox.Ok, QMessageBox.Cancel,
                                     QMessageBox.NoButton, self)

        s = self.font().pointSize()
        f = confirm_dialog.font()
        f.setPointSize(s)
        confirm_dialog.setFont(f)
        confirm_dialog.updateGeometry()

        if confirm_dialog.exec_loop() == QMessageBox.Ok:
            self.inflectionInput.setText("")
            self.peakInput.setText("")
            self.remoteInput.setText("")
            self.remote2Input.setText("")
            self.emit(PYSIGNAL('edgeScanEnergies'), ({},))

    def acceptEnergies(self):
        if self.peakInput.hasAcceptableInput():
            pk = float(self.peakInput.text())
        else:
            pk = None
        if self.inflectionInput.hasAcceptableInput():
            ip = float(self.inflectionInput.text())
        else:
            ip = None
        if self.remoteInput.hasAcceptableInput():
            rm = float(self.remoteInput.text())
        else:
            rm = None
        if self.remote2Input.hasAcceptableInput():
            rm2 = float(self.remote2Input.text())
        else:
            rm2 = None
        energies = {"pk": pk, "ip": ip, "rm": rm, "rm2": rm2}
        self.emit(PYSIGNAL('edgeScanEnergies'), (energies,))

    def propertyChanged(self, propertyName, oldValue, newValue):
        if propertyName == 'mnemonic':
            if self.energyScan is not None:
                self.disconnect(self.energyScan, 'energyScanStarted', self.scanStarted)
                self.disconnect(
                    self.energyScan,
                    'energyScanFinished2',
                    self.scanFinished)
                self.disconnect(self.energyScan, 'energyScanFailed', self.scanFailed)
                self.disconnect(
                    self.energyScan,
                    'scanStatusChanged',
                    self.scanStatusChanged)
                self.disconnect(self.energyScan, 'energyScanReady', self.scanReady)
                self.disconnect(self.energyScan, 'connected', self.connected)
                self.disconnect(self.energyScan, 'disconnected', self.disconnected)
                self.disconnect(self.energyScan, 'addNewPoint', self.addNewPoint)
                self.disconnect(self.energyScan, 'newScan', self.newScan)
                self.disconnect(self.energyScan, 'setElement', self.setElement)
                self.disconnect(self.energyScan, 'setDirectory', self.setDirectory)

            self.clearEnergies()
            self.energyScan = self.getHardwareObject(newValue)
            if self.energyScan is not None:
                self.scanObject = None
                # try:
                #  specversion = self.energyScan.getCommandObject("doEnergyScan").specVersion
                # except:
                #  logging.getLogger().exception("%s: could not get spec version from Energy Scan Hardware Object", self.name())
                # else:
                #  self.scanObject = QSpecScan(specversion)

                self.connect(self.energyScan, 'energyScanStarted', self.scanStarted)
                self.connect(self.energyScan, 'energyScanFinished2', self.scanFinished)
                self.connect(self.energyScan, 'energyScanFailed', self.scanFailed)
                self.connect(
                    self.energyScan,
                    'scanStatusChanged',
                    self.scanStatusChanged)
                self.connect(self.energyScan, 'energyScanReady', self.scanReady)
                self.connect(self.energyScan, 'connected', self.connected)
                self.connect(self.energyScan, 'disconnected', self.disconnected)
                self.connect(self.energyScan, 'chooch_finished', self.chooch_finished)
                self.connect(self.energyScan, 'addNewPoint', self.addNewPoint)
                self.connect(self.energyScan, 'newScan', self.newScan)
                self.connect(self.energyScan, 'setElement', self.setElement)
                self.connect(self.energyScan, 'setDirectory', self.setDirectory)

                if self.energyScan.isConnected():
                    self.connected()
                else:
                    self.disconnected()
            else:
                self.disconnected()

        elif propertyName == 'icons':
            self.setIcons(newValue)
        else:
            BlissWidget.propertyChanged(self, propertyName, oldValue, newValue)

    def run(self):
        logging.getLogger().info("Anonmalous Scattering Factors determination based on Chooch 5.0.6 by Gwyndaf Evans\nCopyright (C) 1994--2007\[email protected]\nG. Evans & R. F. Pettifer (2001)\nJ. Appl. Cryst. 34, 82-86.")

        if self.energyScan is not None:
            if self.energyScan.isConnected():
                self.connected()
            else:
                self.disconnected()
        else:
            self.disconnected()

    def connected(self):
        can_scan = self.energyScan.canScanEnergy()
        if self.element is not None:
            self.setEnabled(can_scan)
        else:
            self.setEnabled(False)
        self.emit(PYSIGNAL('energyScanConnected'), (True, can_scan))
        self.emit(PYSIGNAL('energyScanCanMove'), (can_scan,))

    def disconnected(self):
        self.setEnabled(False)
        self.emit(PYSIGNAL('energyScanConnected'), (False,))
        self.emit(PYSIGNAL('energyScanCanMove'), (False,))

    def scanReady(self, state):
        self.startScanButton.setEnabled(state)
        self.statusBox.setEnabled(state)

    def scanStatusChanged(self, msg=None):
        if msg is None:
            msg = ""
            color = self.scanBox.paletteBackgroundColor()
        else:
            color = self.STATES['progress']
        self.scanStatus.setText(str(msg))
        self.scanStatus.setPaletteBackgroundColor(QColor(color))

    def startEnergyScan(self):
        self.scanParameters = {}
        go_on = True
        if self.sessionId is None or self.sessionId == "":
            res = QMessageBox.question(
                self,
                'Energy scan',
                "You are not properly logged, therefore your scan won't be stored in ISPyB.\nProceed with the energy scan?",
                "Proceed",
                "Cancel")
            if res != 0:
                go_on = False
        if not go_on:
            self.startScanButton.commandFailed()
            return

        if self.sessionId is not None and self.sessionId != "":
            self.scanParameters["sessionId"] = self.sessionId
            self.scanParameters["element"] = self.element[0]
            self.scanParameters["edgeEnergy"] = self.element[1]
            self.scanParameters["startTime"] = time.strftime("%Y-%m-%d %H:%M:%S")

        self.statusBox.setTitle("%s - %s" % (self.element[0], self.element[1]))
        self.inflectionInput.setText("")
        self.peakInput.setText("")
        self.remoteInput.setText("")
        self.remote2Input.setText("")

        scan_result = self.energyScan.startEnergyScan(self.element[0], self.element[1],
                                                      str(self.directoryInput.text()),
                                                      str(self.prefixInput.text()),
                                                      self.sessionId, self.blSampleId)
        if not scan_result:
            self.scanFailed()

    def cancelEnergyScan(self):
        self.energyScan.cancelEnergyScan()

    def scanStarted(self):
        self.choochGraphs.newcurve("spline", [], [])
        self.choochGraphs.newcurve("fp", [], [])
        self.choochGraphs.replot()

        self.startScanButton.commandStarted()
        self.emit(PYSIGNAL("energyScanning"), (True,))
        self.parametersBox.setEnabled(False)
        self.acceptBox.setEnabled(False)
        self.inflectionInput.setEnabled(False)
        self.peakInput.setEnabled(False)
        self.remoteInput.setEnabled(False)
        self.remote2Input.setEnabled(False)

    def scanFailed(self):
        color = self.STATES['error']
        self.scanStatus.setPaletteBackgroundColor(QColor(color))
        self.startScanButton.commandFailed()
        self.emit(PYSIGNAL("energyScanning"), (False,))
        self.parametersBox.setEnabled(True)
        self.acceptBox.setEnabled(True)
        self.inflectionInput.setEnabled(True)
        self.peakInput.setEnabled(True)
        self.remoteInput.setEnabled(True)
        self.remote2Input.setEnabled(True)

    def chooch_finished(self, pk, fppPeak, fpPeak, ip, fppInfl, fpInfl,
                        rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title):
        # display Chooch graphs
        self.choochGraphs.setTitle(title)
        self.choochGraphs.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.choochGraphs.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.choochGraphs.replot()

#    def scanFinished(self, *args):
    def scanFinished(self, scanData):
        print "EnergyScanBrick : scanCommandFinished scanData = ", scanData
        color = self.STATES['ok']
        self.scanStatusChanged("scan finished")

        scanDesc = scanData
        #print 'self.scanObject', self.scanObject
        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, \
            chooch_graph_x, chooch_graph_y1, chooch_graph_y2, \
            title = self.energyScan.choochResults
        #self.energyScan.doChooch(scanData['element'], scanData['edgeEnergy'], scanArchiveFilePrefix='/927bis/ccd/Database', scanFilePrefix='Archive2')
        #self.energyScan.doChooch(self.scanObject, scanDesc)

        # self.element[0],
        # self.element[1])
        # ,
        #scanArchiveFilePrefix = 'scanArchiveFilePrefix' ,
        # scanFilePrefix = 'scanFilePrefix')

        # display Chooch graphs
        self.choochGraphs.setTitle(title)
        self.choochGraphs.newcurve("spline", chooch_graph_x, chooch_graph_y1)
        self.choochGraphs.newcurve("fp", chooch_graph_x, chooch_graph_y2)
        self.choochGraphs.replot()

        # display Chooch results
        energy_str = self['formatString'] % pk
        self.peakInput.setText(energy_str)
        energy_str = self['formatString'] % ip
        self.inflectionInput.setText(energy_str)
        energy_str = self['formatString'] % rm
        self.remoteInput.setText(energy_str)

        self.scanStatus.setPaletteBackgroundColor(QColor(color))

        self.startScanButton.commandDone()
        self.emit(PYSIGNAL("energyScanning"), (False,))
        self.parametersBox.setEnabled(True)
        self.acceptBox.setEnabled(True)
        self.inflectionInput.setEnabled(True)
        self.peakInput.setEnabled(True)
        self.remoteInput.setEnabled(True)
        self.remote2Input.setEnabled(True)

    def addNewPoint(self, x, y):
        self.emit(PYSIGNAL('addNewPoint'), (x, y))

    def newScan(self, scanParameters):
        self.emit(PYSIGNAL('newScan'), (scanParameters,))

    def clearEnergies(self):
        self.inflectionInput.setText("")
        self.peakInput.setText("")
        self.remoteInput.setText("")
        self.remote2Input.setText("")
        self.statusBox.setTitle("(no element)")
class SoleilScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSlot("newScan", ())

        self.defineSlot("newScanPoint", ())

        self.scanObject = None
        self.xdata = []
        self.ydata = []

        self.isConnected = None
        self.canAddPoint = True

        self.addProperty("specVersion", "string", "")
        self.addProperty("backgroundColor", "combo", ("white", "default"), "white")
        self.addProperty("graphColor", "combo", ("white", "default"), "white")
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        QObject.connect(
            self.graph, PYSIGNAL("QtBlissGraphSignal"), self.handleBlissGraphSignal
        )
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMousePressed(const QMouseEvent&)"),
            self.graph.onMousePressed,
        )
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMouseReleased(const QMouseEvent&)"),
            self.graph.onMouseReleased,
        )
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)

    def propertyChanged(self, property, oldValue, newValue):
        if property == "specVersion":
            if self.scanObject is not None:
                self.safeDisconnect()

            self.scanObject = None
            if self.scanObject is not None:
                self.safeConnect()

        elif property == "backgroundColor":
            if newValue == "white":
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))

        elif property == "graphColor":
            if newValue == "white":
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.graph.canvas().setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self)
                )

        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    def newScan(self, scanParameters):
        logging.info("newScan scanParameters %s" % str(scanParameters))
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" % scanParameters["title"])
        self.graph.xlabel(scanParameters["xlabel"])
        self.graph.ylabel(scanParameters["ylabel"])
        self.graph.setx1timescale(False)
        self.xdata = []
        self.ydata = []
        self.graph.newcurve("scan", self.xdata, self.ydata)
        self.graph.replot()

    def newScanPoint(self, x, y):
        logging.info("newScanPoint x %s, y %s" % (x, y))
        self.xdata.append(x)
        self.ydata.append(y)
        self.graph.newcurve("scan", self.xdata, self.ydata, curveinfo="bo-")
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt":
            self.lblPosition.setText(
                "(X: %f, Y: %f)" % (signalDict["x"], signalDict["y"])
            )

    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL("newScanPoint"), self.newScan)
            self.connect(self.scanObject, PYSIGNAL("newPoint"), self.newScanPoint)
            self.isConnected = True

    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL("newScan"), self.newScan)
            self.disconnect(
                self.scanObject, PYSIGNAL("newScanPoint"), self.newScanPoint
            )
            self.isConnected = False
Beispiel #19
0
class SpecScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSignal('newScan', ())

        self.scanObject = None
        self.xdata = []
        self.ylable = ""
        self.mylog = 0

        self.isConnected = None
        #self.canAddPoint = None
        self.canAddPoint = True

        self.addProperty('specVersion', 'string', '')
        self.addProperty('backgroundColor', 'combo', ('white', 'default'), 'white')
        self.addProperty('graphColor', 'combo', ('white', 'default'), 'white')
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        #self.cmdZoomIn = QToolButton(buttonBox)
        #self.cmdZoomOut = QToolButton(buttonBox)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)
                         
        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'), self.handleBlissGraphSignal)
        QObject.disconnect(self.graph, SIGNAL('plotMousePressed(const QMouseEvent&)'), self.graph.onMousePressed)
        QObject.disconnect(self.graph, SIGNAL('plotMouseReleased(const QMouseEvent&)'), self.graph.onMouseReleased)
        #QObject.connect(self.cmdZoomIn, SIGNAL('clicked()'), self.cmdZoomInClicked)
        #QObject.connect(self.cmdZoomOut, SIGNAL('clicked()'), self.cmdZoomOutClicked)

        #self.cmdZoomIn.setIconSet(QIconSet(Icons.load("zoomin")))
        #self.cmdZoomOut.setIconSet(QIconSet(Icons.load("zoomout")))
        #self.cmdZoomIn.setToggleButton(True)
        #self.cmdZoomOut.setToggleButton(True)
        #self.cmdZoomIn.setUsesTextLabel(False)
        #self.cmdZoomOut.setUsesTextLabel(False)
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)


    def propertyChanged(self, property, oldValue, newValue):
        if property == 'specVersion':
            if self.scanObject is not None:
                self.safeDisconnect()
                
            self.scanObject = QSpecScan(newValue)

            if self.scanObject is not None:
                self.safeConnect()

        elif property == 'backgroundColor':
            if newValue == 'white':
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))
        
        elif property == 'graphColor':
            if newValue == 'white':
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.graph.canvas().setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))

        else:
            BlissWidget.propertyChanged(self,property,oldValue,newValue)
               

    def newScan(self, scanParameters):
        #self.canAddPoint = True
        self.emit(PYSIGNAL('newScan'), ())
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' % scanParameters['title'])
        self.xdata = []

        self.graph.clearcurves()
        self.graph.xlabel(scanParameters['xlabel'])
        self.ylabel = scanParameters['ylabel']

        ylabels = self.ylabel.split()
        self.ydatas = [[] for x in range(len(ylabels))]
        for labels,ydata in zip(ylabels,self.ydatas):
            self.graph.newcurve(labels,self.xdata,ydata)
            
        
        self.graph.ylabel(self.ylabel)
        if self.scanObject.getScanType() == SpecScan.TIMESCAN:
            self.graph.setx1timescale(True)
        else:
            self.graph.setx1timescale(False)
        
        try:
            scanParameters['scaletype'] == 'log'
            if self.mylog == 0 :
                self.graph.toggleLogY()
                self.mylog = 1
        except:
            if self.mylog == 1:
              self.graph.toggleLogY()
              self.mylog = 0

        self.graph.replot()
        
    def newScanPoint(self, x, y):
        self.xdata.append(x)
        for label,ydata,yvalue in zip(self.ylabel.split(),self.ydatas,str(y).split()) :
            ydata.append(float(yvalue))
            self.graph.newcurve(label,self.xdata,ydata)
        self.graph.replot()
        
    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt':
            self.lblPosition.setText("(X: %f, Y: %f)" % (signalDict['x'], signalDict['y']))


    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL('newScan'), self.newScan)
            self.connect(self.scanObject, PYSIGNAL('newPoint'), self.newScanPoint)
            self.isConnected=True


    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL('newScan'), self.newScan)
            self.disconnect(self.scanObject, PYSIGNAL('newScanPoint'), self.newScanPoint)
            #self.canAddPoint = False
            self.isConnected = False


    #def instanceMirrorChanged(self,mirror):
    #    if BlissWidget.isInstanceMirrorAllow():
    #        self.safeConnect()
    #    else:
    #        self.safeDisconnect()


    """
Beispiel #20
0
class SoleilScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSlot("newScan", ())

        self.defineSlot("newScanPoint", ())

        self.scanObject = None
        self.xdata = []
        self.ydata = []

        self.isConnected = None
        self.canAddPoint = True

        self.addProperty("specVersion", "string", "")
        self.addProperty("backgroundColor", "combo", ("white", "default"),
                         "white")
        self.addProperty("graphColor", "combo", ("white", "default"), "white")
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)

        QObject.connect(self.graph, PYSIGNAL("QtBlissGraphSignal"),
                        self.handleBlissGraphSignal)
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMousePressed(const QMouseEvent&)"),
            self.graph.onMousePressed,
        )
        QObject.disconnect(
            self.graph,
            SIGNAL("plotMouseReleased(const QMouseEvent&)"),
            self.graph.onMouseReleased,
        )
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)

    def propertyChanged(self, property, oldValue, newValue):
        if property == "specVersion":
            if self.scanObject is not None:
                self.safeDisconnect()

            self.scanObject = None
            if self.scanObject is not None:
                self.safeConnect()

        elif property == "backgroundColor":
            if newValue == "white":
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        elif property == "graphColor":
            if newValue == "white":
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == "default":
                self.graph.canvas().setPaletteBackgroundColor(
                    QWidget.paletteBackgroundColor(self))

        else:
            BlissWidget.propertyChanged(self, property, oldValue, newValue)

    def newScan(self, scanParameters):
        logging.info("newScan scanParameters %s" % str(scanParameters))
        self.lblTitle.setText("<nobr><b>%s</b></nobr>" %
                              scanParameters["title"])
        self.graph.xlabel(scanParameters["xlabel"])
        self.graph.ylabel(scanParameters["ylabel"])
        self.graph.setx1timescale(False)
        self.xdata = []
        self.ydata = []
        self.graph.newcurve("scan", self.xdata, self.ydata)
        self.graph.replot()

    def newScanPoint(self, x, y):
        logging.info("newScanPoint x %s, y %s" % (x, y))
        self.xdata.append(x)
        self.ydata.append(y)
        self.graph.newcurve("scan", self.xdata, self.ydata, curveinfo="bo-")
        self.graph.replot()

    def handleBlissGraphSignal(self, signalDict):
        if signalDict["event"] == "MouseAt":
            self.lblPosition.setText("(X: %f, Y: %f)" %
                                     (signalDict["x"], signalDict["y"]))

    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL("newScanPoint"),
                         self.newScan)
            self.connect(self.scanObject, PYSIGNAL("newPoint"),
                         self.newScanPoint)
            self.isConnected = True

    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL("newScan"), self.newScan)
            self.disconnect(self.scanObject, PYSIGNAL("newScanPoint"),
                            self.newScanPoint)
            self.isConnected = False
class SoleilScanPlotBrick(BlissWidget):
    def __init__(self, *args):
        BlissWidget.__init__(self, *args)

        self.defineSlot('newScan', ())
	
        self.defineSlot('newScanPoint',())

        self.scanObject = None
        self.xdata = []
        self.ydata = []

        self.isConnected = None
        self.canAddPoint = True

        self.addProperty('specVersion', 'string', '')
        self.addProperty('backgroundColor', 'combo', ('white', 'default'), 'white')
        self.addProperty('graphColor', 'combo', ('white', 'default'), 'white')
        self.lblTitle = QLabel(self)
        self.graphPanel = QFrame(self)
        buttonBox = QHBox(self)
        self.lblPosition = QLabel(buttonBox)
        self.graph = QtBlissGraph(self.graphPanel)
                         
        QObject.connect(self.graph, PYSIGNAL('QtBlissGraphSignal'), self.handleBlissGraphSignal)
        QObject.disconnect(self.graph, SIGNAL('plotMousePressed(const QMouseEvent&)'), self.graph.onMousePressed)
        QObject.disconnect(self.graph, SIGNAL('plotMouseReleased(const QMouseEvent&)'), self.graph.onMouseReleased)
        self.graph.canvas().setMouseTracking(True)
        self.graph.enableLegend(False)
        self.graph.enableZoom(False)
        self.graph.setAutoLegend(False)
        self.lblPosition.setAlignment(Qt.AlignRight)
        self.lblTitle.setAlignment(Qt.AlignHCenter)
        self.lblTitle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.lblPosition.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        buttonBox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        
        QVBoxLayout(self.graphPanel)
        self.graphPanel.layout().addWidget(self.graph)

        QVBoxLayout(self)
        self.layout().addWidget(self.lblTitle)
        self.layout().addWidget(buttonBox)
        self.layout().addWidget(self.graphPanel)


    def propertyChanged(self, property, oldValue, newValue):
        if property == 'specVersion':
            if self.scanObject is not None:
                self.safeDisconnect()
                
            self.scanObject = None
            if self.scanObject is not None:
                self.safeConnect()

        elif property == 'backgroundColor':
            if newValue == 'white':
                self.setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))
        
        elif property == 'graphColor':
            if newValue == 'white':
                self.graph.canvas().setPaletteBackgroundColor(Qt.white)
            elif newValue == 'default':
                self.graph.canvas().setPaletteBackgroundColor(QWidget.paletteBackgroundColor(self))

        else:
            BlissWidget.propertyChanged(self,property,oldValue,newValue)
               

    def newScan(self, scanParameters):
        logging.info('newScan scanParameters %s' % str(scanParameters) )
        self.lblTitle.setText('<nobr><b>%s</b></nobr>' % scanParameters['title'])
        self.graph.xlabel(scanParameters['xlabel'])
        self.graph.ylabel(scanParameters['ylabel'])
        self.graph.setx1timescale(False)
        self.xdata = []
        self.ydata = []
        self.graph.newcurve('scan', self.xdata, self.ydata)
        self.graph.replot() 

    def newScanPoint(self, x, y):
        logging.info('newScanPoint x %s, y %s' % (x,y))
        self.xdata.append(x)
        self.ydata.append(y)
        self.graph.newcurve('scan', self.xdata, self.ydata, curveinfo='bo-')
        self.graph.replot() 
        
    def handleBlissGraphSignal(self, signalDict):
        if signalDict['event'] == 'MouseAt':
            self.lblPosition.setText("(X: %f, Y: %f)" % (signalDict['x'], signalDict['y']))


    def safeConnect(self):
        if not self.isConnected:
            self.connect(self.scanObject, PYSIGNAL('newScanPoint'), self.newScan)
            self.connect(self.scanObject, PYSIGNAL('newPoint'), self.newScanPoint)
            self.isConnected=True

    def safeDisconnect(self):
        if self.isConnected:
            self.disconnect(self.scanObject, PYSIGNAL('newScan'), self.newScan)
            self.disconnect(self.scanObject, PYSIGNAL('newScanPoint'), self.newScanPoint)
            self.isConnected = False