class CreateDiscreteWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, Qt.WindowFlags(fl),
                                "Standart")

        if not name:
            self.setObjectName("create_discrete_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget = AcquisitionWidget(
            self,
            "acquisition_widget",
            layout='vertical',
            acq_params=self._acquisition_parameters,
            path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self,
                                                'create_dc_path_widget',
                                                data_model=self._path_template,
                                                layout='vertical')

        self._processing_widget = ProcessingWidget(
            self, data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)

        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._processing_widget.enableProcessingSignal.connect(\
             self._run_processing_toggled)
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.clicked.\
             connect(self.set_max_osc_total_range_clicked)

        # Other ---------------------------------------------------------------
        #self._processing_widget.processing_widget.\
        #     run_processing_parallel_cbox.hide()

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )

        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_acquisition_values")

    def set_tunable_energy(self, state):
        """
        Descript. :
        """
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(
                self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()
            self._acq_widget.use_kappa(False)

            if not dc.is_helical():
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[
                    0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                #self._acq_widget.disable_inverse_beam(True)

                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[
                    0].acquisition_parameters
                self._acq_widget.update_data_model(
                    self._acquisition_parameters, self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(
                    self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)

        try:
            #This is very EMBL specific and soon will be removed
            if self._beamline_setup_hwobj.detector_hwobj.get_roi_mode_name(
            ) == "16M":
                file_size = 18.
                total_num_of_images = 14400
            else:
                file_size = 18. / 4
                total_num_of_images = 14400 * 4

            num_images = float(
                self._acq_widget.acq_widget_layout.num_images_ledit.text())
            total, free, perc = self._beamline_setup_hwobj.machine_info_hwobj.get_ramdisk_size(
            )
            free_mb = free / (2**20)

            if num_images > total_num_of_images * free_mb / (125.8 * 1024):
                msg = "Ramdisk size (%d GB) is not enough to run the collection with " % (
                    free_mb / 1024)
                msg += "%d frames." % num_images
                logging.getLogger("GUI").error(msg)
                result = False
        except:
            pass

        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if isinstance(shape, GraphicsItemPoint):
            snapshot = self._graphics_manager_hwobj.get_scene_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot
        else:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot(
            )

        tasks.extend(self.create_dc(sample, cpos=cpos))
        self._path_template.run_number += 1

        return tasks

    def create_dc(self,
                  sample,
                  run_number=None,
                  start_image=None,
                  num_images=None,
                  osc_start=None,
                  sc=None,
                  cpos=None,
                  inverse_beam=False):
        """
        Descript. :
        """
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)

        if run_number:
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.NATIVE
        dc.run_processing_after = self._processing_widget.processing_widget.\
           run_processing_after_cbox.isChecked()
        dc.run_processing_parallel = self._processing_widget.processing_widget.\
           run_processing_parallel_cbox.isChecked() and \
           acq.acquisition_parameters.num_images > 19

        tasks.append(dc)

        return tasks

    def execute_task(self, sample):
        #All this should be in queue_entry level
        group_data = {
            'sessionId': self._session_hwobj.session_id,
            'experimentType': 'OSC'
        }
        gid = self._beamline_setup_hwobj.lims_client_hwobj.\
              _store_data_collection_group(group_data)
        sample.lims_group_id = gid

        task_list = self._create_task(sample, None)
        task_list[0].lims_group_id = gid

        param_list = queue_model_objects.to_collect_dict(task_list[0], \
                       self._session_hwobj, sample, None)

        self._beamline_setup_hwobj.collect_hwobj.collect(\
             queue_model_enumerables.COLLECTION_ORIGIN_STR.MXCUBE, param_list)

    def set_max_osc_total_range_clicked(self):
        num_images = int(
            self._acq_widget.acq_widget_layout.num_images_ledit.text())
        (lower,
         upper), exp_time = self._acq_widget.update_osc_total_range_limits()
        self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
            "%.2f" % lower)
        self._acq_widget.acq_widget_layout.osc_total_range_ledit.setText(\
            "%.2f" % abs(upper - lower))
        self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
            "%d" % (abs(upper - lower) / float(self._acq_widget.acq_widget_layout.osc_range_ledit.text())))
class CreateDiscreteWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, 
            QtCore.Qt.WindowFlags(fl), "Standart")

        if not name:
            self.setObjectName("create_discrete_widget")
        self.init_models()

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.previous_energy = None
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget =  AcquisitionWidget(self, "acquisition_widget",
             layout='vertical', acq_params=self._acquisition_parameters,
             path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self, 'create_dc_path_widget',
            data_model=self._path_template, layout='vertical')

        self._processing_widget = ProcessingWidget(self,
             data_model=self._processing_parameters)
       
        # Layout --------------------------------------------------------------
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0,0,0,0)

        # SizePolicies --------------------------------------------------------
        
        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.acq_parameters_changed)

        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._processing_widget.enableProcessingSignal.connect(\
             self._run_processing_toggled)

        # Other ---------------------------------------------------------------
        self._processing_widget.processing_widget.\
             run_processing_parallel_cbox.hide()

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters()

    def set_tunable_energy(self, state):
        """
        Descript. :
        """
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()

            if not dc.is_helical():
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                #self._acq_widget.disable_inverse_beam(True)
                
                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[0].acquisition_parameters
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if isinstance(shape, GraphicsItemPoint):
            snapshot = self._graphics_manager_hwobj.get_scene_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot
        else:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot() 

        tasks.extend(self.create_dc(sample, cpos=cpos))
        self._path_template.run_number += 1

        return tasks
    
    def create_dc(self, sample, run_number = None, start_image = None,
                  num_images = None, osc_start = None, sc = None,
                  cpos=None, inverse_beam = False):
        """
        Descript. :
        """
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)

        if run_number:        
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.NATIVE
        dc.run_processing_after = self._processing_widget.processing_widget.\
           run_processing_after_cbox.isChecked()
        dc.run_processing_parallel = False

        tasks.append(dc)

        return tasks

    def execute_task(self, sample):
        #All this should be in queue_entry level
        group_data = {'sessionId': self._session_hwobj.session_id,
                      'experimentType': 'OSC'}
        gid = self._beamline_setup_hwobj.lims_client_hwobj.\
              _store_data_collection_group(group_data)
        sample.lims_group_id = gid

        task_list = self._create_task(sample, None)
        task_list[0].lims_group_id = gid
       
        param_list = queue_model_objects.to_collect_dict(task_list[0], \
                       self._session_hwobj, sample, None)

        self._beamline_setup_hwobj.collect_hwobj.collect(\
             queue_model_enumerables.COLLECTION_ORIGIN_STR.MXCUBE, param_list)
class CreateEnergyScanWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Energy scan')

        if not name:
            self.setObjectName("create_energy_scan_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._periodic_table_widget = PeriodicTableWidget(self)
        self._data_path_widget = DataPathWidget(self,
                                                data_model=self._path_template,
                                                layout='vertical')

        _parameters_gbox = QGroupBox('Parameters', self)
        self._adjust_transmission_cbox = QCheckBox(\
             "Adjust transmission", _parameters_gbox)
        self._adjust_transmission_cbox.setChecked(False)
        self._adjust_transmission_cbox.setEnabled(True)
        self._max_transmission_label = QLabel("Maximum transmission:")
        self._max_transmission_ledit = QLineEdit("20", _parameters_gbox)
        self._max_transmission_ledit.setFixedWidth(80)
        self._max_transmission_ledit.setEnabled(False)

        # Layout --------------------------------------------------------------
        _parameters_gbox_hlayout = QGridLayout(_parameters_gbox)
        _parameters_gbox_hlayout.addWidget(self._adjust_transmission_cbox, 0,
                                           0)
        _parameters_gbox_hlayout.addWidget(self._max_transmission_label, 1, 0)
        _parameters_gbox_hlayout.addWidget(self._max_transmission_ledit, 1, 1)
        _parameters_gbox_hlayout.setColumnStretch(2, 1)
        _parameters_gbox_hlayout.setSpacing(2)

        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._periodic_table_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(_parameters_gbox)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)
        _main_vlayout.setSpacing(6)
        _main_vlayout.addStretch(10)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        #self._periodic_table_widget.elementEdgeSelectedSignal.connect(\
        #     self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.connect(\
             self.path_template_changed)
        self._adjust_transmission_cbox.stateChanged.connect(\
             self.adjust_transmission_state_changed)
        self._max_transmission_ledit.textEdited.connect(\
             self.max_transmission_value_changed)

    def set_expert_mode(self, state):
        self._adjust_transmission_cbox.setEnabled(state)
        self._max_transmission_label.setEnabled(state)
        self._max_transmission_ledit.setEnabled(state)

    def enable_compression(self, state):
        CreateTaskBase.enable_compression(self, False)

    def set_beamline_setup(self, bl_setup_hwobj):
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._periodic_table_widget.set_elements(\
             self._beamline_setup_hwobj.energyscan_hwobj.getElements())
        self.enable_compression(False)

        try:
            max_transmission_value = self._beamline_setup_hwobj.\
                 energyscan_hwobj.get_max_transmission_value()

            self._adjust_transmission_cbox.setEnabled(True)
            self._adjust_transmission_cbox.setChecked(True)
            self._beamline_setup_hwobj.energyscan_hwobj.adjust_transmission(
                True)

            if max_transmission_value:
                self._max_transmission_ledit.setText("%.2f" %
                                                     max_transmission_value)
        except:
            pass

    def init_models(self):
        """
        Descript. :
        """

        CreateTaskBase.init_models(self)
        self.enery_scan = queue_model_objects.EnergyScan()
        self._path_template.start_num = 1
        self._path_template.num_files = 1
        self._path_template.suffix = 'raw'
        self._path_template.compression = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        escan_model = tree_item.get_model()

        if isinstance(tree_item, Qt4_queue_item.EnergyScanQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if escan_model.get_path_template():
                self._path_template = escan_model.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
        elif not(isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
                     isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem)):
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        base_result = CreateTaskBase.approve_creation(self)
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge(
        )
        if not selected_element:
            logging.getLogger("GUI").\
                warning("No element selected, please select an element.")

        return base_result and selected_element

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge(
        )

        if selected_element:
            if not shape:
                cpos = queue_model_objects.CentredPosition()
                cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot(
                )
            else:
                # Shapes selected and sample is mounted, get the
                # centred positions for the shapes
                if isinstance(shape, GraphicsItemPoint):
                    snapshot = self._graphics_manager_hwobj.\
                           get_scene_snapshot(shape)

                    cpos = copy.deepcopy(shape.get_centred_position())
                    cpos.snapshot_image = snapshot

            path_template = self._create_path_template(sample,
                                                       self._path_template)

            energy_scan = queue_model_objects.EnergyScan(
                sample, path_template, cpos)
            energy_scan.set_name(path_template.get_prefix())
            energy_scan.set_number(path_template.run_number)
            energy_scan.element_symbol = selected_element
            energy_scan.edge = selected_edge

            data_collections.append(energy_scan)
            self._path_template.run_number += 1
        else:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return data_collections

    def element_edge_selected(self, element, edge):
        if len(self._current_selected_items) == 1:
            item = self._current_selected_items[0]
            if isinstance(item, Qt4_queue_item.EnergyScanQueueItem):
                item.get_model().element_symbol = str(element)
                item.get_model().edge = str(edge)

    def adjust_transmission_state_changed(self, state):
        self._max_transmission_ledit.setEnabled(state)
        self._beamline_setup_hwobj.energyscan_hwobj.adjust_transmission(state)

    def max_transmission_value_changed(self, value):
        try:
            max_transmission = float(value)
            self._beamline_setup_hwobj.energyscan_hwobj.set_max_transmission(
                max_transmission)
        except:
            pass
