Пример #1
0
class BsxImageDataProxy(CObjectBase):
    signals = [Signal('new_curves_data'), Signal('erase_curve')]
    slots = [Slot('load_files')]

    def init(self):
        logging.debug("<BsxImageDataProxy> Created")

    def load_files(self, filenames):
        if type(filenames) is types.ListType:
            for filename in filenames:
                try:
                    self.load_single_file(filename)
                except:
                    logging.debug("Problem opening file %s", filename)
        else:
            try:
                self.load_single_file(filenames)
            except:
                logging.debug(traceback.format_exc())
                logging.debug("Problem opening file %s", filenames)

    def load_single_file(self, filename):
        if not os.path.exists(filename):
            return

        data = numpy.loadtxt(filename)

        self.emit('erase_curve', filename)
        #TODO: DEBUG
        # Clean up to remove 0.0 data that cause problem in display in Logarithmic scale
        cleanList = [x if x != 0.0 else 0.0001 for x in list(data[:, 1])]
        self.emit('new_curves_data', {filename: [list(data[:, 0]), cleanList]})

    def erase_curves(self):
        self.emit('erase_curve', None)
Пример #2
0
class Login(CObjectBase):

    signals = [Signal("loggedIn")]

    slots = [Slot("loginTry")]

    def __init__(self, *args, **kwargs):
        CObjectBase.__init__(self, *args, **kwargs)

    def init(self):
        pass

    def loginTry(self, userAndPassword):
        print "Got a try of login"
Пример #3
0
class BSSampleChanger(CObjectBase):
    signals = [
        Signal('seuTemperatureChanged'),
        Signal('storageTemperatureChanged'),
        Signal('stateChanged')
    ]

    def __init__(self, *args, **kwargs):
        CObjectBase.__init__(self, *args, **kwargs)

        # Usable channels:
        # "Status", "AlarmList", "BeamLocation",
        # "BeamMarkVolume", "BeamShapeEllipse", "CleanVenturiOK",
        # "CollisionDetected", "CommandException", "CommandOutput",
        # "CoverOpen", "CurrentLiquidPosition", "DetergentEmpty",
        # "Flooding", "OverflowVenturiOK", "PlateID",
        # "PLCState", "HardwareInitPending", "Power12OK",
        # "SampleType", "TemperatureSampleStorage", "TemperatureSEU",
        # "LocalLockout", "State", "VacuumOK",
        # "ViscosityLevel", "WasteFull", "WaterEmpty",
        # "LiquidPositionFixed"

        # The target user-entered temperature
        self.__target_temperature = None

    def init(self):
        self.current_status = self.current_state = 'Not Available'
        self.channels['State'].connect('update', self.stateChanged)
        self.channels['Status'].connect('update', self.statusChanged)
        self.channels['BeamLocation'].connect('update',
                                              self.beamlocationChanged)

    def stateChanged(self, state):
        self.current_state = str(state)
        self.emit('stateChanged', self.current_state, self.current_status)

    def statusChanged(self, status):
        self.current_status = str(status)
        self.emit('stateChanged', self.current_state, self.current_status)

    #TODO: SO - Why is beamlocation not used
    def beamlocationChanged(self, beamlocation):
        self.beam_location = self.getBeamLocation()
        self.emit('beamLocationChanged', self.beam_location)

    def setBeamLocation(self, x1, y1, x2, y2):
        self.channels["BeamLocation"] = "%d %d %d %d" % (x1, y1, x2, y2)

    #
    # We should not need to use this from the Brick. We should just connect to beamLocationChanged
    #
    def getBeamLocation(self):
        # beam is string
        beam = self.channels["BeamLocation"].value()
        try:
            beamLocation = map(int, beam.strip().split())
            return beamLocation
        except:
            return None

    def getState(self):
        # scState is _PyTango.DevState
        scState = self.channels["State"].value()
        return scState

    def getCommandException(self):
        scException = self.channels["CommandException"].value()
        return scException

    def setBeamMark(self, x1, y1, x2, y2, is_ellipse):
        self.setBeamLocation(x1, y1, x2, y2)
        self.channels["BeamShapeEllipse"].set_value(is_ellipse)

    def setLiquidPositionFixed(self, fixed):
        self.channels["LiquidPositionFixed"].set_value(fixed)

    def setSampleType(self, sample_type):
        self.channels["SampleType"].set_value(sample_type)

    def setSEUTemperature(self, temp):
        # Note that this has a timeout in the SC as X minutes/degrees
        self.commands["SEUTemperature"](temp)
        self.wait(7200)

    def setStorageTemperature(self, temp):
        # Note that this has a timeout in the SC as X minutes/degrees
        self.commands["TemperatureSampleStorage"](temp)
        self.wait(7200)

    def setViscosityLevel(self, level):
        self.channels["ViscosityLevel"].set_value(level)

    def setHPLCMode(self, hplc_mode):
        try:
            self.channels["ModeHPLC"].set_value(bool(hplc_mode))
        except:
            return False
        else:
            if not str(self.getState()) in ("STANDBY", "ON"):
                return False
            return True

    def fill(self, plate, row, column, volume):
        print ">>> fill ", plate, row, column, volume
        self.commands['fill'](map(str, (plate, row, column, volume)))

    def flow(self, volume, t):
        self.commands['flow'](map(str, (volume, t)))

    def recuperate(self, *args):
        self.commands['recuperate'](map(str, args))

    def mix(self, *args):
        self.commands['mix'](map(str, args))

    def transfer(self, *args):
        self.commands['transfer'](map(str, args))

    def clean(self):
        self.commands['clean']()

    def isExecuting(self):
        state = str(self.getState())
        if state:
            return (state == "RUNNING")
        else:
            return False

    def doCleanProcedure(self):
        self.clean()
        self.wait()

    def wait(self, timeout=240):
        loopCount = 0
        while self.isExecuting():
            loopCount = loopCount + 1
            time.sleep(0.5)
            # check if timeout*0.5 seconds has passed
            if loopCount > timeout:
                raise RuntimeError, "Timeout from Sample Changer"

        exception = self.getCommandException()
        if exception is not None and exception != "":
            raise RuntimeError, "Sample Changer exception: " + exception

    def doSetSEUTemperatureProcedure(self, temperature):
        self.setSEUTemperature(temperature)

    def doFillProcedure(self, *args):
        self.fill(*args)
        self.wait()

    def doFlowProcedure(self, *args):
        self.flow(*args)
        self.wait()

    def doRecuperateProcedure(self, *args):
        self.recuperate(*args)
        self.wait()
