diff --git a/mxcubecore/HardwareObjects/Bliss.py b/mxcubecore/HardwareObjects/Bliss.py index 143217abcf..83eeb2904d 100644 --- a/mxcubecore/HardwareObjects/Bliss.py +++ b/mxcubecore/HardwareObjects/Bliss.py @@ -7,10 +7,6 @@ import gevent import numpy from bliss.config import static -from bliss.data.node import ( - DataNode, - get_or_create_node, -) from mxcubecore.BaseHardwareObjects import HardwareObject diff --git a/mxcubecore/HardwareObjects/ESRF/BM14EnergyScan.py b/mxcubecore/HardwareObjects/ESRF/BM14EnergyScan.py deleted file mode 100644 index 0c801825dd..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/BM14EnergyScan.py +++ /dev/null @@ -1,46 +0,0 @@ -import logging - -from ESRFEnergyScan import ( - ESRFEnergyScan, - TunableEnergy, -) - -from mxcubecore.TaskUtils import task - - -class BM14EnergyScan(ESRFEnergyScan): - def __init__(self, name): - ESRFEnergyScan.__init__(self, name, TunableEnergy()) - - @task - def energy_scan_hook(self, energy_scan_parameters): - self.energy = energy_scan_parameters["edgeEnergy"] - if self.energy_scan_parameters["findattEnergy"]: - ESRFEnergyScan.move_energy(self, energy_scan_parameters["findattEnergy"]) - - @task - def move_undulators(self, gaps): - return - - @task - def set_mca_roi(self, eroi_min, eroi_max): - self.execute_command("calculateMcaRoi", eroi_min, eroi_max) - - @task - def choose_attenuation(self): - if self.execute_command("chooseAttenuation") == -1: - logging.getLogger("user_level_log").error( - "Cannot find appropriate attenuation" - ) - raise RuntimeError("Cannot find appropriate attenuation") - self.energy_scan_parameters["transmissionFactor"] = ( - self.transmission.get_value() - ) - - @task - def execute_energy_scan(self, energy_scan_parameters): - energy_scan_parameters["exposureTime"] = self.get_property("exposureTime") - self.execute_command("executeScan", energy_scan_parameters) - self.energy_scan_parameters["exposureTime"] = energy_scan_parameters[ - "exposureTime" - ] diff --git a/mxcubecore/HardwareObjects/ESRF/ESRFSession.py b/mxcubecore/HardwareObjects/ESRF/ESRFSession.py index 75416e0a98..3835222f9f 100644 --- a/mxcubecore/HardwareObjects/ESRF/ESRFSession.py +++ b/mxcubecore/HardwareObjects/ESRF/ESRFSession.py @@ -14,6 +14,7 @@ def __init__(self, name): def init(self): Session.Session.init(self) + self._use_acronym = self.get_property("use_acronym", True) archive_base_directory = self["file_info"].get_property( "archive_base_directory" @@ -95,7 +96,7 @@ def get_default_subdir(self, sample_data: dict) -> str: sample_name = sample_data.name protein_acronym = sample_data.crystals[0].protein_acronym - if protein_acronym: + if self._use_acronym and protein_acronym: subdir = "%s/%s-%s/" % (protein_acronym, protein_acronym, sample_name) else: subdir = "%s/" % sample_name diff --git a/mxcubecore/HardwareObjects/ESRF/ID231BeamCmds.py b/mxcubecore/HardwareObjects/ESRF/ID231BeamCmds.py index 9d788b7421..96df834472 100644 --- a/mxcubecore/HardwareObjects/ESRF/ID231BeamCmds.py +++ b/mxcubecore/HardwareObjects/ESRF/ID231BeamCmds.py @@ -14,7 +14,7 @@ def __init__(self, *args): def init(self): controller = self.get_object_by_role("controller") detcover = self.get_object_by_role("detcover") - scintilator = self.get_object_by_role("scintilator") + scintillator = self.get_object_by_role("scintillator") aperture = self.get_object_by_role("aperture") hutchtrigger = self.get_object_by_role("hutchtrigger") cryo = self.get_object_by_role("cryostream") @@ -26,7 +26,7 @@ def init(self): # self.anneal = ControllerCommand("Anneal", controller.anneal_procedure) self.detcover = HWObjActuatorCommand("Detector cover", detcover) - self.scintilator = HWObjActuatorCommand("Scintillator", scintilator) + self.scintillator = HWObjActuatorCommand("Scintillator", scintillator) self.aperture = HWObjActuatorCommand("Aperture", aperture) self.hutchtrigger = HWObjActuatorCommand("Hutchtrigger", hutchtrigger) self.cryo = HWObjActuatorCommand("Cryostream", cryo) @@ -38,7 +38,7 @@ def get_commands(self): self.quick_realign, # self.anneal, self.detcover, - self.scintilator, + self.scintillator, self.aperture, self.hutchtrigger, self.cryo, diff --git a/mxcubecore/HardwareObjects/ESRF/ID232HutchTrigger.py b/mxcubecore/HardwareObjects/ESRF/ID232HutchTrigger.py deleted file mode 100644 index 4400b2720f..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID232HutchTrigger.py +++ /dev/null @@ -1,147 +0,0 @@ -import logging -import sys -import time - -import gevent -import PyTango.gevent - -from mxcubecore import BaseHardwareObjects -from mxcubecore import HardwareRepository as HWR - -""" -Read the state of the hutch from the PSS device server and take actions -when enter (1) or interlock (0) the hutch. -0 = The hutch has been interlocked and the sample environment should be made - ready for data collection. The actions are extract the detector cover, - move the detector to its previous position, set the MD2 to Centring. -1 = The interlock is cleared and the user is entering the hutch to change - the sample(s). The actions are insert the detector cover, move the - detecto to a safe position, set MD2 to sample Transfer. -""" - - -class ID232HutchTrigger(BaseHardwareObjects.HardwareObject): - def __init__(self, name): - BaseHardwareObjects.HardwareObject.__init__(self, name) - self._enabled = True - - def _do_polling(self): - while True: - try: - self.poll() - except Exception: - sys.excepthook(*sys.exc_info()) - time.sleep(self.get_property("interval") / 1000.0 or 1) - - def init(self): - try: - self.device = PyTango.gevent.DeviceProxy(self.get_property("tangoname")) - except PyTango.DevFailed as traceback: - last_error = traceback[-1] - logging.getLogger("HWR").error( - "%s: %s", str(self.name()), last_error["desc"] - ) - self.device = None - - try: - self.flex_device = PyTango.gevent.DeviceProxy( - self.get_property("flex_tangoname") - ) - except PyTango.DevFailed as traceback: - last_error = traceback[-1] - logging.getLogger("HWR").error( - "%s: %s", str(self.name()), last_error["desc"] - ) - self.flex_device = None - - self.pollingTask = None - self.initialized = False - self.__oldValue = None - self.card = None - self.channel = None - - PSSinfo = self.get_property("pss") - try: - self.card, self.channel = map(int, PSSinfo.split("/")) - except Exception: - logging.getLogger().error("%s: cannot find PSS number", self.name()) - return - - if self.device is not None: - self.pollingTask = gevent.spawn(self._do_polling) - self.connected() - - def hutchIsOpened(self): - return self.hutch_opened - - def is_connected(self): - return True - - def connected(self): - self.emit("connected") - - def disconnected(self): - self.emit("disconnected") - - def abort(self): - pass - - def macro(self, entering_hutch, old={"dtox": None}): - logging.info( - "%s: %s hutch", self.name(), "entering" if entering_hutch else "leaving" - ) - dtox = HWR.beamline.detector.distance - udiff_ctrl = self.get_object_by_role("predefined") - ctrl_obj = self.get_object_by_role("controller") - if not entering_hutch: - if old["dtox"] is not None: - print("Moving %s to %g" % (dtox.name(), old["dtox"])) - dtox.set_value(old["dtox"]) - self.flex_device.eval("flex.user_port(0)") - self.flex_device.eval("flex.robot_port(1)") - udiff_ctrl.moveToPhase(phase="Centring", wait=True) - else: - old["dtox"] = dtox.get_value() - ctrl_obj.detcover.set_in() - self.flex_device.eval("flex.robot_port(0)") - dtox.set_value(815) - udiff_ctrl.moveToPhase(phase="Transfer", wait=True) - - def poll(self): - a = self.device.GetInterlockState([self.card - 1, 2 * (self.channel - 1)])[0] - b = self.device.GetInterlockState([self.card - 1, 2 * (self.channel - 1) + 1])[ - 0 - ] - value = a & b - - if value == self.__oldValue: - return - else: - self.__oldValue = value - - self.value_changed(value) - - def value_changed(self, value, *args): - if value == 0: - if self.initialized: - self.emit("hutchTrigger", (1,)) - elif value == 1 and self.initialized: - self.emit("hutchTrigger", (0,)) - - self.hutch_opened = 1 - value - self.initialized = True - - if self._enabled: - self.macro(self.hutch_opened) - - def get_actuator_state(self): - if self._enabled: - return "ENABLED" - else: - return "DISABLED" - - def actuatorIn(self): - self._enabled = True - - def actuatorOut(self): - self._enabled = False diff --git a/mxcubecore/HardwareObjects/ESRF/ID23PhotonFlux.py b/mxcubecore/HardwareObjects/ESRF/ID23PhotonFlux.py deleted file mode 100644 index d998f53841..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID23PhotonFlux.py +++ /dev/null @@ -1,92 +0,0 @@ -import logging -import math -import time - -from calc_flux import CalculateFlux -from PyTango.gevent import DeviceProxy - -from mxcubecore import HardwareRepository as HWR -from mxcubecore.BaseHardwareObjects import HardwareObject -from mxcubecore.TaskUtils import task - - -class ID23PhotonFlux(HardwareObject): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.threshold = [] - - def init(self): - self.counter = DeviceProxy(self.get_property("url")) - try: - self.threshold = map(float, self.get_property("threshold").split()) - except AttributeError: - self.threshold = [0, 9999] - self.shutter = self.get_deviceby_role("shutter") - self.aperture = self.get_object_by_role("aperture") - fname = self.get_property("calibrated_diodes_file") - - self.flux_calc = CalculateFlux() - self.flux_calc.init(fname) - self.shutter.connect("shutterStateChanged", self.shutterStateChanged) - - self.counts_reading_task = self._read_counts_task(wait=False) - - @task - def _read_counts_task(self): - old_counts = None - while True: - counts = self._get_counts() - if counts != old_counts: - old_counts = counts - self.countsUpdated(counts) - time.sleep(1) - - def _get_counts(self): - try: - self.counter.MeasureSingle() - counts = abs(self.counter.ReadData) - if counts < self.threshold[0] or counts > self.threshold[1]: - counts = 0 - except AttributeError: - counts = 0 - logging.getLogger("HWR").exception("%s: could not get counts", self.name()) - try: - egy = HWR.beamline.energy.get_value() * 1000.0 - calib = self.flux_calc.calc_flux_coef(egy) - except Exception: - logging.getLogger("HWR").exception("%s: could not get energy", self.name()) - else: - if self.aperture is None: - aperture_coef = 1 - else: - try: - aperture_coef = self.aperture.getApertureCoef() - except Exception: - aperture_coef = 1.0 - counts = math.fabs(counts * calib[0] * aperture_coef) * 10e6 - return counts - - def connect_notify(self, signal): - if signal == "valueChanged": - self.emitValueChanged() - - def shutterStateChanged(self, _): - self.countsUpdated(self._get_counts()) - - def updateFlux(self, _): - self.countsUpdated(self._get_counts(), ignore_shutter_state=False) - - def countsUpdated(self, counts, ignore_shutter_state=False): - self.emitValueChanged("%1.3g" % counts) - - def get_value(self): - self.updateFlux("dummy") - return self.current_flux - - def emitValueChanged(self, flux=None): - if flux is None: - self.current_flux = None - self.emit("valueChanged", ("?",)) - else: - self.current_flux = flux - self.emit("valueChanged", (self.current_flux,)) diff --git a/mxcubecore/HardwareObjects/ESRF/ID29BeamCmds.py b/mxcubecore/HardwareObjects/ESRF/ID29BeamCmds.py index 6a7fae1a93..9bbacf787a 100644 --- a/mxcubecore/HardwareObjects/ESRF/ID29BeamCmds.py +++ b/mxcubecore/HardwareObjects/ESRF/ID29BeamCmds.py @@ -13,7 +13,7 @@ def __init__(self, *args): def init(self): controller = self.get_object_by_role("controller") detcover = self.get_object_by_role("detcover") - scintilator = self.get_object_by_role("scintilator") + scintillator = self.get_object_by_role("scintillator") aperture = self.get_object_by_role("aperture") hutchtrigger = self.get_object_by_role("hutchtrigger") cryo = self.get_object_by_role("cryo") @@ -26,7 +26,7 @@ def init(self): self.anneal = ControllerCommand("Anneal", controller.anneal_procedure) self.detcover = HWObjActuatorCommand("Detector cover", detcover) - self.scintilator = HWObjActuatorCommand("Scintillator", scintilator) + self.scintillator = HWObjActuatorCommand("Scintillator", scintillator) self.aperture = HWObjActuatorCommand("Aperture", aperture) self.hutchtrigger = HWObjActuatorCommand("Hutchtrigger", hutchtrigger) self.cryo = HWObjActuatorCommand("Cryo", cryo) @@ -37,7 +37,7 @@ def get_commands(self): self.quick_realign, self.anneal, self.detcover, - self.scintilator, + self.scintillator, self.aperture, self.hutchtrigger, self.cryo, diff --git a/mxcubecore/HardwareObjects/ESRF/ID29PhotonFlux.py b/mxcubecore/HardwareObjects/ESRF/ID29PhotonFlux.py deleted file mode 100644 index bf8845c4d7..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID29PhotonFlux.py +++ /dev/null @@ -1,87 +0,0 @@ -import logging -import math -import sys -import time - -from calc_flux import CalculateFlux - -from mxcubecore import HardwareRepository as HWR -from mxcubecore.BaseHardwareObjects import HardwareObject -from mxcubecore.TaskUtils import task - - -class ID29PhotonFlux(HardwareObject): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def init(self): - self.counter = self.get_object_by_role("counter") - self.shutter = self.get_deviceby_role("shutter") - self.aperture = self.get_object_by_role("aperture") - fname = self.get_property("calibrated_diodes_file") - - self.flux_calc = CalculateFlux() - self.flux_calc.init(fname) - self.shutter.connect("shutterStateChanged", self.shutterStateChanged) - - self.counts_reading_task = self._read_counts_task(wait=False) - - @task - def _read_counts_task(self): - old_counts = None - while True: - counts = self._get_counts() - if counts != old_counts: - old_counts = counts - self.countsUpdated(counts) - time.sleep(1) - - def _get_counts(self): - try: - counts = self.counter.getCorrectedPhysValue() - if counts == -9999: - counts = 0 - except Exception: - counts = 0 - logging.getLogger("HWR").exception("%s: could not get counts", self.name()) - try: - egy = HWR.beamline.energy.get_value() * 1000.0 - calib = self.flux_calc.calc_flux_coef(egy) - except Exception: - logging.getLogger("HWR").exception("%s: could not get energy", self.name()) - else: - if self.aperture is None: - aperture_coef = 1 - else: - try: - aperture_coef = self.aperture.getApertureCoef() - except Exception: - sys.excepthook(*sys.exc_info()) - aperture_coef = 1 - counts = math.fabs(counts * calib[0] * aperture_coef) - return counts - - def connect_notify(self, signal): - if signal == "valueChanged": - self.emitValueChanged() - - def shutterStateChanged(self, _): - self.countsUpdated(self._get_counts()) - - def updateFlux(self, _): - self.countsUpdated(self._get_counts(), ignore_shutter_state=False) - - def countsUpdated(self, counts, ignore_shutter_state=False): - self.emitValueChanged("%1.3g" % counts) - - def get_value(self): - self.updateFlux("dummy") - return self.current_flux - - def emitValueChanged(self, flux=None): - if flux is None: - self.current_flux = None - self.emit("valueChanged", ("?",)) - else: - self.current_flux = flux - self.emit("valueChanged", (self.current_flux,)) diff --git a/mxcubecore/HardwareObjects/ESRF/ID29XRFSpectrum.py b/mxcubecore/HardwareObjects/ESRF/ID29XRFSpectrum.py deleted file mode 100644 index 4585b69a6c..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID29XRFSpectrum.py +++ /dev/null @@ -1,263 +0,0 @@ -import logging -import os.path - -import numpy - -from mxcubecore.HardwareObjects.XRFSpectrum import XRFSpectrum - -try: - from PyMca import ( - ClassMcaTheory, - ConfigDict, - QtMcaAdvancedFitReport, - ) -except ImportError: - from PyMca5.PyMca import ( - ClassMcaTheory, - ConfigDict, - QtMcaAdvancedFitReport, - ) - -""" -Next two lines is a trick to avoid core dump in QtMcaAdvancedFitReport -""" -from unittest.mock import MagicMock - -QtMcaAdvancedFitReport.qt = MagicMock() - - -class ID29XRFSpectrum(XRFSpectrum): - def __init__(self, *args, **kwargs): - XRFSpectrum.__init__(self, *args, **kwargs) - self.mca_hwobj = self.get_object_by_role("mca") - self.ctrl_hwobj = self.get_object_by_role("controller") - self.beamsize = self.get_object_by_role("beamsize") - self.fname = self.get_property("cfgfile") - self.config = ConfigDict.ConfigDict() - self.mcafit = ClassMcaTheory.McaTheory(self.fname) - self.default_integration_time = self.get_property("default_integration_time", 3.5) - - def preset_mca(self, ctime=None, fname=None): - try: - ctime = float(ctime) - except (TypeError, ValueError): - ctime = self.default_integration_time - - self.mca_hwobj.set_roi(2, 15, channel=1) - self.mca_hwobj.set_presets(erange=1, ctime=ctime, fname=str(fname)) - self.ctrl_hwobj.mca.set_roi(2, 15, channel=1) - self.ctrl_hwobj.mca.set_presets(erange=1, ctime=ctime, fname=str(fname)) - - def _doSpectrum(self, ctime, filename, wait=True): - try: - ctime = float(ctime) - except (TypeError, ValueError): - ctime = self.default_integration_time - print(f"_doSpectrum ctime {ctime}") - self.choose_attenuation(ctime, filename) - - def choose_attenuation(self, ctime=None, fname=None): - """Choose appropriate maximum attenuation. - Args: - ctime (float): count time [s] - Kwargs: - fname (str): Filename to save the MCA data (full path) - Returns: - (bool): Procedure executed correcly (True) or error (False) - """ - try: - ctime = float(ctime) - except (TypeError, ValueError): - ctime = self.default_integration_time - print(f"ctime {ctime}") - - res = True - if not fname: - fname = self.spectrumInfo["filename"] - fname = str(fname) - - self.preset_mca(ctime, fname) - - self.ctrl_hwobj.detcover.set_in(20) - try: - _transm = self.ctrl_hwobj.find_max_attenuation( - ctime=ctime, fname=fname, roi=[2.0, 15.0] - ) - self.spectrumInfo["beamTransmission"] = _transm - except Exception as exp: - logging.getLogger("user_level_log").exception(str(exp)) - res = False - - self.ctrl_hwobj.diffractometer.fldet_out() - return res - - def _findAttenuation(self, ctime=None): - try: - ctime = float(ctime) - except (TypeError, ValueError): - ctime = self.default_integration_time - return self.choose_attenuation(ctime) - - """ - Next methods are for fitting the data with pymca - """ - - def mcafit_configuration(self, config=None): - """Configure the fitting parameters. The procedure is time consuming. - It is only executed if the last configuration file is not the same. - Args: - config(dict): Configuration dictionary, containing among others the - configuration file name. - """ - change = False - if not config or "file" not in config: - fname = XRFSpectrum._get_cfgfile(self, self.spectrumInfo["energy"]) - else: - fname = config["file"] - - if self.fname != fname: - self.fname = fname - change = True - self.config.read(self.fname) - if "concentrations" not in self.config: - self.config["concentrations"] = {} - change = True - if "attenuators" not in self.config: - self.config["attenuators"] = {"Matrix": [1, "Water", 1.0, 0.01, 45.0, 45.0]} - change = True - if "flux" in config: - self.config["concentrations"]["flux"] = float(config["flux"]) - change = True - if "time" in config: - self.config["concentrations"]["time"] = float(config["time"]) - change = True - - if change: - self.mcafit.configure(self.config) - - def set_data(self, data, calib=None, config=None): - """Execute the fitting. Write the fitted data files to pyarch. - Args: - data (list): The raw data. - calib (list): The mca calibration. - config (dict): The configuration dictionary. - """ - if config: - self.mcafit_configuration(config) - try: - if data[0].size == 2: - xdata = numpy.array(data[:, 0]) * 1.0 - ydata = numpy.array(data[:, 1]) - else: - xdata = data[0] * 1.0 - ydata = data[1] - - # xmin and xmax hard coded while waiting for configuration file - # to be corrected. - # xmin = 292 - # xmax = 4000 - - xmin = int(config["min"]) - xmax = int(config["max"]) - self.mcafit.setData(xdata, ydata, xmin=xmin, xmax=xmax, calibration=calib) - - self.mcafit.estimate() - # fitresult = self._fit() - - fitresult = self.mcafit.startfit(digest=1) - if fitresult: - fitresult = {"fitresult": fitresult[0], "result": fitresult[1]} - - # write the csv file to pyarch - csvname = self.spectrumInfo["fittedDataFileFullPath"] - self._write_csv_file(fitresult, csvname) - - # write html report to pyarch - fname = os.path.basename(self.spectrumInfo["filename"]) - outfile = fname.split(".")[0] - outdir = os.path.dirname(self.spectrumInfo["annotatedPymcaXfeSpectrum"]) - - _kw = { - "outdir": outdir, - "outfile": outfile, - "fitresult": fitresult, - "plotdict": {"logy": False}, - } - - report = QtMcaAdvancedFitReport.QtMcaAdvancedFitReport(**_kw) - text = report.getText() - report.writeReport(text=text) - except Exception as exp: - logging.getLogger().exception("XRFSpectrum: problem fitting %s" % str(exp)) - raise - - def _write_csv_file(self, fitresult, fname=None): - """Write data to a csv file. - Args: - fitresult(dict): Data as dictionary. - Kwargs: - fname (str): Filename to write to (full path). - """ - if not fname: - fname = self.spectrumInfo["fittedDataFileFullPath"] - if os.path.exists(fname): - os.remove(fname) - - # get the significant peaks - peaks_dict = {} - pars_len = len(fitresult["result"]["parameters"]) - grp_len = len(fitresult["result"]["groups"]) - nglobal = pars_len - grp_len - parameters = fitresult["result"]["fittedpar"][:nglobal] + [0.0] * grp_len - - for grp in fitresult["result"]["parameters"][nglobal:]: - idx = fitresult["result"]["parameters"].index(grp) - parameters[idx] = fitresult["result"]["fittedpar"][idx] - xmatrix = fitresult["result"]["xdata"] - ymatrix = self.mcafit.mcatheory(parameters, xmatrix) - ymatrix.shape = [len(ymatrix), 1] - label = "y" + grp - if self.mcafit.STRIP: - peaks_dict[label] = ymatrix + self.mcafit.zz - else: - peaks_dict[label] = ymatrix - peaks_dict[label].shape = (len(peaks_dict[label]),) - parameters[idx] = 0.0 - - delimiter = "," - header = '"channel"%s"Energy"%s"counts"%s"fit"%s"continuum"%s"pileup"' % ( - delimiter, - delimiter, - delimiter, - delimiter, - delimiter, - ) - - # add the peaks labels - for key in peaks_dict: - header += delimiter + ('"%s"' % key) - # logging.getLogger("user_level_log").info("Writing %s" % fname) - with open(fname, "w") as csv_fd: - csv_fd.write(header) - csv_fd.write("\n") - for i in range(fitresult["result"]["xdata"].size): - csv_fd.write( - "%.7g%s%.7g%s%.7g%s%.7g%s%.7g%s%.7g" - % ( - fitresult["result"]["xdata"][i], - delimiter, - fitresult["result"]["energy"][i], - delimiter, - fitresult["result"]["ydata"][i], - delimiter, - fitresult["result"]["yfit"][i], - delimiter, - fitresult["result"]["continuum"][i], - delimiter, - fitresult["result"]["pileup"][i], - ) - ) - for key in peaks_dict: - csv_fd.write("%s%.7g" % (delimiter, peaks_dict[key][i])) - - csv_fd.write("\n") diff --git a/mxcubecore/HardwareObjects/ESRF/ID30A3PhotonFlux.py b/mxcubecore/HardwareObjects/ESRF/ID30A3PhotonFlux.py deleted file mode 100644 index 4a55b2ad59..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID30A3PhotonFlux.py +++ /dev/null @@ -1,109 +0,0 @@ -import time - -from PyTango.gevent import DeviceProxy - -from mxcubecore.BaseHardwareObjects import HardwareObject -from mxcubecore.TaskUtils import task - - -class ID30A3PhotonFlux(HardwareObject): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def init(self): - controller = self.get_object_by_role("controller") - self.musst = controller.musst - self.shutter = self.get_deviceby_role("shutter") - self.factor = self.get_property("current_photons_factor") - - self.shutter.connect("shutterStateChanged", self.shutterStateChanged) - - self.tg_device = DeviceProxy(self.get_property("tango_device")) - self.counts_reading_task = self._read_counts_task(wait=False) - - @task - def _read_counts_task(self): - old_counts = None - while True: - counts = self._get_counts() - if counts != old_counts: - old_counts = counts - self.countsUpdated(counts) - time.sleep(1) - - def _get_counts(self): - """gain = 20 #20uA - keithley_voltage = 2 - musst_voltage = int("".join([x for x in self.musst.putget("#?CHCFG CH5") if x.isdigit()])) - musst_fs = float(0x7FFFFFFF) - counts = abs((gain/keithley_voltage)*musst_voltage*int(self.musst.putget("#?VAL CH5"))/musst_fs) - """ - # try: - self.tg_device.MeasureSingle() - counts = abs(self.tg_device.ReadData) * 1e6 - return counts - - def connect_notify(self, signal): - if signal == "valueChanged": - self.emitValueChanged() - - def shutterStateChanged(self, _): - self.countsUpdated(self._get_counts()) - - def updateFlux(self, _): - self.countsUpdated(self._get_counts(), ignore_shutter_state=True) - - def countsUpdated(self, counts, ignore_shutter_state=False): - if not ignore_shutter_state and self.shutter.getShutterState() != "opened": - self.emitValueChanged(0) - return - flux = counts * self.factor - self.emitValueChanged("%1.3g" % flux) - - """ - try: - counts = counts[self.index] - except TypeError: - logging.getLogger("HWR").error("%s: counts is None", self.name()) - return - flux = None - - try: - egy = HWR.beamline.energy.get_value()*1000.0 - except: - logging.getLogger("HWR").exception("%s: could not get energy", self.name()) - else: - try: - calib_dict = self.calibration_chan.get_value() - if calib_dict is None: - logging.getLogger("HWR").error("%s: calibration is None", self.name()) - else: - calibs = [(float(c["energy"]), float(c[self.counter])) for c in calib_dict.values()] - calibs.sort() - E = [c[0] for c in calibs] - C = [c[1] for c in calibs] - except: - logging.getLogger("HWR").exception("%s: could not get calibration", self.name()) - else: - try: - aperture_coef = self.aperture.getApertureCoef() - except: - aperture_coef = 1 - if aperture_coef <= 0: - aperture_coef = 1 - calib = numpy.interp([egy], E, C) - flux = counts * calib * aperture_coef - #logging.getLogger("HWR").debug("%s: flux-> %f * %f=%f , calib_dict=%r", self.name(), counts, calib, counts*calib, calib_dict) - self.emitValueChanged("%1.3g" % flux) - """ - - def get_value(self): - return self.current_flux - - def emitValueChanged(self, flux=None): - if flux is None: - self.current_flux = None - self.emit("valueChanged", ("?",)) - else: - self.current_flux = flux - self.emit("valueChanged", (self.current_flux,)) diff --git a/mxcubecore/HardwareObjects/ESRF/ID30BPhotonFlux.py b/mxcubecore/HardwareObjects/ESRF/ID30BPhotonFlux.py deleted file mode 100644 index d1c4cd8901..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID30BPhotonFlux.py +++ /dev/null @@ -1,88 +0,0 @@ -# encoding: utf-8 -# -# Project: MXCuBE -# https://github.com/mxcube -# -# This file is part of MXCuBE software. -# -# MXCuBE is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# MXCuBE is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public License -# along with MXCuBE. If not, see . - -""" Photon fluc calculations -Example xml file: - - Photon flux - - - i0 - -""" -import logging - -from mxcubecore import HardwareRepository as HWR -from mxcubecore.HardwareObjects.abstract.AbstractFlux import AbstractFlux - - -class ID30BPhotonFlux(AbstractFlux): - """Photon flux calculation for ID30B""" - - def __init__(self, name): - super(ID30BPhotonFlux, self).__init__(name) - self._counter = None - self._flux_calc = None - self._aperture = None - - def init(self): - """Initialisation""" - super(ID30BPhotonFlux, self).init() - controller = self.get_object_by_role("controller") - # ultimately it should be HWR.beamline.diffractometer.aperture - self._aperture = self.get_object_by_role("aperture") - - try: - self._flux_calc = controller.CalculateFlux() - self._flux_calc.init() - except AttributeError: - logging.getLogger("HWR").exception( - "Could not get flux calculation from BLISS" - ) - - counter = self.get_property("counter_name") - if counter: - self._counter = getattr(controller, counter) - else: - self._counter = self.get_object_by_role("counter") - - HWR.beamline.safety_shutter.connect("stateChanged", self.update_value) - - def get_value(self): - """Calculate the flux value as function of a reading - """ - # counts = self._counter._counter_controller.read_all(self._counter) - # if isinstance(counts, list): - # counts = float(counts[0]) - counts = float(self._counter.raw_read) - if counts == -9999: - counts = 0.0 - - egy = HWR.beamline.energy.get_value() * 1000.0 - calib = self._flux_calc.calc_flux_factor(egy)[self._counter.name] - - try: - label = self._aperture.get_value().name - aperture_factor = self._aperture.get_factor(label) - except AttributeError: - aperture_factor = 1 - counts = abs(counts * calib * aperture_factor) - self._nominal_value = counts - return counts diff --git a/mxcubecore/HardwareObjects/ESRF/ID30BXRFSpectrum.py b/mxcubecore/HardwareObjects/ESRF/ID30BXRFSpectrum.py deleted file mode 100644 index 850f666d64..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID30BXRFSpectrum.py +++ /dev/null @@ -1,428 +0,0 @@ -import logging -import os -import time - -import gevent -import gevent.event -from qt import copy - -from mxcubecore import HardwareRepository as HWR -from mxcubecore.BaseHardwareObjects import HardwareObject - - -class XrfSpectrum(HardwareObject): - def init(self): - - self.scanning = None - self.moving = None - self.ready_event = gevent.event.Event() - - try: - self.config_data = self.get_channel_object("config_data") - except Exception: - self.config_data = None - - try: - self.calib_data = self.get_channel_object(" calib_data") - except Exception: - self.calib_data = None - - try: - self.energySpectrumArgs = self.get_channel_object("spectrum_args") - except KeyError: - logging.getLogger().warning( - "XRFSpectrum: error initializing energy spectrum arguments (missing channel)" - ) - self.energySpectrumArgs = None - - try: - self.spectrumStatusMessage = self.get_channel_object("spectrumStatusMsg") - except KeyError: - self.spectrumStatusMessage = None - logging.getLogger().warning( - "XRFSpectrum: energy messages will not appear (missing channel)" - ) - else: - self.spectrumStatusMessage.connect_signal( - "update", self.spectrumStatusChanged - ) - - try: - self.doSpectrum.connect_signal( - "commandBeginWaitReply", self.spectrumCommandStarted - ) - self.doSpectrum.connect_signal("commandFailed", self.spectrumCommandFailed) - self.doSpectrum.connect_signal( - "commandAborted", self.spectrumCommandAborted - ) - self.doSpectrum.connect_signal("commandReady", self.spectrumCommandReady) - self.doSpectrum.connect_signal( - "commandNotReady", self.spectrumCommandNotReady - ) - except AttributeError as diag: - logging.getLogger().warning( - "XRFSpectrum: error initializing energy spectrum (%s)" % str(diag) - ) - self.doSpectrum = None - else: - self.doSpectrum.connect_signal("connected", self.sConnected) - self.doSpectrum.connect_signal("disconnected", self.sDisconnected) - - if HWR.beamline.lims is None: - logging.getLogger().warning( - "XRFSpectrum: you should specify the database hardware object" - ) - self.spectrumInfo = None - - try: - self.ctrl_hwobj = self.get_object_by_role("controller") - except Exception: - self.ctrl_hwobj = None - - try: - self.mca_hwobj = self.get_object_by_role("mca") - # self.mca_hwobj.set_calibration(calib_cf=[0,0.008324,2.223e-06]) - self.mca_hwobj.set_calibration(calib_cf=self.mca_hwobj.calib_cf) - except Exception: - self.mca_hwobj = None - - try: - self.datapath = self.get_property("datapath") - except Exception: - self.datapath = "/data/pyarch/" - - try: - self.cfgpath = self.get_property("cfgpath") - except Exception: - self.cfgpath = "/users/blissadm/local/userconf" - - if self.is_connected(): - self.sConnected() - - def is_connected(self): - try: - return self.doSpectrum.is_connected() - except Exception: - return False - - # Handler for spec connection - def sConnected(self): - self.emit("connected", ()) - # curr = self.getSpectrumParams() - - # Handler for spec disconnection - def sDisconnected(self): - self.emit("disconnected", ()) - - # Energy spectrum commands - def canSpectrum(self): - if not self.is_connected(): - return False - return self.doSpectrum is not None - - def startXrfSpectrum( - self, ct, directory, prefix, session_id=None, blsample_id=None - ): - self.spectrumInfo = {"sessionId": session_id, "blSampleId": blsample_id} - self.spectrumCommandStarted() - if not os.path.isdir(directory): - logging.getLogger().debug("XRFSpectrum: creating directory %s" % directory) - try: - os.makedirs(directory) - except OSError as diag: - logging.getLogger().error( - "XRFSpectrum: error creating directory %s (%s)" - % (directory, str(diag)) - ) - self.spectrumStatusChanged("Error creating directory") - return False - - curr = self.getSpectrumParams() - - try: - curr["escan_dir"] = directory - curr["escan_prefix"] = prefix - except TypeError: - curr = {} - curr["escan_dir"] = directory - curr["escan_prefix"] = prefix - - a = directory.split(os.path.sep) - suffix_path = os.path.join(*a[4:]) - if "inhouse" in a: - a_dir = os.path.join(self.datapath, a[2], suffix_path) - else: - a_dir = os.path.join(self.datapath, a[4], a[3], *a[5:]) - if a_dir[-1] != os.path.sep: - a_dir += os.path.sep - if not os.path.exists(a_dir): - try: - # logging.getLogger().debug("XRFSpectrum: creating %s", a_dir) - os.makedirs(a_dir) - except OSError as diag: - logging.getLogger().error( - "XRFSpectrum: error creating directory %s (%s)" % (a_dir, str(diag)) - ) - self.spectrumStatusChanged("Error creating directory") - return False - - filename_pattern = os.path.join( - directory, "%s_%s_%%02d" % (prefix, time.strftime("%d_%b_%Y")) - ) - aname_pattern = os.path.join( - "%s/%s_%s_%%02d" % (a_dir, prefix, time.strftime("%d_%b_%Y")) - ) - - filename_pattern = os.path.extsep.join((filename_pattern, "dat")) - html_pattern = os.path.extsep.join((aname_pattern, "html")) - aname_pattern = os.path.extsep.join((aname_pattern, "png")) - filename = filename_pattern % 1 - aname = aname_pattern % 1 - htmlname = html_pattern % 1 - - i = 2 - while os.path.isfile(filename): - filename = filename_pattern % i - aname = aname_pattern % i - htmlname = html_pattern % i - i = i + 1 - - self.spectrumInfo["filename"] = filename - # self.spectrumInfo["scanFileFullPath"] = filename - self.spectrumInfo["jpegScanFileFullPath"] = aname - self.spectrumInfo["exposureTime"] = ct - self.spectrumInfo["annotatedPymcaXfeSpectrum"] = htmlname - logging.getLogger().debug("XRFSpectrum: archive file is %s", aname) - - gevent.spawn(self.reallyStartXrfSpectrum, ct, filename) - - return True - - def reallyStartXrfSpectrum(self, ct, filename): - - if self.doSpectrum: - try: - res = self.doSpectrum(ct, filename, wait=True) - except Exception: - logging.getLogger().exception("XRFSpectrum: problem calling spec macro") - self.spectrumStatusChanged("Error problem spec macro") - else: - self.spectrumCommandFinished(res) - else: - try: - res = self._doSpectrum(ct, filename, wait=True) - except Exception: - logging.getLogger().exception("XRFSpectrum: problem calling procedure") - self.spectrumStatusChanged("Error problem with spectrum procedure") - else: - self.spectrumCommandFinished(res) - - def cancelXrfSpectrum(self, *args): - if self.scanning: - self.doSpectrum.abort() - - def spectrumCommandReady(self): - if not self.scanning: - self.emit("xrfSpectrumReady", (True,)) - self.emit("xrfScanReady", (True,)) - - def spectrumCommandNotReady(self): - if not self.scanning: - self.emit("xrfSpectrumReady", (False,)) - self.emit("xrfScanReady", (False,)) - - def spectrumCommandStarted(self, *args): - self.spectrumInfo["startTime"] = time.strftime("%Y-%m-%d %H:%M:%S") - self.scanning = True - self.emit("xrfSpectrumStarted", ()) - self.emit("xrfScanStarted", ()) - - def spectrumCommandFailed(self, *args): - self.spectrumInfo["endTime"] = time.strftime("%Y-%m-%d %H:%M:%S") - self.scanning = False - self.storeXrfSpectrum() - self.emit("xrfSpectrumFailed", ()) - self.emit("xrfScanFailed", ()) - self.ready_event.set() - - def spectrumCommandAborted(self, *args): - self.scanning = False - self.emit("xrfSpectrumFailed", ()) - self.emit("xrfScanFailed", ()) - self.ready_event.set() - - def spectrumCommandFinished(self, result): - self.spectrumInfo["endTime"] = time.strftime("%Y-%m-%d %H:%M:%S") - logging.getLogger().debug("XRFSpectrum: XRF spectrum result is %s" % result) - self.scanning = False - - if result: - try: - mcaData = self.get_channel_object("mca_data").get_value() - mcaCalib = self.get_channel_object("calib_data").get_value() - except Exception: - mcaData = self.mca_hwobj.read_data(save_data=True) - mcaCalib = self.mca_hwobj.get_calibration() - try: - mcaConfig = self.get_channel_object("config_data").get_value() - self.spectrumInfo["beamTransmission"] = mcaConfig["att"] - self.spectrumInfo["energy"] = mcaConfig["energy"] - self.spectrumInfo["beamSizeHorizontal"] = float(mcaConfig["bsX"]) - self.spectrumInfo["beamSizeVertical"] = float(mcaConfig["bsY"]) - except Exception: - mcaConfig = {} - # self.spectrumInfo["beamTransmission"] = self.transmission_hwobj.get_value() - self.spectrumInfo["energy"] = HWR.beamline.energy.get_value() - beam_info = HWR.beamline.beam.get_beam_info() - self.spectrumInfo["beamSizeHorizontal"] = beam_info["size_x"] - self.spectrumInfo["beamSizeVertical"] = beam_info["size_y"] - mcaConfig["att"] = self.spectrumInfo["beamTransmission"] - mcaConfig["energy"] = self.spectrumInfo["energy"] - mcaConfig["bsX"] = self.spectrumInfo["beamSizeHorizontal"] - mcaConfig["bsY"] = self.spectrumInfo["beamSizeVertical"] - roi = self.mca_hwobj.get_roi() - mcaConfig["min"] = roi["chmin"] - mcaConfig["max"] = roi["chmax"] - mcaConfig["legend"] = self.spectrumInfo["annotatedPymcaXfeSpectrum"] - mcaConfig["htmldir"], _ = os.path.split(mcaConfig["legend"]) - mcaConfig["file"] = self._get_cfgfile(self.spectrumInfo["energy"]) - - # here move the png file - pf = self.spectrumInfo["filename"].split(".") - pngfile = os.path.extsep.join((pf[0], "png")) - if os.path.isfile(pngfile) is True: - try: - copy(pngfile, self.spectrumInfo["jpegScanFileFullPath"]) - except Exception: - logging.getLogger().error("XRFSpectrum: cannot copy %s", pngfile) - - logging.getLogger().debug("finished %r", self.spectrumInfo) - self.storeXrfSpectrum() - # self.emit('xrfSpectrumFinished', (mcaData,mcaCalib,mcaConfig)) - self.emit("xrfScanFinished", (mcaData, mcaCalib, mcaConfig)) - else: - self.spectrumCommandFailed() - self.ready_event.set() - - def spectrumStatusChanged(self, status): - self.emit("xrfScanStatusChanged", (status,)) - self.emit("spectrumStatusChanged", (status,)) - - def storeXrfSpectrum(self): - logging.getLogger().debug("db connection %r", HWR.beamline.lims) - logging.getLogger().debug("spectrum info %r", self.spectrumInfo) - if HWR.beamline.lims is None: - return - try: - int(self.spectrumInfo["sessionId"]) - except Exception: - return - self.spectrumInfo["blSampleId"] - self.spectrumInfo.pop("blSampleId") - - HWR.beamline.lims.storeXfeSpectrum(self.spectrumInfo) - - def updateXrfSpectrum(self, spectrum_id, jpeg_spectrum_filename): - pass - - def getSpectrumParams(self): - if self.energySpectrumArgs: - try: - self.curr = self.energySpectrumArgs.get_value() - return self.curr - except Exception: - logging.getLogger().exception( - "XRFSpectrum: error getting xrfspectrum parameters" - ) - self.spectrumStatusChanged("Error getting xrfspectrum parameters") - return False - else: - return True - - def setSpectrumParams(self, pars): - self.energySpectrumArgs.set_value(pars) - - def _get_cfgfile(self, energy): - if energy > 12.0: - cfgname = "15" - elif energy > 10.0: - cfgname = "12" - elif energy > 7.0: - cfgname = "10" - else: - cfgname = "7" - return os.path.join(self.cfgpath, "%skeV.cfg" % cfgname) - - def _doSpectrum(self, ct, filename, wait=True): - HWR.beamline.energy.get_value() - if not ct: - ct = 5 - safshut = HWR.beamline.safety_shutter - # stop the procedure if hutch not searched - stat = safshut.getShutterState() - if stat == "disabled": - logging.getLogger("user_level_log").exception( - "XRFSpectrum: hutch not searched, exiting" - ) - return False - - fluodet_ctrl = self.get_object_by_role("fluodet_ctrl") - fluodet_ctrl.actuatorIn() - # open the safety and the fast shutter - safshut.openShutter() - init_transm = HWR.beamline.transmission.get_value() - ret = self._findAttenuation(ct) - self.ctrl_hwobj.diffractometer.msclose() - fluodet_ctrl.actuatorOut() - HWR.beamline.transmission.set_value(init_transm) - return ret - - def _findAttenuation(self, ct): - tf = [0.1, 0.2, 0.3, 0.9, 1.3, 1.9, 2.6, 4.3, 6, 8, 12, 24, 36, 50, 71] - min_cnt = self.get_property("min_cnt") - max_cnt = self.get_property("max_cnt") - self.mca_hwobj.set_roi(2, 15, channel=1) - print(self.spectrumInfo["filename"]) - self.mca_hwobj.set_presets( - erange=1, ctime=ct, fname=self.spectrumInfo["filename"] - ) - - # put in max attenuation - HWR.beamline.transmission.set_value(0) - - self.ctrl_hwobj.diffractometer.msopen() - self.mca_hwobj.start_acq() - time.sleep(ct) - ic = sum(self.mca_hwobj.read_roi_data()) / ct - print(ic) - if ic > max_cnt: - self.ctrl_hwobj.diffractometer.msclose() - logging.getLogger("user_level_log").exception( - "The detector is saturated, giving up." - ) - return False - for i in tf: - self.mca_hwobj.clear_spectrum() - logging.getLogger("user_level_log").info("Setting transmission to %g" % i) - HWR.beamline.transmission.set_value(i) - self.mca_hwobj.start_acq() - time.sleep(ct) - ic = sum(self.mca_hwobj.read_roi_data()) / ct - print(ic) - if ic > min_cnt: - self.ctrl_hwobj.diffractometer.msclose() - self.spectrumInfo["beamTransmission"] = ( - HWR.beamline.transmission.get_value() - ) - logging.getLogger("user_level_log").info( - "Transmission used for spectra: %g" - % self.spectrumInfo["beamTransmission"] - ) - break - self.ctrl_hwobj.diffractometer.msclose() - if ic < min_cnt: - logging.getLogger("user_level_log").exception( - "Could not find satisfactory attenuation (is the mca properly set up?), giving up." - ) - return False - return True diff --git a/mxcubecore/HardwareObjects/ESRF/ID30HutchTrigger.py b/mxcubecore/HardwareObjects/ESRF/ID30HutchTrigger.py deleted file mode 100644 index 0cc60455cb..0000000000 --- a/mxcubecore/HardwareObjects/ESRF/ID30HutchTrigger.py +++ /dev/null @@ -1,113 +0,0 @@ -import logging -import sys -import time - -import gevent -import PyTango.gevent - -from mxcubecore import BaseHardwareObjects - - -class ID30HutchTrigger(BaseHardwareObjects.HardwareObject): - def __init__(self, name): - BaseHardwareObjects.HardwareObject.__init__(self, name) - - def _do_polling(self): - while True: - try: - self.poll() - except Exception: - sys.excepthook(*sys.exc_info()) - time.sleep(self.get_property("interval") / 1000.0 or 1) - - def init(self): - try: - self.device = PyTango.gevent.DeviceProxy(self.get_property("tangoname")) - except PyTango.DevFailed as traceback: - last_error = traceback[-1] - logging.getLogger("HWR").error( - "%s: %s", str(self.name()), last_error["desc"] - ) - self.device = None - self.device.imported = False - else: - self.device.imported = True - - self.pollingTask = None - self.initialized = False - self.__oldValue = None - self.card = None - self.channel = None - - PSSinfo = self.get_property("pss") - try: - self.card, self.channel = map(int, PSSinfo.split("/")) - except Exception: - logging.getLogger().error("%s: cannot find PSS number", self.name()) - return - - if self.device is not None: - self.pollingTask = gevent.spawn(self._do_polling) - - self.connected() - - def hutchIsOpened(self): - return self.hutch_opened - - def is_connected(self): - return True - - def connected(self): - self.emit("connected") - - def disconnected(self): - self.emit("disconnected") - - def abort(self): - pass - - def macro(self, entering_hutch, old={"dtox": None, "aperture": None}): - logging.info( - "%s: %s hutch", self.name(), "entering" if entering_hutch else "leaving" - ) - eh_controller = self.get_object_by_role("eh_controller") - if not entering_hutch: - if old["dtox"] is not None: - eh_controller.DtoX.set_value(old["dtox"], wait=False) - if self.get_object_by_role("aperture") and old["aperture"] is not None: - self.get_object_by_role("aperture").moveToPosition(old["aperture"]) - self.get_object_by_role("beamstop").moveToPosition("in") - eh_controller.DtoX.wait_move() - else: - old["dtox"] = eh_controller.DtoX.position() - if self.get_object_by_role("aperture"): - old["aperture"] = self.get_object_by_role("aperture").get_value() - eh_controller.DtoX.set_value(700, wait=False) - if self.get_object_by_role("aperture"): - self.get_object_by_role("aperture").moveToPosition("Outbeam") - self.get_object_by_role("beamstop").moveToPosition("out") - eh_controller.detcover.set_in() - eh_controller.DtoX.wait_move() - - def poll(self): - a = self.device.GetInterlockState([self.card - 1, 2 * (self.channel - 1)])[0] - b = self.device.GetInterlockState([self.card - 1, 2 * (self.channel - 1) + 1])[ - 0 - ] - value = a & b - - if value == self.__oldValue: - return - else: - self.__oldValue = value - - self.value_changed(value) - - def value_changed(self, value, *args): - if value == 0: - if self.initialized: - self.emit("hutchTrigger", (1,)) - elif value == 1 and self.initialized: - self.emit("hutchTrigger", (0,)) - self.hutch_opened = 1 - value - self.initialized = True diff --git a/mxcubecore/HardwareObjects/LimaJungfrauDetector.py b/mxcubecore/HardwareObjects/LimaJungfrauDetector.py deleted file mode 100644 index 881ecf1f2d..0000000000 --- a/mxcubecore/HardwareObjects/LimaJungfrauDetector.py +++ /dev/null @@ -1,217 +0,0 @@ -import logging -import os -import subprocess -import time - -import gevent - -from mxcubecore.BaseHardwareObjects import HardwareObjectState -from mxcubecore.CommandContainer import ConnectionError -from mxcubecore.HardwareObjects.abstract.AbstractDetector import AbstractDetector - - -class LimaJungfrauDetector(AbstractDetector): - def __init__(self, name): - AbstractDetector.__init__(self, name) - self.header = dict() - self.start_angles = list() - - def init(self): - AbstractDetector.init(self) - lima_device = self.get_property("lima_device", "") - - if not lima_device: - return - - t = lima_device.split("/") - t[-2] = "mask" - mask_device = "/".join(t) - - try: - for channel_name in ( - "latency_time", - "State", - "acq_status", - "acq_trigger_mode", - "saving_mode", - "acq_nb_frames", - "acq_expo_time", - "saving_directory", - "saving_prefix", - "saving_suffix", - "saving_next_number", - "saving_index_format", - "saving_format", - "saving_overwrite_policy", - "saving_header_delimiter", - "saving_frame_per_file", - "last_image_saved", - "image_roi", - ): - self.add_channel( - {"type": "tango", "name": channel_name, "tangoname": lima_device}, - channel_name, - ) - - self.add_channel( - {"type": "tango", "name": "mask_file", "tangoname": mask_device}, - "MaskFile", - ) - self.add_channel( - {"type": "tango", "name": "mask_run_level", "tangoname": mask_device}, - "RunLevel", - ) - self.add_command( - {"type": "tango", "name": "start_mask", "tangoname": mask_device}, - "Start", - ) - self.add_command( - {"type": "tango", "name": "stop_mask", "tangoname": mask_device}, - "Stop", - ) - - self.add_command( - {"type": "tango", "name": "prepare_acq", "tangoname": lima_device}, - "prepareAcq", - ) - self.add_command( - {"type": "tango", "name": "start_acq", "tangoname": lima_device}, - "startAcq", - ) - self.add_command( - {"type": "tango", "name": "stop_acq", "tangoname": lima_device}, - "stopAcq", - ) - self.add_command( - {"type": "tango", "name": "reset", "tangoname": lima_device}, "reset" - ) - self.add_command( - {"type": "tango", "name": "set_image_header", "tangoname": lima_device}, - "SetImageHeader", - ) - - # prepareAcq can block after large data transfers (buffered by GPFS): 2 min timeout - self.get_command_object("prepare_acq").set_device_timeout(2 * 60 * 1000) - self._emit_status() - - except ConnectionError: - self.update_state(HardwareObjectState.FAULT) - logging.getLogger("HWR").error( - "Could not connect to detector %s" % lima_device - ) - self._emit_status() - - def has_shutterless(self): - return True - - def wait_ready(self, timeout=3500): - with gevent.Timeout(timeout, RuntimeError("Detector not ready")): - while self.get_channel_value("acq_status") != "Ready": - time.sleep(1) - - def last_image_saved(self): - try: - img = self.get_channel_object("last_image_saved").get_value() + 1 - return img - except Exception: - return 0 - - def get_deadtime(self): - return float(self.get_property("deadtime")) - - def prepare_acquisition(self, number_of_images, exptime, data_root_path, prefix): - self.set_channel_value("acq_trigger_mode", "EXTERNAL_TRIGGER_MULTI") - - self.set_channel_value("acq_nb_frames", number_of_images) - self.set_channel_value("acq_expo_time", exptime) - self.set_channel_value("latency_time", 990e-6) - self.set_channel_value("saving_frame_per_file", 1000) - - mask_file = self.get_property("mask_file", None) - - if mask_file: - self.set_channel_value("mask_file", mask_file) - - self.set_channel_value("mask_run_level", 0) - - self.set_detector_filenames(data_root_path, prefix) - - def find_next_pedestal_dir(self, data_root_path, subdir): - _index = 1 - _indes_str = "%04d" % _index - fpath = os.path.join(data_root_path, f"{subdir}_{_indes_str}") - - while os.path.exists(fpath): - _index += 1 - _indes_str = "%04d" % _index - fpath = os.path.join(data_root_path, f"{subdir}_{_indes_str}") - - return fpath - - def set_detector_filenames(self, data_root_path, prefix): - subprocess.Popen( - "mkdir --parents %s" % (data_root_path), - shell=True, - stdin=None, - stdout=None, - stderr=None, - close_fds=True, - ).wait() - - subprocess.Popen( - "chmod -R 755 %s" % (data_root_path), - shell=True, - stdin=None, - stdout=None, - stderr=None, - close_fds=True, - ).wait() - - self.set_channel_value("saving_mode", "AUTO_FRAME") - self.set_channel_value("saving_directory", data_root_path) - self.set_channel_value("saving_prefix", prefix) - self.set_channel_value("saving_format", "HDF5BS") - - def start_acquisition(self): - self.wait_ready() - self.execute_command("stop_acq") - self.execute_command("start_mask") - self.execute_command("prepare_acq") - self.execute_command("start_acq") - self._emit_status() - - def stop_acquisition(self): - try: - self.execute_command("stop_acq") - except Exception: - pass - finally: - self.wait_ready() - self.execute_command("reset") - self.wait_ready() - self.execute_command("stop_mask") - - self._emit_status() - - def reset(self): - self.stop_acquisition() - - @property - def status(self): - try: - acq_status = self.get_channel_value("acq_status") - except Exception: - acq_status = "OFFLINE" - - status = { - "acq_satus": acq_status.upper(), - } - - return status - - def _emit_status(self): - self.emit("statusChanged", self.status) - - def restart(self) -> None: - self.reset() - return None diff --git a/mxcubecore/HardwareObjects/MicrodiffActuator.py b/mxcubecore/HardwareObjects/MicrodiffActuator.py index f7314293fc..cc9691f828 100644 --- a/mxcubecore/HardwareObjects/MicrodiffActuator.py +++ b/mxcubecore/HardwareObjects/MicrodiffActuator.py @@ -3,7 +3,7 @@ If private_state not specified, True will be send to set in and False for out. Example xml file: - Scintilator + Scintillator wid30bmd2s:9001 ScintillatorPosition {"PARK":"out", "SCINTILLATOR":"in"} diff --git a/mxcubecore/HardwareObjects/sample_centring.py b/mxcubecore/HardwareObjects/sample_centring.py index a69d608400..dcd4715976 100644 --- a/mxcubecore/HardwareObjects/sample_centring.py +++ b/mxcubecore/HardwareObjects/sample_centring.py @@ -65,15 +65,22 @@ def __getattr__(self, attr): def prepare(centring_motors_dict): - logging.debug("Preparing for centring") + logging.getLogger("HWR").debug("Preparing for centring") global SAVED_INITIAL_POSITIONS + global USER_CLICKED_EVENT + global READY_FOR_NEXT_POINT if CURRENT_CENTRING and not CURRENT_CENTRING.ready(): + logging.getLogger("HWR").debug("DEBUG: ENDING CURRENT CENTRING") end() - global USER_CLICKED_EVENT - global READY_FOR_NEXT_POINT + if USER_CLICKED_EVENT and not USER_CLICKED_EVENT.ready(): + logging.getLogger("HWR").debug("DEBUG: USER_CLICKED_EVENT: false") + + # Clear ready flag in case it was stuck + USER_CLICKED_EVENT.set() + USER_CLICKED_EVENT = gevent.event.AsyncResult() READY_FOR_NEXT_POINT = gevent.event.Event() @@ -275,7 +282,7 @@ def centre_plate1Click( READY_FOR_NEXT_POINT.set() i += 1 except Exception: - logging.exception("Exception while centring") + logging.getLogger("HWR").exception("Exception while centring") move_motors(SAVED_INITIAL_POSITIONS) raise RuntimeError("Exception while centring") @@ -327,11 +334,11 @@ def centre_plate( READY_FOR_NEXT_POINT.set() i += 1 except Exception: - logging.exception("Exception while centring") + logging.getLogger("HWR").exception("Exception while centring") move_motors(SAVED_INITIAL_POSITIONS) raise - # logging.info("X=%s,Y=%s", X, Y) + # logging.getLogger("HWR").info("X=%s,Y=%s", X, Y) chi_angle = math.radians(chi_angle) chiRotMatrix = numpy.matrix( [ @@ -386,7 +393,10 @@ def centre_plate( def ready(motor_list): - return all([m.is_ready() for m in motor_list]) + logging.getLogger("HWR").info([m.actuator_name for m in motor_list]) + rstate = [m._ready() for m in motor_list] + logging.getLogger("HWR").info(rstate) + return all(rstate) def wait_ready(motor_positions_dict, timeout=None): @@ -410,7 +420,9 @@ def move_motors(motor_positions_dict): def user_click(x, y, wait=False): READY_FOR_NEXT_POINT.clear() USER_CLICKED_EVENT.set((x, y)) + logging.getLogger("HWR").debug(f"Clicked registred at {x} {y}") if wait: + logging.getLogger("HWR").debug(f"Waiting for rotation ...") READY_FOR_NEXT_POINT.wait() @@ -437,8 +449,12 @@ def center( i = 0 while i < n_points: try: + logging.getLogger("HWR").debug("Waiting for click") x, y = USER_CLICKED_EVENT.get() except Exception: + logging.getLogger("HWR").exception( + "Aborted while waiting for point selection" + ) raise RuntimeError("Aborted while waiting for point selection") USER_CLICKED_EVENT = gevent.event.AsyncResult() X.append(x / float(pixelsPerMm_Hor)) @@ -448,13 +464,14 @@ def center( phi.set_value_relative(phi.direction * phi_angle, timeout=10) READY_FOR_NEXT_POINT.set() i += 1 + logging.getLogger("HWR").debug(f"Click at {x}, {y}") except Exception: - logging.exception("Exception while centring") + logging.getLogger("HWR").exception("Exception while centring") move_motors(SAVED_INITIAL_POSITIONS) READY_FOR_NEXT_POINT.set() raise RuntimeError("Exception while centring") - # logging.info("X=%s,Y=%s", X, Y) + logging.getLogger("HWR").debug("X=%s,Y=%s", X, Y) chi_angle = math.radians(chi_angle) chiRotMatrix = numpy.matrix( [ @@ -500,12 +517,13 @@ def center( def end(centred_pos=None): if centred_pos is None: - centred_pos = CURRENT_CENTRING.get() + centred_pos = CURRENT_CENTRING.get(timeout=1) try: move_motors(centred_pos) except Exception: READY_FOR_NEXT_POINT.set() move_motors(SAVED_INITIAL_POSITIONS) + logging.getLogger("HWR").exception("") raise RuntimeError("Centring aborted") @@ -631,10 +649,10 @@ def auto_center( x, y = find_loop( sample_view, pixelsPerMm_Hor, chi_angle, msg_cb, new_point_cb ) - # logging.info("in autocentre, x=%f, y=%f",x,y) + logging.getLogger("HWR").info("Lucid found loop at, x=%f, y=%f", x, y) if x < 0 or y < 0: for i in range(1, 18): - # logging.info("loop not found - moving back %d" % i) + logging.getLogger("HWR").info("loop not found - moving back %d" % i) phi.set_value_relative(5) x, y = find_loop( sample_view, @@ -660,6 +678,9 @@ def auto_center( break if -1 in (x, y): centring_greenlet.kill() + logging.getLogger("HWR").debug( + f"DEBUG: Incorrect position from auto loop centring {(x,y)}" + ) raise RuntimeError("Could not centre sample automatically.") phi.set_value_relative(-i * 5) else: diff --git a/mxcubecore/configuration/esrf_id29/udiff_scint.xml b/mxcubecore/configuration/esrf_id29/udiff_scint.xml index f9f62542a2..695e337576 100644 --- a/mxcubecore/configuration/esrf_id29/udiff_scint.xml +++ b/mxcubecore/configuration/esrf_id29/udiff_scint.xml @@ -1,5 +1,5 @@ - Scintilator + Scintillator lid292:exp scinton scintoff