Exemplo n.º 4
0
class CreateDiscreteWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, 
            Qt.WindowFlags(fl), "Standard")

        if not name:
            self.setObjectName("create_discrete_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget =  AcquisitionWidget(self, "acquisition_widget",
             layout='vertical', acq_params=self._acquisition_parameters,
             path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self, 'create_dc_path_widget',
            data_model=self._path_template, layout='vertical')

        self._processing_widget = ProcessingWidget(self,
             data_model=self._processing_parameters)
       
        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(6)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        # SizePolicies --------------------------------------------------------
        
        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)

        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._processing_widget.enableProcessingSignal.connect(\
             self._run_processing_toggled)

        # Other ---------------------------------------------------------------

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        #self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters()

        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_acquisition_values")
            self._processing_widget.processing_widget.run_processing_parallel_cbox.setChecked(\
                self._beamline_setup_hwobj._get_run_processing_parallel())
            
    def set_tunable_energy(self, state):
        """
        Descript. :
        """
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()
            self._acq_widget.use_kappa(False)

            if not dc.is_helical():
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                #self._acq_widget.disable_inverse_beam(True)
                
                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[0].acquisition_parameters
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)

        try:
            #This is very EMBL specific and soon will be removed
            if self._beamline_setup_hwobj.detector_hwobj.get_roi_mode_name() == "16M":
                file_size = 18.
                total_num_of_images = 14400
            else:
                file_size = 18. / 4
                total_num_of_images = 14400 * 4

            num_images = float(self._acq_widget.acq_widget_layout.num_images_ledit.text())
            total, free, perc = self._beamline_setup_hwobj.machine_info_hwobj.get_ramdisk_size()
            free_mb = free / (2 ** 20)

            if num_images > total_num_of_images * free_mb / (125.8 * 1024):
                msg = "Ramdisk size (%d GB) is not enough to run the collection with " % (free_mb / 1024)
                msg += "%d frames." % num_images
                logging.getLogger("GUI").error(msg)
                result = False
        except:
            pass    

        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if isinstance(shape, GraphicsItemPoint):
            snapshot = self._graphics_manager_hwobj.get_scene_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot
        else:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot() 

        tasks.extend(self.create_dc(sample, cpos=cpos))
        self._path_template.run_number += 1

        return tasks
    
    def create_dc(self, sample, run_number = None, start_image = None,
                  num_images = None, osc_start = None, sc = None,
                  cpos=None, inverse_beam = False):
        """
        Descript. :
        """
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)

        if run_number:        
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.NATIVE
        dc.run_processing_after = self._processing_widget.processing_widget.\
           run_processing_after_cbox.isChecked()
        if self._processing_widget.processing_widget.\
           run_processing_parallel_cbox.isChecked():
            dc.run_processing_parallel = "Undefined" 

        tasks.append(dc)

        return tasks

    def execute_task(self, sample):
        #All this should be in queue_entry level
        group_data = {'sessionId': self._session_hwobj.session_id,
                      'experimentType': 'OSC'}
        gid = self._beamline_setup_hwobj.lims_client_hwobj.\
              _store_data_collection_group(group_data)
        sample.lims_group_id = gid

        task_list = self._create_task(sample, None)
        task_list[0].lims_group_id = gid
       
        param_list = queue_model_objects.to_collect_dict(task_list[0], \
                       self._session_hwobj, sample, None)

        self._beamline_setup_hwobj.collect_hwobj.collect(\
             queue_model_enumerables.COLLECTION_ORIGIN_STR.MXCUBE, param_list)

    def set_max_osc_total_range_clicked(self):
        num_images = int(self._acq_widget.acq_widget_layout.num_images_ledit.text())
        (lower, upper), exp_time = self._acq_widget.update_osc_total_range_limits()
        self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
            "%.3f" % (lower + 0.001))
        self._acq_widget.acq_widget_layout.osc_total_range_ledit.setText(\
            "%.3f" % abs(upper - lower))
        self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
            "%d" % (abs(upper - lower) / float(self._acq_widget.acq_widget_layout.osc_range_ledit.text())))
Exemplo n.º 5
0
class CreateHelicalWidget(CreateTaskBase):
    def __init__(self, parent = None,name = None, fl = 0):
        CreateTaskBase.__init__(self, parent, name, fl, 'Helical')

        if not name:
            self.setObjectName("create_helical_widget")
        self.init_models() 
         
        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._lines_map = {}

        # Graphic elements ----------------------------------------------------
        self._lines_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_helical_line_widget_layout.ui"))

        self._acq_widget =  AcquisitionWidget(self, "acquisition_widget",
             layout='vertical', acq_params=self._acquisition_parameters,
             path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self, 'create_dc_path_widget',
             data_model=self._path_template, layout='vertical')

        self._processing_widget = ProcessingWidget(self,
             data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._lines_widget)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._lines_widget.lines_treewidget.itemSelectionChanged.connect(\
             self.lines_treewidget_selection_changed)
        self._lines_widget.create_line_button.clicked.connect(\
             self.create_line_button_clicked)
        self._lines_widget.remove_line_button.clicked.connect(\
             self.remove_line_button_clicked)  
        self._lines_widget.overlay_cbox.stateChanged.connect(\
             self.overlay_toggled)
        self._lines_widget.overlay_slider.valueChanged.connect(\
             self.overlay_alpha_changed)
        self._lines_widget.swap_points_button.clicked.connect(\
             self.swap_points_clicked)

        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.acq_parameters_changed)

        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._processing_widget.enableProcessingSignal.connect(\
             self._run_processing_toggled)

        # Other ---------------------------------------------------------------
        for col in range(self._lines_widget.lines_treewidget.columnCount()):
            self._lines_widget.lines_treewidget.resizeColumnToContents(col)
        #self._processing_widget.processing_widget.\
        #     run_processing_parallel_cbox.setChecked(False)

    def init_models(self):
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters()
  
        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_helical_values")

    def set_beamline_setup(self, bl_setup_hwobj):
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)
       
        # At startup, if scene loaded from file, then update listwidget
        shapes = self._graphics_manager_hwobj.get_shapes()
        for shape in shapes: 
            if isinstance(shape, GraphicsItemLine):
                self.shape_created(shape, "Line")

    def shape_created(self, shape, shape_type):
        if shape_type == "Line":
            self._lines_widget.lines_treewidget.clearSelection()
            info_str_list = QtCore.QStringList()
            info_str_list.append(shape.get_display_name())
            info_str_list.append("%d" % shape.get_points_index()[0])
            info_str_list.append("%d" % shape.get_points_index()[1])
            
            lines_treewidget_item = QtGui.QTreeWidgetItem(\
                self._lines_widget.lines_treewidget,
                info_str_list)
            lines_treewidget_item.setSelected(True)
            self._lines_map[shape] = lines_treewidget_item

            self.lines_treewidget_selection_changed()

    def shape_deleted(self, shape, shape_type):
        if shape_type == "Line" and self._lines_map.get(shape):
            shape_index = self._lines_widget.lines_treewidget.\
                 indexFromItem(self._lines_map[shape])
            self._lines_widget.lines_treewidget.\
                 takeTopLevelItem(shape_index.row())
            self._lines_map.pop(shape)

    def shape_changed(self, shape, shape_type):
        lines_treewidget_item = self._lines_map.get(shape)
        if lines_treewidget_item:
            lines_treewidget_item.setText(1, "%d" % shape.get_points_index()[0])
            lines_treewidget_item.setText(2, "%d" % shape.get_points_index()[1])

    def approve_creation(self):
        base_result = CreateTaskBase.approve_creation(self)
   
        if len(self._lines_widget.lines_treewidget.selectedItems()) == 0:
            logging.getLogger("GUI").\
                warning("No lines selected, please select one or more lines.")
            return False
        else:
            return base_result
            
    def update_processing_parameters(self, crystal):
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def select_shape_with_cpos(self, start_cpos, end_cpos, num_images):
        selected_line = None
        self._lines_widget.overlay_slider.setEnabled(False)
        self._lines_widget.overlay_cbox.setEnabled(False)

        self._graphics_manager_hwobj.de_select_all()
        for shape in self._graphics_manager_hwobj.get_shapes():
            if isinstance(shape, GraphicsItemLine):
                (start_cpos_index, end_cpos_index) = shape.get_points_index()
                if start_cpos_index == start_cpos.index and \
                   end_cpos_index == end_cpos.index:
                    self._graphics_manager_hwobj.select_shape(shape)
                    shape.set_num_images(num_images)
                    selected_line = shape

                    self._lines_widget.overlay_slider.setEnabled(True)
                    self._lines_widget.overlay_cbox.setEnabled(True)

        #de-select previous selected list items and
        #select the current shape (Line).
        """
        for (list_item, shape) in self._lines_map.iteritems():
            if selected_line == shape:
                list_item.setSelected(True)
            else:
                list_item.setSelected(False)
        """

    def single_item_selection(self, tree_item):
        CreateTaskBase.single_item_selection(self, tree_item)
                                                             
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            self._processing_parameters = sample_model.processing_parameters
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_widget.update_data_model(self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            data_collection = tree_item.get_model()

            if data_collection.is_helical():
                self.setDisabled(tree_item.get_model().is_executed())

                self._path_template = data_collection.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)
                self._acquisition_parameters = data_collection.acquisitions[0].\
                                               acquisition_parameters

                if len(data_collection.acquisitions) == 2:
                    start_cpos = data_collection.acquisitions[0].acquisition_parameters.\
                                 centred_position
                    end_cpos = data_collection.acquisitions[1].acquisition_parameters.\
                               centred_position
                    num_images = data_collection.acquisitions[0].acquisition_parameters.\
                                 num_images
                    self.select_shape_with_cpos(start_cpos, end_cpos, num_images)

                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                   self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
                
                self._processing_parameters = data_collection.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):

            self._processing_widget.update_data_model(self._processing_parameters)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
  
    def _create_task(self,  sample, shape):
        data_collections = []

        for shape in self.get_selected_lines():
            snapshot = self._graphics_manager_hwobj.get_scene_snapshot(shape)

            # Acquisition for start position
            start_acq = self._create_acq(sample) 
           
            start_graphical_point, end_graphical_point = \
                shape.get_graphical_points() 

            start_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(start_graphical_point.get_centred_position())
            start_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            start_acq.path_template.suffix = self._session_hwobj.suffix

            # Add another acquisition for the end position
            end_acq = self._create_acq(sample)

            end_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(end_graphical_point.get_centred_position())
            end_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            end_acq.path_template.suffix = self._session_hwobj.suffix

            processing_parameters = copy.deepcopy(self._processing_parameters)

            dc = queue_model_objects.DataCollection([start_acq, end_acq],
                                    sample.crystals[0],
                                    processing_parameters)

            dc.set_name(start_acq.path_template.get_prefix())
            dc.set_number(start_acq.path_template.run_number)
            dc.set_experiment_type(EXPERIMENT_TYPE.HELICAL)
            dc.set_requires_centring(False)
            dc.run_processing_after = self._processing_widget.processing_widget.\
               run_processing_after_cbox.isChecked()
            dc.run_processing_parallel = self._processing_widget.processing_widget.\
               run_processing_parallel_cbox.isChecked()

            data_collections.append(dc)
            self._path_template.run_number += 1

        return data_collections

    def lines_treewidget_selection_changed(self):
        self._lines_widget.remove_line_button.setEnabled(False)
        for shape, list_item in self._lines_map.iteritems():
            self._graphics_manager_hwobj.select_shape(shape, list_item.isSelected())
            self._lines_widget.remove_line_button.setEnabled(True)
            self._lines_widget.swap_points_button.setEnabled(True)
            #shape.setSelected(list_item.isSelected())

    def create_line_button_clicked(self):
        self._graphics_manager_hwobj.create_line()

    def remove_line_button_clicked(self):
        line_to_delete = None
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                line_to_delete = line
                break
        if line_to_delete:
            self._graphics_manager_hwobj.delete_shape(line_to_delete)

    def get_selected_lines(self):
        selected_lines = []
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                selected_lines.append(line)
        return selected_lines

    def overlay_toggled(self, state):
        self._graphics_manager_hwobj.set_display_overlay(state)

    def overlay_alpha_changed(self, alpha_value):
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                line.set_fill_alpha(alpha_value)

    def swap_points_clicked(self):
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                self._graphics_manager_hwobj.swap_line_points(line)
Exemplo n.º 6
0
class CreateCharWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Characterisation')

        if not name:
            self.setName("create_char_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._current_selected_item = None
        self.init_models()
        self._char_params_mib = DataModelInputBinder(self._char_params)

        # Graphic elements ----------------------------------------------------
        self._acq_widget = \
            AcquisitionWidgetSimple(self, acq_params = self._acquisition_parameters,
                                    path_template = self._path_template)

        self._data_path_gbox = QtGui.QGroupBox('Data location', self)
        self._data_path_widget = DataPathWidget(self._data_path_gbox,
                                                data_model=self._path_template,
                                                layout='vertical')

        self._vertical_dimension_widget = uic.loadUi(
            os.path.join(
                os.path.dirname(__file__),
                'ui_files/Qt4_vertical_crystal_dimension_widget_layout.ui'))

        self._char_widget = uic.loadUi(
            os.path.join(
                os.path.dirname(__file__),
                'ui_files/Qt4_characterise_simple_widget_vertical_layout.ui'))

        gbox = self._char_widget.findChild(QtGui.QGroupBox,
                                           "characterisation_gbox")
        p = gbox.palette()
        p.setColor(QtGui.QPalette.Window, QtCore.Qt.red)
        p.setColor(QtGui.QPalette.Highlight, QtCore.Qt.red)
        gbox.setPalette(p)

        # Layout --------------------------------------------------------------
        _data_path_gbox_layout = QtGui.QVBoxLayout(self)
        _data_path_gbox_layout.addWidget(self._data_path_widget)
        _data_path_gbox_layout.setSpacing(0)
        _data_path_gbox_layout.setContentsMargins(0, 0, 0, 0)
        self._data_path_gbox.setLayout(_data_path_gbox_layout)

        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_gbox)
        _main_vlayout.addWidget(self._char_widget)
        _main_vlayout.addWidget(self._vertical_dimension_widget)
        _main_vlayout.setSpacing(0)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(_main_vlayout)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------

        # Other ---------------------------------------------------------------
        self._char_params_mib.bind_value_update(
            'opt_sad', self._char_widget.optimised_sad_cbx, bool, None)

        self._char_params_mib.bind_value_update(
            'account_rad_damage', self._char_widget.account_rad_dmg_cbx, bool,
            None)

        #self._char_params_mib.bind_value_update('determine_rad_params',
        #                                        induced_burn_cbx,
        #                                        bool, None)

        self._char_params_mib.bind_value_update(
            'strategy_complexity', self._char_widget.start_comp_cbox, int,
            None)

        self._char_params_mib.\
            bind_value_update('max_crystal_vdim',
                              self._vertical_dimension_widget.max_vdim_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vdim',
                              self._vertical_dimension_widget.min_vdim_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vphi',
                              self._vertical_dimension_widget.min_vphi_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('max_crystal_vphi',
                              self._vertical_dimension_widget.max_vphi_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._vertical_dimension_widget.space_group_ledit.addItems(
            XTAL_SPACEGROUPS)

        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)

        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)

        self._vertical_dimension_widget.space_group_ledit.activated.\
             connect(self._space_group_change)

        self.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        #self.connect(induced_burn_cbx, QtCore.SIGNAL("toggled(bool)"),
        #             self.use_induced_burn)

    def use_induced_burn(self, state):
        """
        Descript. :
        """
        self._acquisition_parameters.induce_burn = state

    def _space_group_change(self, index):
        """
        Descript. :
        """
        self._char_params.space_group = queue_model_enumerables.\
                                        XTAL_SPACEGROUPS[index]

    def _set_space_group(self, space_group):
        """
        Descript. :
        """
        index = 0

        if space_group in XTAL_SPACEGROUPS:
            index = XTAL_SPACEGROUPS.index(space_group)

        self._space_group_change(index)
        self._vertical_dimension_widget.space_group_ledit.setCurrentIndex(
            index)

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._init_models()

    def _init_models(self):
        """
        Descript. :
        """
        self._char = queue_model_objects.Characterisation()
        self._char_params = self._char.characterisation_parameters
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )

        if self._beamline_setup_hwobj is not None:
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_char_acq_parameters()

            self._char_params = self._beamline_setup_hwobj.\
                                get_default_characterisation_parameters()
            try:
                transmission = self._beamline_setup_hwobj.transmission_hwobj.getAttFactor(
                )
                transmission = round(float(transmission), 1)
            except AttributeError:
                transmission = 0

            try:
                resolution = self._beamline_setup_hwobj.resolution_hwobj.getPosition(
                )
                resolution = round(float(resolution), 3)
            except AttributeError:
                resolution = 0

            try:
                energy = self._beamline_setup_hwobj.energy_hwobj.getCurrentEnergy(
                )
                energy = round(float(energy), 4)
            except AttributeError:
                energy = 0

            self._acquisition_parameters.resolution = resolution
            self._acquisition_parameters.energy = energy
            self._acquisition_parameters.transmission = transmission
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )

        return

        self._path_template.reference_image_prefix = 'ref'
        # The num images drop down default value is 1
        # we would like it to be 2
        self._acquisition_parameters.num_images = 2
        self._char.characterisation_software =\
            queue_model_enumerables.COLLECTION_ORIGIN.EDNA
        self._path_template.num_files = 2
        self._acquisition_parameters.shutterless = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            self._init_models()
            self._set_space_group(self._char_params.space_group)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self._char_params_mib.set_model(self._char_params)
            #self._char_params = copy.deepcopy(self._char_params)
            #self._acquisition_parameters = copy.deepcopy(self._acquisition_parameters)

        elif isinstance(tree_item, Qt4_queue_item.CharacterisationQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            self._char = tree_item.get_model()

            if self._char.get_path_template():
                self._path_template = self._char.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)

            data_collection = self._char.reference_image_collection

            self._char_params = self._char.characterisation_parameters
            self._char_params_mib.set_model(self._char_params)

            self._acquisition_parameters = data_collection.acquisitions[0].\
                                           acquisition_parameters

            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self.get_acquisition_widget().use_osc_start(True)

            if len(data_collection.acquisitions) == 1:
                self.select_shape_with_cpos(self._acquisition_parameters.\
                                            centred_position)

            self._processing_parameters = data_collection.processing_parameters
        else:
            self.setDisabled(True)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._char_params.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        for shape in selected_shapes:
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                result = True
        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. when a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if not shape:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_snapshot()
        else:
            # Shapes selected and sample is mounted, get the
            # centred positions for the shapes
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                snapshot = self._graphics_manager_hwobj.\
                           get_snapshot([shape])

                cpos = copy.deepcopy(shape.get_centred_positions()[0])
                cpos.snapshot_image = snapshot

        char_params = copy.deepcopy(self._char_params)
        acq = self._create_acq(sample)
        dc = queue_model_objects.\
                DataCollection([acq], sample.crystals[0],
                               self._processing_parameters)

        # Reference images for characterisations should be taken 90 deg apart
        # this is achived by setting overap to -89
        acq.acquisition_parameters.overlap = -89
        acq.acquisition_parameters.centred_position = cpos

        dc.acquisitions[0] = acq
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.EDNA_REF

        char = queue_model_objects.Characterisation(dc, char_params)
        char.set_name(dc.acquisitions[0].\
                      path_template.get_prefix())
        char.set_number(dc.acquisitions[0].\
                        path_template.run_number)

        tasks.append(char)
        self._path_template.run_number += 1

        return tasks