Пример #4
0
class BsxAttenuators(CObjectBase):

    signals = [
        Signal("attenuatorsStateChanged"),
        Signal("attenuatorsFactorChanged")
    ]

    slots = [Slot("toggleFilter"), Slot("setTransmission")]

    def __init__(self, *args, **kwargs):
        CObjectBase.__init__(self, *args, **kwargs)

    def init(self):
        self.__attenuatorsState = None
        self.__attenuatorsFactor = None
        self.__attenuatorsList = []
        for data_elt in self.config["//data"]:
            key = data_elt.attrib["name"]
            bits = map(int, data_elt.attrib['bits'].split())
            for b in bits:
                self.__attenuatorsList.append([key, b])
        # the list contains [label, bits] lists
        # sort by bits
        self.__attenuatorsList.sort(key=lambda x: x[1])

        # Set up all channels
        self.channels["attenuatorsState_oh"].connect(
            "update", self.attenuatorsStateChanged)
        self.channels["attenuatorsState_exp"].connect(
            "update", self.attenuatorsStateChanged)
        self.channels["attenuatorsFactor_oh"].connect(
            "update", self.attenuatorsFactorChanged)
        self.channels["attenuatorsFactor_exp"].connect(
            "update", self.attenuatorsFactorChanged)

    def connectNotify(self, pValue):
        try:
            value = getattr(self, pValue[:-7]).value()
            getattr(self, pValue)(value)
        except:
            pass

    def getAttenuatorsList(self):
        logging.getLogger().debug('is sending attribute list %s',
                                  self.__attenuatorsList)
        if len(self.__attenuatorsList) == 0:
            return None
        else:
            return self.__attenuatorsList

    def getAttenuatorsState(self):
        self.__attenuatorsState = self.channels["attenuatorsState_oh"].value()
        return self.__attenuatorsState

    def getAttenuatorsFactor(self):
        self.__attenuatorsFactor = self.channels["attenuatorsFactor_oh"].value(
        )
        return self.__attenuatorsFactor

    # =============================================
    #  COMMANDS
    # =============================================
    def toggleFilter(self, pValue):
        self.commands["toggleFilter"](pValue)

    def setTransmission(self, pValue):
        self.commands["setTransmission"](pValue)

    # =============================================
    #  CHANNELS
    # =============================================
    def attenuatorsStateChanged(self, pValue):
        self.__attenuatorsState = int(pValue)
        self.emit("attenuatorsStateChanged", self.__attenuatorsState)

    def attenuatorsFactorChanged(self, pValue):
        self.__attenuatorsFactor = int(pValue)
        self.emit("attenuatorsFactorChanged", self.__attenuatorsFactor)