Exemplo n.º 7
0
class CreateEnergyScanWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Energy scan')

        if not name:
            self.setObjectName("create_energy_scan_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._periodic_table_widget = PeriodicTableWidget(self)
        self._data_path_widget = DataPathWidget(self,
                                                data_model=self._path_template,
                                                layout='vertical')

        # Layout --------------------------------------------------------------
        self.main_layout = QtGui.QVBoxLayout(self)
        self.main_layout.addWidget(self._periodic_table_widget)
        self.main_layout.addWidget(self._data_path_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(6)
        self.main_layout.addStretch(10)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._periodic_table_widget.elementEdgeSelectedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.acq_parameters_changed)

    def init_models(self):
        """
        Descript. :
        """

        CreateTaskBase.init_models(self)
        self.enery_scan = queue_model_objects.EnergyScan()
        self._path_template.start_num = 1
        self._path_template.num_files = 1
        self._path_template.suffix = 'raw'

    def set_energy_scan_hwobj(self, energy_scan_hwobj):
        """
        Descript. :
        """

        self._periodic_table_widget.set_elements(\
             energy_scan_hwobj.getElements())

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        escan_model = tree_item.get_model()

        if isinstance(tree_item, Qt4_queue_item.EnergyScanQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if escan_model.get_path_template():
                self._path_template = escan_model.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
        elif not(isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
                     isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem)):
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        base_result = CreateTaskBase.approve_creation(self)
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge(
        )
        if not selected_element:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return base_result and selected_element

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge(
        )

        if selected_element:
            if not shape:
                cpos = queue_model_objects.CentredPosition()
                cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot(
                )
            else:
                # Shapes selected and sample is mounted, get the
                # centred positions for the shapes
                if isinstance(shape, GraphicsItemPoint):
                    snapshot = self._graphics_manager_hwobj.\
                           get_scene_snapshot(shape)

                    cpos = copy.deepcopy(shape.get_centred_position())
                    cpos.snapshot_image = snapshot

            path_template = self._create_path_template(sample,
                                                       self._path_template)

            energy_scan = queue_model_objects.EnergyScan(
                sample, path_template, cpos)
            energy_scan.set_name(path_template.get_prefix())
            energy_scan.set_number(path_template.run_number)
            energy_scan.element_symbol = selected_element
            energy_scan.edge = selected_edge

            data_collections.append(energy_scan)
            self._path_template.run_number += 1
        else:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return data_collections

    def element_edge_selected(self, element, edge):
        if len(self._current_selected_items) == 1:
            item = self._current_selected_items[0]
            if isinstance(item, Qt4_queue_item.EnergyScanQueueItem):
                item.get_model().element_symbol = str(element)
                item.get_model().edge = str(edge)
Exemplo n.º 8
0
class CreateCharWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Characterisation')
        self.setObjectName("create_char_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._vertical_dimension_widget = None
        self._current_selected_item = None
        self.init_models()
        self._char_params_mib = DataModelInputBinder(self._char_params)

        # Graphic elements ----------------------------------------------------
        self._acq_widget = \
            AcquisitionWidgetSimple(self, acq_params = self._acquisition_parameters,
                                    path_template = self._path_template)

        self._data_path_widget = DataPathWidget(self,
                                                data_model=self._path_template,
                                                layout='vertical')

        self._vertical_dimension_widget = loadUi(
            os.path.join(
                os.path.dirname(__file__),
                'ui_files/Qt4_vertical_crystal_dimension_widget_layout.ui'))

        self._char_widget = loadUi(
            os.path.join(
                os.path.dirname(__file__),
                'ui_files/Qt4_characterise_simple_widget_vertical_layout.ui'))

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._char_widget)
        _main_vlayout.addWidget(self._vertical_dimension_widget)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)
        _main_vlayout.setSpacing(6)
        _main_vlayout.addStretch(0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)

        self._vertical_dimension_widget.space_group_ledit.activated.\
             connect(self._space_group_change)
        #self.connect(induced_burn_cbx, QtCore.SIGNAL("toggled(bool)"),
        #             self.use_induced_burn)

        self._char_widget.characterisation_gbox.toggled.connect(\
             self.characterisation_gbox_toggled)
        self._char_widget.wait_result_cbx.toggled.connect(\
             self.wait_results_cbx_toggled)
        self._char_widget.execute_plan_cbx.toggled.connect(\
             self.run_diffraction_plan_cbx_toggled)

        # Other ---------------------------------------------------------------
        self._char_params_mib.bind_value_update(
            'opt_sad', self._char_widget.optimised_sad_cbx, bool, None)

        self._char_params_mib.bind_value_update(
            'account_rad_damage', self._char_widget.account_rad_dmg_cbx, bool,
            None)

        #self._char_params_mib.bind_value_update('determine_rad_params',
        #                                        induced_burn_cbx,
        #                                        bool, None)

        self._char_params_mib.bind_value_update(
            'strategy_complexity', self._char_widget.start_comp_cbox, int,
            None)

        self._char_params_mib.\
            bind_value_update('max_crystal_vdim',
                              self._vertical_dimension_widget.max_vdim_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vdim',
                              self._vertical_dimension_widget.min_vdim_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vphi',
                              self._vertical_dimension_widget.min_vphi_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('max_crystal_vphi',
                              self._vertical_dimension_widget.max_vphi_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._vertical_dimension_widget.space_group_ledit.addItems(
            XTAL_SPACEGROUPS)

    def enable_compression(self, state):
        CreateTaskBase.enable_compression(self, False)

    def use_induced_burn(self, state):
        """
        Descript. :
        """
        self._acquisition_parameters.induce_burn = state

    def _space_group_change(self, index):
        """
        Descript. :
        """
        self._char_params.space_group = queue_model_enumerables.\
                                        XTAL_SPACEGROUPS[index]

    def _set_space_group(self, space_group):
        """
        Descript. :
        """
        index = 0

        if self._vertical_dimension_widget:
            if space_group in XTAL_SPACEGROUPS:
                index = XTAL_SPACEGROUPS.index(space_group)

            self._space_group_change(index)
            self._vertical_dimension_widget.space_group_ledit.\
                 setCurrentIndex(index)

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._init_models()

    def _init_models(self):
        """
        Descript. :
        """
        self._char = queue_model_objects.Characterisation()
        self._char_params = self._char.characterisation_parameters
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )
        self._set_space_group(self._processing_parameters.space_group)

        if self._beamline_setup_hwobj is not None:
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_char_acq_parameters()

            self._char_params = self._beamline_setup_hwobj.\
                                get_default_characterisation_parameters()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )

        self._path_template.reference_image_prefix = 'ref'
        # The num images drop down default value is 1
        # we would like it to be 2
        self._acquisition_parameters.num_images = 2
        self._char.characterisation_software =\
            queue_model_enumerables.COLLECTION_ORIGIN.EDNA
        self._path_template.num_files = 2
        self._path_template.compression = False
        self._acquisition_parameters.shutterless = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            #self._init_models()
            if self._char_params.space_group == "":
                sample_model = tree_item.get_model()
                self._set_space_group(
                    sample_model.processing_parameters.space_group)
            #self._acq_widget.update_data_model(self._acquisition_parameters,
            #                                   self._path_template)
            #self._char_params_mib.set_model(self._char_params)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.CharacterisationQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            self._char = tree_item.get_model()

            if self._char.get_path_template():
                self._path_template = self._char.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)

            data_collection = self._char.reference_image_collection

            self._char_params = self._char.characterisation_parameters
            self._char_params_mib.set_model(self._char_params)

            self._acquisition_parameters = data_collection.acquisitions[0].\
                                           acquisition_parameters

            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            #self.get_acquisition_widget().use_osc_start(True)

            if len(data_collection.acquisitions) == 1:
                self.select_shape_with_cpos(self._acquisition_parameters.\
                                            centred_position)

            self._processing_parameters = data_collection.processing_parameters
        else:
            self.setDisabled(True)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._char_params.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        for shape in selected_shapes:
            if isinstance(shape, GraphicsItemPoint):
                result = True
        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. when a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if not shape or not isinstance(shape, GraphicsItemPoint):
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot(
            )
        else:
            # Shapes selected and sample is mounted, get the
            # centred positions for the shapes
            snapshot = self._graphics_manager_hwobj.\
                        get_scene_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot

        char_params = copy.deepcopy(self._char_params)
        acq = self._create_acq(sample)
        dc = queue_model_objects.\
                DataCollection([acq], sample.crystals[0],
                               self._processing_parameters)

        # Reference images for characterisations should be taken 90 deg apart
        # this is achived by setting overap to -89
        acq.acquisition_parameters.overlap = -89
        acq.acquisition_parameters.centred_position = cpos

        dc.acquisitions[0] = acq
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.EDNA_REF
        dc.run_processing_parallel = False

        char = queue_model_objects.Characterisation(dc, char_params)
        char.set_name(dc.acquisitions[0].\
                      path_template.get_prefix())
        char.set_number(dc.acquisitions[0].\
                        path_template.run_number)
        char.run_characterisation = self._char_widget.characterisation_gbox.isChecked(
        )
        char.wait_result = self._char_widget.wait_result_cbx.isChecked()
        char.run_diffraction_plan = self._char_widget.execute_plan_cbx.isChecked(
        )

        tasks.append(char)
        self._path_template.run_number += 1

        return tasks

    def characterisation_gbox_toggled(self, state):
        if self._char:
            self._char.run_characterisation = state

    def wait_results_cbx_toggled(self, state):
        if self._char:
            self._char.wait_result = state

    def run_diffraction_plan_cbx_toggled(self, state):
        if self._char:
            self._char.run_diffraction_plan = state
class CreateHelicalWidget(CreateTaskBase):
    def __init__(self, parent = None,name = None, fl = 0):
        CreateTaskBase.__init__(self, parent, name, fl, 'Helical')

        if not name:
            self.setObjectName("create_helical_widget")
         
        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()
        self._prev_pos = None
        self._current_pos = None
        self._list_item_map = {}
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._lines_gbox = QtGui.QGroupBox('Lines', self)
        self._lines_list_widget = QtGui.QListWidget(self._lines_gbox)
        self._lines_list_widget.setFixedWidth(300)
        self._lines_list_widget.setFixedHeight(100)
        self._lines_list_widget.setToolTip(\
             "Select the line(s) to perfrom helical scan on")

        add_button = QtGui.QPushButton("+", self._lines_gbox)
        add_button.setFixedWidth(20)
        add_button.setFixedHeight(20)
        remove_button = QtGui.QPushButton("-", self._lines_gbox)
        remove_button.setFixedWidth(20)
        remove_button.setFixedHeight(20)        

        add_button_tool_tip = "Add a line between two saved positions, " \
                              "CTRL click to select more than one position"
        add_button.setToolTip(add_button_tool_tip)
        remove_button_tool_tip = "Remove selected line(s)"
        remove_button.setToolTip(remove_button_tool_tip)

        self._acq_gbox = QtGui.QGroupBox('Acquisition', self)
        self._acq_widget =  AcquisitionWidget(self._acq_gbox,
                              "acquisition_widget",
                              layout='vertical',
                              acq_params=self._acquisition_parameters,
                              path_template=self._path_template)

        self._data_path_gbox = QtGui.QGroupBox('Data location', self)
        self._data_path_widget = \
            DataPathWidget(self._data_path_gbox,
                           'create_dc_path_widget',
                           data_model=self._path_template,
                           layout='vertical')

        self._processing_gbox = QtGui.QGroupBox('Processing', self)
        self._processing_gbox.setObjectName('processing_gbox')
        self._processing_widget = \
            ProcessingWidget(self._processing_gbox,
                             data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _lines_gbox_gridlayout = QtGui.QGridLayout(self)
        _lines_gbox_gridlayout.addWidget(self._lines_list_widget, 0, 0, 2, 1)
        _lines_gbox_gridlayout.addWidget(add_button, 0, 1)
        _lines_gbox_gridlayout.addWidget(remove_button, 1, 1) 
        _lines_gbox_gridlayout.setSpacing(2)
        _lines_gbox_gridlayout.setColumnStretch(2, 10)
        _lines_gbox_gridlayout.setContentsMargins(2, 2, 2, 2)
        self._lines_gbox.setLayout(_lines_gbox_gridlayout)

        _acq_gbox_layout = QtGui.QVBoxLayout(self)
        _acq_gbox_layout.addWidget(self._acq_widget)
        _acq_gbox_layout.setSpacing(0)
        _acq_gbox_layout.setContentsMargins(0,0,0,0)
        self._acq_gbox.setLayout(_acq_gbox_layout)

        _data_path_gbox_layout = QtGui.QVBoxLayout(self)
        _data_path_gbox_layout.addWidget(self._data_path_widget)
        _data_path_gbox_layout.setSpacing(0)
        _data_path_gbox_layout.setContentsMargins(0,0,0,0)
        self._data_path_gbox.setLayout(_data_path_gbox_layout)

        _processing_gbox_layout = QtGui.QVBoxLayout(self)
        _processing_gbox_layout.addWidget(self._processing_widget)
        _processing_gbox_layout.setSpacing(0)
        _processing_gbox_layout.setContentsMargins(0,0,0,0)
        self._processing_gbox.setLayout(_processing_gbox_layout)

        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._lines_gbox)
        _main_vlayout.addWidget(self._acq_gbox)
        _main_vlayout.addWidget(self._data_path_gbox)
        _main_vlayout.addWidget(self._processing_gbox)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0,0,0,0)
        self.setLayout(_main_vlayout)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        add_button.clicked.connect(self.add_clicked)

        remove_button.clicked.connect(self.remove_clicked)

        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)

        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)

        QtCore.QObject.connect(self._lines_list_widget, 
                               QtCore.SIGNAL("selectionChanged()"),
                               self.list_box_selection_changed)

        QtCore.QObject.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

    def init_models(self):
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters()
  
        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
            self._path_template = queue_model_objects.PathTemplate()

    def add_clicked(self):
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        if len(selected_shapes) == 2:
            p1 = selected_shapes[0]
            p2 = selected_shapes[1]
            
            line = graphics_manager.GraphicsItemLine(p1, p2)
            line.show()

            self._graphics_manager_hwobj.add_shape(line)
            points_index = line.get_points_index()
            if points_index:
                display_name = "Line (points: %d, %d / kappa: %.2f phi: %.2f)" %\
                       (points_index[0], points_index[1],
                        p1.centred_position.kappa, p1.centred_position.kappa_phi)
            else:
                display_name = "Line (points: #, #)"
            list_widget_item = QtGui.QListWidgetItem(display_name, self._lines_list_widget)
            self._list_item_map[list_widget_item] = line

            # De select previous items
            for item in self.selected_items():
                item.setSelected(False)

            list_widget_item.setSelected(True)
        else:
            print "No points selected"

    def remove_clicked(self):
        selected_items = self.selected_items()

        if selected_items:
            for item in selected_items:
                self._lines_list_widget.takeItem(self._lines_list_widget.row(item))
                line = self._list_item_map[item]
                self._graphics_manager_hwobj.delete_shape(line)
                del self._list_item_map[item]

    # Calback from graphics_manager, called when a shape is deleted
    def shape_deleted(self, shape):
        if isinstance(shape, graphics_manager.Point):
            items_to_remove = []

            for (list_item, line) in self._list_item_map.iteritems():
                #if shape
 
                for qub_object in shape.get_qub_objects():
                    if qub_object in line.get_qub_objects():
                        items_to_remove.append((list_item, line))

            for (list_item, line) in items_to_remove:
                self._lines_list_widget.takeItem(self._lines_list_widget.row(list_item))
                del self._list_item_map[list_item]

    def centred_position_selection(self, positions):
        if len(positions) == 1:
            self._prev_pos = positions[0]
            
        elif len(positions) == 2:

            for pos in positions:
                if pos != self._prev_pos:
                    self._current_pos = pos
        else:
            self._prev_pos = None
            self._current_pos = None

    def list_box_selection_changed(self):
        self.show_selected_lines()

    def selected_items(self):
        selected_items = []
                
        for item_index in range(self._lines_list_widget.count()):
            if self._lines_list_widget.item(item_index).isSelected():
                selected_items.append(self._lines_list_widget.item(item_index))

        return selected_items
        
    def show_selected_lines(self):
        selected_items = self.selected_items()

        for list_item in self._list_item_map.keys():
            line = self._list_item_map[list_item]
            if list_item in selected_items:
                self._graphics_manager.select_shape(line)
            else:
                self._graphics_manager.de_select_shape(line)

    def approve_creation(self):
        base_result = CreateTaskBase.approve_creation(self)
    
        selected_lines = False
        
        if self.selected_items():
            selected_lines = True
        else:
            logging.getLogger("user_level_log").\
                warning("No lines selected, please select one or more lines.")

        return base_result and selected_lines 
            
    def update_processing_parameters(self, crystal):
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def select_shape_with_cpos(self, start_cpos, end_cpos):
        self._graphics_manager_hwobj.de_select_all()
        selected_line = None

        for shape in self._graphics_manager_hwobj.get_shapes():
            if isinstance(shape, graphics_manager.GraphicsItemLine):
                if shape.get_centred_positions()[0] == start_cpos and\
                       shape.get_centred_positions()[1] == end_cpos:
                    self._graphics_manager_hwobj.de_select_all()
                    shape.setSelected(True)
                    selected_line = shape

        #de-select previous selected list items and
        #select the current shape (Line).
        for (list_item, shape) in self._list_item_map.iteritems():

            if selected_line is shape:
                list_item.setSelected(True)
            else:
                list_item.setSelected(False)

    def single_item_selection(self, tree_item):
        CreateTaskBase.single_item_selection(self, tree_item)
                                                             
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            self._processing_parameters = sample_model.processing_parameters
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_widget.update_data_model(self._processing_parameters)

        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            data_collection = tree_item.get_model()

            if data_collection.experiment_type == EXPERIMENT_TYPE.HELICAL:
                if tree_item.get_model().is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                self._path_template = data_collection.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)
                
                self._acquisition_parameters = data_collection.acquisitions[0].\
                                               acquisition_parameters

                if len(data_collection.acquisitions) == 2:
                    start_cpos = data_collection.acquisitions[0].acquisition_parameters.\
                                 centred_position
                    end_cpos = data_collection.acquisitions[1].acquisition_parameters.\
                               centred_position

                    self.select_shape_with_cpos(start_cpos, end_cpos)

                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                   self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
                
                self._processing_parameters = data_collection.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):

            self._processing_widget.update_data_model(self._processing_parameters)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
  
    def _create_task(self,  sample, shape):
        data_collections = []

        if isinstance(shape, graphics_manager.GraphicsItemLine):
            snapshot = self._graphics_manager_hwobj.get_snapshot(shape)

            # Acquisition for start position
            start_acq = self._create_acq(sample) 
            
            start_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(shape.cp_start.centred_position)
            start_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            start_acq.path_template.suffix = self._session_hwobj.suffix

            # Add another acquisition for the end position
            end_acq = self._create_acq(sample)

            end_acq.acquisition_parameters.\
                centred_position = shape.cp_end.centred_position
            end_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            end_acq.path_template.suffix = self._session_hwobj.suffix

            processing_parameters = copy.deepcopy(self._processing_parameters)

            dc = queue_model_objects.DataCollection([start_acq, end_acq],
                                    sample.crystals[0],
                                    processing_parameters)

            dc.set_name(start_acq.path_template.get_prefix())
            dc.set_number(start_acq.path_template.run_number)
            dc.experiment_type = EXPERIMENT_TYPE.HELICAL

            data_collections.append(dc)
            self._path_template.run_number += 1

        return data_collections