Пример #5
0
class BiosaxsClient(CObjectBase):
    signals = [Signal("onSuccess"), Signal("onError")]
    slots = [
        Slot("getExperimentNamesByProposalCodeNumber"),
        Slot("setUser"),
        Slot("getRobotXMLByExperimentId")
    ]

    def init(self):
        self.client = None

        #Prod machine
        self.URL = 'http://ispyb.esrf.fr:8080/ispyb-ejb3/ispybWS/ToolsForBiosaxsWebService?wsdl'

        #Test machine
        #self.URL = 'http://ispyvalid.esrf.fr:8080/ispyb-ejb3/ispybWS/ToolsForBiosaxsWebService?wsdl'
        #Alejandro's local machine
        #self.URL = 'http://pcantolinos:8080/ispyb-ejb3/ispybWS/ToolsForBiosaxsWebService?wsdl'
        print "ISPyB Server: " + self.URL

        self.selectedExperimentId = None

        #Login information
        self.user = None
        self.password = None
        self.proposalType = None
        self.proposalNumber = None

        self.timeout = 5
        self.experiments = None

    def __initWebservice(self):

        self.httpAuthenticatedToolsForAutoprocessingWebService = HttpAuthenticated(
            username=self.user, password=self.password)
        self.client = Client(
            self.URL,
            transport=self.httpAuthenticatedToolsForAutoprocessingWebService,
            cache=None,
            timeout=self.timeout)
        self.experiments = []
        self.response = None

    def setUser(self, user, password, proposalType, proposalNumber):
        self.user = user  #"mx1438"
        self.password = password  #"Rfo4-73"
        self.proposalType = proposalType
        self.proposalNumber = proposalNumber

    #Return list containing [["ExperimentName1", "experimentId1"], ["ExperimentName2", "experimentId2"]]
    def getExperimentNames(self):
        #        print "------------ Getting experiment Names"
        experimentNames = []
        for experiment in self.experiments:
            experimentNames.append([
                experiment.experiment.name, experiment.experiment.experimentId
            ])
        return experimentNames

    def getExperimentNamesByProposalCodeNumber(self, code, number):
        if (self.client is None):
            self.__initWebservice()
        response = self.client.service.findExperimentByProposalCode(
            code, number)
        self.experiments = []
        for experiment in response:
            self.experiments.append(Experiment(experiment))
        experimentNames = self.getExperimentNames()
        self.emit("onSuccess", "getExperimentNamesByProposalCodeNumber",
                  experimentNames)
        #self.emit("onSuccess", "getExperimentNamesByProposalCodeNumber", experimentNames)

    def getPyarchDestination(self):
        # This happens because I need the experiment ID but because the experiment has not been created yet I have to replace it in the server side
        # so I will replace /data/pyarch/bm29/%s%s/__ID__ by the good ID
        if (self.selectedExperimentId is None):
            self.selectedExperimentId = "__ID__"

        if (self.URL ==
                'http://ispyb.esrf.fr:8080/ispyb-ejb3/ispybWS/ToolsForBiosaxsWebService?wsdl'
            ):
            return "/data/pyarch/bm29/%s%s/%s" % (self.proposalType,
                                                  self.proposalNumber,
                                                  self.selectedExperimentId)
        return "/data/pyarch/bm29/testing/%s%s/%s" % (
            self.proposalType, self.proposalNumber, self.selectedExperimentId)

    def getSpecimenIdBySampleCode(self, sampleCode):
        print "[ISPyB] getSpecimenIdBySampleCode " + str(sampleCode)
        if self.experiment is None:
            print "[ISPyB] Experiment is None"
            return None
        if self.selectedExperimentId is None:
            print "[ISPyB] Experiment is None"
            return None
        for experiment in self.experiments:
            #print experiment.experiment.experimentId
            if experiment.experiment.experimentId == self.selectedExperimentId:
                for sample in experiment.experiment.samples:
                    for specimen in sample.specimen3VOs:
                        if specimen.code == sampleCode:
                            return specimen.specimenId
        return None

    # Return an array of samples which a given concentration
    def getSpecimensByConcentration(self, concentration):
        print "[ISPyB] getSpecimenByConcentration: " + str(concentration)
        if self.experiment is None:
            print "[ISPyB] Experiment is None"
            return None
        if self.selectedExperimentId is None:
            print "[ISPyB] Experiment is None"
            return None

        samples = []
        for experiment in self.experiments:
            if experiment.experiment.experimentId == self.selectedExperimentId:
                for sample in experiment.experiment.samples:
                    if (float(sample.concentration)) == (float(concentration)):
                        samples.append(sample)
        return samples

    def getBufferIdByAcronym(self, bufferName):
        for myBuffer in self.experiment.getBuffers():
            if bufferName == myBuffer.acronym:
                return myBuffer.bufferId
        return None

    #It looks for a code in the comments that identifies the measurments
    # [1] This is a comment
    # ---
    #  |_ Id
    def getMeasurementIdByCommentId(self, commentId):
        try:
            for experiment in self.experiments:
                if experiment.experiment.experimentId == self.selectedExperimentId:
                    for sample in experiment.experiment.samples:
                        for specimen in sample.specimen3VOs:
                            if str(specimen.comment).find("[" +
                                                          str(commentId) +
                                                          "]") != -1:
                                return specimen.specimenId
        except:
            traceback.print_exc()
            raise Exception
        return -1

    def getMeasurementIdBySampleCodeConcentrationAndSEU(
            self, sampleCode, concentration, seu, bufferName):
        try:
            print "[ISPyB] getMeasurementIdBySampleCodeConcentrationAndSEU " + str(
                sampleCode) + " " + str(concentration) + " " + str(
                    seu) + " " + str(bufferName)
            if self.experiment is None:
                print "[ISPyB] Experiment is None"
                return None
            if self.selectedExperimentId is None:
                print "[ISPyB] Experiment is None"
                return None
            bufferId = self.getBufferIdByAcronym(bufferName)
            print "[ISPyB] bufferId " + str(bufferId)
            for experiment in self.experiments:
                #print experiment.experiment.experimentId
                if experiment.experiment.experimentId == self.selectedExperimentId:
                    samples = self.getSpecimensByConcentration(concentration)
                    for sample in samples:
                        if sample.bufferId == bufferId:
                            for specimen in sample.specimen3VOs:
                                if (float(specimen.exposureTemperature)
                                        == float(seu) and
                                    (str(specimen.code) == str(sampleCode))):
                                    return specimen.specimenId
        except Exception:
            print "[ISPyB] error"
            traceback.print_exc()
            raise Exception
        print "[ISPyB] Measurement not found with conc: %s SEU: %s and sampleCode:%s" % (
            str(concentration), str(seu), str(sampleCode))
        return -1

    ### Mode: before, after, sample
    def saveFrameSet(self, mode, sampleCode, exposureTemperature,
                     storageTemperature, timePerFrame, timeStart, timeEnd,
                     energy, detectorDistance, fileArray, snapshotCapillary,
                     currentMachine, tocollect, pars, specimenId):
        try:
            print "[ISPyB] Request for saveFrameSet " + str(mode) + " " + str(
                sampleCode)
            if (self.client is None):
                self.__initWebservice()

            #specimenId = self.getMeasurementIdBySampleCodeConcentrationAndSEU(sampleCode, concentration, ispybSEUtemperature, bufferName)
            print "[ISPyB] Specimen: " + str(specimenId)
            if specimenId is None:
                specimenId = -1

            self.client.service.saveFrame(
                mode, self.selectedExperimentId, specimenId, sampleCode,
                exposureTemperature, storageTemperature, timePerFrame,
                timeStart, timeEnd, energy, detectorDistance,
                fileArray, snapshotCapillary, currentMachine, str(tocollect),
                str(pars), pars["beamCenterX"], pars["beamCenterY"],
                pars["radiationRelative"], pars["radiationAbsolute"],
                pars["pixelSizeX"], pars["pixelSizeY"], pars["normalisation"],
                tocollect["transmission"])
        except Exception:
            print "[ISPyB] error", sys.exc_info()[0]
            #traceback.print_exc()

    def getPlatesByPlateGroupId(self, plateGroupId, experimentId):
        plates = []
        for experiment in self.experiments:
            if experiment.experiment.experimentId == experimentId:
                experimentPlates = experiment.getPlates()
                for plate in experimentPlates:
                    if plate.plategroup3VO is not None:
                        if plate.plategroup3VO.plateGroupId == plateGroupId:
                            plates.append(plate)
        return plates

    def getRobotXMLByExperimentId(self, experimentId):
        self.selectedExperimentId = experimentId
        if (self.client is None):
            self.__initWebservice()
        for experiment in self.experiments:
            plates = []
            if experiment.experiment.experimentId is experimentId:
                self.selectedExperimentId = experimentId
                for plate in experiment.getPlates():
                    plates.append(plate.samplePlateId)
                return self.client.service.getRobotXMLByPlateIds(
                    experimentId, plates)
        return None

    def getPlateGroupByExperimentId(self, experimentId):
        self.selectedExperimentId = experimentId
        for experiment in self.experiments:
            if experiment.experiment.experimentId == experimentId:
                print experiment.experiment.experimentId
                #It works but I don't know how to deserialize in bricks side
                #return str(experiment.getPlateGroups())
                groups = experiment.getPlateGroups()
                names = []
                for group in groups:
                    names.append([group.name, group.plateGroupId])
                return names
        return []

    def getRobotXMLByPlateGroupId(self, plateGroupId, experimentId):
        plates = self.getPlatesByPlateGroupId(plateGroupId, experimentId)
        ids = []
        for plate in plates:
            ids.append(plate.samplePlateId)
        xml = self.client.service.getRobotXMLByPlateIds(experimentId, str(ids))
        self.emit("onSuccess", "getRobotXMLByPlateGroupId", xml)

    def setExperimentAborted(self):
        try:
            self.updateStatus("ABORTED")
        except Exception:
            traceback.print_exc()
            raise Exception

    def updateStatus(self, status):
        try:
            if (self.client is None):
                self.__initWebservice()
        except Exception:
            print "[ISPyB] It has been not possible to connect with ISPyB. No connection"
            raise Exception
        try:
            if (self.selectedExperimentId is not None):
                self.client.service.updateStatus(self.selectedExperimentId,
                                                 status)

                #If status is inished we compress the folder
                if status == "FINISHED":
                    #Zipping file
                    zipFilePath = self.getPyarchDestination() + "/" + str(
                        self.selectedExperimentId) + ".zip"
                    temporalPath = "/tmp/" + str(
                        self.selectedExperimentId) + ".zip"
                    self.zipFolder(self.getPyarchDestination(), temporalPath)
                    self.movefile(temporalPath, self.getPyarchDestination())
                    self.client.service.setDataAcquisitionFilePath(
                        self.selectedExperimentId, zipFilePath)
        except Exception:
            traceback.print_exc()
            raise Exception

    def zipFolder(self, path, archivename):
        print "ISPyB: zipping " + path + " on " + archivename
        myZipFile = zipfile.ZipFile(archivename, 'w')
        rootlen = len(path) + 1
        assert os.path.isdir(path)
        for base, dirs, files in os.walk(path):
            for file in files:
                fn = os.path.join(base, file)
                myZipFile.write(fn, fn[rootlen:])
        myZipFile.close()

    def movefile(self, afile, destination):
        try:
            print "[ISPyB] Moving %s to : %s " % (afile, destination)
            if not os.path.isdir(destination):
                print "[ISPyB] Creating directory %s " % (destination)
                os.makedirs(destination)
            shutil.move(afile, destination)
        except IOError as error:
            print "[ISPyB] Handled error while directory creation in pyarch: %s " % error

    def copyfile(self, afile, pyarch):
        try:
            print "[ISPyB] Copying %s to pyarch: %s " % (afile, pyarch)
            if not os.path.isdir(pyarch):
                print "[ISPyB] Creating directory %s " % (pyarch)
                os.makedirs(pyarch)
            shutil.copy(afile, pyarch)
        except IOError as error:
            print "[ISPyB] Handled error while directory creation in pyarch: %s " % error

    #def createExperiment( self, proposalCode, proposalNumber, samples, storageTemperature, mode, extraflowTime, experimentType, sourceFile, name ):
    def createExperiment(self, samples, storageTemperature, mode,
                         extraflowTime, experimentType, sourceFile, name):
        try:
            if (self.client is None):
                self.__initWebservice()
        except Exception:
            print "[ISPyB] It has been not possible to connect with ISPyB. No connection"
            raise Exception

        try:
            self.experiment = None
            self.selectedExperimentId = None
            expectedXMLFilePath = self.getPyarchDestination() + '/' + name
            print "[ISPyB] Request to ISPyB: create new experiment for proposal " + str(
                self.proposalType) + str(self.proposalNumber)
            experiment = self.client.service.createExperiment(
                #                                                               proposalCode,
                #                                                               proposalNumber,
                self.proposalType,
                self.proposalNumber,
                str(samples),
                storageTemperature,
                mode,
                extraflowTime,
                experimentType,
                expectedXMLFilePath,
                name)
            if (experiment is None):
                print "[ISPyB] ISPyB could not create the experiment from robot file"
                raise Exception

            print "[ISPyB] Experiment Created: " + str(experiment.experimentId)
            self.selectedExperimentId = experiment.experimentId
            self.experiment = Experiment(experiment)
            self.experiments.append(Experiment(experiment))
            print "[ISPyB] selectedExperimentId: " + str(
                self.selectedExperimentId)
        except Exception:
            print "[ISPyB] handled error"
            traceback.print_exc()
            raise Exception

        # Copying xml file to pyarch. It doesnt raise an exception
        self.copyfile(sourceFile, self.getPyarchDestination())