Exemplo n.º 10
0
class CreateDiscreteWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl),
                                "Standart")

        if not name:
            self.setObjectName("Qt4_create_discrete_widget")
        self.init_models()

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.previous_energy = None
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget = AcquisitionWidget(
            self,
            "acquisition_widget",
            layout='vertical',
            acq_params=self._acquisition_parameters,
            path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self,
                                                'create_dc_path_widget',
                                                data_model=self._path_template,
                                                layout='vertical')

        self._processing_widget = ProcessingWidget(
            self, data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)
        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)
        self._data_path_widget.pathTemplateChangedSignal.connect(\
             self.handle_path_conflict)

        self._acq_widget.acqParametersChangedSignal.connect(\
             self.handle_path_conflict)
        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._processing_widget.enableProcessingSignal.connect(\
             self._enable_processing_toggled)

        # Other ---------------------------------------------------------------

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )

    def set_tunable_energy(self, state):
        """
        Descript. :
        """
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(
                self._processing_parameters)
            self._acq_widget.disable_inverse_beam(False)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()

            if dc.experiment_type != queue_model_enumerables.EXPERIMENT_TYPE.HELICAL:
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[
                    0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                self._acq_widget.disable_inverse_beam(True)

                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[
                    0].acquisition_parameters
                self._acq_widget.update_data_model(
                    self._acquisition_parameters, self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(
                    self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if isinstance(shape, GraphicsItemPoint):
            snapshot = self._graphics_manager_hwobj.get_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot
        else:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_snapshot()

        if self._acq_widget.use_inverse_beam():
            total_num_images = self._acquisition_parameters.num_images
            subwedge_size = self._acq_widget.get_num_subwedges()
            osc_range = self._acquisition_parameters.osc_range
            osc_start = self._acquisition_parameters.osc_start
            run_number = self._path_template.run_number

            subwedges = queue_model_objects.create_inverse_beam_sw(
                total_num_images, subwedge_size, osc_range, osc_start,
                run_number)

            self._acq_widget.set_use_inverse_beam(False)

            for sw in subwedges:
                tasks.extend(
                    self.create_dc(sample,
                                   sw[3],
                                   sw[0],
                                   sw[1],
                                   sw[2],
                                   cpos=cpos,
                                   inverse_beam=True))
                self._path_template.run_number += 1
        else:
            tasks.extend(self.create_dc(sample, cpos=cpos))
            self._path_template.run_number += 1
        return tasks

    def create_dc(self,
                  sample,
                  run_number=None,
                  start_image=None,
                  num_images=None,
                  osc_start=None,
                  sc=None,
                  cpos=None,
                  inverse_beam=False):
        """
        Descript. :
        """
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)

        if run_number:
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.NATIVE

        tasks.append(dc)

        return tasks
Exemplo n.º 11
0
class CreateDiscreteWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl), "Standart")

        if not name:
            self.setObjectName("Qt4_create_discrete_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.previous_energy = None
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget =  AcquisitionWidget(self, "acquisition_widget",
             layout='vertical', acq_params=self._acquisition_parameters,
             path_template=self._path_template)

        self._data_path_gbox = QtGui.QGroupBox('Data location', self)
        self._data_path_gbox.setObjectName('data_path_gbox')        
        self._data_path_widget = \
            DataPathWidget(self._data_path_gbox,
                           'create_dc_path_widget',
                           data_model=self._path_template,
                           layout='vertical')

        self._processing_gbox = QtGui.QGroupBox('Processing', self)
        self._processing_gbox.setObjectName('processing_gbox')
        self._processing_widget = \
            ProcessingWidget(self._processing_gbox,
                             data_model=self._processing_parameters)
       
        # Layout --------------------------------------------------------------
        self._data_path_gbox_layout = QtGui.QVBoxLayout(self)
        self._data_path_gbox_layout.addWidget(self._data_path_widget)
        self._data_path_gbox_layout.setSpacing(0)
        self._data_path_gbox_layout.setContentsMargins(0, 0, 0, 0)
        self._data_path_gbox.setLayout(self._data_path_gbox_layout)

        self._processing_gbox_layout = QtGui.QVBoxLayout(self)
        self._processing_gbox_layout.addWidget(self._processing_widget)
        self._processing_gbox_layout.setSpacing(0)
        self._processing_gbox_layout.setContentsMargins(0, 0, 0, 0)
        self._processing_gbox.setLayout(self._processing_gbox_layout)

        self.main_layout = QtGui.QVBoxLayout(self)
        self.main_layout.addWidget(self._acq_widget)
        self.main_layout.addWidget(self._data_path_gbox)
        self.main_layout.addWidget(self._processing_gbox)
        self.main_layout.addSpacing(10)
        self.main_layout.setSpacing(0)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.main_layout)

        # SizePolicies --------------------------------------------------------
        """self._acq_widget.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                       QtGui.QSizePolicy.Fixed)
        self._data_path_gbox.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)
        self._processing_gbox.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)"""
        
        # Qt signal/slot connections ------------------------------------------
        self._processing_gbox.toggled.connect(self._use_processing_toggled)
        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)
        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)

        self.connect(self._acq_widget, QtCore.SIGNAL('mad_energy_selected'),
                     self.mad_energy_selected)

        self.connect(self._acq_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        self.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        # Other ---------------------------------------------------------------

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters()

    def set_tunable_energy(self, state):
        """
        Descript. :
        """
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def mad_energy_selected(self, name, energy, state):
        """
        Descript. :
        """
        item = self._current_selected_items[0]
        model = item.get_model()
        
        if state:
            self._path_template.mad_prefix = name
        else:
            self._path_template.mad_prefix = ''

        run_number = self._beamline_setup_hwobj.queue_model_hwobj.\
            get_next_run_number(self._path_template)

        data_path_widget = self.get_data_path_widget()
        data_path_widget.set_run_number(run_number)
        data_path_widget.set_prefix(self._path_template.base_prefix)

        if self.isEnabled():
            if isinstance(item, Qt4_queue_item.TaskQueueItem) and \
                   not isinstance(item, Qt4_queue_item.DataCollectionGroupQueueItem):
                model.set_name(self._path_template.get_prefix())
                item.setText(0, model.get_name())

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(self._processing_parameters)
            self._acq_widget.disable_inverse_beam(False)

        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()

            if dc.experiment_type != queue_model_enumerables.EXPERIMENT_TYPE.HELICAL:
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                self._acq_widget.disable_inverse_beam(True)
                
                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[0].acquisition_parameters
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        for shape in selected_shapes:
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                result = True
        return result

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if not shape:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_snapshot()
        else:
            # Shapes selected and sample is mounted, get the
            # centred positions for the shapes
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                snapshot = self._graphics_manager_hwobj.\
                           get_snapshot([shape])

                cpos = copy.deepcopy(shape.get_centred_positions()[0])
                cpos.snapshot_image = snapshot

        if self._acq_widget.use_inverse_beam():
            total_num_images = self._acquisition_parameters.num_images
            subwedge_size = self._acq_widget.get_num_subwedges()
            osc_range = self._acquisition_parameters.osc_range
            osc_start = self._acquisition_parameters.osc_start
            run_number = self._path_template.run_number

            subwedges = queue_model_objects.create_inverse_beam_sw(total_num_images,
                        subwedge_size, osc_range, osc_start, run_number)

            self._acq_widget.set_use_inverse_beam(False)

            for sw in subwedges:
                tasks.extend(self.create_dc(sample, sw[3], sw[0], sw[1],
                                            sw[2], cpos=cpos,
                                            inverse_beam = True))
                self._path_template.run_number += 1
        else:
            tasks.extend(self.create_dc(sample, cpos=cpos))
            self._path_template.run_number += 1

        return tasks
    
    def create_dc(self, sample, run_number = None, start_image = None,
                  num_images = None, osc_start = None, sc = None,
                  cpos=None, inverse_beam = False):
        """
        Descript. :
        """
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)
       
        if run_number:        
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.NATIVE

        tasks.append(dc)

        return tasks
Exemplo n.º 12
0
class CreateHelicalWidget(CreateTaskBase):
    def __init__(self, parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, fl, 'Helical')

        if not name:
            self.setObjectName("create_helical_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()
        self._prev_pos = None
        self._current_pos = None
        self._list_item_map = {}
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._lines_gbox = QtGui.QGroupBox('Lines', self)
        self._lines_list_widget = QtGui.QListWidget(self._lines_gbox)
        self._lines_list_widget.setFixedWidth(300)
        self._lines_list_widget.setFixedHeight(100)
        self._lines_list_widget.setToolTip(\
             "Select the line(s) to perfrom helical scan on")

        add_button = QtGui.QPushButton("+", self._lines_gbox)
        add_button.setFixedWidth(20)
        add_button.setFixedHeight(20)
        remove_button = QtGui.QPushButton("-", self._lines_gbox)
        remove_button.setFixedWidth(20)
        remove_button.setFixedHeight(20)

        add_button_tool_tip = "Add a line between two saved positions, " \
                              "CTRL click to select more than one position"
        add_button.setToolTip(add_button_tool_tip)
        remove_button_tool_tip = "Remove selected line(s)"
        remove_button.setToolTip(remove_button_tool_tip)

        self._acq_widget = AcquisitionWidget(
            self,
            "acquisition_widget",
            layout='vertical',
            acq_params=self._acquisition_parameters,
            path_template=self._path_template)

        self._data_path_gbox = QtGui.QGroupBox('Data location', self)
        self._data_path_widget = \
            DataPathWidget(self._data_path_gbox,
                           'create_dc_path_widget',
                           data_model=self._path_template,
                           layout='vertical')

        self._processing_gbox = QtGui.QGroupBox('Processing', self)
        self._processing_gbox.setObjectName('processing_gbox')
        self._processing_widget = \
            ProcessingWidget(self._processing_gbox,
                             data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _lines_gbox_gridlayout = QtGui.QGridLayout(self)
        _lines_gbox_gridlayout.addWidget(self._lines_list_widget, 0, 0, 2, 1)
        _lines_gbox_gridlayout.addWidget(add_button, 0, 1)
        _lines_gbox_gridlayout.addWidget(remove_button, 1, 1)
        _lines_gbox_gridlayout.setSpacing(2)
        _lines_gbox_gridlayout.setColumnStretch(2, 10)
        _lines_gbox_gridlayout.setContentsMargins(2, 2, 2, 2)
        self._lines_gbox.setLayout(_lines_gbox_gridlayout)

        _data_path_gbox_layout = QtGui.QVBoxLayout(self)
        _data_path_gbox_layout.addWidget(self._data_path_widget)
        _data_path_gbox_layout.setSpacing(0)
        _data_path_gbox_layout.setContentsMargins(0, 0, 0, 0)
        self._data_path_gbox.setLayout(_data_path_gbox_layout)

        _processing_gbox_layout = QtGui.QVBoxLayout(self)
        _processing_gbox_layout.addWidget(self._processing_widget)
        _processing_gbox_layout.setSpacing(0)
        _processing_gbox_layout.setContentsMargins(0, 0, 0, 0)
        self._processing_gbox.setLayout(_processing_gbox_layout)

        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._lines_gbox)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_gbox)
        _main_vlayout.addWidget(self._processing_gbox)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(_main_vlayout)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        add_button.clicked.connect(self.add_clicked)

        remove_button.clicked.connect(self.remove_clicked)

        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)

        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)

        QtCore.QObject.connect(self._lines_list_widget,
                               QtCore.SIGNAL("selectionChanged()"),
                               self.list_box_selection_changed)

        QtCore.QObject.connect(self._data_path_widget,
                               QtCore.SIGNAL("pathTemplateChanged"),
                               self.handle_path_conflict)

    def init_models(self):
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )

        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )
            self._path_template = queue_model_objects.PathTemplate()

    def add_clicked(self):
        selected_shapes = self._graphics_manager_hwobj.get_selected_points()

        if len(selected_shapes) == 2:
            p1 = selected_shapes[0]
            p2 = selected_shapes[1]

            line = graphics_manager.GraphicsItemLine(p1, p2)
            line.show()

            self._graphics_manager_hwobj.add_shape(line)
            points_index = line.get_points_index()
            if points_index:
                display_name = "Line (points: %d, %d / kappa: %.2f phi: %.2f)" %\
                       (points_index[0], points_index[1],
                        p1.centred_position.kappa, p1.centred_position.kappa_phi)
            else:
                display_name = "Line (points: #, #)"
            list_widget_item = QtGui.QListWidgetItem(display_name,
                                                     self._lines_list_widget)
            self._list_item_map[list_widget_item] = line

            # De select previous items
            for item in self.selected_items():
                item.setSelected(False)

            list_widget_item.setSelected(True)
        else:
            print "Select two points to create a helical line."

    def remove_clicked(self):
        selected_items = self.selected_items()

        if selected_items:
            for item in selected_items:
                self._lines_list_widget.takeItem(
                    self._lines_list_widget.row(item))
                line = self._list_item_map[item]
                self._graphics_manager_hwobj.delete_shape(line)
                del self._list_item_map[item]

    # Calback from graphics_manager, called when a shape is deleted
    def shape_deleted(self, shape):
        if isinstance(shape, graphics_manager.GraphicsItemPoint):

            items_to_remove = []

            for (list_item, line) in self._list_item_map.iteritems():
                if shape in line.get_graphics_points():
                    items_to_remove.append((list_item, line))

            for (list_item, line) in items_to_remove:
                self._lines_list_widget.takeItem(
                    self._lines_list_widget.row(list_item))
                del self._list_item_map[list_item]

    def centred_position_selection(self, positions):
        if len(positions) == 1:
            self._prev_pos = positions[0]

        elif len(positions) == 2:

            for pos in positions:
                if pos != self._prev_pos:
                    self._current_pos = pos
        else:
            self._prev_pos = None
            self._current_pos = None

    def list_box_selection_changed(self):
        self.show_selected_lines()

    def selected_items(self):
        selected_items = []

        for item_index in range(self._lines_list_widget.count()):
            if self._lines_list_widget.item(item_index).isSelected():
                selected_items.append(self._lines_list_widget.item(item_index))

        return selected_items

    def show_selected_lines(self):
        selected_items = self.selected_items()

        for list_item in self._list_item_map.keys():
            line = self._list_item_map[list_item]
            if list_item in selected_items:
                self._graphics_manager.select_shape(line)
            else:
                self._graphics_manager.de_select_shape(line)

    def approve_creation(self):
        base_result = CreateTaskBase.approve_creation(self)

        selected_lines = False

        if self.selected_items():
            selected_lines = True
        else:
            logging.getLogger("user_level_log").\
                warning("No lines selected, please select one or more lines.")

        return base_result and selected_lines

    def update_processing_parameters(self, crystal):
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def select_shape_with_cpos(self, start_cpos, end_cpos):
        self._graphics_manager_hwobj.de_select_all()
        selected_line = None

        for shape in self._graphics_manager_hwobj.get_shapes():
            if isinstance(shape, graphics_manager.GraphicsItemLine):
                if shape.get_centred_positions()[0] == start_cpos and\
                       shape.get_centred_positions()[1] == end_cpos:
                    self._graphics_manager_hwobj.de_select_all()
                    shape.setSelected(True)
                    selected_line = shape

        #de-select previous selected list items and
        #select the current shape (Line).
        for (list_item, shape) in self._list_item_map.iteritems():

            if selected_line is shape:
                list_item.setSelected(True)
            else:
                list_item.setSelected(False)

    def single_item_selection(self, tree_item):
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            self._processing_parameters = sample_model.processing_parameters
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_widget.update_data_model(
                self._processing_parameters)

        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            data_collection = tree_item.get_model()

            if data_collection.experiment_type == EXPERIMENT_TYPE.HELICAL:
                if tree_item.get_model().is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                self._path_template = data_collection.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = data_collection.acquisitions[0].\
                                               acquisition_parameters

                if len(data_collection.acquisitions) == 2:
                    start_cpos = data_collection.acquisitions[0].acquisition_parameters.\
                                 centred_position
                    end_cpos = data_collection.acquisitions[1].acquisition_parameters.\
                               centred_position

                    self.select_shape_with_cpos(start_cpos, end_cpos)

                self._acq_widget.update_data_model(
                    self._acquisition_parameters, self._path_template)
                self.get_acquisition_widget().use_osc_start(True)

                self._processing_parameters = data_collection.processing_parameters
                self._processing_widget.update_data_model(
                    self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):

            self._processing_widget.update_data_model(
                self._processing_parameters)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)

    def _create_task(self, sample, shape):
        data_collections = []

        if isinstance(shape, graphics_manager.GraphicsItemLine):
            snapshot = self._graphics_manager_hwobj.get_snapshot(shape)

            # Acquisition for start position
            start_acq = self._create_acq(sample)

            start_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(shape.cp_start.centred_position)
            start_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            start_acq.path_template.suffix = self._session_hwobj.suffix

            # Add another acquisition for the end position
            end_acq = self._create_acq(sample)

            end_acq.acquisition_parameters.\
                centred_position = shape.cp_end.centred_position
            end_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            end_acq.path_template.suffix = self._session_hwobj.suffix

            processing_parameters = copy.deepcopy(self._processing_parameters)

            dc = queue_model_objects.DataCollection([start_acq, end_acq],
                                                    sample.crystals[0],
                                                    processing_parameters)

            dc.set_name(start_acq.path_template.get_prefix())
            dc.set_number(start_acq.path_template.run_number)
            dc.experiment_type = EXPERIMENT_TYPE.HELICAL

            data_collections.append(dc)
            self._path_template.run_number += 1

        return data_collections
class CreateEnergyScanWidget(CreateTaskBase):
    """
    Descript. :
    """ 

    def __init__(self, parent=None,name=None, fl=0):
        """
        Descript. :
        """
 
        CreateTaskBase.__init__(self, parent, name, fl, 'Energy scan')

        if not name:
            self.setObjectName("create_energy_scan_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._periodic_table_widget = PeriodicTableWidget(self)
        self._data_path_widget = DataPathWidget(self, 
             data_model = self._path_template, layout = 'vertical')

        _parameters_gbox = QGroupBox('Parameters', self)
        self._adjust_transmission_cbox = QCheckBox(\
             "Adjust transmission", _parameters_gbox)
        self._adjust_transmission_cbox.setChecked(False)
        self._adjust_transmission_cbox.setEnabled(True)
        self._max_transmission_label = QLabel("Maximum transmission:")
        self._max_transmission_ledit = QLineEdit("20", _parameters_gbox)
        self._max_transmission_ledit.setFixedWidth(80)
        self._max_transmission_ledit.setEnabled(False)

        # Layout --------------------------------------------------------------
        _parameters_gbox_hlayout = QGridLayout(_parameters_gbox)
        _parameters_gbox_hlayout.addWidget(self._adjust_transmission_cbox, 0, 0)
        _parameters_gbox_hlayout.addWidget(self._max_transmission_label, 1, 0) 
        _parameters_gbox_hlayout.addWidget(self._max_transmission_ledit, 1, 1)
        _parameters_gbox_hlayout.setColumnStretch(2, 1)
        _parameters_gbox_hlayout.setSpacing(2)

        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._periodic_table_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(_parameters_gbox)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)
        _main_vlayout.setSpacing(6)
        _main_vlayout.addStretch(10)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        #self._periodic_table_widget.elementEdgeSelectedSignal.connect(\
        #     self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.connect(\
             self.path_template_changed)
        self._adjust_transmission_cbox.stateChanged.connect(\
             self.adjust_transmission_state_changed)
        self._max_transmission_ledit.textEdited.connect(\
             self.max_transmission_value_changed)

    def set_expert_mode(self, state):
        self._adjust_transmission_cbox.setEnabled(state)
        self._max_transmission_label.setEnabled(state)
        self._max_transmission_ledit.setEnabled(state)

    def enable_compression(self, state):
        CreateTaskBase.enable_compression(self, False)

    def set_beamline_setup(self, bl_setup_hwobj):
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._periodic_table_widget.set_elements(\
             self._beamline_setup_hwobj.energyscan_hwobj.getElements())
        self.enable_compression(False)

        try:
            max_transmission_value = self._beamline_setup_hwobj.\
                 energyscan_hwobj.get_max_transmission_value()

            self._adjust_transmission_cbox.setEnabled(True) 
            self._adjust_transmission_cbox.setChecked(True)
            self._beamline_setup_hwobj.energyscan_hwobj.adjust_transmission(True)
  
            if max_transmission_value:
                self._max_transmission_ledit.setText("%.2f" % max_transmission_value)
        except:
            pass

    def init_models(self):
        """
        Descript. :
        """
       
        CreateTaskBase.init_models(self)
        self.enery_scan = queue_model_objects.EnergyScan()
        self._path_template.start_num = 1
        self._path_template.num_files = 1
        self._path_template.suffix = 'raw'
        self._path_template.compression = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        escan_model = tree_item.get_model()

        if isinstance(tree_item, Qt4_queue_item.EnergyScanQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if escan_model.get_path_template():
                self._path_template = escan_model.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
        elif not(isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
                     isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem)):
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        base_result = CreateTaskBase.approve_creation(self)
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge()
        if not selected_element:
            logging.getLogger("GUI").\
                warning("No element selected, please select an element.")

        return base_result and selected_element

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge()   

        if selected_element:
            if not shape:
                cpos = queue_model_objects.CentredPosition()
                cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot()
            else:
                # Shapes selected and sample is mounted, get the
                # centred positions for the shapes
                if isinstance(shape, GraphicsItemPoint):
                    snapshot = self._graphics_manager_hwobj.\
                           get_scene_snapshot(shape)

                    cpos = copy.deepcopy(shape.get_centred_position())
                    cpos.snapshot_image = snapshot

            path_template = self._create_path_template(sample, self._path_template)

            energy_scan = queue_model_objects.EnergyScan(sample,
                                                         path_template,
                                                         cpos)
            energy_scan.set_name(path_template.get_prefix())
            energy_scan.set_number(path_template.run_number)
            energy_scan.element_symbol = selected_element
            energy_scan.edge = selected_edge

            data_collections.append(energy_scan)
            self._path_template.run_number += 1
        else:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return data_collections

    def element_edge_selected(self, element, edge):
        if len(self._current_selected_items) == 1:
            item = self._current_selected_items[0]
            if isinstance(item, Qt4_queue_item.EnergyScanQueueItem):
                item.get_model().element_symbol = str(element)
                item.get_model().edge = str(edge)

    def adjust_transmission_state_changed(self, state):
        self._max_transmission_ledit.setEnabled(state)
        self._beamline_setup_hwobj.energyscan_hwobj.adjust_transmission(state)
   
    def max_transmission_value_changed(self, value):
        try:
            max_transmission = float(value)
            self._beamline_setup_hwobj.energyscan_hwobj.set_max_transmission(max_transmission)
        except:
            pass