Пример #6
0
class EnergyWaveLength(CObjectBase):

    signals = [Signal("energyChanged")]

    slots = [
        Slot("setEnergy"),
        Slot("getEnergy"),
        Slot("pilatusReady"),
        Slot("pilatusReset"),
        Slot("setPilatusFill"),
        Slot("energyAdjustPilatus")
    ]

    def __init__(self, *args, **kwargs):
        CObjectBase.__init__(self, *args, **kwargs)
        # Threshold in keV (to change the sensitivity)
        self.__pilatusThreshold = 12.00
        self.__energyAdjust = True
        self.pilatusThreshold = None

    def init(self):
        # The keV to Angstrom calc
        self.hcOverE = 12.3984
        self.deltaPilatus = 0.1
        # Runnning = Nothing should be possible
        self.__pilatus_status = "Running"
        # make another connection
        self.pilatusFillMode = self.channels.get("fill_mode")
        # get spec motor as described in href and the corresponding energy.xml
        self.__energyMotor = self.objects["getEnergy"]
        if self.__energyMotor is not None:
            # connect to the [Only if MOVING or ON] - to avoid constant upgrades
            self.__energyMotor.connect("stateChanged", self.newEnergy)
        else:
            logging.error("No connection to energy motor in spec")
        # Connect to fill_mode and correct it back each time it changes
        self.channels["fill_mode"].connect("update", self.fillModeChanged)

    def newEnergy(self, pState):
        if pState == 'ON':
            pValue = self.__energyMotor.position()
            self.__energy = float(pValue)
            # Calculate wavelength
            wavelength = self.hcOverE / self.__energy
            wavelengthStr = "%.4f" % wavelength
            # set value of BSX_GLOBAL
            self.channels["collectWaveLength"].set_value(wavelengthStr)
            self.emit("energyChanged", pValue)
            # if in movement already, just return....
            if not self.pilatusReady():
                return
            self.__currentPilatusThreshold = float(
                self.channels["pilatus_threshold"].value())
            if math.fabs(self.__energy -
                         self.__currentPilatusThreshold) > self.deltaPilatus:
                if self.__energyAdjust:
                    #TODO: DEBUG
                    print ">> changing energy by motor"
                    # if not set Threshold, try to connect it now
                    if self.pilatusThreshold is None:
                        self.pilatusThreshold = self.channels.get(
                            "pilatus_threshold")
                        if self.pilatusThreshold is None:
                            logging.error(
                                "Tried and failed to connect to Pilatus")
                        else:
                            self.pilatusThreshold.set_value(self.__energy)
                            while not self.pilatusReady():
                                time.sleep(0.5)
                    else:
                        self.pilatusThreshold.set_value(self.__energy)
                        while not self.pilatusReady():
                            time.sleep(0.5)

    def getPilatusThreshold(self):
        return float(self.channels["pilatus_threshold"].value())

    def getEnergy(self):
        return self.__energyMotor.position()

    def setEnergy(self, pValue):
        self.__energy = float(pValue)
        self.commands["setEnergy"](self.__energy)
        # Check if we need and can set new Energy on Pilatus first.
        self.__currentPilatusThreshold = float(
            self.channels["pilatus_threshold"].value())
        if math.fabs(self.__energy -
                     self.__currentPilatusThreshold) > self.deltaPilatus:
            if self.__energyAdjust:
                # if not set Threshold, try to connect it now
                if self.pilatusThreshold is None:
                    self.pilatusThreshold = self.channels.get(
                        "pilatus_threshold")
                    if self.pilatusThreshold is None:
                        logging.error("Tried and failed to connect to Pilatus")
                    else:
                        self.pilatusThreshold.set_value(self.__energy)
                        while not self.pilatusReady():
                            time.sleep(0.5)

                else:
                    self.pilatusThreshold.set_value(self.__energy)
                    while not self.pilatusReady():
                        time.sleep(0.5)

    def fillModeChanged(self, pValue):
        # read value first
        mode = self.pilatusFillMode.value()
        if mode != "ON":
            while not self.pilatusReady():
                time.sleep(0.5)
            self.setPilatusFill()

    def setPilatusFill(self):
        # Just for safety set fill mode to ON => gapfill -1
        self.pilatusFillMode.set_value("ON")

    def energyAdjustPilatus(self, pValue):
        # True or false for following energy with Pilatus
        self.__energyAdjust = pValue

    def pilatusReady(self):
        # Check if Pilatus is ready
        self.__pilatus_status = self.channels["pilatus_status"].value()
        if self.__pilatus_status == "Ready":
            return True
        else:
            return False

    def pilatusReset(self):
        # reset the pilatus
        self.commands["pilatus_reset"]()