Exemplo n.º 14
0
class CreateStillScanWidget(CreateTaskBase):

    def __init__(self,parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name,
            Qt.WindowFlags(fl), "Still")

        if not name:
            self.setObjectName("create_still_scan_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._acq_widget =  AcquisitionStillWidget(self, "acquisition_widget",
             layout='vertical', acq_params=self._acquisition_parameters,
             path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self, 'create_dc_path_widget',
            data_model=self._path_template, layout='vertical')

        self._processing_widget = ProcessingWidget(self,
             data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(6)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)
        self._processing_widget.enableProcessingSignal.connect(\
             self._run_processing_toggled)

        # Other ---------------------------------------------------------------

    def use_osc_start(self, status):
        pass

    def update_exp_time_limits(self, status):
        pass

    def init_models(self):
        CreateTaskBase.init_models(self)
        self._processing_parameters = queue_model_objects.ProcessingParameters()

        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_acquisition_values")
            self._acquisition_parameters.num_triggers = 1
            self._acquisition_parameters.num_images_per_trigger = 1
            self._processing_widget.processing_widget.run_processing_parallel_cbox.setChecked(\
                self._beamline_setup_hwobj._get_run_processing_parallel())
 
    def set_tunable_energy(self, state):
        self._acq_widget.set_tunable_energy(state)

    def update_processing_parameters(self, crystal):
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_parameters = sample_model.processing_parameters
            self._processing_widget.update_data_model(self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            dc = tree_item.get_model()
            self._acq_widget.use_kappa(False)

            if not dc.is_helical():
                if dc.is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                energy_scan_result = sample_data_model.crystals[0].energy_scan_result
                self._acq_widget.set_energies(energy_scan_result)

                #self._acq_widget.disable_inverse_beam(True)

                self._path_template = dc.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)

                self._acquisition_parameters = dc.acquisitions[0].acquisition_parameters
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
                if len(dc.acquisitions) == 1:
                    self.select_shape_with_cpos(self._acquisition_parameters.\
                                                centred_position)

                self._processing_parameters = dc.processing_parameters
                self._processing_widget.update_data_model(self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

    def _create_task(self, sample, shape):
        tasks = []

        cpos = queue_model_objects.CentredPosition()
        cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot()

        tasks.extend(self.create_dc(sample, cpos=cpos))
        self._path_template.run_number += 1

        return tasks

    def create_dc(self, sample, run_number=None, start_image=None,
                  num_images=None, osc_start=None, sc=None,
                  cpos=None, inverse_beam=False):
        tasks = []

        # Acquisition for start position
        acq = self._create_acq(sample)

        if run_number:
            acq.path_template.run_number = run_number

        if start_image:
            acq.acquisition_parameters.first_image = start_image
            acq.path_template.start_num = start_image

        if num_images:
            acq.acquisition_parameters.num_images = num_images
            acq.path_template.num_files = num_images

        if osc_start:
            acq.acquisition_parameters.osc_start = osc_start

        if inverse_beam:
            acq.acquisition_parameters.inverse_beam = False

        acq.acquisition_parameters.centred_position = cpos

        processing_parameters = copy.deepcopy(self._processing_parameters)
        dc = queue_model_objects.DataCollection([acq], sample.crystals[0],
                                                processing_parameters)
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.STILL
        dc.run_processing_after = self._processing_widget.processing_widget.\
           run_processing_after_cbox.isChecked()
        dc.run_processing_parallel = self._processing_widget.processing_widget.\
           run_processing_parallel_cbox.isChecked()
        dc.set_requires_centring(False)

        tasks.append(dc)

        return tasks
class CreateEnergyScanWidget(CreateTaskBase):
    """
    Descript. :
    """ 

    def __init__(self, parent = None,name = None, fl = 0):
        """
        Descript. :
        """
 
        CreateTaskBase.__init__(self, parent, name, fl, 'Energy scan')

        if not name:
            self.setObjectName("create_energy_scan_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._periodic_table_widget = PeriodicTableWidget(self)
        self._data_path_widget = DataPathWidget(self, 
             data_model = self._path_template, layout = 'vertical')

        # Layout --------------------------------------------------------------
        self.main_layout = QtGui.QVBoxLayout(self)
        self.main_layout.addWidget(self._periodic_table_widget)
        self.main_layout.addWidget(self._data_path_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(6)
        self.main_layout.addStretch(10)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._periodic_table_widget.elementEdgeSelectedSignal.\
             connect(self.acq_parameters_changed)
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.acq_parameters_changed)

    def init_models(self):
        """
        Descript. :
        """
       
        CreateTaskBase.init_models(self)
        self.enery_scan = queue_model_objects.EnergyScan()
        self._path_template.start_num = 1
        self._path_template.num_files = 1
        self._path_template.suffix = 'raw'

    def set_energy_scan_hwobj(self, energy_scan_hwobj):
        """
        Descript. :
        """
 
        self._periodic_table_widget.set_elements(\
             energy_scan_hwobj.getElements())

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        escan_model = tree_item.get_model()

        if isinstance(tree_item, Qt4_queue_item.EnergyScanQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if escan_model.get_path_template():
                self._path_template = escan_model.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
        elif not(isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
                     isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem)):
            self.setDisabled(True)

    def approve_creation(self):
        """
        Descript. :
        """
        base_result = CreateTaskBase.approve_creation(self)
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge()
        if not selected_element:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return base_result and selected_element

    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. When a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_element, selected_edge = self._periodic_table_widget.get_selected_element_edge()   

        if selected_element:
            if not shape:
                cpos = queue_model_objects.CentredPosition()
                cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot()
            else:
                # Shapes selected and sample is mounted, get the
                # centred positions for the shapes
                if isinstance(shape, GraphicsItemPoint):
                    snapshot = self._graphics_manager_hwobj.\
                           get_scene_snapshot(shape)

                    cpos = copy.deepcopy(shape.get_centred_position())
                    cpos.snapshot_image = snapshot

            path_template = self._create_path_template(sample, self._path_template)

            energy_scan = queue_model_objects.EnergyScan(sample,
                                                         path_template,
                                                         cpos)
            energy_scan.set_name(path_template.get_prefix())
            energy_scan.set_number(path_template.run_number)
            energy_scan.element_symbol = selected_element
            energy_scan.edge = selected_edge

            data_collections.append(energy_scan)
            self._path_template.run_number += 1
        else:
            logging.getLogger("GUI").\
                info("No element selected, please select an element.")

        return data_collections

    def element_edge_selected(self, element, edge):
        if len(self._current_selected_items) == 1:
            item = self._current_selected_items[0]
            if isinstance(item, Qt4_queue_item.EnergyScanQueueItem):
                item.get_model().element_symbol = str(element)
                item.get_model().edge = str(edge)
Exemplo n.º 16
0
class CreateHelicalWidget(CreateTaskBase):
    def __init__(self, parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, fl, 'Helical')

        if not name:
            self.setObjectName("create_helical_widget")
        self.init_models()

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._lines_map = {}

        # Graphic elements ----------------------------------------------------
        self._lines_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_helical_line_widget_layout.ui"))

        self._acq_widget = AcquisitionWidget(
            self,
            "acquisition_widget",
            layout='vertical',
            acq_params=self._acquisition_parameters,
            path_template=self._path_template)

        self._data_path_widget = DataPathWidget(self,
                                                'create_dc_path_widget',
                                                data_model=self._path_template,
                                                layout='vertical')

        self._processing_widget = ProcessingWidget(
            self, data_model=self._processing_parameters)

        # Layout --------------------------------------------------------------
        _main_vlayout = QtGui.QVBoxLayout(self)
        _main_vlayout.addWidget(self._lines_widget)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._processing_widget)
        _main_vlayout.addStretch(0)
        _main_vlayout.setSpacing(2)
        _main_vlayout.setContentsMargins(0, 0, 0, 0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        #self._lines_widget.lines_treewidget.itemSelectionChanged.connect(\
        #     self.lines_treewidget_selection_changed)
        self._lines_widget.create_line_button.clicked.connect(\
             self.create_line_button_clicked)
        self._lines_widget.remove_line_button.clicked.connect(\
             self.remove_line_button_clicked)

        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)
        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)
        self._data_path_widget.pathTemplateChangedSignal.connect(\
             self.handle_path_conflict)

        self._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(\
             self.handle_path_conflict)

        self._processing_widget.enableProcessingSignal.connect(\
             self._enable_processing_toggled)

        # Other ---------------------------------------------------------------
        for col in range(self._lines_widget.lines_treewidget.columnCount()):
            self._lines_widget.lines_treewidget.resizeColumnToContents(col)

    def init_models(self):
        CreateTaskBase.init_models(self)
        self._energy_scan_result = queue_model_objects.EnergyScanResult()
        self._processing_parameters = queue_model_objects.ProcessingParameters(
        )

        if self._beamline_setup_hwobj is not None:
            has_shutter_less = self._beamline_setup_hwobj.\
                               detector_has_shutterless()
            self._acquisition_parameters.shutterless = has_shutter_less

            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_helical_values")
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )
            self._path_template = queue_model_objects.PathTemplate()

    def shape_created(self, shape, shape_type):
        if shape_type == "Line":
            self._lines_widget.lines_treewidget.clearSelection()
            info_str_list = QtCore.QStringList()
            info_str_list.append(shape.get_display_name())
            info_str_list.append("%d" % shape.get_points_index()[0])
            info_str_list.append("%d" % shape.get_points_index()[1])

            lines_treewidget_item = QtGui.QTreeWidgetItem(\
                self._lines_widget.lines_treewidget,
                info_str_list)
            lines_treewidget_item.setSelected(True)
            self._lines_map[shape] = lines_treewidget_item

            self.lines_treewidget_selection_changed()

    def shape_deleted(self, shape, shape_type):
        if self._lines_map.get(shape):
            shape_index = self._lines_widget.lines_treewidget.\
                 indexFromItem(self._lines_map[shape])
            self._lines_widget.lines_treewidget.\
                 takeTopLevelItem(shape_index.row())
            self._lines_map.pop(shape)

    def approve_creation(self):
        base_result = CreateTaskBase.approve_creation(self)

        if len(self._lines_widget.lines_treewidget.selectedItems()) == 0:
            logging.getLogger("user_level_log").\
                warning("No lines selected, please select one or more lines.")
            return False
        else:
            return base_result

    def update_processing_parameters(self, crystal):
        self._processing_parameters.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma
        self._processing_widget.update_data_model(self._processing_parameters)

    def select_shape_with_cpos(self, start_cpos, end_cpos, num_images):
        selected_line = None

        for shape in self._graphics_manager_hwobj.get_shapes():
            if isinstance(shape, GraphicsItemLine):
                (line_start_cpos,
                 line_end_cpos) = shape.get_centred_positions()
                if line_start_cpos == start_cpos and line_end_cpos == end_cpos:
                    self._graphics_manager_hwobj.de_select_all()
                    self._graphics_manager_hwobj.select_line(shape)
                    shape.set_num_images(num_images)
                    selected_line = shape

        #de-select previous selected list items and
        #select the current shape (Line).
        for (list_item, shape) in self._lines_map.iteritems():
            if selected_line == shape:
                list_item.setSelected(True)
            else:
                list_item.setSelected(False)

    def single_item_selection(self, tree_item):
        CreateTaskBase.single_item_selection(self, tree_item)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            sample_model = tree_item.get_model()
            self._processing_parameters = sample_model.processing_parameters
            #self._processing_parameters = copy.deepcopy(self._processing_parameters)
            self._processing_widget.update_data_model(
                self._processing_parameters)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):
            data_collection = tree_item.get_model()

            if data_collection.experiment_type == EXPERIMENT_TYPE.HELICAL:
                self.setDisabled(tree_item.get_model().is_executed())

                self._path_template = data_collection.get_path_template()
                self._data_path_widget.update_data_model(self._path_template)
                self._acquisition_parameters = data_collection.acquisitions[0].\
                                               acquisition_parameters

                if len(data_collection.acquisitions) == 2:
                    start_cpos = data_collection.acquisitions[0].acquisition_parameters.\
                                 centred_position
                    end_cpos = data_collection.acquisitions[1].acquisition_parameters.\
                               centred_position
                    num_images = data_collection.acquisitions[0].acquisition_parameters.\
                                 num_images
                    self.select_shape_with_cpos(start_cpos, end_cpos,
                                                num_images)

                self._acq_widget.update_data_model(
                    self._acquisition_parameters, self._path_template)
                self.get_acquisition_widget().use_osc_start(True)

                self._processing_parameters = data_collection.processing_parameters
                self._processing_widget.update_data_model(
                    self._processing_parameters)
            else:
                self.setDisabled(True)
        else:
            self.setDisabled(True)

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionGroupQueueItem) or \
           isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem):

            self._processing_widget.update_data_model(
                self._processing_parameters)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)

    def _create_task(self, sample, shape):
        data_collections = []

        for shape in self.get_selected_lines():
            snapshot = self._graphics_manager_hwobj.get_snapshot(shape)

            # Acquisition for start position
            start_acq = self._create_acq(sample)

            start_graphical_point, end_graphical_point = \
                shape.get_graphical_points()
            start_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(start_graphical_point.get_centred_position())
            start_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            start_acq.path_template.suffix = self._session_hwobj.suffix

            # Add another acquisition for the end position
            end_acq = self._create_acq(sample)

            end_acq.acquisition_parameters.\
                centred_position = copy.deepcopy(end_graphical_point.get_centred_position())
            end_acq.acquisition_parameters.centred_position.\
                snapshot_image = snapshot

            end_acq.path_template.suffix = self._session_hwobj.suffix

            processing_parameters = copy.deepcopy(self._processing_parameters)

            dc = queue_model_objects.DataCollection([start_acq, end_acq],
                                                    sample.crystals[0],
                                                    processing_parameters)

            dc.set_name(start_acq.path_template.get_prefix())
            dc.set_number(start_acq.path_template.run_number)
            dc.set_experiment_type(EXPERIMENT_TYPE.HELICAL)
            dc.set_requires_centring(False)

            data_collections.append(dc)
            self._path_template.run_number += 1

        return data_collections

    def lines_treewidget_selection_changed(self):
        for shape, list_item in self._lines_map.iteritems():
            shape.setSelected(list_item.isSelected())

    def create_line_button_clicked(self):
        self._graphics_manager_hwobj.create_line()

    def remove_line_button_clicked(self):
        line_to_delete = None
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                line_to_delete = line
                break
        if line_to_delete:
            self._graphics_manager_hwobj.delete_shape(line_to_delete)

    def get_selected_lines(self):
        selected_lines = []
        for line, treewidget_item in self._lines_map.iteritems():
            if treewidget_item.isSelected():
                selected_lines.append(line)
        return selected_lines
Exemplo n.º 17
0
class CreateCharWidget(CreateTaskBase):
    """
    Descript. :
    """

    def __init__(self,parent = None,name = None, fl = 0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Characterisation')
        self.setObjectName("create_char_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._vertical_dimension_widget = None
        self._current_selected_item = None
        self.init_models()
        self._char_params_mib = DataModelInputBinder(self._char_params)
   
        # Graphic elements ----------------------------------------------------
        self._acq_widget = \
            AcquisitionWidgetSimple(self, acq_params = self._acquisition_parameters,
                                    path_template = self._path_template)

        self._data_path_widget = DataPathWidget(self, 
             data_model = self._path_template, layout = 'vertical')

        self._vertical_dimension_widget = loadUi(os.path.join(os.path.dirname(__file__),
             'ui_files/Qt4_vertical_crystal_dimension_widget_layout.ui'))

        self._char_widget = loadUi(os.path.join(os.path.dirname(__file__),
             'ui_files/Qt4_characterise_simple_widget_vertical_layout.ui')) 

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self) 
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_widget)
        _main_vlayout.addWidget(self._char_widget)
        _main_vlayout.addWidget(self._vertical_dimension_widget)
        _main_vlayout.setContentsMargins(2, 2, 2, 2)
        _main_vlayout.setSpacing(6)
        _main_vlayout.addStretch(0)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------
        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)

        self._vertical_dimension_widget.space_group_ledit.activated.\
             connect(self._space_group_change)
        #self.connect(induced_burn_cbx, QtCore.SIGNAL("toggled(bool)"),
        #             self.use_induced_burn)

        self._char_widget.characterisation_gbox.toggled.connect(\
             self.characterisation_gbox_toggled)
        self._char_widget.wait_result_cbx.toggled.connect(\
             self.wait_results_cbx_toggled)
        self._char_widget.execute_plan_cbx.toggled.connect(\
             self.run_diffraction_plan_cbx_toggled)

        # Other ---------------------------------------------------------------
        self._char_params_mib.bind_value_update(
             'opt_sad', self._char_widget.optimised_sad_cbx,
             bool, None)

        self._char_params_mib.bind_value_update(
             'account_rad_damage', self._char_widget.account_rad_dmg_cbx,
             bool, None)

        #self._char_params_mib.bind_value_update('determine_rad_params', 
        #                                        induced_burn_cbx,
        #                                        bool, None)

        self._char_params_mib.bind_value_update(
             'strategy_complexity', self._char_widget.start_comp_cbox,
             int, None)

        self._char_params_mib.\
            bind_value_update('max_crystal_vdim',
                              self._vertical_dimension_widget.max_vdim_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vdim',
                              self._vertical_dimension_widget.min_vdim_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vphi',
                              self._vertical_dimension_widget.min_vphi_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('max_crystal_vphi',
                              self._vertical_dimension_widget.max_vphi_ledit, float,
                              QDoubleValidator(0.0, 1000, 2, self))
        
        self._vertical_dimension_widget.space_group_ledit.addItems(
            queue_model_enumerables.XTAL_SPACEGROUPS
        )

        self._data_path_widget.data_path_layout.compression_cbox.setVisible(False)

    def enable_compression(self, state):
        CreateTaskBase.enable_compression(self, False)

    def use_induced_burn(self, state):
        """
        Descript. :
        """
        self._acquisition_parameters.induce_burn = state

    def _space_group_change(self, index):
        """
        Descript. :
        """
        self._char_params.space_group = (
            queue_model_enumerables.XTAL_SPACEGROUPS[index]
        )

    def _set_space_group(self, space_group):
        """
        Descript. :
        """
        index  = 0
     
        if self._vertical_dimension_widget: 
            if space_group in queue_model_enumerables.XTAL_SPACEGROUPS:
                index = queue_model_enumerables.XTAL_SPACEGROUPS.index(space_group)

            self._space_group_change(index)
            self._vertical_dimension_widget.space_group_ledit.\
                 setCurrentIndex(index)

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._init_models()

    def _init_models(self):
        """
        Descript. :
        """
        self._char = queue_model_objects.Characterisation()
        self._char_params = self._char.characterisation_parameters
        self._processing_parameters = queue_model_objects.ProcessingParameters()
        self._set_space_group(self._processing_parameters.space_group)

        if self._beamline_setup_hwobj is not None:            
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_char_acq_parameters()

            self._char_params = self._beamline_setup_hwobj.\
                                get_default_characterisation_parameters()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        
        self._path_template.reference_image_prefix = 'ref'
        # The num images drop down default value is 1
        # we would like it to be 2
        self._acquisition_parameters.num_images = 2
        self._char.characterisation_software =\
            queue_model_enumerables.COLLECTION_ORIGIN.EDNA
        self._path_template.num_files = 2
        self._path_template.compression = False
        self._acquisition_parameters.shutterless = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            #self._init_models() 
            if self._char_params.space_group == "":
                sample_model = tree_item.get_model()
                self._set_space_group(sample_model.processing_parameters.space_group)
            #self._acq_widget.update_data_model(self._acquisition_parameters,
            #                                   self._path_template)
            #self._char_params_mib.set_model(self._char_params)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.CharacterisationQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            self._char = tree_item.get_model()

            if self._char.get_path_template():
                self._path_template = self._char.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
            
            data_collection = self._char.reference_image_collection

            self._char_params = self._char.characterisation_parameters
            self._char_params_mib.set_model(self._char_params)

            self._acquisition_parameters = data_collection.acquisitions[0].\
                                           acquisition_parameters

            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            #self.get_acquisition_widget().use_osc_start(True)

            if len(data_collection.acquisitions) == 1:
                self.select_shape_with_cpos(self._acquisition_parameters.\
                                            centred_position)

            self._processing_parameters = data_collection.processing_parameters
        else:
            self.setDisabled(True)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._char_params.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        for shape in selected_shapes:
            if isinstance(shape, GraphicsItemPoint):
                result = True
        return result
        
    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. when a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if not shape or not isinstance(shape, GraphicsItemPoint):
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_scene_snapshot()
        else:
            # Shapes selected and sample is mounted, get the
            # centred positions for the shapes
            snapshot = self._graphics_manager_hwobj.\
                        get_scene_snapshot(shape)
            cpos = copy.deepcopy(shape.get_centred_position())
            cpos.snapshot_image = snapshot 

        char_params = copy.deepcopy(self._char_params)
        acq = self._create_acq(sample)
        dc = queue_model_objects.\
                DataCollection([acq], sample.crystals[0],
                               self._processing_parameters)

        # Reference images for characterisations should be taken 90 deg apart
        # this is achived by setting overap to -89
        acq.acquisition_parameters.overlap = -89
        acq.acquisition_parameters.centred_position = cpos        
        
        dc.acquisitions[0] = acq
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.EDNA_REF
        dc.run_processing_parallel = False

        char = queue_model_objects.Characterisation(dc, 
                                                    char_params)
        char.set_name(dc.acquisitions[0].\
                      path_template.get_prefix())
        char.set_number(dc.acquisitions[0].\
                        path_template.run_number)
        char.run_characterisation = self._char_widget.characterisation_gbox.isChecked()
        char.wait_result = self._char_widget.wait_result_cbx.isChecked()
        char.run_diffraction_plan = self._char_widget.execute_plan_cbx.isChecked()
        char.diff_plan_compression = self._tree_brick.compression_state

        tasks.append(char)
        self._path_template.run_number += 1

        return tasks

    def characterisation_gbox_toggled(self, state):
        if self._char:
            self._char.run_characterisation = state

    def wait_results_cbx_toggled(self, state):
        if self._char:
            self._char.wait_result = state
 
    def run_diffraction_plan_cbx_toggled(self, state):
        if self._char:
            self._char.run_diffraction_plan = state
Exemplo n.º 18
0
class CreateCharWidget(CreateTaskBase):
    """
    Descript. :
    """

    def __init__(self,parent = None,name = None, fl = 0):
        """
        Descript. :
        """

        CreateTaskBase.__init__(self, parent, name, fl, 'Characterisation')

        if not name:
            self.setName("create_char_widget")

        # Hardware objects ----------------------------------------------------

        # Internal variables --------------------------------------------------
        self._current_selected_item = None
        self.init_models()
        self._char_params_mib = DataModelInputBinder(self._char_params)
   
        # Graphic elements ----------------------------------------------------
        self._acq_widget = \
            AcquisitionWidgetSimple(self, acq_params = self._acquisition_parameters,
                                    path_template = self._path_template)

        self._data_path_gbox = QtGui.QGroupBox('Data location', self)
        self._data_path_widget = DataPathWidget(
                               self._data_path_gbox,
                               data_model = self._path_template,
                               layout = 'vertical')

        self._vertical_dimension_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
             'ui_files/Qt4_vertical_crystal_dimension_widget_layout.ui'))
        
        self._char_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
             'ui_files/Qt4_characterise_simple_widget_vertical_layout.ui')) 

        gbox =  self._char_widget.findChild(QtGui.QGroupBox, "characterisation_gbox")
        p = gbox.palette();
        p.setColor(QtGui.QPalette.Window, QtCore.Qt.red);
        p.setColor(QtGui.QPalette.Highlight, QtCore.Qt.red);
        gbox.setPalette(p);

        # Layout --------------------------------------------------------------
        _data_path_gbox_layout = QtGui.QVBoxLayout(self)
        _data_path_gbox_layout.addWidget(self._data_path_widget)
        _data_path_gbox_layout.setSpacing(0)
        _data_path_gbox_layout.setContentsMargins(0,0,0,0)
        self._data_path_gbox.setLayout(_data_path_gbox_layout)

        _main_vlayout = QtGui.QVBoxLayout(self) 
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_gbox)
        _main_vlayout.addWidget(self._char_widget)
        _main_vlayout.addWidget(self._vertical_dimension_widget)
        _main_vlayout.setSpacing(0)
        _main_vlayout.setContentsMargins(0,0,0,0)
        self.setLayout(_main_vlayout)

        # SizePolicies --------------------------------------------------------

        # Qt signal/slot connections ------------------------------------------

        # Other ---------------------------------------------------------------
        self._char_params_mib.bind_value_update(
             'opt_sad', self._char_widget.optimised_sad_cbx,
             bool, None)

        self._char_params_mib.bind_value_update(
             'account_rad_damage', self._char_widget.account_rad_dmg_cbx,
             bool, None)

        #self._char_params_mib.bind_value_update('determine_rad_params', 
        #                                        induced_burn_cbx,
        #                                        bool, None)

        self._char_params_mib.bind_value_update(
             'strategy_complexity', self._char_widget.start_comp_cbox,
             int, None)

        self._char_params_mib.\
            bind_value_update('max_crystal_vdim',
                              self._vertical_dimension_widget.max_vdim_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vdim',
                              self._vertical_dimension_widget.min_vdim_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('min_crystal_vphi',
                              self._vertical_dimension_widget.min_vphi_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))

        self._char_params_mib.\
            bind_value_update('max_crystal_vphi',
                              self._vertical_dimension_widget.max_vphi_ledit, float,
                              QtGui.QDoubleValidator(0.0, 1000, 2, self))
        
        self._vertical_dimension_widget.space_group_ledit.addItems(XTAL_SPACEGROUPS)

        self._data_path_widget.data_path_layout.prefix_ledit.textChanged.\
             connect(self._prefix_ledit_change)

        self._data_path_widget.data_path_layout.run_number_ledit.textChanged.\
             connect(self._run_number_ledit_change)

        self._vertical_dimension_widget.space_group_ledit.activated.\
             connect(self._space_group_change)

        self.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        #self.connect(induced_burn_cbx, QtCore.SIGNAL("toggled(bool)"),
        #             self.use_induced_burn)

    def use_induced_burn(self, state):
        """
        Descript. :
        """
        self._acquisition_parameters.induce_burn = state

    def _space_group_change(self, index):
        """
        Descript. :
        """
        self._char_params.space_group = queue_model_enumerables.\
                                        XTAL_SPACEGROUPS[index]
    def _set_space_group(self, space_group):
        """
        Descript. :
        """
        index  = 0
        
        if space_group in XTAL_SPACEGROUPS:
            index = XTAL_SPACEGROUPS.index(space_group)

        self._space_group_change(index)
        self._vertical_dimension_widget.space_group_ledit.setCurrentIndex(index)

    def init_models(self):
        """
        Descript. :
        """
        CreateTaskBase.init_models(self)
        self._init_models()

    def _init_models(self):
        """
        Descript. :
        """
        self._char = queue_model_objects.Characterisation()
        self._char_params = self._char.characterisation_parameters
        self._processing_parameters = queue_model_objects.ProcessingParameters()

        if self._beamline_setup_hwobj is not None:            
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_char_acq_parameters()

            self._char_params = self._beamline_setup_hwobj.\
                                get_default_characterisation_parameters()
            try:
                transmission = self._beamline_setup_hwobj.transmission_hwobj.getAttFactor()
                transmission = round(float(transmission), 1)
            except AttributeError:
                transmission = 0

            try:
                resolution = self._beamline_setup_hwobj.resolution_hwobj.getPosition()
                resolution = round(float(resolution), 3)
            except AttributeError:
                resolution = 0

            try:
                energy = self._beamline_setup_hwobj.energy_hwobj.getCurrentEnergy()
                energy = round(float(energy), 4)
            except AttributeError:
                energy = 0

            self._acquisition_parameters.resolution = resolution
            self._acquisition_parameters.energy = energy
            self._acquisition_parameters.transmission = transmission
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
        
          
        return 
    
        self._path_template.reference_image_prefix = 'ref'
        # The num images drop down default value is 1
        # we would like it to be 2
        self._acquisition_parameters.num_images = 2
        self._char.characterisation_software =\
            queue_model_enumerables.COLLECTION_ORIGIN.EDNA
        self._path_template.num_files = 2
        self._acquisition_parameters.shutterless = False

    def single_item_selection(self, tree_item):
        """
        Descript. :
        """
        CreateTaskBase.single_item_selection(self, tree_item)
        
        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            self._init_models()
            self._set_space_group(self._char_params.space_group)
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                                self._path_template)
            self._char_params_mib.set_model(self._char_params)
            #self._char_params = copy.deepcopy(self._char_params)
            #self._acquisition_parameters = copy.deepcopy(self._acquisition_parameters)

        elif isinstance(tree_item, Qt4_queue_item.CharacterisationQueueItem):
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            self._char = tree_item.get_model()

            if self._char.get_path_template():
                self._path_template = self._char.get_path_template()

            self._data_path_widget.update_data_model(self._path_template)
            
            data_collection = self._char.reference_image_collection

            self._char_params = self._char.characterisation_parameters
            self._char_params_mib.set_model(self._char_params)

            self._acquisition_parameters = data_collection.acquisitions[0].\
                                           acquisition_parameters

            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self.get_acquisition_widget().use_osc_start(True)

            if len(data_collection.acquisitions) == 1:
                self.select_shape_with_cpos(self._acquisition_parameters.\
                                            centred_position)

            self._processing_parameters = data_collection.processing_parameters
        else:
            self.setDisabled(True)

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        self._processing_parameters.space_group = crystal.space_group
        self._char_params.space_group = crystal.space_group
        self._processing_parameters.cell_a = crystal.cell_a
        self._processing_parameters.cell_alpha = crystal.cell_alpha
        self._processing_parameters.cell_b = crystal.cell_b
        self._processing_parameters.cell_beta = crystal.cell_beta
        self._processing_parameters.cell_c = crystal.cell_c
        self._processing_parameters.cell_gamma = crystal.cell_gamma

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_shapes = self._graphics_manager_hwobj.get_selected_shapes()

        for shape in selected_shapes:
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                result = True
        return result
        
    # Called by the owning widget (task_toolbox_widget) to create
    # a collection. when a data collection group is selected.
    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        tasks = []

        if not shape:
            cpos = queue_model_objects.CentredPosition()
            cpos.snapshot_image = self._graphics_manager_hwobj.get_snapshot()
        else:
            # Shapes selected and sample is mounted, get the
            # centred positions for the shapes
            if isinstance(shape, Qt4_GraphicsManager.GraphicsItemPoint):
                snapshot = self._graphics_manager_hwobj.\
                           get_snapshot([shape])

                cpos = copy.deepcopy(shape.get_centred_positions()[0])
                cpos.snapshot_image = snapshot 

        char_params = copy.deepcopy(self._char_params)
        acq = self._create_acq(sample)
        dc = queue_model_objects.\
                DataCollection([acq], sample.crystals[0],
                               self._processing_parameters)

        # Reference images for characterisations should be taken 90 deg apart
        # this is achived by setting overap to -89
        acq.acquisition_parameters.overlap = -89
        acq.acquisition_parameters.centred_position = cpos        
        
        dc.acquisitions[0] = acq
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.EDNA_REF

        char = queue_model_objects.Characterisation(dc, 
                                                    char_params)
        char.set_name(dc.acquisitions[0].\
                      path_template.get_prefix())
        char.set_number(dc.acquisitions[0].\
                        path_template.run_number)

        tasks.append(char)
        self._path_template.run_number += 1

        return tasks