Пример #7
0
class Reprocess(CObjectBase):
    __CHANNEL_LIST = [
        "reprocessDirectoryChanged", "reprocessPrefixChanged",
        "reprocessRunNumberChanged", "reprocessFrameFirstChanged",
        "reprocessFrameLastChanged", "reprocessConcentrationChanged",
        "reprocessCommentsChanged", "reprocessCodeChanged",
        "reprocessMaskFileChanged", "reprocessDetectorDistanceChanged",
        "reprocessWaveLengthChanged", "reprocessPixelSizeXChanged",
        "reprocessPixelSizeYChanged", "reprocessBeamCenterXChanged",
        "reprocessBeamCenterYChanged", "reprocessNormalisationChanged",
        "reprocessBeamStopDiodeChanged", "reprocessMachineCurrentChanged",
        "reprocessKeepOriginalChanged", "reprocessStatusChanged"
    ]

    signals = [Signal(channel) for channel in __CHANNEL_LIST]
    slots = [Slot("reprocess")]

    def __init__(self, *args, **kwargs):
        CObjectBase.__init__(self, *args, **kwargs)

    def init(self):
        self.frameFirst = ""
        self.frameLast = ""
        self.concentration = ""
        self.comment = ""
        self.code = ""
        self.maskFile = ""
        self.detectorDistance = ""
        self.waveLength = ""
        self.pixelSizeX = ""
        self.pixelSizeY = ""
        self.beamCenterX = ""
        self.beamCenterY = ""
        self.normalisation = ""
        self.beamStopDiode = ""
        self.machineCurrent = ""

    def reprocess(self, pDirectory, pPrefix, pRunNumber, pFrameFirst,
                  pFrameLast, pConcentration, pComments, pCode, pMaskFile,
                  pDetectorDistance, pWaveLength, pPixelSizeX, pPixelSizeY,
                  pBeamCenterX, pBeamCenterY, pNormalisation, pBeamStopDiode,
                  pMachineCurrent, pKeepOriginal, pTimeOut, pFeedback):
        # Fixed since 2011
        self.detector = "Pilatus"
        # Fixed by SO 5/9 2012
        self.operation = "Complete reprocess"
        self.directory = pDirectory
        self.prefix = pPrefix
        self.runNumber = pRunNumber

        if pFrameFirst is None:
            self.frameFirst = pFrameFirst

        if pFrameLast is None:
            self.frameLast = pFrameLast

        if pConcentration is not None:
            self.concentration = pConcentration

        if pComments is not None:
            self.comments = pComments

        if pCode is not None:
            self.code = pCode

        if pMaskFile is not None:
            self.maskFile = pMaskFile

        if pDetectorDistance is not None:
            self.detectorDistance = pDetectorDistance

        if pWaveLength is not None:
            self.waveLength = pWaveLength

        if pPixelSizeX is not None:
            self.pixelSizeX = pPixelSizeX

        if pPixelSizeY is not None:
            self.pixelSizeY = pPixelSizeY

        if pBeamCenterX is not None:
            self.beamCenterX = pBeamCenterX

        if pBeamCenterY is not None:
            self.beamCenterY = pBeamCenterY

        if pNormalisation is not None:
            self.normalisation = pNormalisation

        if pBeamStopDiode is not None:
            self.beamStopDiode = pBeamStopDiode

        if pMachineCurrent is not None:
            self.machineCurrent = pMachineCurrent

        self.keepOriginal = pKeepOriginal

        self.commands["reprocess"](
            self.directory, self.prefix, self.runNumber, self.frameFirst,
            self.frameLast, self.concentration, self.comments, self.code,
            self.maskFile, self.detectorDistance, self.waveLength,
            self.pixelSizeX, self.pixelSizeY, self.beamCenterX,
            self.beamCenterY, self.normalisation, self.beamStopDiode,
            self.machineCurrent, self.keepOriginal, pTimeOut, pFeedback)

    def reprocessAbort(self):
        self.commands["reprocess"].abort()

    def reprocessDirectoryChanged(self, pValue):
        self.emit("reprocessDirectoryChanged", pValue)

    def reprocessPrefixChanged(self, pValue):
        self.emit("reprocessPrefixChanged", pValue)

    def reprocessRunNumberChanged(self, pValue):
        self.emit("reprocessRunNumberChanged", pValue)

    def reprocessFrameFirstChanged(self, pValue):
        self.emit("reprocessFrameFirstChanged", pValue)

    def reprocessFrameLastChanged(self, pValue):
        self.emit("reprocessFrameLastChanged", pValue)

    def reprocessConcentrationChanged(self, pValue):
        self.emit("reprocessConcentrationChanged", pValue)

    def reprocessCommentsChanged(self, pValue):
        self.emit("reprocessCommentsChanged", pValue)

    def reprocessCodeChanged(self, pValue):
        self.emit("reprocessCodeChanged", pValue)

    def reprocessMaskFileChanged(self, pValue):
        self.emit("reprocessMaskFileChanged", pValue)

    def reprocessDetectorDistanceChanged(self, pValue):
        self.emit("reprocessDetectorDistanceChanged", pValue)

    def reprocessWaveLengthChanged(self, pValue):
        self.emit("reprocessWaveLengthChanged", pValue)

    def reprocessPixelSizeXChanged(self, pValue):
        self.emit("reprocessPixelSizeXChanged", pValue)

    def reprocessPixelSizeYChanged(self, pValue):
        self.emit("reprocessPixelSizeYChanged", pValue)

    def reprocessBeamCenterXChanged(self, pValue):
        self.emit("reprocessBeamCenterXChanged", pValue)

    def reprocessBeamCenterYChanged(self, pValue):
        self.emit("reprocessBeamCenterYChanged", pValue)

    def reprocessNormalisationChanged(self, pValue):
        self.emit("reprocessNormalisationChanged", pValue)

    def reprocessBeamStopDiodeChanged(self, pValue):
        self.emit("reprocessBeamStopDiodeChanged", pValue)

    def reprocessMachineCurrentChanged(self, pValue):
        self.emit("reprocessMachineCurrentChanged", pValue)

    def reprocessKeepOriginalChanged(self, pValue):
        self.emit("reprocessKeepOriginalChanged", pValue)

    def reprocessStatusChanged(self, pValue):
        self.emit("reprocessStatusChanged", pValue)